我是Python的新手,我正在学习使用PyGame和PyGame开始游戏开发这本书。有一个例子(清单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。我已经在网上搜索过了,我试着到处移动显示更新,但这些都不起作用。它快把我逼疯了!
谢谢!
发布于 2014-12-24 06:43:44
看起来你已经知道为什么它要用矩形画无穷大了。
我猜你想要随机绘制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()发布于 2014-12-24 07:38:30
代码确实会无限地运行。但是,内部循环确实创建了10个矩形。因此,从技术上讲,该脚本确实绘制了十个随机放置、随机着色的矩形。它这样做的次数是无限的。
注意:这是绘制十个随机放置、随机着色的矩形的部分。
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))发布于 2014-12-24 06:34:53
它将绘制许多矩形,并且它的无限退出不会绘制10次,因为除了-sys yes.It -之外,没有任何参数表示break while循环。所以你必须为此定义一个变量。
通常在事件语句中应该有一个if语句,它会将while的布尔值更改为False,并停止循环。
您可以简单地将代码更改为:
import pygame
from pygame.locals import *
from sys import exit
from random import *
pygame.init()
screen = pygame.display.set_mode((640, 480), 0,32)
count=0 #new variable for stop the loop
while count<10: #new limit
for event in pygame.event.get():
if event.type == QUIT:
exit()
screen.lock()
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))
count+=1 #variable updating after drawing each rectangle
screen.unlock()
pygame.display.update()这可能是书中的输入错误,我不知道,但是这个循环是无限的,所以你可以把它改成这样:)
https://stackoverflow.com/questions/27628659
复制相似问题