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

时间:2017-02-20 19:47:19

标签: python

我正在用Python制作Pong游戏。为此,我正在使用pygame。我试图让一个图像在按键上连续移动。我尝试了多种方法,但都没有。这是我的运动代码:

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()

缩进是正常的,我是stackoverflow的新手!我有一个除外,这就是尝试的原因。谢谢你的帮助!

1 个答案:

答案 0 :(得分:0)

如果按下向上箭头键,此代码将向下按下向下箭头键向下移动图像(如果用户按下向下键,则不应更改Y轴和wheaty而不是改变wheatx?)。对其他箭头键执行类似操作。

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)