## 【wk12_1123】函式模組_期末專題參考
## 【inclass practice】
ch07_函式與模組
7.1 自訂函式
- 變數有效範圍
7.2 數值函式
- 數值函式整理
- 指數、商數、餘數及四捨六入
- 最大值、最小值、總和及排序
7.3 字串函式
- 字串函式整理
- 連接及分割字串
- 檢查起始或結束字串
- 字串排版相關函式
- 搜尋即取代字串
```python
# 大樂透中獎號碼
import random as r
list1 = r.sample(range(1, 50), 7)
special = list1.pop()
print(f"特別號 = {special}")
print(f"中獎號碼 = {list1}")
```
特別號 = 48
中獎號碼 = [46, 14, 43, 45, 42, 22]
```python
# 1A2B
# 函式1 : 數字相同 + 位置相同
# 函式2 : 數字相同 + 位置不同
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")
```
4317
0A3B
```python
# 1A2B
# 函式1 : 數字相同 + 位置相同
# 函式2 : 數字相同 + 位置不同
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
return a, b
secret = "".join(r.sample("123456789", 4))
print(secret)
while True :
guess = input("guess, enter 4 numbers, enter直接結束遊戲")
if len(guess) == 0 :
print(f"bye")
break
a, b = evaluate(guess)
print(f"{a}A{b}B")
if a == 4 :
break
if a == 4 :
print("bingo")
```
2645
guess, enter 4 numbers, enter直接結束遊戲 1234
0A2B
guess, enter 4 numbers, enter直接結束遊戲
bye
```python
! pip install pygame
```
Requirement already satisfied: pygame in c:\users\selin\anaconda3\lib\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)
```
```python
# 貪吃蛇專案導讀
import pygame, sys, time, random
difficulty = 10
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)
frame_size_x = 720
frame_size_y = 480
food_pos = [random.randrange(1, (frame_size_x//10)) * 10, random.randrange(1, (frame_size_y//10)) * 10]
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')
food_spawn = True
direction = 'RIGHT'
change_to = direction
snake_pos = [100, 50]
snake_body = [[100, 50], [100-10, 50], [100-(2*10), 50]]
pygame.display.set_caption('Snake !')
game_window = pygame.display.set_mode((frame_size_x, frame_size_y))
fps_controller = pygame.time.Clock()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
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))
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.insert(0, list(snake_pos))
if snake_pos[0] == food_pos[0] and snake_pos[1] == food_pos[1]:
# score += 1 # 這行被註解掉,因為 score 變量沒有被定義
food_spawn = False
else:
snake_body.pop()
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
game_window.fill(black)
for pos in snake_body:
pygame.draw.rect(game_window, green, pygame.Rect(pos[0], pos[1], 10, 10))
pygame.display.update()
fps_controller.tick(difficulty)
```
[+] Game successfully initialised
## 【afterclass practice】
1. 尋找期末專題主題
2. {範例}
- 學生分蘋果
- 總和及排序
- 檢查網址格式
- 以字串排版函式列印成績單
- 轉換日期格式
3. {綜合演練}
- 實作3
- 實作4
### 尋找期末專題主題
消消樂
### 範例
```python
#學生分蘋果
# divmod
person = int(input("請輸入學生人數: "))
apple = int(input("請輸入蘋果總數: "))
ret = divmod(apple, person)
print("每個學生可分得蘋果 " + str(ret[0]) + " 個")
print("蘋果剩餘 " + str(ret[1]) + " 個")
```
請輸入學生人數: 50
請輸入蘋果總數: 46
每個學生可分得蘋果 0 個
蘋果剩餘 46 個
```python
#總和及排序
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:結束): 200
請輸入電費 (-1:結束): 500
請輸入電費 (-1:結束): 123
請輸入電費 (-1:結束): 555
請輸入電費 (-1:結束): -1
共輸入 4 個數
最多電費為:555
最少電費為:123
電費總和為:1378
電費由大到小排序為:[555, 500, 200, 123]
```python
#檢查網址格式
# startswith
web = input("請輸入網址:")
if web.startswith("http://") or web.startswith("https://"):
print("輸入的網址格式正確!")
else:
print("輸入的網址格式錯誤!")
```
請輸入網址: https://changgunguniversity-my.sharepoint.com/personal/d000000225_cgu_edu_tw/_layouts/15/onedrive.aspx?ga=1&id=%2Fpersonal%2Fd000000225%5Fcgu%5Fedu%5Ftw%2FDocuments%2F%5F00%E3%80%90%E8%AA%B2%E7%A8%8B%E8%B3%87%E6%BA%90%E3%80%91%2F00%5FPython%E9%9B%B6%E5%9F%BA%E7%A4%8E%E5%85%A5%E9%96%80%E7%8F%AD%2F%E5%90%84%E7%AB%A0%E7%AF%84%E4%BE%8B%5Fpy%2Fch07%2Fstartswith%2Epy&parent=%2Fpersonal%2Fd000000225%5Fcgu%5Fedu%5Ftw%2FDocuments%2F%5F00%E3%80%90%E8%AA%B2%E7%A8%8B%E8%B3%87%E6%BA%90%E3%80%91%2F00%5FPython%E9%9B%B6%E5%9F%BA%E7%A4%8E%E5%85%A5%E9%96%80%E7%8F%AD%2F%E5%90%84%E7%AB%A0%E7%AF%84%E4%BE%8B%5Fpy%2Fch07
輸入的網址格式正確!
```python
#以字串排版函式列印成績單
# just
listname = ["Alice", "Amy", "Alex"]
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))
```
姓名 座號 國文 數學 英文
Alice 1 100 87 79
Amy 2 74 88 100
Alex 3 82 65 8
```python
#轉換日期格式
# replace
date1 = input("YYYY-MM-DD = ")
date1 = "西元 " + date1
date1 = date1.replace("-", " 年 ", 1)
date1 = date1.replace("-", " 月 ", 1)
date1 += " 日"
print(date1)
```
YYYY-MM-DD = 2023-11-16
西元 2023 年 11 月 16 日
### 綜合演練
#### 實作3
以十二小時(上午、下午)顯示現在時刻。
```python
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)
```
現在時刻:上午 6 點 43 分 58 秒
#### 實作4:
小華媽媽上菜市場買菜,找錢時她希望在1元、5元、10元、50元硬幣中找回最少的硬幣。小華就利用自訂函式幫媽媽寫了一個程式。
```python
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
```
請輸入換幣金額: 100
50元 * 2個
## 【self practice】
```python
# str.ljust(width[, fillchar])
# 將字符串向左對齊,使其寬度達到指定的 width。可選參數 fillchar 用於填充不足的空格,預設為空格
text = "Hello"
result = text.ljust(10, '*')
print(result)
```
Hello*****
```python
# str.rjust(width[, fillchar])
# 將字符串向右對齊,使其寬度達到指定的 width。可選參數 fillchar 用於填充不足的空格,預設為空格
text = "Hello"
result = text.rjust(10, '*')
print(result)
```
*****Hello
```python
# str.center(width[, fillchar])
# 將字符串居中,使其寬度達到指定的 width。可選參數 fillchar 用於填充不足的空格,預設為空格
text = "Hello"
result = text.center(10, '*')
print(result)
```
**Hello***