用Python做出可以计数的贪吃蛇小游戏
时间: 2023-11-05 19:13:22 浏览: 66
好的,以下是一个简单的Python计数贪吃蛇小游戏的代码实现:
```python
import pygame
import random
# 初始化Pygame
pygame.init()
# 设置游戏界面大小、背景颜色
width, height = 640, 480
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("贪吃蛇")
# 定义颜色
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
# 定义字体
font = pygame.font.SysFont(None, 25)
# 定义蛇和食物的大小
block_size = 20
# 定义蛇的初始位置和长度
snake_pos = [100, 50]
snake_body = [[100, 50], [90, 50], [80, 50]]
# 定义食物的初始位置
food_pos = [random.randrange(1, (width // block_size)) * block_size,
random.randrange(1, (height // block_size)) * block_size]
# 定义初始分数
score = 0
# 定义方向
direction = "RIGHT"
change_to = direction
# 定义游戏结束函数
def game_over():
# 显示游戏结束信息
msg = font.render("游戏结束! 按 Q 退出或按 C 重新开始", True, RED)
screen.blit(msg, [width / 6, height / 3])
# 刷新游戏界面
pygame.display.update()
# 等待用户响应
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
pygame.quit()
quit()
elif event.key == pygame.K_c:
game_loop()
# 定义游戏主循环函数
def game_loop():
# 声明全局变量
global direction, change_to, score, snake_pos, snake_body, food_pos
# 判断是否撞墙或撞到自己
if snake_pos[0] < 0 or snake_pos[0] > width - block_size or snake_pos[1] < 0 or snake_pos[1] > height - block_size:
game_over()
for block in snake_body[1:]:
if snake_pos[0] == block[0] and snake_pos[1] == block[1]:
game_over()
# 判断是否吃到食物
if snake_pos[0] == food_pos[0] and snake_pos[1] == food_pos[1]:
food_pos = [random.randrange(1, (width // block_size)) * block_size,
random.randrange(1, (height // block_size)) * block_size]
score += 1
else:
snake_body.pop()
# 更新蛇的位置
snake_body.insert(0, list(snake_pos))
if change_to == "UP":
snake_pos[1] -= block_size
elif change_to == "DOWN":
snake_pos[1] += block_size
elif change_to == "LEFT":
snake_pos[0] -= block_size
elif change_to == "RIGHT":
snake_pos[0] += block_size
# 更新方向
direction = change_to
# 设置背景颜色
screen.fill(BLACK)
# 画蛇和食物
for pos in snake_body:
pygame.draw.rect(screen, WHITE, pygame.Rect(
pos[0], pos[1], block_size, block_size))
pygame.draw.rect(screen, RED, pygame.Rect(
food_pos[0], food_pos[1], block_size, block_size))
# 显示分数
score_text = font.render(f"Score: {score}", True, WHITE)
screen.blit(score_text, [0, 0])
# 刷新游戏界面
pygame.display.update()
# 设置游戏帧率
fps_controller.tick(15)
# 创建游戏帧率控制对象
fps_controller = pygame.time.Clock()
# 运行游戏循环
while True:
# 监听用户事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP and direction != "DOWN":
change_to = "UP"
elif event.key == pygame.K_DOWN and direction != "UP":
change_to = "DOWN"
elif event.key == pygame.K_LEFT and direction != "RIGHT":
change_to = "LEFT"
elif event.key == pygame.K_RIGHT and direction != "LEFT":
change_to = "RIGHT"
# 调用游戏主循环函数
game_loop()
```
在这个游戏中,蛇会不断地向前移动,玩家需要控制蛇的方向,让它吃到食物并不断增长身体长度,直到撞墙或撞到自己游戏结束。游戏界面上方会显示当前得分。
阅读全文