import pygame
import time
import random
import sys
# 初始化Pygame
pygame.init()
# 游戏窗口的尺寸
WIDTH, HEIGHT = 800, 600
# 设置窗口
win = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("贪吃蛇游戏")
# 颜色定义
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
# 初始化贪吃蛇位置
snake_x, snake_y = WIDTH // 2, HEIGHT // 2
snake_speed = 13 # 贪吃蛇的速度控制
# 贪吃蛇初始长度和速度
snake_length = 1
snake_direction = "RIGHT"
# 初始化食物位置
food_x, food_y = random.randrange(1, (WIDTH // 10)) * 10, random.randrange(1, (HEIGHT // 10)) * 10
# 分数
score = 0
# 用于控制游戏循环的变量
game_over = False
# 时钟对象,用于控制游戏速度
clock = pygame.time.Clock()
# 定义贪吃蛇身体坐标列表
snake_body = []
snake_body.append([snake_x, snake_y])
def show_game_over_message():
font = pygame.font.Font(None, 36)
game_over_text = font.render("游戏结束,分数:" + str(score), True, WHITE)
game_over_rect = game_over_text.get_rect(center=(WIDTH // 2, HEIGHT // 2))
win.blit(game_over_text, game_over_rect)
pygame.display.flip()
pygame.time.wait(2000) # 显示游戏结束消息2秒钟
restart_game()
def restart_game():
global snake_x, snake_y, snake_length, snake_direction, food_x, food_y, score, game_over
snake_x, snake_y = WIDTH // 2, HEIGHT // 2
snake_length = 1
snake_direction = "RIGHT"
food_x, food_y = random.randrange(1, (WIDTH // 10)) * 10, random.randrange(1, (HEIGHT // 10)) * 10
score = 0
game_over = False
snake_body.clear()
snake_body.append([snake_x, snake_y])
# 游戏主循环
while not game_over:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP and snake_direction != "DOWN":
snake_direction = "UP"
if event.key == pygame.K_DOWN and snake_direction != "UP":
snake_direction = "DOWN"
if event.key == pygame.K_LEFT and snake_direction != "RIGHT":
snake_direction = "LEFT"
if event.key == pygame.K_RIGHT and snake_direction != "LEFT":
snake_direction = "RIGHT"
# 移动贪吃蛇头部
if snake_direction == "UP":
snake_y -= 10
if snake_direction == "DOWN":
snake_y += 10
if snake_direction == "LEFT":
snake_x -= 10
if snake_direction == "RIGHT":
snake_x += 10
# 检查是否撞墙
if snake_x < 0 or snake_x >= WIDTH or snake_y < 0 or snake_y >= HEIGHT:
show_game_over_message()
# 增加蛇的长度
snake_head = [snake_x, snake_y]
snake_body.append(snake_head)
if len(snake_body) > snake_length:
del snake_body[0]
# 检查是否吃到食物
if snake_x == food_x and snake_y == food_y:
food_x, food_y = random.randrange(1, (WIDTH // 10)) * 10, random.randrange(1, (HEIGHT // 10)) * 10
snake_length += 1
score += 1
# 绘制窗口
win.fill(BLACK)
for segment in snake_body:
pygame.draw.rect(win, GREEN, [segment[0], segment[1], 10, 10])
pygame.draw.rect(win, WHITE, [food_x, food_y, 10, 10])
# 更新窗口
pygame.display.update()
# 控制游戏速度
clock.tick(snake_speed)
# 游戏结束,退出Pygame
pygame.quit()
sys.exit()
利用python做一个简单的贪吃蛇小游戏
最新推荐文章于 2024-07-18 15:53:23 发布