用python制作一个贪吃蛇小游戏
时间: 2023-05-20 15:06:05 浏览: 242
好的,以下是一个简单的贪吃蛇小游戏的 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('贪吃蛇')
# 设置游戏时钟
clock = pygame.time.Clock()
# 蛇的初始位置和长度
snake_x = 100
snake_y = 100
snake_length = 1
snake_body = [(snake_x, snake_y)]
# 食物的初始位置
food_x = random.randint(0, WINDOW_WIDTH - 10)
food_y = random.randint(0, WINDOW_HEIGHT - 10)
# 游戏循环
while True:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
# 处理键盘输入
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
snake_x -= 10
elif keys[pygame.K_RIGHT]:
snake_x += 10
elif keys[pygame.K_UP]:
snake_y -= 10
elif keys[pygame.K_DOWN]:
snake_y += 10
# 判断是否吃到食物
if snake_x == food_x and snake_y == food_y:
snake_length += 1
food_x = random.randint(0, WINDOW_WIDTH - 10)
food_y = random.randint(0, WINDOW_HEIGHT - 10)
# 更新蛇的身体
snake_body.insert(0, (snake_x, snake_y))
if len(snake_body) > snake_length:
snake_body.pop()
# 绘制游戏界面
window.fill(BLACK)
pygame.draw.rect(window, GREEN, (food_x, food_y, 10, 10))
for x, y in snake_body:
pygame.draw.rect(window, WHITE, (x, y, 10, 10))
pygame.display.update()
# 控制游戏帧率
clock.tick(30)
```
希望这个代码能够帮到你!
阅读全文