内容目录
由ChatGPT生成的一个贪吃蛇游戏
使用了pygame库
代码
import pygame
import random
# 初始化游戏
pygame.init()
# 游戏窗口大小
window_width = 800
window_height = 600
# 定义颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
# 创建游戏窗口
game_display = pygame.display.set_mode((window_width, window_height))
pygame.display.set_caption('贪食蛇')
# 设置游戏时钟
clock = pygame.time.Clock()
# 定义蛇的大小
snake_block_size = 10
# 设置字体
font_style = pygame.font.SysFont(None, 50)
# 定义函数,用于显示消息
def message(msg, color):
message_text = font_style.render(msg, True, color)
game_display.blit(message_text, [window_width/6, window_height/3])
# 定义函数,用于绘制蛇
def draw_snake(snake_block_size, snake_list):
for x in snake_list:
pygame.draw.rect(game_display, black, [x[0], x[1], snake_block_size, snake_block_size])
# 定义游戏循环
def game_loop():
snake_x_change=0
snake_y_change=0
game_over = False
game_close = False
# 初始化蛇的位置和长度
snake_x = window_width / 2
snake_y = window_height / 2
snake_list = []
snake_length = 1
# 初始化食物的位置
food_x = round(random.randrange(0, window_width - snake_block_size) / 10.0) * 10.0
food_y = round(random.randrange(0, window_height - snake_block_size) / 10.0) * 10.0
# 游戏循环
while not game_over:
# 游戏结束后显示消息
while game_close == True:
game_display.fill(white)
message("你输了!按Q退出,按C重新开始", red)
pygame.display.update()
# 处理按键事件
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
game_over = True
game_close = False
if event.key == pygame.K_c:
game_loop()
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
snake_x_change = -snake_block_size
snake_y_change = 0
elif event.key == pygame.K_RIGHT:
snake_x_change = snake_block_size
snake_y_change = 0
elif event.key == pygame.K_UP:
snake_y_change = -snake_block_size
snake_x_change = 0
elif event.key == pygame.K_DOWN:
snake_y_change = snake_block_size
snake_x_change = 0
# 判断蛇是否撞墙
if snake_x >= window_width or snake_x < 0 or snake_y >= window_height or snake_y < 0:
game_close = True
# 更新蛇的位置
snake_x += snake_x_change
snake_y += snake_y_change
# 绘制游戏窗口
game_display.fill(white)
pygame.draw.rect(game_display, red, [food_x, food_y, snake_block_size, snake_block_size])
snake_head = []
snake_head.append(snake_x)
snake_head.append(snake_y)
snake_list.append(snake_head)
if len(snake_list) > snake_length:
del snake_list[0]
# 判断蛇是否吃到食物
for x in snake_list[:-1]:
if x == snake_head:
game_close = True
draw_snake(snake_block_size, snake_list)
pygame.display.update()
# 判断蛇是否吃到食物
if snake_x == food_x and snake_y == food_y:
food_x = round(random.randrange(0, window_width - snake_block_size) / 10.0) * 10.0
food_y = round(random.randrange(0, window_height - snake_block_size) / 10.0) * 10.0
snake_length += 1
# 设置游戏帧率
clock.tick(20)
# 退出游戏
pygame.quit()
quit()
# 启动游戏循环
game_loop()
运行效果