初始化Pygame
```python
import pygame
pygame.init()
```
设置窗口大小
```python
screen = pygame.display.set_mode((800, 600))
```
定义颜色
```python
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
```
游戏主循环
```python
running = True
rect_x = 100
rect_y = 100
rect_speed = 5
```
事件处理
```python
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
```
绘制矩形
```python
screen.fill(WHITE) 填充背景色
pygame.draw.rect(screen, BLACK, (rect_x, rect_y, 100, 50)) 绘制矩形
pygame.display.flip() 更新显示
```
更新矩形位置
```python
rect_x += rect_speed
rect_y += rect_speed
```
边界检查
```python
if rect_x > 800 - 100 or rect_x < 100 or rect_y > 600 - 50 or rect_y < 50:
rect_speed = -rect_speed
```
完整的代码如下:
```python
import pygame
初始化Pygame
pygame.init()
设置窗口大小
screen = pygame.display.set_mode((800, 600))
定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
游戏主循环
running = True
rect_x = 100
rect_y = 100
rect_speed = 5
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
填充背景色
screen.fill(WHITE)
绘制矩形
pygame.draw.rect(screen, BLACK, (rect_x, rect_y, 100, 50))
更新显示
pygame.display.flip()
更新矩形位置
rect_x += rect_speed
rect_y += rect_speed
边界检查
if rect_x > 800 - 100 or rect_x < 100 or rect_y > 600 - 50 or rect_y < 50:
rect_speed = -rect_speed
退出Pygame
pygame.quit()
```
这个代码会创建一个800x600的窗口,并在其中绘制一个初始位置在(100, 100)的黑色矩形,每次循环矩形会向右下角移动5个像素,当矩形碰到窗口边缘时会反向移动。