用pygame开发的贪吃蛇小游戏

发布时间 2023-09-09 11:03:33作者: IT老boy

import pygame
import sys
import random

初始化Pygame

pygame.init()

游戏窗口的宽度和高度

WIDTH, HEIGHT = 400, 400

定义颜色

BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)

设置游戏窗口

screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("贪吃蛇游戏")

定义贪吃蛇的初始位置

snake_pos = [100, 50]
snake_body = [[100, 50], [90, 50], [80, 50]]

定义食物的初始位置

food_pos = [random.randrange(1, (WIDTH//10)) * 10, random.randrange(1, (HEIGHT//10)) * 10]
food_spawn = True

定义初始方向

direction = 'RIGHT'
change_to = direction

定义游戏速度(帧数)

FPS = 15

定义得分

score = 0

游戏主循环

while True:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
change_to = 'UP'
if event.key == pygame.K_DOWN:
change_to = 'DOWN'
if event.key == pygame.K_LEFT:
change_to = 'LEFT'
if event.key == pygame.K_RIGHT:
change_to = 'RIGHT'

# 防止贪吃蛇反向移动
if change_to == 'UP' and not direction == 'DOWN':
    direction = 'UP'
if change_to == 'DOWN' and not direction == 'UP':
    direction = 'DOWN'
if change_to == 'LEFT' and not direction == 'RIGHT':
    direction = 'LEFT'
if change_to == 'RIGHT' and not direction == 'LEFT':
    direction = 'RIGHT'

# 根据方向移动贪吃蛇头部
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 += 10
    food_spawn = False
else:
    snake_body.pop()

if not food_spawn:
    food_pos = [random.randrange(1, (WIDTH//10)) * 10, random.randrange(1, (HEIGHT//10)) * 10]

food_spawn = True
screen.fill(BLACK)

for pos in snake_body:
    pygame.draw.rect(screen, GREEN, pygame.Rect(pos[0], pos[1], 10, 10))

pygame.draw.rect(screen, WHITE, pygame.Rect(food_pos[0], food_pos[1], 10, 10))

if (snake_pos[0] < 0 or snake_pos[0] > WIDTH-10 or
    snake_pos[1] < 0 or snake_pos[1] > HEIGHT-10):
    pygame.quit()
    sys.exit()

for block in snake_body[1:]:
    if snake_pos[0] == block[0] and snake_pos[1] == block[1]:
        pygame.quit()
        sys.exit()

pygame.display.flip()
pygame.display.update()
pygame.time.Clock().tick(FPS)