2017-12-18 11 views
1

私は現在動いているスクエアをプログラミングしています。私は自分の鍵でそれを制御し、境界から外れないようにしたい。しかし、境界の外に出ないようにすることはできません(窓の側面)。ここに私のコードは次のとおりです。pygame moving squareはバウンダリー外に出る

import sys, pygame 
pygame.init() 

width, height = 700, 700 

screen = pygame.display.set_mode((width, height), pygame.RESIZABLE) 
clock = pygame.time.Clock() 

FPS = 120 
x1 = 0 
y1 = 0 

xmb1 = False 
xmf1 = False 
ymb1 = False 
ymf1 = False 
squareh = 50 
squarew = 50 
squares = 3 

BLACK = (0,0,0) 
WHITE = (255,255,255) 

while 1: 
    for event in pygame.event.get(): 
     if event.type == pygame.QUIT: 
      pygame.display.quit() 
      sys.exit() 
     elif event.type == pygame.KEYDOWN: 
      if event.key == pygame.K_LEFT: 
       xmb1 = True 
      if event.key == pygame.K_RIGHT: 
       xmf1 = True 
      if event.key == pygame.K_UP: 
       ymb1 = True 
      if event.key == pygame.K_DOWN: 
       ymf1 = True 
     elif event.type == pygame.KEYUP: 
      if event.key == pygame.K_LEFT: 
       xmb1 = False 
      if event.key == pygame.K_RIGHT: 
       xmf1 = False 
      if event.key == pygame.K_UP: 
       ymb1 = False 
      if event.key == pygame.K_DOWN: 
       ymf1 = False 

    if x1 == 0: 
     xmb1 = False 
    if y1 == 0: 
     ymb1 = False 
    if x1 == width - squarew: 
     xmfl = False 
    if y1 == height - squareh: 
     ymf1 == False 
    if xmb1: 
     x1 -= squares 
    if xmf1: 
     x1 += squares 
    if ymb1: 
     y1 -= squares 
    if ymf1: 
     y1 += squares 
    screen.fill(BLACK) 
    pygame.draw.rect(screen, WHITE, (x1, y1, squareh, squarew), 0) 
    pygame.display.flip() 
    clock.tick(FPS) 

誰がこの問題を解決する方法を知っていますか?私は最近、pygameの学んだ

答えて

1

あなたはしかし、あなたの質問に答えるために

(1で)ではなくxmf1の(小文字のLと)xmflという変数を持っている(最後の夜を!):

この

if xmb1 and not (x1 <= 0): 
    x1 -= squares 
if xmf1 and not (x1 + squarew >= width): 
    x1 += squares 
if ymb1 and not (y1 <= 0): 
    y1 -= squares 
if ymf1 and not (y1 + squareh >= height): 
    y1 += squares 

if xmb1: 
    x1 -= squares 
if xmf1: 
    x1 += squares 
if ymb1: 
    y1 -= squares 
if ymf1: 
    y1 += squares 

:私はこのコードを変更します

私はy方向を後方に持っているかもしれません...それは私がパイゲームを使ってからしばらくありました。

コードが行うことは、私たちがすでにボードの端にいるかどうかをチェックすることです。私たちが端にいたら、それ以上の動きを許さないでください。私たちが端にいなければ、先に進んでください。

これが役立つかどうか、私があなたに質問に答えられるかどうかを教えてください。

+0

ありがとうございました! – 05bs001