2014-03-02 147 views
0

所以我想用python和pygame模塊製作遊戲。我從YouTube視頻中獲得了這些代碼,但它不起作用。當你按下箭頭鍵時,代碼應該會讓球移動,但是每當我按下箭頭鍵球就會保持原位。如果您發現任何問題,請您糾正我的代碼。這是我的代碼:Python遊戲開發幫助

bif="hills.jpg" 
mif="ball.png" 

import pygame, sys 
from pygame.locals import * 

pygame.init() 

screen=pygame.display.set_mode((604,367),0,32) 

background=pygame.image.load(bif).convert() 
mouse_c=pygame.image.load(mif).convert_alpha() 

x,y=0,0 
movex, movey=0,0 

while True: 

    for event in pygame.event.get(): 
     if event.type == QUIT: 
      pygame.quit() 
      sys.exit() 
      if event.type==KEYDOWN: 
       if event.key==K_LEFT: 
        movex=-1 
       elif event.key==K_RIGHT: 
        movex=+1 
       elif event.key==K_UP: 
        movey=-1 
       elif event.key==K_DOWN: 
        movey=+1 
      if event.type==KEYUP: 
       if event.key==K_LEFT: 
        movex=0 
       elif event.key==K_RIGHT: 
        movex=0 
       elif event.key==K_UP: 
        movey=0 
       elif event.key==K_DOWN: 
        movey=0 
    x+=movex 
    y+=movey 

    screen.blit(background,(0,0)) 
    screen.blit(mouse_c,(x,y)) 

    pygame.display.update() 

回答

0

您的移動球的代碼僅在event.type == QUIT:時執行。這裏是正確縮進的代碼

bif="hills.jpg" 
mif="ball.png" 

import pygame, sys 
from pygame.locals import * 

pygame.init() 

screen=pygame.display.set_mode((604,367),0,32) 

background=pygame.image.load(bif).convert() 
mouse_c=pygame.image.load(mif).convert_alpha() 

x,y=0,0 
movex, movey=0,0 

while True: 

    for event in pygame.event.get(): 
     if event.type == QUIT: 
      pygame.quit() 
      sys.exit() 
     if event.type==KEYDOWN: 
      if event.key==K_LEFT: 
       movex=-1 
      elif event.key==K_RIGHT: 
       movex=+1 
      elif event.key==K_UP: 
       movey=-1 
      elif event.key==K_DOWN: 
       movey=+1 
     if event.type==KEYUP: 
      if event.key==K_LEFT: 
       movex=0 
      elif event.key==K_RIGHT: 
       movex=0 
      elif event.key==K_UP: 
       movey=0 
      elif event.key==K_DOWN: 
       movey=0 
    x+=movex 
    y+=movey 

    screen.blit(background,(0,0)) 
    screen.blit(mouse_c,(x,y)) 

    pygame.display.update()