python写贪吃蛇的游戏,并且能可视化
时间: 2023-06-11 10:09:03 浏览: 156
好的,我来帮你写一个基于Python的贪吃蛇游戏,使用Pygame库来可视化。以下是代码:
```python
import pygame
import random
# 初始化Pygame
pygame.init()
# 游戏窗口的大小
window_size = (800, 600)
# 设置游戏窗口
screen = pygame.display.set_mode(window_size)
pygame.display.set_caption("贪吃蛇游戏")
# 定义颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)
# 定义常量
block_size = 20
font_size = 30
# 定义字体
font = pygame.font.SysFont(None, font_size)
# 显示文本的函数
def message_to_screen(msg, color, x_pos, y_pos):
screen_text = font.render(msg, True, color)
screen.blit(screen_text, [x_pos, y_pos])
# 游戏循环
def gameLoop():
game_over = False
game_close = False
# 蛇的初始位置
x1 = window_size[0] / 2
y1 = window_size[1] / 2
# 蛇的移动速度
x1_change = 0
y1_change = 0
# 食物的初始位置
foodx = round(random.randrange(0, window_size[0] - block_size) / 20.0) * 20.0
foody = round(random.randrange(0, window_size[1] - block_size) / 20.0) * 20.0
# 游戏循环
while not game_over:
# 游戏结束或游戏重新开始
while game_close == True:
screen.fill(white)
message_to_screen("游戏结束,按Q退出或按C重新开始", red, window_size[0] / 2 - 200, window_size[1] / 2)
pygame.display.update()
# 检测用户按键
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
game_over = True
game_close = False
if event.key == pygame.K_c:
gameLoop()
# 检测用户按键
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x1_change = -block_size
y1_change = 0
elif event.key == pygame.K_RIGHT:
x1_change = block_size
y1_change = 0
elif event.key == pygame.K_UP:
y1_change = -block_size
x1_change = 0
elif event.key == pygame.K_DOWN:
y1_change = block_size
x1_change = 0
# 让蛇移动
x1 += x1_change
y1 += y1_change
# 绘制蛇和食物
screen.fill(white)
pygame.draw.rect(screen, green, [foodx, foody, block_size, block_size])
pygame.draw.rect(screen, black, [x1, y1, block_size, block_size])
pygame.display.update()
# 判断蛇是否吃到了食物
if x1 == foodx and y1 == foody:
print("Yummy!!")
elif x1 >= window_size[0] or x1 < 0 or y1 >= window_size[1] or y1 < 0:
game_close = True
# 控制游戏刷新速度
clock = pygame.time.Clock()
clock.tick(15)
# 退出Pygame
pygame.quit()
# 退出Python
quit()
# 运行游戏
gameLoop()
```
运行代码后,你将看到一个窗口,蛇在屏幕中央,食物在屏幕的某个位置。你可以用方向键控制蛇的移动,吃到食物后,会在控制台打印出"Yummy!!"。游戏会在蛇撞到边界时结束,如果想重新开始,按'C'键即可。