帮我写一个python的简单贪吃蛇小游戏
时间: 2023-04-04 08:02:37 浏览: 93
100行python代码完成的贪吃蛇游戏,简单方便快捷,下载即可运行,可做毕业设计
好的,我可以回答这个问题。以下是一个简单的 Python 贪吃蛇小游戏的代码示例:
```python
import pygame
import random
# 初始化 Pygame
pygame.init()
# 游戏窗口大小
WINDOW_WIDTH = 640
WINDOW_HEIGHT = 480
# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
# 创建游戏窗口
window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption('贪吃蛇')
# 定义贪吃蛇的初始位置和大小
snake_x = 100
snake_y = 100
snake_width = 20
snake_height = 20
# 定义贪吃蛇的移动速度
snake_speed = 5
# 定义食物的初始位置和大小
food_x = random.randint(0, WINDOW_WIDTH - snake_width)
food_y = random.randint(0, WINDOW_HEIGHT - snake_height)
food_width = 20
food_height = 20
# 定义游戏循环标志
game_running = True
# 游戏循环
while game_running:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_running = False
# 获取键盘输入
keys = pygame.key.get_pressed()
# 移动贪吃蛇
if keys[pygame.K_LEFT]:
snake_x -= snake_speed
if keys[pygame.K_RIGHT]:
snake_x += snake_speed
if keys[pygame.K_UP]:
snake_y -= snake_speed
if keys[pygame.K_DOWN]:
snake_y += snake_speed
# 检测贪吃蛇是否吃到了食物
if snake_x < food_x + food_width and snake_x + snake_width > food_x and snake_y < food_y + food_height and snake_y + snake_height > food_y:
food_x = random.randint(0, WINDOW_WIDTH - snake_width)
food_y = random.randint(0, WINDOW_HEIGHT - snake_height)
# 绘制游戏界面
window.fill(BLACK)
pygame.draw.rect(window, GREEN, (snake_x, snake_y, snake_width, snake_height))
pygame.draw.rect(window, RED, (food_x, food_y, food_width, food_height))
pygame.display.update()
# 退出 Pygame
pygame.quit()
```
希望这个代码示例能够帮助你完成贪吃蛇小游戏。
阅读全文