import random
import pygame
# 初始化Pygame
pygame.init()
# 设置游戏窗口大小和标题
window_width = 800
window_height = 600
window = pygame.display.set_mode((window_width, window_height))
pygame.display.set_caption("贪吃蛇")
# 定义颜色
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)
# 设置蛇头初始位置和速度
snake_position = [100, 50]
snake_body = [[100, 50], [90, 50], [80, 50]]
food_position = [random.randrange(1, (window_width // 10)) * 10, random.randrange(1, (window_height // 10)) * 10]
food_spawn = True
direction = 'RIGHT'
changeto = ''
# 设置时钟对象
clock = pygame.time.Clock()
# 定义游戏结束的函数
def game_over():
font = pygame.font.SysFont('consolas', 72)
text = font.render('Game Over', True, red)
text_rect = text.get_rect()
text_rect.midtop = (window_width / 2, window_height / 4)
window.fill(black)
window.blit(text, text_rect)
pygame.display.flip()
pygame.time.wait(5000)
pygame.quit()
# 游戏主循环
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT or event.key == ord('d'):
changeto = 'RIGHT'
if event.key == pygame.K_LEFT or event.key == ord('a'):
changeto = 'LEFT'
if event.key == pygame.K_UP or event.key == ord('w'):
changeto = 'UP'
if event.key == pygame.K_DOWN or event.key == ord('s'):
changeto = 'DOWN'
# 确定蛇移动的方向
if changeto == 'RIGHT' and direction != 'LEFT':
direction = 'RIGHT'
if changeto == 'LEFT' and direction != 'RIGHT':
direction = 'LEFT'
if changeto == 'UP' and direction != 'DOWN':
direction = 'UP'
if changeto == 'DOWN' and direction != 'UP':
direction = 'DOWN'
# 根据方向移动蛇头
if direction == 'RIGHT':
snake_position[0] += 10
if direction == 'LEFT':
snake_position[0] -= 10
if direction == 'UP':
snake_position[1] -= 10
if direction == 'DOWN':
snake_position[1] += 10
# 增加蛇身体长度
snake_body.insert(0, list(snake_position))
if snake_position[0] == food_position[0] and snake_position[1] == food_position[1]:
food_spawn = False
else:
snake_body.pop()
# 生成新的食物位置
if not food_spawn:
food_position = [random.randrange(1, (window_width // 10)) * 10,
random.randrange(1, (window_height // 10)) * 10]
food_spawn = True
# 绘制游戏窗口
window.fill(black)
for pos in snake_body:
pygame.draw.rect(window, green, pygame.Rect(pos[0], pos[1], 10, 10))
pygame.draw.rect(window, white, pygame.Rect(food_position[0], food_position[1], 10, 10))
# 判断游戏结束条件
if snake_position[0] < 0 or snake_position[0] > window_width - 10:
game_over()
if snake_position[1] < 0 or snake_position[1] > window_height - 10:
game_over()
for block in snake_body[1:]:
if snake_position[0] == block[0] and snake_position[1] == block[1]:
game_over()
# 更新游戏显示
pygame.display.update()
# 设置刷新率为15帧
clock.tick(15)
别卷了,玩会游戏吧-----贪吃蛇游戏(附Python代码)
最新推荐文章于 2024-04-28 22:18:52 发布