Ollie R
Ollie R

Reputation: 31

How to move an image in pygame/python with keypress?

I am making a Pong game in Python. To do this, I am using pygame. I am trying to make an image move continuously on a keypress. I have tried multiple methods, but none have worked. here is my code for the movement:

import pygame, sys
from pygame.locals import *
import time

try: #try this code
pygame.init()

FPS = 120 #fps setting
fpsClock = pygame.time.Clock()

#window
DISPLAYSURF = pygame.display.set_mode((1000, 900), 0, 32)
pygame.display.set_caption('Movement with Keys')

WHITE = (255, 255, 255)
wheatImg = pygame.image.load('gem4.png')
wheatx = 10
wheaty = 10
direction = 'right'

pygame.mixer.music.load('overworld 8-bit.WAV')
pygame.mixer.music.play(-1, 0.0)
#time.sleep(5)
#soundObj.stop()

while True: #main game loop
     DISPLAYSURF.fill(WHITE)

     bign = pygame.event.get()
     for event in bign:
         if event.type == pygame.KEYDOWN:
             if event.key == pygame.K_d:
                 pygame.mixer.music.stop()
     keys_pressed = key.get_pressed()
     if keys_pressed[K_d]:
         wheatx += 20

     #events = pygame.event.get()
     #for event in events:
      #   if event.type == pygame.KEYDOWN:
       #      if event.key == pygame.K_p:
        #         pygame.mixer.music.stop()
         #        time.sleep(1)
          #       pygame.mixer.music.load('secondscreen.wav')
           #      pygame.mixer.music.play()

     DISPLAYSURF.blit(wheatImg, (wheatx, wheaty))

     pygame.display.update()
     fpsClock.tick(FPS)


     for event in pygame.event.get():
         if event.type == QUIT:
             pygame.quit()
             sys.exit()

Indentation is normal, I am new to stackoverflow! I have an except, which is why the try is there. Thanks for the help!

Upvotes: 1

Views: 1008

Answers (1)

smoggers
smoggers

Reputation: 3192

This code will move the image down upon the down arrow key being pressed and up if the up arrow key is pressed (should you not be changing the Y-axis and wheaty if the user presses the down key rather than altering wheatx ?). Do similar for the other arrow keys.

while True:
     DISPLAYSURF.fill(WHITE)
     bign = pygame.event.get()
     for event in bign:
         if event.type == QUIT:
             pygame.quit()
             sys.exit()
         elif event.type == pygame.KEYDOWN:
             pygame.mixer.music.stop()
             if event.key == pygame.K_DOWN:
                 wheaty +=20
             elif event.key == pygame.K_UP:
                 wheaty -= 20
     DISPLAYSURF.blit(wheatImg, (wheatx, wheaty))
     pygame.display.update()
     fpsClock.tick(FPS)

Upvotes: 1

Related Questions