在电脑游戏的发展史中,贪吃蛇游戏无疑是其中的经典之作。许多人对其简单而上瘾的游戏玩法念念不忘。对编程爱好者来说,重新编写一个贪吃蛇游戏不仅是对青春回忆的一种致敬,也是一个极佳的学习机会。本文将引导你在Windows系统的PyCharm环境下,使用Python和pygame库来实现这个经典游戏。

前置准备:安装Pygame

首先,确保你的电脑上已经安装了Python。接着,在PyCharm中安装pygame库。这是一个流行的Python库,专为编写游戏而设计。在PyCharm的终端中输入以下命令来安装:

pip install pygame
创建游戏窗口

启动新项目后,创建一个新的Python文件,例如命名为 snake_game.py。游戏的第一步是设置游戏窗口。Pygame库允许你轻松定义窗口的大小和标题:

import pygame

pygame.init()
width, height = 640, 480
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption('贪吃蛇游戏')
定义游戏元素

接下来,定义游戏中的基本元素:蛇的位置、食物的位置以及蛇的身体。为了让蛇移动,我们需要定义一个方向并根据键盘输入来更新这个方向:

snake_pos = [100, 50]
snake_body = [[100, 50], [90, 50], [80, 50]]
food_pos = [random.randrange(1, (width//10)) * 10, random.randrange(1, (height//10)) * 10]
food_spawn = True
direction = 'RIGHT'
change_to = direction
游戏逻辑

游戏的核心逻辑包括处理键盘事件、更新蛇的位置、处理食物的生成与消耗,以及检测游戏结束的条件:

for event in pygame.event.get():
    if event.type == pygame.KEYDOWN:
        if event.key == pygame.K_RIGHT:
            change_to = 'RIGHT'
        elif event.key == pygame.K_LEFT:
            change_to = 'LEFT'
        elif event.key == pygame.K_UP:
            change_to = 'UP'
        elif event.key == pygame.K_DOWN:
            change_to = 'DOWN'

# 更新蛇的位置
if direction == 'RIGHT':
    snake_pos[0] += 10
elif direction == 'LEFT':
    snake_pos[0] -= 10
elif direction == 'UP':
    snake_pos[1] -= 10
elif direction == 'DOWN':
    snake_pos[1] += 10
游戏结束和计分

游戏结束的条件是蛇撞到自己或游戏边界。同时,每次吃到食物时,蛇的长度增加,分数也相应增加:

if snake_pos[0] < 0 or snake_pos[0] > width-10 or snake_pos[1] < 0 or snake_pos[1] > height-10:
    game_over()
for block in snake_body[1:]:
    if snake_pos[0] == block[0] and snake_pos[1] == block[1]:
        game_over()
渲染和刷新

最后,游戏需要不断刷新屏幕以显示最新的游戏状态。Pygame的 display.update() 函数负责这一功能。设置适当的帧率可以使游戏运行平滑:

pygame.display.update()
clock.tick(10)  # 控制游戏速度
总代码和运行结果
import pygame
import random
import sys
import time  # 导入所需的模块
pygame.init()
# 游戏窗口设置
width, height = 640, 480
screen = pygame.display.set_mode((width, height))
clock = pygame.time.Clock()
pygame.display.set_caption('贪吃蛇游戏')
# 颜色定义
black = (0, 0, 0)
white = (255, 255, 255)
red = (255, 0, 0)
green = (0, 255, 0)
# 贪吃蛇初始设置
snake_pos = [100, 50]
snake_body = [[100, 50], [90, 50], [80, 50]]
food_pos = [random.randrange(1, (width // 10)) * 10, random.randrange(1, (height // 10)) * 10]
food_spawn = True
direction = 'RIGHT'
change_to = direction
# 游戏分数
score = 0
# 设置速度
speed = 10
# 路径 to the custom font file
font_path = 'C:\Windows\Fonts\SIMSUNB.TTF'  # Modify this path as necessary
def game_over():
my_font = pygame.font.Font(font_path, 90)  # Use the custom font
game_over_surface = my_font.render('你输了', True, red)
game_over_rect = game_over_surface.get_rect()
game_over_rect.midtop = (width / 2, height / 4)
screen.blit(game_over_surface, game_over_rect)
show_score(0)
pygame.display.flip()
time.sleep(2)
pygame.quit()
sys.exit()
def show_score(choice=1):
s_font = pygame.font.Font(font_path, 24)  # Use the custom font
s_surface = s_font.render('分数 : {0}'.format(score), True, black)
s_rect = s_surface.get_rect()
if choice == 1:
s_rect.midtop = (width / 10, 15)
else:
s_rect.midtop = (width / 2, height / 1.25)
screen.blit(s_surface, s_rect)
# 游戏主循环
while True:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
change_to = 'RIGHT'
if event.key == pygame.K_LEFT:
change_to = 'LEFT'
if event.key == pygame.K_UP:
change_to = 'UP'
if event.key == pygame.K_DOWN:
change_to = 'DOWN'
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# 确定方向
if change_to == 'RIGHT' and not direction == 'LEFT':
direction = 'RIGHT'
if change_to == 'LEFT' and not direction == 'RIGHT':
direction = 'LEFT'
if change_to == 'UP' and not direction == 'DOWN':
direction = 'UP'
if change_to == 'DOWN' and not direction == 'UP':
direction = 'DOWN'
# 移动蛇头
if direction == 'RIGHT':
snake_pos[0] += 10
if direction == 'LEFT':
snake_pos[0] -= 10
if direction == 'UP':
snake_pos[1] -= 10
if direction == 'DOWN':
snake_pos[1] += 10
# 蛇身体增长机制
snake_body.insert(0, list(snake_pos))
if snake_pos[0] == food_pos[0] and snake_pos[1] == food_pos[1]:
score += 10
food_spawn = False
else:
snake_body.pop()
if not food_spawn:
food_pos = [random.randrange(1, (width // 10)) * 10, random.randrange(1, (height // 10)) * 10]
food_spawn = True
# 绘制所有元素
screen.fill(white)
for pos in snake_body:
pygame.draw.rect(screen, green, pygame.Rect(pos[0], pos[1], 10, 10))
pygame.draw.rect(screen, red, pygame.Rect(food_pos[0], food_pos[1], 10, 10))
# 如果蛇撞到边界或自己
if snake_pos[0] < 0 or snake_pos[0] > width - 10 or snake_pos[1] < 0 or snake_pos[1] > height - 10:
game_over()
for block in snake_body[1:]:
if snake_pos[0] == block[0] and snake_pos[1] == block[1]:
game_over()
show_score()
pygame.display.update()
clock.tick(speed)

贪吃蛇游戏的编程之旅:在Windows PyCharm中使用Python插图

通过这些步骤,你可以在自己的电脑上重新创造经典的贪吃蛇游戏。这不仅仅是一个怀旧之旅,更是一个展示如何从头到尾构建一个完整游戏项目的绝佳示例。无论你是编程新手还是希望复习基础知识的老手,编写一个像贪吃蛇这样的简单游戏都是一个很好的开始。

本站无任何商业行为
个人在线分享 » 贪吃蛇游戏的编程之旅:在Windows PyCharm中使用Python
E-->