Reputation: 37
I am trying to move an image and wanted to press some key on the keyboard to move dynamically through the window.
I'm doing it this way below, but notice that the image only moves when I press the keyboard key and move the mouse along:
import sys
import pygame
UP = False
DOWN = False
LEFT = False
RIGHT = False
pygame.init()
screen = pygame.display.set_mode((800, 600))
clock = pygame.time.Clock()
img = pygame.image.load('tank.png')
tank = [(img), (50, 50)]
while True:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
UP = True
elif event.key == pygame.K_DOWN:
DOWN = True
elif event.key == pygame.K_LEFT:
LEFT = True
elif event.key == pygame.K_RIGHT:
RIGHT = True
if event.type == pygame.KEYUP:
if event.key == pygame.K_UP:
UP = False
elif event.key == pygame.K_DOWN:
DOWN = False
elif event.key == pygame.K_LEFT:
LEFT = False
elif event.key == pygame.K_RIGHT:
RIGHT = False
if (UP):
tank = [tank[0], (tank[1][0], tank[1][1] - 10)]
elif (DOWN):
tank = [tank[0], (tank[1][0], tank[1][1] + 10)]
elif (LEFT):
tank = [tank[0], (tank[1][0] - 10, tank[1][1])]
elif (RIGHT):
tank = [tank[0], (tank[1][0] + 10, tank[1][1])]
screen.fill((0,0,0))
screen.blit(tank[0], tank[1])
pygame.display.update()
I didn't want that to happen, I just want to press the keyboard key and move the image freely regardless of whether or not the mouse moves through the window.
How can I solve this problem?
Upvotes: 2
Views: 115
Reputation: 6395
Your problem is simple - your movement code is not part of the outer while, but the inner event-loop. This results in the movement only executed in case of an event happening. Mouse or keyboard is irrelevant. See this for a somewhat improved and working version:
import sys
import pygame
def main():
pressed = set()
pygame.init()
screen = pygame.display.set_mode((800, 600))
clock = pygame.time.Clock()
img = pygame.image.load('tank.jpg')
tank = [(img), (50, 50)]
while True:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
if event.type == pygame.KEYDOWN:
pressed.add(event.key)
if event.type == pygame.KEYUP and event.key in pressed:
pressed.remove(event.key)
if pygame.K_UP in pressed:
tank = [tank[0], (tank[1][0], tank[1][1] - 10)]
if pygame.K_DOWN in pressed:
tank = [tank[0], (tank[1][0], tank[1][1] + 10)]
elif pygame.K_LEFT in pressed:
tank = [tank[0], (tank[1][0] - 10, tank[1][1])]
elif pygame.K_RIGHT in pressed:
tank = [tank[0], (tank[1][0] + 10, tank[1][1])]
screen.fill((0,0,0))
screen.blit(tank[0], tank[1])
pygame.display.update()
if __name__ == '__main__':
main()
Upvotes: 3