2017-01-28 2 views
1

파이 게임에서 뭔가를 만들기 시작했으나 왼쪽이나 오른쪽으로 이동할 때 문제가 발생했습니다. 내가 오른쪽 화살표 키를 누르는 것에서 왼쪽으로 누르는 것에서 오른쪽으로 한 개를 놓아 버리면 블록이 움직이지 않게됩니다. 이 내 코드파이 게임이 왼쪽 및 오른쪽으로 이동합니다.

bg = "sky.jpg" 
ms = "ms.png" 
import pygame, sys 
from pygame.locals import * 
x,y = 0,0 
movex,movey=0,0 
pygame.init() 
screen=pygame.display.set_mode((664,385),0,32) 
background=pygame.image.load(bg).convert() 
mouse_c=pygame.image.load(ms).convert_alpha() 
m = 0 
pygame.event.pump() 
while 1: 
    for event in pygame.event.get(): 
     if event.type == QUIT: 
      pygame.quit() 
      sys.exit() 
     if event.type==KEYDOWN: 
      if event.key==K_LEFT: 
       movex =-0.5 
       m = m + 1 
      if event.key==K_RIGHT: 
       movex=+0.5 
       m = m + 1 
     elif event.type == KEYUP: 
      if event.key==K_LEFT and not event.key==K_RIGHT: 
        movex = 0 
      if event.key==K_RIGHT and not event.key==K_LEFT: 
        movex =0 

    x+=movex 
    y=200 
    screen.blit(background, (0,0)) 
    screen.blit(mouse_c,(x,y)) 
    pygame.display.update() 

오른쪽 화살표 키를 누르면 왼쪽 화살표 키는 정지의를 대신 갈 것이라고 발표되면 내가 그렇게 변경할 수있는 방법이 무엇입니까? P.S. 저는 여전히 파이 게임을 배우고 있으며 모듈에 아주 익숙합니다. 이것이 어리석은 질문 인 것처럼 보이면 나는 유감 스럽다 그러나 나는 그것에 어떤 응답도 찾아 낼 수 없었다.

+0

ms.png은'event.key하지 확인 느낌이 없도록 event.key' 하나만 값을 유지할 수있는 블록 – 1234USSR4321

+0

'이다 == 다음 예는 K_RIGHT :'벌써'event.key == K_LEFT' – furas

답변

0

귀하의 문제는 당신이

if event.key==K_LEFT and not event.key==K_RIGHT: 

로를 keyDown 이벤트를 테스트 할 때 event.key==K_LEFT에 해당하는 경우 때문에 이벤트의 핵심은 결국 K_LEFT을하기 때문에 항상 그것은 또한 항상 (not event.key==K_RIGHT이며, 진정한 얻을 수 있다는 것입니다).

이런 종류의 문제에 대한 나의 접근 방식은 동작의 의도와 을 구분하는 것입니다. 그래서, 키 이벤트, 단순히 다음과 같이 일하도록되어 어떤 조치를 을 추적 할 것 :

moveLeft = False 
moveRight = False 

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: moveLeft = True 
     if event.key == K_RIGHT: moveRight = True 
    elif event.type == KEYUP: 
     if event.key == K_LEFT: moveLeft = False 
     if event.key == K_RIGHT: moveRight = False 

을 그리고, 루프의 "주"부분에, 당신은 기반의 조치를 취할 수 있습니다 입력과 같은 :

while True: 
    for event in pygame.event.get(): 
    ... 
    if moveLeft : x -= 0.5 
    if moveRight : x += 0.5 
0

마지막으로 누른 버튼을 추적하는 대기열을 만들 수 있습니다. 오른쪽 화살표 키를 누르면 속도가 목록에 먼저 표시되고 왼쪽 화살표 키를 누르면 새 속도가 목록에 먼저 입력됩니다. 그래서 마지막에 눌려진 버튼이 항상 목록에서 첫 번째가됩니다. 그런 다음 릴리스 할 때 목록에서 버튼을 제거하기 만하면됩니다.

import pygame 
pygame.init() 

screen = pygame.display.set_mode((720, 480)) 
clock = pygame.time.Clock() 
FPS = 30 

rect = pygame.Rect((350, 220), (32, 32)) # Often used to track the position of an object in pygame. 
image = pygame.Surface((32, 32)) # Images are Surfaces, so here I create an 'image' from scratch since I don't have your image. 
image.fill(pygame.Color('white')) # I fill the image with a white color. 
velocity = [0, 0] # This is the current velocity. 
speed = 200 # This is the speed the player will move in (pixels per second). 
dx = [] # This will be our queue. It'll keep track of the horizontal movement. 

while True: 
    dt = clock.tick(FPS)/1000.0 # This will give me the time in seconds between each loop. 

    for event in pygame.event.get(): 
     if event.type == pygame.QUIT: 
      raise SystemExit 
     elif event.type == pygame.KEYDOWN: 
      if event.key == pygame.K_LEFT: 
       dx.insert(0, -speed) 
      elif event.key == pygame.K_RIGHT: 
       dx.insert(0, speed) 
     elif event.type == pygame.KEYUP: 
      if event.key == pygame.K_LEFT: 
       dx.remove(-speed) 
      elif event.key == pygame.K_RIGHT: 
       dx.remove(speed) 

    if dx: # If there are elements in the list. 
     rect.x += dx[0] * dt 

    screen.fill((0, 0, 0)) 
    screen.blit(image, rect) 
    pygame.display.update() 

    # print dx # Uncomment to see what's happening. 

당연히 모든 것을 깔끔하게 처리하고 Player 클래스를 만들어야합니다.

0

문제는 중복되는 주요 기능입니다; 첫 번째 오른쪽을 누른 상태에서 왼쪽으로 xmove가 먼저 1로 설정되고 -1로 변경됩니다. 하지만 다른 키를 계속 누르고 있어도 키 중 하나를 해제하고 xmove를 0으로 재설정합니다. 당신이 원하는 것은 각 키에 대한 부울을 만드는 것입니다.

demo.py :

import pygame 

window = pygame.display.set_mode((800, 600)) 

rightPressed = False 
leftPressed = False 

white = 255, 255, 255 
black = 0, 0, 0 

x = 250 
xmove = 0 

while True: 
    window.fill(white) 
    pygame.draw.rect(window, black, (x, 300, 100, 100)) 
    for event in pygame.event.get(): 
     if event.type == pygame.KEYDOWN: 
      if event.key == pygame.K_RIGHT: 
       rightPressed = True 
      if event.key == pygame.K_LEFT: 
       leftPressed = True 
     if event.type == pygame.KEYUP: 
      if event.key == pygame.K_RIGHT: 
       rightPressed = False 
      if event.key == pygame.K_LEFT: 
       leftPressed = False 
    xmove = 0 
    if rightPressed: 
     xmove = 1 
    if leftPressed: 
     xmove = -1 
    x += xmove 
    pygame.display.flip() 
+0

그것은 내 답변의 정확한 사본입니다. – Meyer

+0

안녕 마이어, 나는 너의 답을 보지 못했다. 나는 당신의 코드를 훔치지 않았거나 전혀 당신을 복사하려고하지 않을 것이라고 약속 할 수 있습니다. – XCode

+0

아무 걱정없이, 그것은 결국 상당히 명백한 접근법입니다. 같은 답변을 두 번 게시하기 전에 다른 답변을 반드시 읽으십시오. – Meyer

관련 문제