如何限制桨的运动?

时间:2014-04-07 02:25:51

标签: python pygame

我想这样做,以便这个乒乓球游戏中的球拍不会移动到游戏窗口的两侧。 (不会向右或向左移动太远)。我已经尝试过写一个解决方案,并且只能将屏幕完全移出屏幕,但只有不到一半的人仍可以离开屏幕。

如何修改我的代码,以便拨片根本不会移出屏幕?游戏窗口设置为600乘600.我使用update_paddle移动球拍。

这是我的桨类/方法:

import pygame

class Paddle:
   def __init__(self, x, y, c, w, h):
       self.x = x
       self.y = y
       self.color = c
       self.width = w
       self.height = h

   def draw_paddle(self, screen):
      pygame.draw.rect(screen, self.color,
         pygame.Rect(self.x, self.y, self.width, self.height), 0)

   def update_paddle(self, dir, dx):
      if (dir == 'left') and (self.x >= 0):
         self.x = self.x - dx
      elif (dir == 'right') and (self.x + self.width <= 600):
         self.x += dx

   def get_left(self):
      if (self.x < 300):
         return self.x

   def get_right(self):
      if (self.x >= 300):
         return self.x

3 个答案:

答案 0 :(得分:2)

我们想要说的是桨位,(它的顶部,左角,因为应该定位使得桨从不离开屏幕,或者更确切地说:

  • 球拍的左侧不得比屏幕左边缘向左移动,并且
  • 球拍的右侧不得比屏幕右边缘向右移动。

等等,让我们看一下左右调整拨片位置的方法。那只是update_paddle(),它有左右移动的独立路径。让我们看看你的错误,从左边开始:

if (dir == 'left') and (self.x >= 0):
    self.x = self.x - dx

x正好为零时,所有测试都通过,因此允许桨进一步向左移动,它可能会略微偏离屏幕;我们不希望这样,我们想让它远离屏幕。最好的办法是让它一直到达左边缘,然后将其保留在屏幕上:

if dir == 'left':
    self.x = max(self.x - dx, 0)

右移动也会出现同样的问题:

else:  # LEM: dir == 'right':
   self.x = min(self.x + dx, 600 - self.width)

答案 1 :(得分:1)

您的结束位置需要测试右侧的self.x + self.width / 2和左侧的self.x-self.width / 2以及self.y和self.height / 2的类似情况。顶部和底部。这是基于self.x,self.y是桨的中心。由于你可以防止桨板的中心离开屏幕,你会发现它位于边缘,使桨板的其余部分离开屏幕。

答案 2 :(得分:1)

问题是,您正在测试是否已经已经已经离开了屏幕,而不是测试您是否将会 self.x为1且您向左移动了10个像素,则您将使用当前代码以-9结束。

我建议无条件地进行移动,然后将你的位置固定在屏幕上。

def update_paddle(self, dir, dx):
   if (dir == 'left'): # always move by dx, even if that moves you off the screen
      self.x -= dx
   else: # (dir == 'right')
      self.x += dx

   self.x = min(max(self.x, 0), 600 - self.width) # clamp to screen afterwards

与屏幕边界问题无关,我还建议让负dx表示向左移动,而不是使用dir参数。对于两个方向,函数的第一部分只是self.x += dx