[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]

Re: [pygame] moving a box diagnally





On Sun, Sep 19, 2010 at 5:08 AM, kevin hayes <kevinosky@xxxxxxxxx> wrote:
Hi, I'm just beginning to learn python and pygame. I've gone through the first four chapters of "Game Programming, The L-line, the Express Line to Learning. ÂRight now I'm working on an exercise that asks me to "make a box that moves in a diagonal path. Can someone tell me why when I run the code the program only executes while I move the mouse? Also, can you tell me how i can change my code to avoid this? Thanks, Kevin

here is my code:

import pygame
pygame.init()

screen = pygame.display.set_mode((640, 480))
pygame.display.set_caption("Diagonal Red Square")

background = "">
background = "">
background.fill((0, 0, 0))

box = pygame.Surface((20, 20))
box = box.convert()
box.fill((255, 0, 0))

box_x = 0 Â #box variable for the x-axis
box_y = 0 Â #" " y-axis

clock = pygame.time.Clock()
keepGoing = True

while keepGoing:
ÂÂ Âclock.tick(30)
ÂÂ Âfor event in pygame.event.get():
ÂÂ Â Â Âif event.type == pygame.QUIT:
ÂÂ Â Â Â Â ÂkeepGoing = False

ÂÂ Â Â Âbox_x += 5
ÂÂ Â Â Âbox_y += 5

ÂÂ Âif box_y > screen.get_height(): Â#checking for screen boundaries
ÂÂ Â Â Â Â Âbox_y = 0
ÂÂ Âif box_x > screen.get_width():
ÂÂ Â Â Â Â Âbox_x = 0
ÂÂ ÂÂ

ÂÂ Âscreen.blit(background, (0, 0))
ÂÂ Âscreen.blit(box, (box_x, box_y))
ÂÂ Âpygame.display.flip()

pygame.quit()

You change the box position only if an event is present, so you need to move the mouse or press keys to move.

Move out of the event loop the lines that change the position, that is, dedent one level the lines:
box_x += ...
box_y += ...

--
claudio