编一个贪吃蛇游戏
下面是一个简单的贪吃蛇游戏的Python代码示例:
import pygame
import random
# 初始化游戏
pygame.init()
# 游戏窗口尺寸
window_width = 600
window_height = 400
# 定义颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
# 定义蛇的大小和速度
snake_size = 10
snake_speed = 15
# 初始化游戏窗口
window = pygame.display.set_mode((window_width, window_height))
pygame.display.set_caption('贪吃蛇')
clock = pygame.time.Clock()
# 定义字体
font_style = pygame.font.SysFont(None, 30)
score_font = pygame.font.SysFont(None, 50)
# 显示得分
def show_score(score):
score_text = score_font.render("得分:" + str(score), True, black)
window.blit(score_text, [10, 10])
# 绘制蛇
def draw_snake(snake_size, snake_list):
for x in snake_list:
pygame.draw.rect(window, black, [x[0], x[1], snake_size, snake_size])
# 游戏结束
def game_over():
message = font_style.render("游戏结束", True, red)
window.blit(message, [window_width/2 - 100, window_height/2 - 50])
# 主函数
def game():
game_over = False
game_close = False
# 初始位置
x1 = window_width / 2
y1 = window_height / 2
# 初始移动方向
x1_change = 0
y1_change = 0
# 蛇的身体
snake_list = []
snake_length = 1
# 随机生成食物的位置
foodx = round(random.randrange(0, window_width - snake_size) / 10.0) * 10.0
foody = round(random.randrange(0, window_height - snake_size) / 10.0) * 10.0
# 游戏循环
while not game_over:
while game_close:
window.fill(white)
game_over()
show_score(snake_length - 1)
pygame.display.update()
# 点击窗口关闭按钮或按下q键退出游戏
for event in pygame.event.get():
if event.type == pygame.QUIT or (event.type == pygame.KEYDOWN and event.key == pygame.K_q):
game_over = True
game_close = False
# 按下空格键重新开始游戏
if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
game()
# 移动蛇的位置
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_size
y1_change = 0
elif event.key == pygame.K_RIGHT:
x1_change = snake_size
y1_change = 0
elif event.key == pygame.K_UP:
y1_change = -snake_size
x1_change = 0
elif event.key == pygame.K_DOWN:
y1_change = snake_size
x1_change = 0
# 检查是否撞到墙壁
if x1 >= window_width or x1 < 0 or y1 >= window_height or y1 < 0:
game_close = True
# 更新蛇的位置
x1 += x1_change
y1 += y1_change
window.fill(white)
pygame.draw.rect(window, red, [foodx, foody, snake_size, snake_size])
snake_head = []
snake_head.append(x1)
snake_head.append(y1)
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_close = True
# 绘制蛇和食物
draw_snake(snake_size, snake_list)
show_score(snake_length - 1)
pygame.display.update()
# 检查是否吃到食物
if x1 == foodx and y1 == foody:
foodx = round(random.randrange(0, window_width - snake_size) / 10.0) * 10.0
foody = round(random.randrange(0, window_height - snake_size) / 10.0) * 10.0
snake_length += 1
clock.tick(snake_speed)
pygame.quit()
# 运行游戏
game()
你可以复制上面的代码并在Python环境中运行,即可开始玩贪吃蛇游戏。使用方向键控制蛇的移动,吃到食物会增加得分并使蛇变长,如果蛇撞到墙壁或自己的身体,则游戏结束
原文地址: https://www.cveoy.top/t/topic/iEvt 著作权归作者所有。请勿转载和采集!