请你用python语句写一个贪吃蛇的小游戏
时间: 2023-03-13 19:22:15 浏览: 102
答案:可以这样写:import pygame
import random
# 定义颜色
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
# 设置游戏界面宽度、高度以及每个小方块的像素大小
WIDTH = 800
HEIGHT = 600
BLOCK_SIZE = 20
# 初始化pygame、设置标题以及游戏界面大小
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption('贪吃蛇小游戏')
# 定义蛇的初始位置
snake_x = WIDTH / 2
snake_y = HEIGHT / 2
snake_list = []
snake_length = 1
# 定义食物的初始位置
food_x = round(random.randrange(0, WIDTH - BLOCK_SIZE) / BLOCK_SIZE) * BLOCK_SIZE
food_y = round(random.randrange(0, HEIGHT - BLOCK_SIZE) / BLOCK_SIZE) * BLOCK_SIZE
# 定义游戏结束函数
def game_over():
font = pygame.font.SysFont('Arial', 25)
game_over_text = font.render('游戏结束!', True, (0, 0, 0))
screen.blit(game_over_text, (WIDTH/2 - 100, HEIGHT/2))
pygame.display.update()
time.sleep(2)
# 主循环
running = True
while running:
# 设置背景颜色
screen.fill(GREEN)
# 事件监听
for event in pygame.event.get():
# 监听到退出事件时,退出游戏
if event.type == pygame.QUIT:
running = False
# 增加蛇的长度
head = []
head.append(snake_x)
head.append(snake_y)
snake_list.append(head)
if len(snake_list) > snake_length:
del snake_list[0]
# 绘制蛇
for position in snake_list:
pygame.draw.rect(screen, BLACK, [position[0], position[1], BLOCK_SIZE, BLOCK_SIZE])
# 绘制食物
pygame.draw.rect(screen, RED, [food_x, food_y, BLOCK_SIZE, BLOCK_SIZE])
# 更新页面
pygame.display.update()
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![application/x-zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)