import pygame
import sys
import random
pygame.init()
# 畫面設定
WIDTH, HEIGHT = 800, 600
WHITE = (255, 255, 255)
RED = (255, 0, 0)
BLUE = (0, 100, 255)
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("球四向反彈")
# 玩家方塊
player_width = 100
player_height = 20
player_x = WIDTH // 2 - player_width // 2
player_y = HEIGHT - 75
player_speed = 8
# 球
ball_radius = 20
ball_x = random.randint(ball_radius, WIDTH - ball_radius)
ball_y = 100
ball_x_speed = 4 # 新增:水平速度
ball_y_speed = 5 # 垂直速度
# 分數
score = 0
font = pygame.font.SysFont(None, 36)
clock = pygame.time.Clock()
running = True
while running:
clock.tick(60)
# 處理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# 玩家左右移動
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
player_x -= player_speed
if keys[pygame.K_RIGHT]:
player_x += player_speed
player_x = max(0, min(WIDTH - player_width, player_x))
# 球移動(新增水平速度)
ball_x += ball_x_speed
ball_y += ball_y_speed
# 撞到左右邊界反彈
if ball_x - ball_radius <= 0 or ball_x + ball_radius >= WIDTH:
ball_x_speed = -ball_x_speed
# 撞到方塊反彈(僅從上方)
if (
player_y <= ball_y + ball_radius <= player_y + player_height
and player_x <= ball_x <= player_x + player_width
and ball_y_speed > 0
):
ball_y_speed = -ball_y_speed
score += 1
# 撞到頂部反彈
if ball_y - ball_radius <= 0:
ball_y_speed = -ball_y_speed
# 掉出畫面底部(沒接到):重置球與分數
if ball_y > HEIGHT:
ball_x = random.randint(ball_radius, WIDTH - ball_radius)
ball_y = 100
ball_x_speed = random.choice([-4, 4]) # 重新設定方向
ball_y_speed = 5
score = 0
# 畫圖
screen.fill(WHITE)
pygame.draw.rect(screen, RED, (player_x, player_y, player_width, player_height))
pygame.draw.circle(screen, BLUE, (int(ball_x), int(ball_y)), ball_radius)
score_text = font.render(f"Score: {score}", True, (0, 0, 0))
screen.blit(score_text, (10, 10))
pygame.display.flip()
pygame.quit()
sys.exit()
沒有留言:
張貼留言