用python代码实现贪吃蛇游戏
时间: 2023-05-18 08:07:02 浏览: 125
可以使用Python的Pygame库来实现贪吃蛇游戏。以下是一个简单的示例代码:
```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
# 定义游戏循环标志
running = True
# 游戏循环
while running:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# 获取键盘输入
keys = pygame.key.get_pressed()
# 移动蛇
if keys[pygame.K_LEFT]:
snake_x -= snake_speed
elif keys[pygame.K_RIGHT]:
snake_x += snake_speed
elif keys[pygame.K_UP]:
snake_y -= snake_speed
elif 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()
```
这段代码使用Pygame库创建了一个游戏窗口,并实现了贪吃蛇的基本功能,包括蛇的移动和食物的生成。你可以根据自己的需求对代码进行修改和扩展。
阅读全文