import pygame
from setting import FIRST_STEP, SECOND_STEP, BG_COLOR, WIDTH, HEIGHT
def ballNum(ladderNum, time):
index = 0
if FIRST_STEP <= time < SECOND_STEP:
index = 1
if SECOND_STEP <= time:
index = 2
base_count = ladderNum * 2
return base_count + index * 5
class Ball(pygame.sprite.Sprite):
def __init__(self, x, y, radius, color, speed):
super().__init__()
self.image = pygame.Surface((radius * 2, radius * 2), pygame.SRCALPHA)
pygame.draw.circle(self.image, color, (radius, radius), radius)
self.rect = self.image.get_rect()
self.rect.center = (x, y)
self.speed = speed
def update(self):
self.rect.x += self.speed[0]
self.rect.y += self.speed[1]
if self.rect.left <= 0 or self.rect.right >= WIDTH:
self.speed[0] *= -1
if self.rect.top <= 0 or self.rect.bottom >= HEIGHT:
self.speed[1] *= -1
import pygame
import random
from setting import WIDTH, HEIGHT, FPS, BG_COLOR, SCORE, TIME
from utils import Ball, ballNum
def main(difficulty_level):
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("小球躲避游戏")
clock = pygame.time.Clock()
player = Ball(WIDTH // 2, HEIGHT // 2, 20, (0, 0, 255), [0, 0])
obstacles = pygame.sprite.Group()
running = True
game_over = False
score = 0
timer = 0
while running:
clock.tick(FPS)
screen.fill(BG_COLOR)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
running = False
if not game_over and event.key == pygame.K_SPACE:
pass
if not game_over:
timer += 1
if timer % (30 // difficulty_level) == 0:
ox = random.randint(0, WIDTH)
oy = random.randint(0, HEIGHT)
obs = Ball(ox, oy, 15, (255, 0, 0), [random.choice([-1, 1]), random.choice([-1, 1])])
obstacles.add(obs)
player.update()
for obs in obstacles:
obs.update()
if player.rect.colliderect(obs.rect):
game_over = True
score += 1
screen.blit(player.image, player.rect)
obstacles.draw(screen)
font = pygame.font.SysFont("arial", 24)
text = font.render(f"Score: {score}", True, (0, 0, 0))
screen.blit(text, (10, 10))
else:
font = pygame.font.SysFont("arial", 48)
text = font.render("Game Over", True, (255, 0, 0))
rect = text.get_rect(center=(WIDTH//2, HEIGHT//2))
screen.blit(text, rect)
sub_font = pygame.font.SysFont("arial", 24)
sub_text = sub_font.render("Press R to Restart", True, (0, 0, 0))
sub_rect = sub_text.get_rect(center=(WIDTH//2, HEIGHT//2 + 40))
screen.blit(sub_text, sub_rect)
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_r:
main(difficulty_level)
return
pygame.display.flip()
pygame.quit()