写一个Python贪吃蛇
时间: 2024-04-10 17:26:20 浏览: 74
写一个Python贪吃蛇游戏可以通过使用Pygame库来实现。下面是一个简单的示例代码:
```python
import pygame
import random
# 初始化游戏
pygame.init()
# 定义游戏窗口的大小
window_width = 800
window_height = 600
# 定义贪吃蛇的大小和速度
snake_size = 20
snake_speed = 10
# 定义颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
# 创建游戏窗口
window = pygame.display.set_mode((window_width, window_height))
pygame.display.set_caption('贪吃蛇')
# 定义贪吃蛇的初始位置和移动方向
snake_x = window_width / 2
snake_y = window_height / 2
snake_dx = 0
snake_dy = 0
# 定义食物的初始位置
food_x = round(random.randrange(0, window_width - snake_size) / snake_size) * snake_size
food_y = round(random.randrange(0, window_height - snake_size) / snake_size) * snake_size
# 定义贪吃蛇的身体
snake_body = []
snake_length = 1
# 游戏主循环
running = True
while running:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# 处理键盘事件,控制贪吃蛇的移动方向
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
snake_dx = -snake_size
snake_dy = 0
elif event.key == pygame.K_RIGHT:
snake_dx = snake_size
snake_dy = 0
elif event.key == pygame.K_UP:
snake_dy = -snake_size
snake_dx = 0
elif event.key == pygame.K_DOWN:
snake_dy = snake_size
snake_dx = 0
# 更新贪吃蛇的位置
snake_x += snake_dx
snake_y += snake_dy
# 判断贪吃蛇是否吃到食物
if snake_x == food_x and snake_y == food_y:
food_x = round(random.randrange(0, window_width - snake_size) / snake_size) * snake_size
food_y = round(random.randrange(0, window_height - snake_size) / snake_size) * snake_size
snake_length += 1
# 绘制游戏窗口
window.fill(black)
pygame.draw.rect(window, red, [food_x, food_y, snake_size, snake_size])
snake_head = []
snake_head.append(snake_x)
snake_head.append(snake_y)
snake_body.append(snake_head)
if len(snake_body) > snake_length:
del snake_body
for segment in snake_body[:-1]:
if segment == snake_head:
running = False
for segment in snake_body:
pygame.draw.rect(window, white, [segment, segment, snake_size, snake_size])
pygame.display.update()
# 控制游戏速度
pygame.time.Clock().tick(snake_speed)
# 退出游戏
pygame.quit()
```
阅读全文