Python 贪吃蛇游戏代码:简单易懂,快速上手
很高兴能够为您提供一个简单的贪吃蛇游戏代码。以下代码使用了 Python 的 pygame 库,您可以轻松地复制、粘贴并运行它。
import pygame
import random
# 初始化游戏引擎
pygame.init()
# 创建游戏窗口
screen_width = 600
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption('贪吃蛇')
# 定义颜色
black = (0, 0, 0)
white = (255, 255, 255)
red = (255, 0, 0)
green = (0, 255, 0)
# 定义贪吃蛇和食物的大小
snake_block_size = 10
food_block_size = 10
# 定义时钟对象
clock = pygame.time.Clock()
# 定义字体对象
font = pygame.font.SysFont(None, 25)
# 定义函数:绘制贪吃蛇
def draw_snake(snake_block_size, snake_list):
for x in snake_list:
pygame.draw.rect(screen, green, [x[0], x[1], snake_block_size, snake_block_size])
# 定义函数:显示消息
def message(msg, color):
text = font.render(msg, True, color)
screen.blit(text, [screen_width / 6, screen_height / 3])
# 定义函数:游戏循环
def game_loop():
game_over = False
game_close = False
# 初始化贪吃蛇的位置和长度
snake_list = []
snake_length = 1
snake_x = screen_width / 2
snake_y = screen_height / 2
snake_x_change = 0
snake_y_change = 0
# 初始化食物的位置
food_x = round(random.randrange(0, screen_width - food_block_size) / 10.0) * 10.0
food_y = round(random.randrange(0, screen_height - food_block_size) / 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:
snake_x_change = -snake_block_size
snake_y_change = 0
elif event.key == pygame.K_RIGHT:
snake_x_change = snake_block_size
snake_y_change = 0
elif event.key == pygame.K_UP:
snake_y_change = -snake_block_size
snake_x_change = 0
elif event.key == pygame.K_DOWN:
snake_y_change = snake_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_close = True
# 更新贪吃蛇的位置
snake_x += snake_x_change
snake_y += snake_y_change
# 绘制游戏窗口
screen.fill(white)
pygame.draw.rect(screen, red, [food_x, food_y, food_block_size, food_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_close = True
# 绘制贪吃蛇和食物
draw_snake(snake_block_size, snake_list)
pygame.display.update()
# 贪吃蛇吃到食物
if snake_x == food_x and snake_y == food_y:
food_x = round(random.randrange(0, screen_width - food_block_size) / 10.0) * 10.0
food_y = round(random.randrange(0, screen_height - food_block_size) / 10.0) * 10.0
snake_length += 1
# 设置游戏速度
clock.tick(15)
# 结束游戏
pygame.quit()
quit()
# 运行游戏循环
game_loop()
使用上述代码,您可以实现一个简单的贪吃蛇游戏。希望对您有所帮助。
原文地址: https://www.cveoy.top/t/topic/mTM6 著作权归作者所有。请勿转载和采集!