比較有權威的翻譯網(wǎng)站推薦(最權威的翻譯網(wǎng)站)
2023-08-25
更新時間:2023-08-25 18:07:53作者:佚名
最近有很多的同學問,能不能用Python做出一個小游戲來,而且最好要講清楚每一段干嘛是用來干嘛的
那行,今天將來講解一下用Python pygame做一個貪吃蛇的小游戲
據(jù)說是貪吃蛇游戲是1976年,Gremlin公司推出的經(jīng)典街機游戲,那我們今天用Python制作的這個貪吃蛇小游戲是一個像素版的,雖然簡陋,但還是可以玩起來的
import pygame import random import copy
pygame.init() clock = pygame.time.Clock() # 設置游戲時鐘 pygame.display.set_caption("貪吃蛇-解答、源碼、相關資料可私信我") # 初始化標題 screen = pygame.display.set_mode((500, 500)) # 初始化窗口 窗體的大小為 500 500
snake_list = [[10, 10]]
move_up = False move_down = False move_left = False move_right = True
x = random.randint(10, 490) y = random.randint(10, 490) food_point = [x, y]
running = True while running: # 游戲時鐘 刷新頻率 clock.tick(20)
screen.fill([255, 255, 255])
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)
snake_rect = [] for pos in snake_list: # 1.7.1 繪制蛇的身子 snake_rect.append(pygame.draw.circle(screen, [255, 0, 0], pos, 5, 0))
pos = len(snake_list) - 1 while pos > 0: snake_list[pos] = copy.deepcopy(snake_list[pos - 1]) pos -= 1
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
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
pos = len(snake_list) - 1 while pos > 0: snake_list[pos] = copy.deepcopy(snake_list[pos - 1]) pos -= 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
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()