## wk12_1123_ch07_函式模組_期末專題參考
1. 大樂透
2. 1A2B
## 【inclass practice】
```python
import random as r
list1=r.sample(range(1,50),7)
print(list1)
special=list1.pop()
print(f"特別號={special}")
print(f"中獎號碼={list1}")
```
[29, 3, 6, 34, 21, 26, 9]
特別號=9
中獎號碼=[29, 3, 6, 34, 21, 26]
```python
print(r.sample("123456789",4))
```
['6', '4', '3', '2']
```python
secret="".join(r.sample("123456789",4))
print(secret)
guess="1234"
a=0
b=0
for i in range (4):
if guess[i]== secret[i]:
a=a+1
elif guess[i] in secret :
b=b+1
print(f"{a}A{b}B")
```
2879
0A1B
```python
def evaluate(guess):
a=0
b=0
for i in range (4):
if guess[i]== secret[i]:
a=a+1
elif guess[i] in secret :
b=b+1
print(f"{a}A{b}B")
if a==4:
print("bingo")
secret="".join(r.sample("123456789",4))
print(secret)
while True:
guess=input("guess,enter 4 numbers,press enter to end")
if len(guess)==0:
print(f"byebye")
break
else:
evaluate(guess)
```
8721
guess,enter 4 numbers,press enter to end8712
1A0B
2A0B
2A1B
2A2B
guess,enter 4 numbers,press enter to end8721
1A0B
2A0B
3A0B
4A0B
bingo
guess,enter 4 numbers,press enter to end
byebye
```python
!pip install pygame
```
Defaulting to user installation because normal site-packages is not writeable
Requirement already satisfied: pygame in c:\users\user\appdata\roaming\python\python310\site-packages (2.5.2)
```python
"""
Snake Eater
Made with PyGame
"""
import pygame, sys, time, random
# Difficulty settings
# Easy -> 10
# Medium -> 25
# Hard -> 40
# Harder -> 60
# Impossible-> 120
difficulty = 25
# Window size
frame_size_x = 720
frame_size_y = 480
# Checks for errors encountered
check_errors = pygame.init()
# pygame.init() example output -> (6, 0)
# second number in tuple gives number of errors
if check_errors[1] > 0:
print(f'[!] Had {check_errors[1]} errors when initialising game, exiting...')
sys.exit(-1)
else:
print('[+] Game successfully initialised')
# Initialise game window
pygame.display.set_caption('Snake Eater')
game_window = pygame.display.set_mode((frame_size_x, frame_size_y))
# Colors (R, G, B)
black = pygame.Color(0, 0, 0)
white = pygame.Color(255, 255, 255)
red = pygame.Color(255, 0, 0)
green = pygame.Color(0, 255, 0)
blue = pygame.Color(0, 0, 255)
# FPS (frames per second) controller
fps_controller = pygame.time.Clock()
# Game variables
snake_pos = [100, 50]
snake_body = [[100, 50], [100-10, 50], [100-(2*10), 50]]
food_pos = [random.randrange(1, (frame_size_x//10)) * 10, random.randrange(1, (frame_size_y//10)) * 10]
food_spawn = True
direction = 'RIGHT'
change_to = direction
score = 0
# Game Over
def game_over():
my_font = pygame.font.SysFont('times new roman', 90)
game_over_surface = my_font.render('YOU DIED', True, red)
game_over_rect = game_over_surface.get_rect()
game_over_rect.midtop = (frame_size_x/2, frame_size_y/4)
game_window.fill(black)
game_window.blit(game_over_surface, game_over_rect)
show_score(0, red, 'times', 20)
pygame.display.flip()
time.sleep(3)
pygame.quit()
sys.exit()
# Score
def show_score(choice, color, font, size):
score_font = pygame.font.SysFont(font, size)
score_surface = score_font.render('Score : ' + str(score), True, color)
score_rect = score_surface.get_rect()
if choice == 1:
score_rect.midtop = (frame_size_x/10, 15)
else:
score_rect.midtop = (frame_size_x/2, frame_size_y/1.25)
game_window.blit(score_surface, score_rect)
# pygame.display.flip()
# Main logic
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# Whenever a key is pressed down
elif event.type == pygame.KEYDOWN:
# W -> Up; S -> Down; A -> Left; D -> Right
if event.key == pygame.K_UP or event.key == ord('w'):
change_to = 'UP'
if event.key == pygame.K_DOWN or event.key == ord('s'):
change_to = 'DOWN'
if event.key == pygame.K_LEFT or event.key == ord('a'):
change_to = 'LEFT'
if event.key == pygame.K_RIGHT or event.key == ord('d'):
change_to = 'RIGHT'
# Esc -> Create event to quit the game
if event.key == pygame.K_ESCAPE:
pygame.event.post(pygame.event.Event(pygame.QUIT))
# Making sure the snake cannot move in the opposite direction instantaneously
if change_to == 'UP' and direction != 'DOWN':
direction = 'UP'
if change_to == 'DOWN' and direction != 'UP':
direction = 'DOWN'
if change_to == 'LEFT' and direction != 'RIGHT':
direction = 'LEFT'
if change_to == 'RIGHT' and direction != 'LEFT':
direction = 'RIGHT'
# Moving the snake
if direction == 'UP':
snake_pos[1] -= 10
if direction == 'DOWN':
snake_pos[1] += 10
if direction == 'LEFT':
snake_pos[0] -= 10
if direction == 'RIGHT':
snake_pos[0] += 10
# Snake body growing mechanism
snake_body.insert(0, list(snake_pos))
if snake_pos[0] == food_pos[0] and snake_pos[1] == food_pos[1]:
score += 1
food_spawn = False
else:
snake_body.pop()
# Spawning food on the screen
if not food_spawn:
food_pos = [random.randrange(1, (frame_size_x//10)) * 10, random.randrange(1, (frame_size_y//10)) * 10]
food_spawn = True
# GFX
game_window.fill(black)
for pos in snake_body:
# Snake body
# .draw.rect(play_surface, color, xy-coordinate)
# xy-coordinate -> .Rect(x, y, size_x, size_y)
pygame.draw.rect(game_window, green, pygame.Rect(pos[0], pos[1], 10, 10))
# Snake food
pygame.draw.rect(game_window, white, pygame.Rect(food_pos[0], food_pos[1], 10, 10))
# Game Over conditions
# Getting out of bounds
if snake_pos[0] < 0 or snake_pos[0] > frame_size_x-10:
game_over()
if snake_pos[1] < 0 or snake_pos[1] > frame_size_y-10:
game_over()
# Touching the snake body
for block in snake_body[1:]:
if snake_pos[0] == block[0] and snake_pos[1] == block[1]:
game_over()
show_score(1, white, 'consolas', 20)
# Refresh game screen
pygame.display.update()
# Refresh rate
fps_controller.tick(difficulty)
```
[+] Game successfully initialised
An exception has occurred, use %tb to see the full traceback.
SystemExit
```python
import pygame, sys, time, random
difficulty = 10
frame_size_x = 720
frame_size_y = 480
pygame.display.set_caption('Snake 1')
game_window = pygame.display.set_mode((frame_size_x, frame_size_y))
fps_controller = pygame.time.Clock()
# Colors (R, G, B)
black = pygame.Color(0, 0, 0)
white = pygame.Color(255, 255, 255)
red = pygame.Color(255, 0, 0)
green = pygame.Color(0, 255, 0)
blue = pygame.Color(0, 0, 255)
# Game variables
snake_pos = [100, 50]
snake_body = [[100, 50], [100-10, 50], [100-(2*10), 50]]
food_pos = [random.randrange(1, (frame_size_x//10)) * 10, random.randrange(1, (frame_size_y//10)) * 10]
food_spawn = True
direction = 'RIGHT'
change_to = direction
score = 0
# Main logic
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# Whenever a key is pressed down
elif event.type == pygame.KEYDOWN:
# W -> Up; S -> Down; A -> Left; D -> Right
if event.key == pygame.K_UP or event.key == ord('w'):
change_to = 'UP'
if event.key == pygame.K_DOWN or event.key == ord('s'):
change_to = 'DOWN'
if event.key == pygame.K_LEFT or event.key == ord('a'):
change_to = 'LEFT'
if event.key == pygame.K_RIGHT or event.key == ord('d'):
change_to = 'RIGHT'
# Esc -> Create event to quit the game
if event.key == pygame.K_ESCAPE:
pygame.event.post(pygame.event.Event(pygame.QUIT))
# Making sure the snake cannot move in the opposite direction instantaneously
if change_to == 'UP' and direction != 'DOWN':
direction = 'UP'
if change_to == 'DOWN' and direction != 'UP':
direction = 'DOWN'
if change_to == 'LEFT' and direction != 'RIGHT':
direction = 'LEFT'
if change_to == 'RIGHT' and direction != 'LEFT':
direction = 'RIGHT'
# Moving the snake
if direction == 'UP':
snake_pos[1] -= 10
if direction == 'DOWN':
snake_pos[1] += 10
if direction == 'LEFT':
snake_pos[0] -= 10
if direction == 'RIGHT':
snake_pos[0] += 10
# Snake body growing mechanism
snake_body.insert(0, list(snake_pos))
if snake_pos[0] == food_pos[0] and snake_pos[1] == food_pos[1]:
score += 1
food_spawn = False
else:
snake_body.pop()
# GFX
game_window.fill(black)
for pos in snake_body:
# Snake body
# .draw.rect(play_surface, color, xy-coordinate)
# xy-coordinate -> .Rect(x, y, size_x, size_y)
pygame.draw.rect(game_window, green, pygame.Rect(pos[0], pos[1], 10, 10))
# Snake food
pygame.draw.rect(game_window, white, pygame.Rect(food_pos[0], food_pos[1], 10, 10))
pygame.display.update()
fps_controller.tick(difficulty)
```
An exception has occurred, use %tb to see the full traceback.
SystemExit
## 【afterclass practice】
{範例}
1. 學生分蘋果
2. 總和及排序
3. 檢查網址格式
4. 以字串排版函式列印成績單
5. 轉換日期格式
```python
#1.
person = int(input("請輸入學生人數: "))
apple = int(input("請輸入蘋果總數: "))
ret = divmod(apple, person)
print("每個學生可分得蘋果 " + str(ret[0]) + " 個")
print("蘋果剩餘 " + str(ret[1]) + " 個")
```
請輸入學生人數: 5
請輸入蘋果總數: 24
每個學生可分得蘋果 4 個
蘋果剩餘 4 個
```python
#2.
innum = 0
list1 = []
while(innum != -1):
innum = int(input("請輸入電費 (-1:結束):"))
list1.append(innum)
list1.pop()
print("共輸入 %d 個數" % len(list1))
print("最多電費為:%d" % max(list1))
print("最少電費為:%d" % min(list1))
print("電費總和為:%d" % sum(list1))
print("電費由大到小排序為:{}".format(sorted(list1, reverse=True)))
```
請輸入電費 (-1:結束):20
請輸入電費 (-1:結束):30
請輸入電費 (-1:結束):-1
共輸入 2 個數
最多電費為:30
最少電費為:20
電費總和為:50
電費由大到小排序為:[30, 20]
```python
#3.
web = input("請輸入網址:")
if web.startswith("http://") or web.startswith("https://"):
print("輸入的網址格式正確!")
else:
print("輸入的網址格式錯誤!")
```
請輸入網址:123
輸入的網址格式錯誤!
```python
#4.
listname = ["林大明", "陳阿中", "張小英"]
listchinese = [100, 74, 82]
listmath = [87, 88, 65]
listenglish = [79, 100, 8]
print("姓名 座號 國文 數學 英文")
for i in range(0,3):
print(listname[i].ljust(5), str(i+1).rjust(3), str(listchinese[i]).rjust(5), str(listmath[i]).rjust(5), str(listenglish[i]).rjust(5))
```
姓名 座號 國文 數學 英文
林大明 1 100 87 79
陳阿中 2 74 88 100
張小英 3 82 65 8
```python
#5.
date1 = "2017-8-23"
date1 = "西元 " + date1
date1 = date1.replace("-", " 年 ", 1)
date1 = date1.replace("-", " 月 ", 1)
date1 += " 日"
print(date1)
```
西元 2017 年 8 月 23 日
{綜合演練}
1. 實作3
2. 實作4
```python
#1.
import time as t
time1 = t.localtime()
show = "現在時刻:"
if time1.tm_hour < 12:
show += "上午 "
hour = time1.tm_hour
else:
show += "下午 "
hour = time1.tm_hour - 12
show += str(hour) + " 點 " + str(time1.tm_min) + " 分 "
show += str(time1.tm_sec) + " 秒"
print(show)
```
現在時刻:下午 2 點 50 分 6 秒
```python
#2.
def change(n,coin): # 換硬幣
m = n // coin # 硬幣數
return m
money=[50,10,5,1]
n=int(input("請輸入換幣金額:"))
while (n>0):
for i in range(len(money)):
coin = money[i]
if (n >= coin):
m = change(n,coin) # 換硬幣
print("{}元 * {}個" .format(coin,m))
n= n % coin
```
請輸入換幣金額:200
50元 * 4個