[Python] 纯文本查看 复制代码
import pygame
import random
pygame.init()
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("Ball Catcher")
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
font = pygame.font.SysFont(None, 36)
class Ball(pygame.sprite.Sprite):
def __init__(self, color, score):
super().__init__()
self.radius = random.randint(10, 30)
self.color = color
self.score = score
self.speed = random.randint(1, 5)
self.image = pygame.Surface([self.radius * 2, self.radius * 2], pygame.SRCALPHA)
pygame.draw.circle(self.image, self.color, (self.radius, self.radius), self.radius)
self.render_score()
self.rect = self.image.get_rect()
self.rect.x = random.randint(0, SCREEN_WIDTH - self.rect.width)
self.rect.y = 0
def render_score(self):
text_surface = font.render(str(self.score), True, WHITE)
text_rect = text_surface.get_rect(center=(self.radius, self.radius))
self.image.blit(text_surface, text_rect)
def update(self):
self.rect.y += self.speed
class Paddle(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.length = 5 # 盘子的长度
self.width = self.length * 20 # 盘子的宽度
self.image = pygame.Surface([self.width, 20])
self.image.fill(WHITE)
self.rect = self.image.get_rect()
self.rect.x = (SCREEN_WIDTH - self.width) // 2
self.rect.y = SCREEN_HEIGHT - 20
def update(self):
pos = pygame.mouse.get_pos()
self.rect.x = pos[0] - self.width // 2
if self.rect.x < 0:
self.rect.x = 0
if self.rect.x > SCREEN_WIDTH - self.width:
self.rect.x = SCREEN_WIDTH - self.width
def decrease_length(self):
if self.length > 0:
self.length -= 1
self.width = self.length * 20
self.image = pygame.Surface([self.width, 20])
self.image.fill(WHITE)
self.rect = self.image.get_rect(center=self.rect.center)
if self.length == 0:
return True
return False
all_sprites = pygame.sprite.Group()
balls = pygame.sprite.Group()
paddle = Paddle()
all_sprites.add(paddle)
# 主循环
running = True
score = 0
clock = pygame.time.Clock()
game_over = False
while running:
# 事件处理
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
all_sprites.update()
if not game_over and random.randint(1, 100) < 5:
ball_color, ball_score = random.choice([(RED, -1), (GREEN, 1), (BLUE, 2)])
ball = Ball(ball_color, ball_score)
all_sprites.add(ball)
balls.add(ball)
hits = pygame.sprite.spritecollide(paddle, balls, True)
for ball in hits:
score += ball.score
if ball.color == RED:
if paddle.decrease_length():
game_over = True
screen.fill((0, 0, 0))
all_sprites.draw(screen)
text = font.render("Score: " + str(score), True, WHITE)
screen.blit(text, [10, 10])
# 显示游戏结束信息
if game_over:
game_over_text = font.render("Game Over", True, RED)
screen.blit(game_over_text, [(SCREEN_WIDTH - game_over_text.get_width()) // 2, SCREEN_HEIGHT // 2])
pygame.display.flip()
clock.tick(30)
# 退出Pygame
pygame.quit()