前言
最近有很多的同學問,能不能用Python做出一個小游戲來,而且最好要講清楚每一段干嘛是用來干嘛的
那行,今天將來講解一下用Python pygame做一個貪吃蛇的小游戲
據說是貪吃蛇游戲是1976年,Gremlin公司推出的經典街機游戲,那我們今天用Python制作的這個貪吃蛇小游戲是一個像素版的,雖然簡陋,但還是可以玩起來的
對于本篇文章有疑問的同學可以加【資料白嫖、解答交流群:910981974】
我們主要要做的內容
- 創建游戲視窗
- 繪制貪吃蛇與食物
- 蛇吃食物
貪吃蛇的棋盤模型


現在就開始我們的代碼,首先,還是匯入模塊
import pygame import random import copy
1. 創建游戲視窗
1.1 游戲初始化
pygame.init() clock = pygame.time.Clock() # 設定游戲時鐘 pygame.display.set_caption("貪吃蛇-解答、原始碼、相關資料可私信我") # 初始化標題 screen = pygame.display.set_mode((500, 500)) # 初始化視窗 表單的大小為 500 500
1.2 初始化蛇的位置 蛇的長度 10 10 也就是蛇的 X Y 坐標
snake_list = [[10, 10]]
首先設定蛇的一個運行方向 接下來判斷鍵盤事件在決定蛇的運行方向
蛇可以運行起來了,那么接下來就是,吃食物增加自己的長度和不吃食物在不同的位置顯示
初始小蛇方向
move_up = False move_down = False move_left = False move_right = True
1.3 初始化食物的位置
x = random.randint(10, 490) y = random.randint(10, 490) food_point = [x, y]
1.4 開啟游戲回圈
running = True while running: # 游戲時鐘 重繪頻率 clock.tick(20)
1.5 填充背景為白色
screen.fill([255, 255, 255])
1.6 繪制背景
for x in range(0, 501, 10): pygame.draw.line(screen, (195, 197, 199), (x, 0), (x, 500), 1) pygame.draw.line(screen, (195, 197, 199), (0, x), (500, x), 1) food_rect = pygame.draw.circle(screen, [255, 0, 0], food_point, 15, 0)

1.7繪制蛇
snake_rect = [] for pos in snake_list: # 1.7.1 繪制蛇的身子 snake_rect.append(pygame.draw.circle(screen, [255, 0, 0], pos, 5, 0))

2. 繪制貪吃蛇與食物
2.1 獲取蛇的長度,移動蛇的身子
pos = len(snake_list) - 1 while pos > 0: snake_list[pos] = copy.deepcopy(snake_list[pos - 1]) pos -= 1
2.2 更改蛇頭位置
if move_up: snake_list[pos][1] -= 10 if snake_list[pos][1] < 0: snake_list[pos][1] = 500 if move_down: snake_list[pos][1] += 10 if snake_list[pos][1] > 500: snake_list[pos][1] = 0 if move_left: snake_list[pos][0] -= 10 if snake_list[pos][0] < 0: snake_list[pos][0] = 500 if move_right: snake_list[pos][0] += 10 if snake_list[pos][0] > 500: snake_list[pos][0] = 0
2.3 鍵盤控制移動職位
for event in pygame.event.get(): # print(event) # 判斷按下的按鍵 if event.type == pygame.KEYDOWN: # 上鍵 if event.key == pygame.K_UP: move_up = True move_down = False move_left = False move_right = False # 下鍵 if event.key == pygame.K_DOWN: move_up = False move_down = True move_left = False move_right = False # 左鍵 if event.key == pygame.K_LEFT: move_up = False move_down = False move_left = True move_right = False # 右鍵 if event.key == pygame.K_RIGHT: move_up = False move_down = False move_left = False move_right = True
2.4 獲取蛇的長度,移動蛇的身子
pos = len(snake_list) - 1 while pos > 0: snake_list[pos] = copy.deepcopy(snake_list[pos - 1]) pos -= 1

3. 蛇吃食物
3.1 碰撞檢測 如果蛇吃掉食物
if food_rect.collidepoint(pos): # 貪吃蛇吃掉食物 snake_list.append(food_point) # 重置食物位置 food_point = [random.randint(10, 490), random.randint(10, 490)] food_rect = pygame.draw.circle(screen, [255, 0, 0], food_point, 15, 0) break
3.2 如果蛇吃掉了自己
head_rect = snake_rect[0] count = len(snake_rect) while count > 1: if head_rect.colliderect(snake_rect[count - 1]): running = False count -= 1 pygame.display.update()

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/380189.html
標籤:Python
