以下是一个使用 Python 和 PyGame
库在 PyCharm
中创建一个简单的小游戏(贪吃蛇游戏)的示例代码,希望对您有所帮助:
import pygame
import random
# 基础设置
# 屏幕高度
SCREEN_HEIGHT = 480
# 屏幕宽度
SCREEN_WIDTH = 600
# 小方格大小
GRID_SIZE = 20
# 颜色设置
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
# 初始化 `PyGame`
pygame.init()
# 创建屏幕
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("贪吃蛇游戏")
# 游戏时钟
clock = pygame.time.Clock()
# 蛇的初始位置和速度
snake_pos = [200, 100]
snake_speed = [0, 0]
# 食物的初始位置
food_pos = [random.randint(0, SCREEN_WIDTH // GRID_SIZE - 1) * GRID_SIZE,
random.randint(0, SCREEN_HEIGHT // GRID_SIZE - 1) * GRID_SIZE]
# 蛇的身体列表
snake_body = [[snake_pos[0], snake_pos[1]]]
# 游戏结束标志
game_over = False
# 游戏循环
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_UP and snake_speed[1]!= GRID_SIZE:
snake_speed = [0, -GRID_SIZE]
elif event.key == pygame.K_DOWN and snake_speed[1]!= -GRID_SIZE:
snake_speed = [0, GRID_SIZE]
elif event.key == pygame.K_LEFT and snake_speed[0]!= GRID_SIZE:
snake_speed = [-GRID_SIZE, 0]
elif event.key == pygame.K_RIGHT and snake_speed[0]!= -GRID_SIZE:
snake_speed = [GRID_SIZE, 0]
# 根据速度移动蛇头
snake_pos[0] += snake_speed[0]
snake_pos[1] += snake_speed[1]
# 判断蛇是否吃到食物
if snake_pos[0] == food_pos[0] and snake_pos[1] == food_pos[1]:
food_pos = [random.randint(0, SCREEN_WIDTH // GRID_SIZE - 1) * GRID_SIZE,
random.randint(0, SCREEN_HEIGHT // GRID_SIZE - 1) * GRID_SIZE]
else:
# 去除蛇尾
del snake_body[0]
# 判断蛇是否撞到自己或边界
if [snake_pos[0], snake_pos[1]] in snake_body[1:]:
game_over = True
elif snake_pos[0] < 0 or snake_pos[0] >= SCREEN_WIDTH or snake_pos[1] < 0 or snake_pos[1] >= SCREEN_HEIGHT:
game_over = True
# 增加蛇的长度
snake_body.append(list(snake_pos))
# 绘制背景
screen.fill(BLACK)
# 绘制食物
pygame.draw.rect(screen, GREEN, [food_pos[0], food_pos[1], GRID_SIZE, GRID_SIZE])
# 绘制蛇
for pos in snake_body:
pygame.draw.rect(screen, WHITE, [pos[0], pos[1], GRID_SIZE, GRID_SIZE])
# 刷新屏幕
pygame.display.flip()
# 控制游戏帧率
clock.tick(10)
# 退出游戏
pygame.quit()
您可以在 PyCharm
中运行这段代码,开始您的贪吃蛇游戏。当然,这只是一个简单的示例,您可以根据自己的需求对游戏进行扩展和完善。希望这个示例对您有帮助!如果您还有其他问题,欢迎继续提问
更多小游戏开发需求欢迎私聊交流