用python实现球球大作战

时间:2024-03-19 21:42:12
import pygame
import sys
# 初始化pygame
pygame.init()
# 设置窗口大小
screen_width, screen_height = 800, 600
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("简单的球球大作战")
# 设置颜色
WHITE = (255, 255, 255)
RED = (255, 0, 0)
# 创建球球
ball_radius = 20
ball_pos = [screen_width // 2, screen_height // 2]
ball_speed = [2, 2]
# 游戏主循环
running = True
while running:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
ball_speed[1] = -ball_speed[1]
elif event.key == pygame.K_DOWN:
ball_speed[1] = abs(ball_speed[1])
elif event.key == pygame.K_LEFT:
ball_speed[0] = -ball_speed[0]
elif event.key == pygame.K_RIGHT:
ball_speed[0] = abs(ball_speed[0])
# 更新球球位置
ball_pos[0] += ball_speed[0]
ball_pos[1] += ball_speed[1]
# 边界检测
if ball_pos[0] - ball_radius < 0 or ball_pos[0] + ball_radius > screen_width:
ball_speed[0] = -ball_speed[0]
if ball_pos[1] - ball_radius < 0 or ball_pos[1] + ball_radius > screen_height:
ball_speed[1] = -ball_speed[1]
# 绘制背景
screen.fill(WHITE)
# 绘制球球
pygame.draw.circle(screen, RED, ball_pos, ball_radius)
# 更新屏幕
pygame.display.flip()
# 控制帧率
pygame.time.Clock().tick(60)
# 退出pygame
pygame.quit()
sys.exit()