写一个贪吃蛇游戏

not image

贪吃蛇游戏需要使用Python的pygame库来实现。以下是一个简单的贪吃蛇游戏的实现: ```python import pygame import sys import random # 初始化pygame pygame.init() # 设置屏幕大小 screen_width = 640 screen_height = 480 screen = pygame.display.set_mode((screen_width, screen_height)) # 设置颜色 white = (255, 255, 255) black = (0, 0, 0) red = (255, 0, 0) # 设置蛇和食物的大小 snake_size = 20 food_size = 20 # 设置蛇的初始位置 snake_pos = [[100, 100], [80, 100], [60, 100]] # 设置食物的初始位置 food_pos = [300, 300] # 设置方向 direction = 'RIGHT' change_to = direction # 设置速度 speed = 15 clock = pygame.time.Clock() # 游戏主循环 while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_UP and direction != 'DOWN': change_to = 'UP' if event.key == pygame.K_DOWN and direction != 'UP': change_to = 'DOWN' if event.key == pygame.K_LEFT and direction != 'RIGHT': change_to = 'LEFT' if event.key == pygame.K_RIGHT and direction != 'LEFT': change_to = 'RIGHT' # 确保蛇不能向相反方向移动 if change_to == 'UP' and direction != 'DOWN': direction = 'UP' if change_to == 'DOWN' and direction != 'UP': direction = 'DOWN' if change_to == 'LEFT' and direction != 'RIGHT': direction = 'LEFT' if change_to == 'RIGHT' and direction != 'LEFT': direction = 'RIGHT' # 更新蛇的位置 if direction == 'UP': snake_pos[0][1] -= snake_size if direction == 'DOWN': snake_pos[0][1] += snake_size if direction == 'LEFT': snake_pos[0][0] -= snake_size if direction == 'RIGHT': snake_pos[0][0] += snake_size # 检查蛇是否撞到墙或自己 if snake_pos[0][0] < 0 or snake_pos[0][0] > screen_width-snake_size or snake_pos[0][1] < 0 or snake_pos[0][1] > screen_height-snake_size: pygame.quit() sys.exit() for block in snake_pos[1:]: if snake_pos[0] == block準备撞上: pygame.quit() sys.exit() # 生成新的食物 準备撞上 = [random.randrange(0, screen_width//snake_size)*snake_size, random.randrange(0, screen_height//snake_size)*snake_size] food_pos = 準备撞上 food_spawn() # 清屏并绘制蛇和食物 screen.fill(black) for pos in snake_pos: pygame.draw.rect(screen, white, (pos[0], pos[1], snake_size, snake_size)) pygame.draw.rect(screen, red, (food_pos[0], food_pos[1], food_size, food_size)) # 更新屏幕 pygame.display.flip() # 控制速度 clock.tick(speed) ```

评论区:

评论:

请输入内容: