简体   繁体   English

如何使用keypress在pygame / python中移动图像?

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

I am making a Pong game in Python. 我正在用Python制作Pong游戏。 To do this, I am using pygame. 为此,我正在使用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! 缩进是正常的,我是stackoverflow的新手! I have an except, which is why the try is there. 我有一个除外,这就是尝试的原因。 Thanks for the help! 谢谢您的帮助!

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 ?). 此代码将在向下箭头键向下移动图像被挤压和了,如果向上箭头键被按下(你应该不会改变Y轴和wheaty如果用户按下向下键,而不是改变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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM