import pygame
import random
# 初始化pygame
pygame.init()
# 游戏区域大小
width = 500
height = 500
# 创建游戏窗口
screen = pygame.display.set_mode((width, height))
# 设置游戏标题
pygame.display.set_caption("贪吃蛇")
# 定义颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
# 定义蛇的初始位置和大小
snake_block = 10
snake_speed = 15
# 定义字体
font_style = pygame.font.SysFont(None, 30)
def our_snake(snake_block, snake_list):
for x in snake_list:
pygame.draw.rect(screen, black, [x[0], x[1], snake_block, snake_block])
def message(msg, color):
mesg = font_style.render(msg, True, color)
screen.blit(mesg, [width / 6, height / 3])
# 游戏循环
def game_loop():
game_over = False
game_close = False
x1 = width / 2
y1 = height / 2
x1_change = 0
y1_change = 0
snake_List = []
Length_of_snake = 1
foodx = round(random.randrange(0, width - snake_block) / 10.0) * 10.0
foody = round(random.randrange(0, height - snake_block) / 10.0) * 10.0
# 游戏主循环
while not game_over:
while game_close == True:
screen.fill(white)
message("你输了,按Q退出,按C重新开始", 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:
game_loop()
# 处理按键事件
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 = -snake_block
y1_change = 0
elif event.key == pygame.K_RIGHT:
x1_change = snake_block
y1_change = 0
elif event.key == pygame.K_UP:
y1_change = -snake_block
x1_change = 0
elif event.key == pygame.K_DOWN:
y1_change = snake_block
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(white)
pygame.draw.rect(screen, red, [foodx, foody, snake_block, snake_block])
snake_Head = []
snake_Head.append(x1)
snake_Head.append(y1)
snake_List.append(snake_Head)
# 控制蛇的长度
if len(snake_List) > Length_of_snake:
del snake_List[0]
# 判断是否吃到食物
for x in snake_List[:-1]:
if x == snake_Head:
game_close = True
our_snake(snake_block, snake_List)
pygame.display.update()
# 判断是否吃到食物,更新食物位置
if x1 == foodx and y1 == foody:
foodx = round(random.randrange(0, width - snake_block) / 10.0) * 10.0
foody = round(random.randrange(0, height - snake_block) / 10.0) * 10.0
Length_of_snake += 1
# 控制游戏速度
pygame.time.delay(snake_speed)
# 退出pygame
pygame.quit()
# 启动游戏循环
game_loop()