我正在尝试绘制一个简单的矩形行,但是当我执行此代码时,它不会向屏幕绘制任何内容。我无法弄清楚为什么。我可能忽略了一些非常明显的事情,但我只需要有人指点我。
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,我找到了一个解决方案:而不是范围(10)放入范围(1,100,10),并将x更改为列。但是我仍然不明白为什么我的代码不起作用,因为它对我来说似乎没问题。
答案 0 :(得分:2)
你永远不会在循环中将x
重置为零,因此广场会快速从屏幕右侧分流。
screen.fill(black)
x=0
for column in range(10):
pygame.draw.rect(screen,white,[x,0,width, height])
x += width
结果:
答案 1 :(得分:0)
您的变量x
在2帧内超出了屏幕范围,因为您不断为其添加宽度。你的盒子正在被绘制,但它们在屏幕上移动的速度太快而无法看到(你只是看不到它在你开始时再次将屏幕涂成黑色的每一帧)。
在每帧上将x重置为零,您将看到方框:
# line 48
x = 0
for column in range(10):
pygame.draw.rect(screen,white,[x,0,width, height])
x += width