首页 > 代码库 > pygame学习之绘制移动的矩形

pygame学习之绘制移动的矩形

 1 import pygame
 2 from pygame.locals import *
 3 
 4 pygame.init()
 5 screen = pygame.display.set_mode((600, 500))
 6 pygame.display.set_caption("drawing a rectangle")
 7 pos_x = 300
 8 pos_y = 250
 9 vel_x = 2                            # 设置速度变量
10 vel_y = 1
11 while True:
12     for event in pygame.event.get():
13         if event.type in (QUIT, KEYDOWN):
14             exit()
15     screen.fill((0, 0, 200))
16     pos_x += vel_x
17     pos_y += vel_y
18 
19     if pos_x > 500 or pos_x < 0:
20         vel_x = -vel_x                       # 让矩形在窗口范围内移动
21     if pos_y > 400 or pos_y < 0:
22         vel_y = -vel_y
23     color = 255, 255, 0
24     width = 0
25     pos = pos_x, pos_y, 100, 100             # 矩形长和宽都为100
26     pygame.draw.rect(screen, color, pos, width)
27     pygame.display.update()

 

pygame学习之绘制移动的矩形