gpt4 book ai didi

Python PyGame 使用 for 循环绘制矩形

转载 作者:行者123 更新时间:2023-11-30 23:16:41 24 4
gpt4 key购买 nike

我是 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com