初始版本
初始版本,只存在基本数据结构——双向队列。
游戏思路
贪吃蛇通过不断得吃食物来增长自身,如果贪吃蛇碰到边界或者自身则游戏失败。
食物是绿色矩形来模拟,坐标为随机数生成,定义一个蛇长变量,判断蛇头坐标和食物坐标是否接近,如果蛇头接近食物,蛇长增加一个单位。
蛇结构体通过双向队列
实现蛇的移动和增长。用pygame相应库函数读取键盘事件,每次事件发生都对应蛇头的相应方向,例如按键盘下键贪吃蛇向下走。蛇的移动是通过在队头添加一个新的坐标,然后删掉队尾元素实现的。队列的长度始终为蛇长变量的值。
得分变量为蛇长变量减去一个单位,初始化的时候蛇长就为1个单位长度,故而需要减1。
完整代码
import pygame
import random
pygame.init()
# 以RGB的形式定义颜色
white = (255, 255, 255)
yellow = (255, 255, 102)
black = (0, 0, 0)
red = (213, 50, 80)
green = (0, 255, 0)
blue = (50, 153, 213)
# 设置窗体大小
dis_width = 800
dis_height = 600
dis = pygame.display.set_mode((dis_width, dis_height))
pygame.display.set_caption('贪吃蛇 KevenDuan1.0')
# 创建clock对象
clock = pygame.time.Clock()
# 蛇的宽度
snake_block = 15
# 蛇的速度
snake_speed = 15
# 从系统库里获取字体
font_style = pygame.font.SysFont("bahnschrift", 25)
score_font = pygame.font.SysFont("comicsansms", 35)
def Your_score(score):
value = score_font.render("Score: " + str(score), True, yellow)
# 在主surface里添加字体surface
dis.blit(value, [0, 0])
def our_snake(snake_block, snake_list):
for x in snake_list:
pygame.draw.rect(dis, black, [x[0], x[1], snake_block, snake_block])
def message(msg, color):
mesg = font_style.render(msg, True, color)
dis.blit(mesg, [dis_width // 2 - 180, dis_height // 2])
def gameLoop():
game_over = False
game_close = False
x1 = dis_width / 2
y1 = dis_height / 2
x1_change = 0
y1_change = 0
# 存放蛇的身体
snake_List = []
# 蛇的长度
Length_of_snake = 1
# 食物坐标随机生成
foodx = round(random.randrange(snake_block, dis_width - snake_block, snake_block))
foody = round(random.randrange(snake_block, dis_height - snake_block, snake_block))
print(foodx, foody)
while not game_over:
while game_close == True:
dis.fill(blue)
message("Game over, press p again or q quit!", red)
Your_score(Length_of_snake - 1)
# 修改得分
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_p:
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 or event.key == pygame.K_a:
x1_change = -snake_block
y1_change = 0
elif event.key == pygame.K_RIGHT or event.key == pygame.K_d:
x1_change = snake_block
y1_change = 0
elif event