Python 是一種通用編程語言,可以用于開發各種應用程序。其中一個有趣的項目是用 Python 編寫一個小球彈彈彈游戲。該游戲要求用戶幫助小球通過反彈避免撞到四周的墻壁。
import pygame # Initialize Pygame pygame.init() # Set up screen size screen_width = 500 screen_height = 500 screen = pygame.display.set_mode((screen_width, screen_height)) # Set up ball ball_radius = 20 ball_color = (255, 255, 255) ball_pos = [screen_width//2, screen_height//2] ball_speed = [1, 1] # Run game loop running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False # Move ball ball_pos[0] += ball_speed[0] ball_pos[1] += ball_speed[1] # Bounce ball off walls if ball_pos[0]< ball_radius or ball_pos[0] >screen_width - ball_radius: ball_speed[0] = -ball_speed[0] if ball_pos[1]< ball_radius or ball_pos[1] >screen_height - ball_radius: ball_speed[1] = -ball_speed[1] # Draw ball on screen screen.fill((0, 0, 0)) pygame.draw.circle(screen, ball_color, ball_pos, ball_radius) pygame.display.flip() # Quit Pygame pygame.quit()
在這段代碼中,我們使用 Pygame 庫創建一個屏幕并設置一個小球。該小球在屏幕上移動,并通過墻壁反彈。當用戶關閉屏幕時,游戲循環結束并退出 Pygame。這是一個簡單而有趣的游戲項目,可以通過添加更多功能和玩家交互來進行擴展。