# wk12_1123_Snake_Pygame
## {實戰#2} : 貪吃蛇專案導讀
```python
! pip install pygame
```
```python
import pygame, sys, time, random
difficulty = 110
# 難度(difficulty)設定
# Easy -> 10
# Medium -> 25
# Hard -> 40
# Harder -> 60
# Impossible-> 120
```
pygame 2.5.2 (SDL 2.28.3, Python 3.11.5)
Hello from the pygame community. https://www.pygame.org/contribute.html
```python
# 基礎設定
frame_size_x = 720
frame_size_y = 480
direction = 'RIGHT'
change_to = direction
food_pos = [random.randrange(1, (frame_size_x//10)) * 10, random.randrange(1, (frame_size_y//10)) * 10]
food_spawn = True
score = 0
```
```python
# 顏色設定(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)
```
```python
# 蛇外觀設定
snake_pos = [100, 50]
snake_body = [[100, 50], [100-10, 50], [100-(2*10), 50]]
```
```python
fps_controller = pygame.time.Clock() #幀率設定
pygame.display.set_caption('Snake!')
game_window = pygame.display.set_mode((frame_size_x, frame_size_y))
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.KEYDOWN:
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'
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'
if direction == 'UP': #蛇移動控制指標,注意 : 越往下,y越大!!!
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
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))
# .draw.rect(play_surface, color, xy-coordinate)
# xy-coordinate -> .Rect(x, y, size_x, size_y)
pygame.display.update() #重置畫面
fps_controller.tick(difficulty) #重置速度
```
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[6], line 42
39 snake_pos[0] += 10
41 snake_body.insert(0, list(snake_pos)) #蛇變長的設定
---> 42 if snake_pos[0] == food_pos[0] and snake_pos[1] == food_pos[1]:
43 score += 1
44 food_spawn = False
NameError: name 'food_pos' is not defined
```python
# 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')
# 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()
# 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)
```
pygame 2.5.2 (SDL 2.28.3, Python 3.10.9)
Hello from the pygame community. https://www.pygame.org/contribute.html
[+] Game successfully initialised
An exception has occurred, use %tb to see the full traceback.
SystemExit
C:\ProgramData\anaconda3\lib\site-packages\IPython\core\interactiveshell.py:3468: UserWarning: To exit: use 'exit', 'quit', or Ctrl-D.
warn("To exit: use 'exit', 'quit', or Ctrl-D.", stacklevel=1)