[Python] 纯文本查看 复制代码 import pygame
import random
# 初始化 Pygame
pygame.init()
# 屏幕大小
screen_width = 600
screen_height = 400
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("贪吃蛇")
# 颜色
white = (255, 255, 255)
black = (0, 0, 0)
green = (0, 255, 0)
red = (255, 0, 0)
# 蛇块大小
block_size = 10
# 蛇的初始位置和速度
snake_x = screen_width / 2
snake_y = screen_height / 2
snake_x_change = 0
snake_y_change = 0
# 蛇身
snake_list = []
snake_length = 1
# 食物位置
food_x = round(random.randrange(0, screen_width - block_size) / 10.0) * 10.0
food_y = round(random.randrange(0, screen_height - block_size) / 10.0) * 10.0
# 游戏时钟
clock = pygame.time.Clock()
# 游戏结束标志
game_over = False
# 字体
font_style = pygame.font.SysFont(None, 25)
def message(msg, color):
mesg = font_style.render(msg, True, color)
screen.blit(mesg, [screen_width/6, screen_height/3])
# 游戏循环
while not game_over:
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 and snake_x_change != block_size:
snake_x_change = -block_size
snake_y_change = 0
elif event.key == pygame.K_RIGHT and snake_x_change != -block_size:
snake_x_change = block_size
snake_y_change = 0
elif event.key == pygame.K_UP and snake_y_change != block_size:
snake_y_change = -block_size
snake_x_change = 0
elif event.key == pygame.K_DOWN and snake_y_change != -block_size:
snake_y_change = block_size
snake_x_change = 0
# 边界检测
if snake_x >= screen_width or snake_x < 0 or snake_y >= screen_height or snake_y < 0:
game_over = True
# 更新蛇的位置
snake_x += snake_x_change
snake_y += snake_y_change
# 绘制背景
screen.fill(black)
# 绘制食物
pygame.draw.rect(screen, red, [food_x, food_y, block_size, block_size])
# 蛇身逻辑
snake_head = []
snake_head.append(snake_x)
snake_head.append(snake_y)
snake_list.append(snake_head)
if len(snake_list) > snake_length:
del snake_list[0]
# 碰撞检测(自身)
for x in snake_list[:-1]:
if x == snake_head:
game_over = True
# 绘制蛇
for x in snake_list:
pygame.draw.rect(screen, green, [x[0], x[1], block_size, block_size])
# 吃到食物
if snake_x == food_x and snake_y == food_y:
food_x = round(random.randrange(0, screen_width - block_size) / 10.0) * 10.0
food_y = round(random.randrange(0, screen_height - block_size) / 10.0) * 10.0
snake_length += 1
pygame.display.update()
# 控制游戏速度
clock.tick(15)
message("游戏结束!", red)
pygame.display.update()
pygame.time.delay(2000)
pygame.quit()
quit()
|