Python PyGame 使用 for 循环绘制矩形

标签 python pygame

我是 PyGame 新手,我正在使用《Beginning Game Development with Python and PyGame》一书进行学习。有一个示例( list 4-9),作者表示脚本将在 PyGame 屏幕上绘制十个随机放置、随机着色的矩形。这是书中的代码:

import pygame 
from pygame.locals import *
from sys import exit
from random import *

pygame.init()

screen = pygame.display.set_mode((640, 480), 0,32)
while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            exit()
    screen.lock()
    for count in range(10):
        random_color = (randint(0,255), randint(0,255), randint(0,255))
        random_pos = (randint(0,639), randint(0,479))
        random_size = (639-randint(random_pos[0], 639), 479-randint(random_pos[1],479))
        pygame.draw.rect(screen, random_color, Rect(random_pos, random_size))
    screen.unlock()
    pygame.display.update()

当我这样做时会发生什么(这就是我逻辑上期望发生的情况)是它绘制了无限多个矩形。它只是继续执行 for 循环,因为 while 循环始终为 True。我在网上搜索过相关信息,并尝试移动显示更新,但这些东西不起作用。这让我发疯!

谢谢!

最佳答案

看起来你已经知道为什么它用矩形绘制无限了。

我猜你想一次绘制 10 个具有随机大小、位置和颜色的随机矩形。

然后你可以这样做:

import pygame 
from pygame.locals import *
from sys import exit
from random import *

pygame.init()

screen = pygame.display.set_mode((640, 480), 0,32)

class Rectangle:
    def __init__(self, pos, color, size):
        self.pos = pos
        self.color = color
        self.size = size
    def draw(self):
        pygame.draw.rect(screen, self.color, Rect(self.pos, self.size))

rectangles = []     

for count in range(10):
    random_color = (randint(0,255), randint(0,255), randint(0,255))
    random_pos = (randint(0,639), randint(0,479))
    random_size = (639-randint(random_pos[0], 639), 479-randint(random_pos[1],479))

    rectangles.append(Rectangle(random_pos, random_color, random_size))



while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            exit()
    screen.lock()
    for rectangle in rectangles:
        rectangle.draw()
    screen.unlock()
    pygame.display.update()

关于Python PyGame 使用 for 循环绘制矩形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27628659/

相关文章:

python - Sphinx 自动摘要指令中的 "generated"选项是什么?

python - 如何将长度为 n 的元组解压缩为 m<n 变量

python - 内置范围或 numpy.arange : which is more efficient?

python-3.x - Pygame TypeError : 'int' object is not callable

python - 在 Windows 7 上以编程方式更改系统范围内的扬声器平衡

python - 在 Python 中使用 SocketHandler 记录时捕获错误

python - 窗口在 10 秒内未关闭

python - 似乎无法在 Sprite 上的 pygame 中渲染多行

python - 我在 Pygame、Python 3 中制作的这个简单游戏遇到了滞后问题。我该如何解决这个问题?

python - 在窗口中创建坐标查找