一共有200行代码的python贪吃蛇游戏
时间: 2024-01-08 15:03:55 浏览: 28
以下是一个简单的200行代码的Python贪吃蛇游戏示例:
```python
import pygame
import random
# 初始化pygame
pygame.init()
# 定义颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)
# 设置窗口大小
width = 600
height = 400
# 创建窗口
screen = pygame.display.set_mode((width, height))
# 设置游戏标题
pygame.display.set_caption("Snake Game")
# 设置时钟
clock = pygame.time.Clock()
# 定义字体
font = pygame.font.SysFont(None, 25)
# 定义块大小
block_size = 10
# 定义速度
speed = 15
# 定义函数:显示消息
def message(msg, color):
screen_text = font.render(msg, True, color)
screen.blit(screen_text, [width/6, height/3])
# 定义函数:游戏循环
def gameLoop():
game_over = False
game_close = False
# 初始位置
x1 = width / 2
y1 = height / 2
# 初始方向
x1_change = 0
y1_change = 0
# 食物位置
foodx = round(random.randrange(0, width - block_size) / 10.0) * 10.0
foody = round(random.randrange(0, height - block_size) / 10.0) * 10.0
while not game_over:
while game_close == True:
screen.fill(white)
message("You Lost! Press Q-Quit or C-Play Again", red)
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
# 碰到边界游戏结束
if x1 >= width or x1 < 0 or y1 >= height or y1 < 0:
game_close = True
# 更新蛇位置
x1 += x1_change
y1 += y1_change
# 填充背景
screen.fill(black)
# 绘制食物
pygame.draw.rect(screen, blue, [foodx, foody, block_size, block_size])
# 绘制蛇
pygame.draw.rect(screen, green, [x1, y1, block_size, block_size])
# 刷新屏幕
pygame.display.update()
# 吃到食物
if x1 == foodx and y1 == foody:
print("Yummy!!")
# 设置帧率
clock.tick(speed)
# 关闭pygame
pygame.quit()
# 退出python
quit()
# 开始游戏
gameLoop()
```
这个示例代码实现了基本的贪吃蛇游戏功能,包括蛇的移动、食物的生成、碰到边界的判定、吃到食物的判定等。当蛇撞到边界或者自己的身体时,游戏结束,可以选择重新开始或退出游戏。