Kivy Pong游戏on_touch_move可以同时移动两个球拍

问题描述

几个月前,我开始学习python,我想开始开发自己的应用程序。我选择了Kivy,并且跟随this tutorial

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

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

有人可以解释为什么一个代码可以正常运行,为什么另一个不能正常运行吗? 预先感谢!

解决方法

如果您的条件不同于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: 它将检查第一季度

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...