2025年5月7日 星期三

左右移動方塊

 import pygame

import sys


# 初始化

pygame.init()


# 視窗大小與顏色

WIDTH, HEIGHT = 800, 600

WHITE = (255, 255, 255)

RED = (255, 0, 0)


# 視窗

screen = pygame.display.set_mode((WIDTH, HEIGHT))

pygame.display.set_caption("左右移動方塊")


# 方塊設定

player_size = 50

player_x = WIDTH // 2

player_y = HEIGHT - 75  # 固定在底部上方約 2 公分

player_speed = 5


# 遊戲主迴圈

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


    # 邊界限制(只限 x)

    player_x = max(0, min(WIDTH - player_size, player_x))


    # 畫面更新

    screen.fill(WHITE)

    pygame.draw.rect(screen, RED, (player_x, player_y, player_size, player_size))

    pygame.display.flip()


pygame.quit()

sys.exit()

沒有留言:

張貼留言