用python 写一个 贪吃蛇小游戏
时间: 2023-03-23 21:03:04 浏览: 265
好的,我可以帮你用 Python 写一个简单的贪吃蛇小游戏。以下是代码:
```python
import pygame
import random
# 初始化 Pygame
pygame.init()
# 定义窗口大小和背景颜色
WINDOW_WIDTH = 500
WINDOW_HEIGHT = 500
BACKGROUND_COLOR = (255, 255, 255)
# 创建游戏窗口
game_window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption('贪吃蛇小游戏')
# 定义贪吃蛇和食物的颜色和大小
SNAKE_COLOR = (0, 255, 0)
FOOD_COLOR = (255, 0, 0)
BLOCK_SIZE = 20
# 定义游戏帧率和时钟
FPS = 10
clock = pygame.time.Clock()
# 定义游戏结束函数
def game_over():
font = pygame.font.SysFont(None, 50)
text = font.render('游戏结束!', True, (255, 0, 0))
game_window.blit(text, (WINDOW_WIDTH/2 - text.get_width()/2, WINDOW_HEIGHT/2 - text.get_height()/2))
pygame.display.update()
pygame.time.delay(3000)
pygame.quit()
quit()
# 定义绘制贪吃蛇和食物的函数
def draw_snake(snake_block, snake_list):
for block in snake_list:
pygame.draw.rect(game_window, SNAKE_COLOR, [block[0], block[1], snake_block, snake_block])
def draw_food():
pygame.draw.rect(game_window, FOOD_COLOR, [food_x, food_y, BLOCK_SIZE, BLOCK_SIZE])
# 定义主函数
def main():
# 定义贪吃蛇初始位置和长度
snake_x = WINDOW_WIDTH / 2
snake_y = WINDOW_HEIGHT / 2
snake_list = []
snake_length = 1
# 定义贪吃蛇移动方向和速度
velocity_x = 0
velocity_y = 0
snake_speed = 20
# 定义食物初始位置
global food_x, food_y
food_x = round(random.randrange(0, WINDOW_WIDTH - BLOCK_SIZE) / 20.0) * 20.0
food_y = round(random.randrange(0, WINDOW_HEIGHT - BLOCK_SIZE) / 20.0) * 20.0
# 游戏循环
game_over_flag = False
while not game_over_flag:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over_flag = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
velocity_x = -snake_speed
velocity_y = 0
elif event.key == pygame.K_RIGHT:
velocity_x = snake_speed
velocity_y = 0
elif event.key == pygame.K_UP:
velocity_y = -snake_speed
velocity_x = 0
elif event.key == pygame.K_DOWN:
velocity_y = snake_speed
velocity_x = 0
# 移动贪吃蛇
snake_x += velocity_x
snake_y += velocity_y
# 判断是否
阅读全文