2017-01-28 7 views
0

현재 파이 게임으로 브레이크 아웃 게임의 간단한 버전을 만들고자합니다. 문제는 내가 박쥐를 화면에서 움직이기를 원한다는 것입니다.이 때문에 이벤트를 처리하고 오른쪽/왼쪽 화살표를 누르면 박쥐가 즉시 오른쪽/왼쪽으로 움직입니다. 그러나 내 코드가 작동하지 않습니다; 키를 누를 때마다 단순히 움직이는 것보다 박쥐의 길이가 늘어나고 있습니다. 코드와 예제를 살펴 보았지만 여전히 잃어 버렸습니다. 화면에 뭔가 블럭 전송하면파이 게임과의 브레이크 아웃 게임 - 이벤트 처리하기

import pygame, sys 

pygame.init() 

width, height = 800, 600 
screen = pygame.display.set_mode([width, height]) 
bat_speed = 30 
bat = pygame.image.load('bat.png').convert() 
batrect = bat.get_rect() 

while 1: 
    for event in pygame.event.get(): 
     if event.type == pygame.QUIT: 
      sys.exit() 
     if event.type == pygame.KEYDOWN: 
      if event.key == pygame.K_LEFT:       
       batrect = batrect.move(-bat_speed, 0)  
       if (batrect.left < 0):       
        batrect.left = 0  
      if event.key == pygame.K_RIGHT:      
       batrect = batrect.move(bat_speed, 0) 
       if (batrect.right > width):        
        batrect.right = width 

    screen.blit(bat, batrect) 
    pygame.display.flip() 

pygame.quit() 

답변

0

가 거기있을 거 :

여기 내 코드입니다. 무슨 일이 일어나고있는 것은 박쥐가 다른 위치에서 블리 팅하고있어 박쥐의 폭이 늘어나는 것처럼 보입니다. 간단한 수정은 박쥐를 그리기 전에 화면을 지우는 것입니다. 당신이 모든 조건을 확인하지 않을 때 위처럼

while 1: 
    for event in pygame.event.get(): 
     if event.type == pygame.QUIT: 
      sys.exit() 
     elif event.type == pygame.KEYDOWN: 
      if event.key == pygame.K_LEFT:       
       batrect = batrect.move(-bat_speed, 0)  
       if (batrect.left < 0):       
        batrect.left = 0  
      elif event.key == pygame.K_RIGHT:      
       batrect = batrect.move(bat_speed, 0) 
       if (batrect.right > width):        
        batrect.right = width 

    screen.fill((0, 0, 0)) # This will fill the screen with a black color. 
    screen.blit(bat, batrect) 
    pygame.display.flip() 

또한, 대신 여러 ifelif를 사용합니다.