0

我正在尝试绘制一排简单的矩形,但不知何故,当我执行此代码时,它不会在屏幕上绘制任何内容。我不知道为什么。我可能忽略了一些非常明显的东西,但我只需要有人指出它。

我的代码:

import pygame

# Define some colors
black    = (   0,   0,   0)
white    = ( 255, 255, 255)
green    = (   0, 255,   0)
red      = ( 255,   0,   0)

pygame.init()

# Set the width and height of the screen [width,height]
size = [255,255]
screen = pygame.display.set_mode(size)

pygame.display.set_caption("My Game")
width = 20
height = 20
margin = 5
x = 0

#Loop until the user clicks the close button.
done = False

# Used to manage how fast the screen updates
clock = pygame.time.Clock()

# -------- Main Program Loop -----------
while done == False:
    # ALL EVENT PROCESSING SHOULD GO BELOW THIS COMMENT
    for event in pygame.event.get(): # User did something
        if event.type == pygame.QUIT: # If user clicked close
            done = True # Flag that we are done so we exit this loop
    # ALL EVENT PROCESSING SHOULD GO ABOVE THIS COMMENT


    # ALL GAME LOGIC SHOULD GO BELOW THIS COMMENT

    # ALL GAME LOGIC SHOULD GO ABOVE THIS COMMENT

    # ALL CODE TO DRAW SHOULD GO BELOW THIS COMMENT

    # First, clear the screen to white. Don't put other drawing commands
    # above this, or they will be erased with this command.
    screen.fill(black)
    for column in range(10):
        pygame.draw.rect(screen,white,[x,0,width, height])
        x += width

    # ALL CODE TO DRAW SHOULD GO ABOVE THIS COMMENT

    # Go ahead and update the screen with what we've drawn.
    pygame.display.flip()

    # Limit to 20 frames per second
    clock.tick(20)

# Close the window and quit.
pygame.quit()

我在 stackoverflow 和 Google 上环顾四周,找到了一个解决方案:代替 range(10) 放入 range(1,100,10),并将 x 更改为列。但我仍然不明白为什么我的代码不起作用,因为它对我来说似乎没问题。

4

2 回答 2

2

您永远不会在循环中重置x为零,因此方块会迅速从屏幕右侧分流。

screen.fill(black)
x=0
for column in range(10):
    pygame.draw.rect(screen,white,[x,0,width, height])
    x += width

结果:

在此处输入图像描述

于 2013-07-17T12:36:36.683 回答
0

您的变量x在 2 帧内超出屏幕范围,因为您不断增加它的宽度。您的框正在绘制中,但它们移出屏幕太快而无法看到(您只是看不到它绘制,因为您在开始时再次将屏幕涂黑)。

在每一帧上将 x 重置为零,您将看到以下框:

# line 48
x = 0
for column in range(10):
    pygame.draw.rect(screen,white,[x,0,width, height])
    x += width
于 2013-07-17T12:37:43.073 回答