qcode
  • 创作工场专业版,一问多答!更智能、更完整、更原创
  • 这是一个超强内容创作平台,它会写文章、做设计、绘图、敲代码,有问必答!
🔥点击使用-免登录深度版🔥

贪吃蛇游戏代码

时间2023-09-10 18:09:50 提问来自 重庆市重庆市 的网友 分类创作 浏览293
贪吃蛇游戏代码如下: ```python import pygame import sys import random pygame.init() # 设置屏幕大小 screen_width = 800 screen_height = 600 screen = pygame.display.set_mode((screen_width, screen_height)) # 设置颜色 white = (255, 255, 255) black = (0, 0, 0) red = (255, 0, 0) green = (0, 255, 0) # 设置蛇的初始位置 snake_pos = [100, 50] snake_body = [[100, 50], [90, 50], [80, 50]] # 设置食物的初始位置 food_pos = [random.randrange(1, screen_width // 10) * 10, random.randrange(1, screen_height // 10) * 10] food_spawn = True # 设置方向 direction = "RIGHT" change_to = direction # 设置速度 speed = 15 clock = pygame.time.Clock() # 设置字体 font = pygame.font.SysFont("arial", 25) def game_over(): msg = font.render("Game Over!", True, red) screen.blit(msg, [screen_width // 2 - 50, screen_height // 2 - 25]) pygame.display.flip() pygame.time.wait(2000) pygame.quit() sys.exit() 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 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[1] -= speed if direction == "DOWN": snake_pos[1] += speed if direction == "LEFT": snake_pos[0] -= speed if direction == "RIGHT": snake_pos[0] += speed snake_body.insert(0, list(snake_pos)) if snake_pos == food_pos: food_spawn = False else: snake_body.pop() if not food_spawn: food_pos = [random.randrange(1, screen_width // 10) * 10, random.randrange(1, screen_height // 10) * 10] food_spawn = True snake_body.append(list(snake_pos)) 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] >= screen_width or snake_pos[0] < 0 or snake_pos[1] >= screen_height or snake_pos[1] < 0: game_over() ```

不满意?免费深度重写!

免责声明:
以上内容除特别注明外均来源于网友提问,创作工场回答,未经许可,严谨转载。

上一篇 基于游戏开发的毕业设计 下一篇 电极丝有哪些方面的性能需要检测