请用python语言编写一个贪吃蛇游戏小程序
时间: 2023-11-16 09:02:58 浏览: 103
小游戏-使用Python开发的贪吃蛇小游戏-GluttonousSnake.zip
抱歉,作为AI语言模型,我无法提供完整的视觉化游戏程序。以下是一段基于Python的简单贪吃蛇游戏的示例代码:
```
import pygame
import random
pygame.init()
# 设置游戏界面大小、背景颜色和标题
width, height = 600, 400
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("贪吃蛇")
bg_color = (255, 255, 255)
# 设置蛇的属性
snake_init_pos = [[100, 100], [80, 100], [60, 100]]
snake_color = (0, 255, 0)
snake_direction = "right"
# 设置食物的属性
food_position = [400, 300]
food_color = (255, 0, 0)
# 设置字体
score_font = pygame.font.SysFont(None, 40)
# 设置计分板初始值
score = 0
# 显示分数
def show_score():
score_text = score_font.render("Score: " + str(score), True, (0, 0, 0))
screen.blit(score_text, (0, 0))
# 游戏结束
def game_over():
end_font = pygame.font.SysFont(None, 70)
end_text = end_font.render("Game Over", True, (0, 0, 0))
screen.blit(end_text, (150, 150))
pygame.display.update()
pygame.time.wait(2000)
pygame.quit()
sys.exit()
# 主函数
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# 键盘事件,控制蛇的方向
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
snake_direction = "right"
elif event.key == pygame.K_LEFT:
snake_direction = "left"
elif event.key == pygame.K_UP:
snake_direction = "up"
elif event.key == pygame.K_DOWN:
snake_direction = "down"
# 移动蛇
if snake_direction == "right":
snake_init_pos[0][0] += 20
elif snake_direction == "left":
snake_init_pos[0][0] -= 20
elif snake_direction == "up":
snake_init_pos[0][1] -= 20
elif snake_direction == "down":
snake_init_pos[0][1] += 20
# 判断是否吃到食物
if snake_init_pos[0] == food_position:
food_position = [random.randrange(1, width/20)*20,
random.randrange(1, height/20)*20]
score += 10
else:
snake_init_pos.pop()
# 判断游戏是否结束
if snake_init_pos[0][0] < 0 or snake_init_pos[0][0] > width-20 \
or snake_init_pos[0][1] < 0 or snake_init_pos[0][1] > height-20 \
or snake_init_pos[0] in snake_init_pos[1:]:
game_over()
screen.fill(bg_color)
# 画蛇和食物
for pos in snake_init_pos:
pygame.draw.rect(screen, snake_color, pygame.Rect(
pos[0], pos[1], 20, 20))
pygame.draw.rect(screen, food_color, pygame.Rect(
food_position[0], food_position[1], 20, 20))
# 显示分数
show_score()
pygame.display.update()
# 设置帧率
pygame.time.Clock().tick(5)
```
该程序使用pygame模块来实现游戏界面的绘制和事件的响应。在游戏中,玩家通过键盘来控制蛇的运动方向,当蛇吃到食物时,分数加10,同时随机生成新的食物位置。当蛇碰到边界或者自己的身体时,游戏结束。程序中使用了计分板来实时显示分数。
阅读全文