import pygame
import time
import random
# 初始化
pygame.init()
# 颜色定义
white = (255, 255, 255)
yellow = (255, 255, 102)
black = (0, 0, 0)
red = (213, 50, 80)
green = (0, 255, 0)
blue = (50, 153, 213)
# 窗口尺寸
width = 600
height = 400
# 创建窗口
game_window = pygame.display.set_mode((width, height))
pygame.display.set_caption('贪吃蛇游戏')
# 时钟
clock = pygame.time.Clock()
# 蛇块大小与速度
block_size = 10
snake_speed = 15
# 字体
font_style = pygame.font.SysFont("bahnschrift", 25)
score_font = pygame.font.SysFont("comicsansms", 35)
# 显示分数
def show_score(score):
value = score_font.render("分数: " + str(score), True, yellow)
game_window.blit(value, [0, 0])
# 画蛇
def draw_snake(block_size, snake_list):
for block in snake_list:
pygame.draw.rect(game_window, green, [block[0], block[1], block_size, block_size])
# 显示消息
def message(msg, color):
mesg = font_style.render(msg, True, color)
game_window.blit(mesg, [width / 6, height / 3])
# 游戏循环
def game_loop():
game_over = False
game_close = False
# 初始位置
x = width / 2
y = height / 2
# 移动增量
x_change = 0
y_change = 0
# 蛇的身体
snake_list = []
snake_length = 1
# 食物位置
food_x = round(random.randrange(0, width - block_size) / 10.0) * 10.0
food_y = round(random.randrange(0, height - block_size) / 10.0) * 10.0
while not game_over:
while game_close:
game_window.fill(blue)
message("按Q退出或C重新开始", red)
show_score(snake_length - 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_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:
x_change = -block_size
y_change = 0
elif event.key == pygame.K_RIGHT:
x_change = block_size
y_change = 0
elif event.key == pygame.K_UP:
y_change = -block_size
x_change = 0
elif event.key == pygame.K_DOWN:
y_change = block_size
x_change = 0
# 边界检测
if x >= width or x < 0 or y >= height or y < 0:
game_close = True
x += x_change
y += y_change
game_window.fill(black)
pygame.draw.rect(game_window, red, [food_x, food_y, block_size, block_size])
snake_head = []
snake_head.append(x)
snake_head.append(y)
snake_list.append(snake_head)
if len(snake_list) > snake_length:
del snake_list[0]
# 碰撞检测
for block in snake_list[:-1]:
if block == snake_head:
game_close = True
draw_snake(block_size, snake_list)
show_score(snake_length - 1)
pygame.display.update()
# 吃到食物
if x == food_x and y == food_y:
food_x = round(random.randrange(0, width - block_size) / 10.0) * 10.0
food_y = round(random.randrange(0, height - block_size) / 10.0) * 10.0
snake_length += 1
clock.tick(snake_speed)
pygame.quit()
quit()
# 启动游戏
game_loop()