做一个基于pygame的小游戏不用图像资源
下面是一个简单的基于pygame的小游戏,名为“跳跳球”:
import pygame
import random
# 初始化游戏
pygame.init()
WIDTH, HEIGHT = 600, 400
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("跳跳球")
clock = pygame.time.Clock()
# 定义颜色
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
# 定义游戏元素
ball_x = WIDTH // 2
ball_y = HEIGHT - 50
ball_radius = 10
ball_color = GREEN
ball_speed = 0
ball_acceleration = 0.5
ball_jump = 10
platform_width = 80
platform_height = 10
platform_x = WIDTH // 2 - platform_width // 2
platform_y = HEIGHT - platform_height - 20
platform_color = BLUE
score = 0
font = pygame.font.Font(None, 36)
# 游戏循环
running = True
while running:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
ball_speed = -ball_jump
# 更新游戏元素
ball_speed += ball_acceleration
ball_y += ball_speed
if ball_y + ball_radius > platform_y:
if platform_x <= ball_x <= platform_x + platform_width:
ball_speed = -ball_jump
score += 1
else:
running = False
if ball_y + ball_radius > HEIGHT:
running = False
platform_x += random.randint(-1, 1)
# 绘制画面
screen.fill(WHITE)
pygame.draw.circle(screen, ball_color, (ball_x, int(ball_y)), ball_radius)
pygame.draw.rect(screen, platform_color, (platform_x, platform_y, platform_width, platform_height))
score_text = font.render("Score: {}".format(score), True, BLACK)
screen.blit(score_text, (10, 10))
pygame.display.flip()
# 控制帧率
clock.tick(60)
# 结束游戏
pygame.quit()
游戏规则:控制小球跳跃,让其在平台上跳跃,每次成功跳跃到平台上得1分,如果小球掉落到屏幕下方或者没有成功跳跃到平台上,游戏结束。平台会随机左右移动。
原文地址: https://www.cveoy.top/t/topic/b95p 著作权归作者所有。请勿转载和采集!