Kivy Pong Game on touch_move同时移动两个球拍



我几个月前就开始学习python了,我想开始开发自己的应用程序。我选择了Kivy,下面是我的教程。

本教程使用以下代码添加触摸和移动:

def on_touch_move(self, touch):
if touch.x < self.width / 1 / 4:
self.player1.center_y = touch.y
if touch.x > self.width * 3 / 4:
self.player2.center_y = touch.y

当我使用这个代码时,我的两个球拍同时移动。我添加了一些括号:

def on_touch_move(self, touch):
if touch.x < self.width / (1 / 4):
self.player1.center_y = touch.y
if touch.x > self.width * 3 / 4:
self.player2.center_y = touch.y

在这之后,我可以移动我的左手划桨,但我的右手也移动了左手划桨。

我最终使用了kivy网站上的代码,它确实起了作用:

def on_touch_move(self, touch):
if touch.x < self.width/3:
self.player1.center_y = touch.y
if touch.x > self.width - self.width/3:
self.player2.center_y = touch.y

有人能解释一下为什么一个代码能正常运行,为什么另一个不能正常运行吗?提前感谢!

您的if条件与Kivy的条件不同,因此它们不会同时返回true。

让我们看看你的代码:

def on_touch_move(self, touch):
if touch.x < self.width / (1 / 4):
self.player1.center_y = touch.y
if touch.x > self.width * 3 / 4:
self.player2.center_y = touch.y
# which simplifies to ↓ because dividing by a quarter is the same as multiplying by four
def on_touch_move(self, touch):
if touch.x < self.width * 4: # will always be true (checking if touching anywhere on 4 times the screen width)
self.player1.center_y = touch.y
if touch.x > self.width * 3 / 4: # checking if touching last quarter of screen
self.player2.center_y = touch.y

现在让我们简化Kivy的代码:

def on_touch_move(self, touch):
if touch.x < self.width / 3: # checking if touching first third of screen
self.player1.center_y = touch.y
if touch.x > self.width * 2 / 3: # checking if touching last third of screen
self.player2.center_y = touch.y

正如您所看到的,您的第一个if语句始终处于激发状态,因此您可能希望将其更改为:if touch.x < self.width * 1 / 4:将检查第一季度

最新更新