Reputation: 837
I'm trying to draw a simple row of rectangles, but somewhow when I execute this code it doesn't draw anything to the screen. I can't figure out why. I am probably overlooking something very obvious, but I just need someone to point me to it.
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()
I have looked around on stackoverflow and Google, and I found one solution: instead of range(10) put in range(1,100,10),and change x into column. But I still do not understand why my code doesn't work, because it seems alright to me.
Upvotes: 0
Views: 484
Reputation: 19534
Your variable x
is growing out of bounds of your screen within 2 frames because you keep adding width to it. Your boxes are being drawn, but they move off screen too quickly to see (you just don't see it draw as each frame you paint the screen black again at the start).
Reset x to zero on each frame and you'll see the boxes:
# line 48
x = 0
for column in range(10):
pygame.draw.rect(screen,white,[x,0,width, height])
x += width
Upvotes: 0
Reputation: 76184
You never reset x
to zero within the loop, so the squares are quickly shunted off the right side of the screen.
screen.fill(black)
x=0
for column in range(10):
pygame.draw.rect(screen,white,[x,0,width, height])
x += width
Result:
Upvotes: 2