import pygame
import sys
# 初始化Pygame
pygame.init()
# 设置窗口大小
win_size = (800, 600)
screen = pygame.display.set_mode(win_size)
# 设置标题
pygame.display.set_caption("我的Pygame游戏")
# 设置颜色
WHITE = (255, 255, 255)
RED = (255, 0, 0)
# 设置矩形的初始位置和速度
rect_pos = [100, 100]
rect_speed = [2, 2]
# 游戏主循环
while True:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# 绘制背景
screen.fill(WHITE)
# 绘制矩形
pygame.draw.rect(screen, RED, (rect_pos[0], rect_pos[1], 50, 50))
# 更新矩形位置
rect_pos[0] += rect_speed[0]
rect_pos[1] += rect_speed[1]
# 如果矩形碰到窗口边缘,则反向移动
if rect_pos[0] < 0 or rect_pos[0] > win_size[0] - 50:
rect_speed[0] = -rect_speed[0]
if rect_pos[1] < 0 or rect_pos[1] > win_size[1] - 50:
rect_speed[1] = -rect_speed[1]
# 更新屏幕显示
pygame.display.flip()
# 控制帧率
pygame.time.Clock().tick(60)
评论