Python PyGame 使用 for 循环绘制矩形 [英] Python PyGame draw rectangles using for loop

查看:65
本文介绍了Python PyGame 使用 for 循环绘制矩形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 PyGame 的新手,我正在学习使用 Python 和 PyGame 开始游戏开发这本书.有一个例子(清单 4-9),作者说一个脚本将在 PyGame 屏幕上绘制十个随机放置、随机着色的矩形.这是书中的代码:

I'm new to PyGame and I am learning using the book Beginning Game Development with Python and PyGame. There is an example (Listing 4-9) where the author says a script will draw ten randomly placed, randomly colored rectangles on the PyGame screen. Here is the code from the book:

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.我在网上搜索过这个,我尝试移动显示更新,但这些东西没有用.它让我发疯!

What happens when I do this (and this is what I would expect to happen logically) is that it draws infinitely many rectangles. It just keeps doing the for loop because the while loop is always True. I have searched online about this, and I tried moving the display update around, but those things didn't work. It is driving me crazy!

谢谢!

推荐答案

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

Looks like you already knew why it were drawing infinite with rectangles.

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

I guess you want to draw 10 random rectangles with random size, pos and color once.

然后你可以这样做:

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 循环绘制矩形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆