Wednesday, 15 May 2013

python pygame dont recognize keyboard event -



python pygame dont recognize keyboard event -

i want create programme move rectangle via keyboard when runs doesnt moves dont understand event commands cant find whats wrong have done think problem sequence of command beginner cant find can help me thnks!

import pygame import sys pygame.locals import * fps = 30 fpsclock = pygame.time.clock() w = 640 h = 420 bluish = (0, 0, 255) white = (255, 255, 255) x = w / 3 y = 350 boxa = 20 movex = 0 def drawwindow(): global screen pygame.init() screen = pygame.display.set_mode((w, h)) screen.fill(blue) def drawbox(box): if box.right > (w - boxa): box.right = (w - boxa) if box.left < 0: box.left = 0 pygame.draw.rect(screen, white, box) def main(): global x global movex drawwindow() box1 = pygame.rect(x, y, boxa, boxa) drawbox(box1) while true: event in pygame.event.get(): if event.type == quit: pygame.quit() sys.exit() if event.type == keydown: if event.key == k_right: movex = +4 if event.key == k_left: movex = -4 if event.type == keyup: if event.key == k_right: movex = 0 if event.key == k_left: movex = 0 x += movex pygame.display.update() fpsclock.tick(fps) if __name__ == '__main__': main()

keyboard events beingness accepted properly. can verified sticking print statement within 1 of if event.key == ... blocks.

one of problems never redrawing box after drawing it. every iteration of game loop should redraw background (ideally area changes, that's later) , box in new position. this:

while true: # [event handling code omitted brevity] x += movex drawwindow() drawbox(box1) pygame.display.update() fpsclock.tick(fps)

however there's problem. changing x or movex has no effect on anything, because not used anywhere 1 time main loop entered. rather x += movex, box move if x attribute changed, in next code:

while true: # [event handling code omitted brevity] box1.x += movex # line changed drawwindow() # line added drawbox(box1) # line added pygame.display.update() fpsclock.tick(fps)

running code changes above, box moves.

python events pygame

No comments:

Post a Comment