帮我用python写一个贪吃蛇游戏
时间: 2024-05-09 19:20:34 浏览: 181
Python编写一个贪吃蛇游戏
贪吃蛇是一个经典的游戏,在Python中也可以编写。下面是一个简单的代码实现:
```
import pygame
import sys
import random
# 初始化Pygame
pygame.init()
# 设置窗口大小
win_width = 720
win_height = 720
# 创建窗口
screen = pygame.display.set_mode((win_width, win_height))
# 设置窗口标题
pygame.display.set_caption("贪吃蛇游戏")
# 设置蛇的初始位置和大小
x = 50
y = 50
block_size = 10
# 设置蛇的初始方向
x_change = 0
y_change = 0
# 定义食物的位置
foodx = round(random.randrange(0, win_width - block_size) / 10.0) * 10.0
foody = round(random.randrange(0, win_height - block_size) / 10.0) * 10.0
# 开始游戏的主循环
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
# 如果是键盘事件
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x_change = -block_size
y_change = 0
elif event.key == pygame.K_RIGHT:
x_change = block_size
y_change = 0
elif event.key == pygame.K_UP:
y_change = -block_size
x_change = 0
elif event.key == pygame.K_DOWN:
y_change = block_size
x_change = 0
# 更新蛇的位置
x += x_change
y += y_change
# 绘制蛇和食物
screen.fill((255, 255, 255))
pygame.draw.rect(screen, (0, 128, 0), [foodx, foody, block_size, block_size])
pygame.draw.rect(screen, (255, 0, 0), [x, y, block_size, block_size])
# 刷新窗口
pygame.display.update()
```
这是一个简单的贪吃蛇代码的实现
阅读全文