2017-02-20 72 views
1

我在Python中製作Pong遊戲。爲此,我正在使用pygame。我試圖讓一個圖像在按鍵上不斷移動。我嘗試了多種方法,但都沒有奏效。這裏是我的機芯代碼:如何使用按鍵在pygame/python中移動圖像?

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!我有一個除外,這就是爲什麼嘗試在那裏。謝謝您的幫助!

+0

您是否收到錯誤?你說它不工作,但什麼不工作?你也調用'key.get_pressed()',但它應該是'pygame.key.get_pressed()',如果我沒有錯。 –

回答

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) 
+0

謝謝,工作完美!與我在改變所有內容之前使用的代碼沒有什麼不同,但我認爲'event.type == QUIT'因爲它是分開的而被搞亂了。但是,當我按住鍵時,我怎樣才能持續移動?謝謝! :) –

+1

不要擔心,修復它! –