python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > Python Lightly实现贪吃蛇

Python在线编译器Lightly轻松实现贪吃蛇游戏

作者:杰西笔记

今天我将带领大家使用Python的Pygame库在Lightly在线编译器中实现一个经典的贪吃蛇游戏,文中的示例代码讲解详细,感兴趣的小伙伴可以了解下

前言

今天我将带领大家使用Python的Pygame库在Lightly在线编译器中实现一个经典的贪吃蛇游戏。Lightly是一个非常方便的在线开发环境,无需安装任何软件,直接在浏览器中就能编写和运行Python代码。

https://www.lightlycode.com/python

一、环境准备

安装Pygame库

在Lightly中,我们首先需要安装Pygame库。虽然Lightly已经预装了许多常用库,但为了确保最新版本,我们可以在终端中运行:

pip install pygame

Lightly的终端位于界面底部,点击"+"号可以打开新终端。

二、贪吃蛇游戏实现

下面我将完整展示贪吃蛇游戏的代码,并解释关键部分:

import pygame
import random

# 初始化
pygame.init()
width, height = 400, 300
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("贪吃蛇 - 极简中文版")
clock = pygame.time.Clock()

# 颜色定义
black = (0, 0, 0)
green = (0, 255, 0)
red = (255, 0, 0)
white = (255, 255, 255)

# 蛇和食物初始化
snake = [(width // 2, height // 2)]
food = (random.randint(0, (width - 10) // 10) * 10, 
        random.randint(0, (height - 10) // 10) * 10)
dx, dy = 10, 0  # 初始向右移动

# 字体设置(支持中文)
try:
    font = pygame.font.Font(None, 30)
except:
    pass

try:
    font = pygame.font.SysFont("SimHei", 25)  # 黑体
except:
    font = pygame.font.SysFont("Microsoft YaHei", 25)  # 微软雅黑
    if not font:
        font = pygame.font.SysFont("arial", 25)  # 兜底方案

# 游戏主循环
running = True
game_over = False
score = 0

while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        # 游戏进行中的键盘控制
        if not game_over:
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_UP and dy == 0:
                    dx, dy = 0, -10
                elif event.key == pygame.K_DOWN and dy == 0:
                    dx, dy = 0, 10
                elif event.key == pygame.K_LEFT and dx == 0:
                    dx, dy = -10, 0
                elif event.key == pygame.K_RIGHT and dx == 0:
                    dx, dy = 10, 0
        else:
            # 游戏结束后的键盘控制
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_r:
                    # 重新开始
                    snake = [(width // 2, height // 2)]
                    food = (random.randint(0, (width - 10) // 10) * 10,
                            random.randint(0, (height - 10) // 10) * 10)
                    dx, dy = 10, 0
                    score = 0
                    game_over = False
                elif event.key == pygame.K_q:
                    running = False

    # 游戏结束画面
    if game_over:
        screen.fill(black)
        game_over_text = font.render("游戏结束!", True, red)
        score_text = font.render(f"得分: {score}", True, white)
        restart_text = font.render("按 R 重新开始, Q 退出", True, white)
        screen.blit(game_over_text, (width // 2 - 60, height // 2 - 40))
        screen.blit(score_text, (width // 2 - 50, height // 2))
        screen.blit(restart_text, (width // 2 - 100, height // 2 + 40))
        pygame.display.flip()
        continue

    # 蛇的移动逻辑
    head = snake[0]
    new_head = ((head[0] + dx) % width, (head[1] + dy) % height)
    snake.insert(0, new_head)

    # 食物检测
    if new_head == food:
        food = (random.randint(0, (width - 10) // 10) * 10,
                random.randint(0, (height - 10) // 10) * 10)
        score += 1
    else:
        snake.pop()

    # 碰撞检测(撞到自己)
    if snake[0] in snake[1:]:
        game_over = True

    # 绘制游戏画面
    screen.fill(black)
    # 绘制蛇身
    for part in snake:
        pygame.draw.rect(screen, green, (*part, 10, 10))
    # 绘制食物
    pygame.draw.rect(screen, red, (*food, 10, 10))
    # 显示分数
    score_surface = font.render(f"得分: {score}", True, white)
    screen.blit(score_surface, (10, 10))

    pygame.display.flip()
    clock.tick(10)  # 控制游戏速度

pygame.quit()

三、代码解析

1. 初始化设置

2. 游戏对象初始化

3. 字体处理

特别处理了中文字体显示问题,尝试使用系统自带的中文字体:

4. 游戏主循环

事件处理

游戏逻辑

画面渲染

5. 游戏速度控制

clock.tick(10) 控制游戏帧率为10FPS,使蛇的移动速度适中。

四、在Lightly中运行游戏

五、游戏操作说明

方向键:控制蛇的移动方向

R键:游戏结束后重新开始

Q键:游戏结束后退出

六、可能的改进方向

演示效果

七、总结

通过这个项目,我们学习了:

到此这篇关于Python在线编译器Lightly轻松实现贪吃蛇游戏的文章就介绍到这了,更多相关Python Lightly实现贪吃蛇内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文