贪吃蛇
背景介绍
贪吃蛇是一款经典的电子游戏,起源于20世纪70年代。游戏的目标是控制一条蛇在一个有边界的区域内移动,吃掉尽可能多的食物,同时避免撞到自己的身体或撞到边界。随着蛇吃掉更多的食物,它的身体会不断变长,增加了游戏的难度。
游戏规则
贪吃蛇的游戏规则非常简单。玩家通过操作键盘上的箭头键控制蛇的移动方向,蛇会不断地向前移动,直到玩家改变它的方向或蛇撞到了自己的身体或边界。
游戏中有食物随机出现在区域内的不同位置,蛇吃到食物后身体会增加一个单位的长度,并在区域内随机生成新的食物。玩家的分数会随着吃到的食物数量增加而增加,游戏结束条件为蛇撞到了自己的身体或撞到了边界。
代码示例
下面是一个使用Python编写的简单贪吃蛇代码示例:
import pygame
import sys
import random
# 初始化游戏
pygame.init()
# 设置游戏区域大小
width = 800
height = 600
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("贪吃蛇")
# 定义颜色
black = pygame.Color(0, 0, 0)
white = pygame.Color(255, 255, 255)
red = pygame.Color(255, 0, 0)
green = pygame.Color(0, 255, 0)
blue = pygame.Color(0, 0, 255)
# 设置帧率
fps = pygame.time.Clock()
# 定义蛇的初始位置和大小
snake_position = [100, 50]
snake_body = [[100, 50], [90, 50], [80, 50]]
# 定义食物的初始位置
food_position = [random.randrange(1, (width // 10)) * 10, random.randrange(1, (height // 10)) * 10]
food_spawn = True
# 定义初始移动方向
direction = "RIGHT"
change_to = direction
# 定义游戏结束函数
def game_over():
pygame.quit()
sys.exit()
# 游戏主循环
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT or event.key == ord("d"):
change_to = "RIGHT"
if event.key == pygame.K_LEFT or event.key == ord("a"):
change_to = "LEFT"
if event.key == pygame.K_UP or event.key == ord("w"):
change_to = "UP"
if event.key == pygame.K_DOWN or event.key == ord("s"):
change_to = "DOWN"
# 确保蛇不能直接掉头
if change_to == "RIGHT" and direction != "LEFT":
direction = "RIGHT"
if change_to == "LEFT" and direction != "RIGHT":
direction = "LEFT"
if change_to == "UP" and direction != "DOWN":
direction = "UP"
if change_to == "DOWN" and direction != "UP":
direction = "DOWN"
# 根据移动方向更新蛇的位置
if direction == "RIGHT":
snake_position[0] += 10
if direction == "LEFT":
snake_position[0] -= 10
if direction == "UP":
snake_position[1] -= 10
if direction == "DOWN":
snake_position[1] += 10
# 更新蛇的身体
snake_body.insert(0, list(snake_position))
if snake_position[0] == food_position[0] and snake_position[1] == food_position[1]:
food_spawn = False
else:
snake_body.pop()
# 生成新的食物
if not food_spawn:
food_position = [random.randrange(1, (width // 10)) * 10, random.randrange(1, (height // 10))