草庐IT

android - KIVY - Python 在按下按钮时继续执行

coder 2023-12-27 原文

我目前正在尝试为 IOS/Android 制作一款平台游戏,但我遇到了一个问题。我创建了两个按钮和一个角色。我希望角色在释放按钮之前一直移动。我的意思是:我可以在按下按钮时移动角色一次,但我希望它一直移动直到释放按钮。

我尝试了多种解决方案,例如我使用了 pythons 时间模块:

class Level1(Screen):
    posx = NumericProperty(0)
    posy = NumericProperty(0)
    moving = True
    i = 0
    def __init__(self, **kwargs):
        super(Level1, self).__init__(**kwargs)

    def rightmove(self):
        self.posx = self.posx+1
        time.sleep(10)

    def goright(self):
        while self.moving == True:
            self.rightmove()
            i += 1
            if i == 10:
                break


    def stopright(self):
        self.moving == False

但它不起作用。 它认为它以某种方式陷入了无限循环,因为当我按下按钮时,应用程序停止工作(“应用程序停止工作...”错误)。

我几乎不知道该如何解决这个问题。最近几个小时我一直在尝试,但还没有找到解决方案。 这是我的 .py 文件:

from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen, FadeTransition,         SlideTransition
from kivy.config import Config
from kivy.core.window import Window
from kivy.uix.label import Label
from kivy.uix.image import Image
from kivy.uix.widget import Widget
from kivy.properties import ObjectProperty, NumericProperty
from kivy.clock import Clock
from kivy.uix.floatlayout import FloatLayout
import time
Config.set('graphics','resizable',0) #don't make the app re-sizeable
#Graphics fix
 #this fixes drawing issues on some phones
Window.clearcolor = (0,0,0,1.) 

language = "english"
curr1msg = 1

class HomeScreen(Screen):
    pass  

class OptionsScreen(Screen):
    pass

class GameScreen(Screen):
    pass

class LevelScreen(Screen):
    pass

class Level1intro(Screen):
    global language
    global curr1msg
    if language == "english" and curr1msg == 1:
        pName = "Pedro"
        msg1 = """Hello my friend!
My name is Pedro and I have a problem. Will you help me?
My spanish studens have a spanish test tomorrow, but I lost the exams!
You are the only one who can help me!"""
        cont = "Press anywhere to continue..."
    elif language == "swedish" and curr1msg == 1:
        pName = "Pedro"
        msg1 = """Hejsan!
Jag är Pedro och jag har ett problem. Kan du hjälpa mig?
Mina spanska-elever har ett spanskaprov imorgon men jag har tappat bort     proven!
Du är den enda som kan hjälpa mig!"""
        cont = "Tryck på skärmen för att fortsätta..."

class Level1(Screen):
        posx = NumericProperty(0)
        posy = NumericProperty(0)
        moving = True
        i = 0
        def __init__(self, **kwargs):
            super(Level1, self).__init__(**kwargs)

        def rightmove(self):
            self.posx = self.posx+1
            time.sleep(10)

        def goright(self):
            while self.moving == True:
                self.rightmove()
                i += 1
                if i == 10:
                    break


        def stopright(self):
            self.moving == False


class ScreenManagement(ScreenManager):
    pass


presentation = Builder.load_file("main.kv")

class MainApp(App):
    def build(self):
        return presentation

if __name__ == "__main__":
    MainApp().run()

这是我的 .kv 文件:

#: import FadeTransition kivy.uix.screenmanager.FadeTransition
#: import SlideTransition kivy.uix.screenmanager.SlideTransition
ScreenManagement:
    transition: FadeTransition()
    HomeScreen:
    OptionsScreen:
    LevelScreen:
    Level1intro:
    Level1:

<HomeScreen>:
    name: 'home'

    FloatLayout:
        canvas:
            Rectangle:
                source:"images/home_background.jpg"
                size: self.size
        Image:
            source:"images/logo.png"
            allow_stretch: False
            keep_ratio: False
            opacity: 1.0
            size_hint: 0.7, 0.8
            pos_hint: {'center_x': 0.5, 'center_y': 0.9}
        Button:
            size_hint: 0.32,0.32
            pos_hint: {"x":0.34, "y":0.4}
            on_press:
                app.root.transition = SlideTransition(direction="left")
                app.root.current = "level"
            background_normal: "images/play_button.png"
            allow_stretch: False
        Button:
            size_hint: 0.25,0.25
            pos_hint: {"x":0.38, "y":0.15}
            on_press:
                app.root.transition = SlideTransition(direction="left")
                app.root.current = 'options'
            background_normal: "images/settings_button.png"

<OptionsScreen>:
    name: 'options'

<LevelScreen>
    name: "level"

    FloatLayout:
        canvas:
            Rectangle:
                source:"images/home_background.jpg"
                size: self.size
        Label:
            text: "[b]Choose Level[/b]"
            markup: 1
            font_size: 40
            color: 1,0.5,0,1
            pos: 0,250
        Button:
            size_hint: 0.1,0.1
            pos_hint: {"x": 0.1, "y": 0.8}
            on_press:
                app.root.current = "level1intro"
            Image:
                source:"images/level1.png"
                allow_stretch: True
                y: self.parent.y + self.parent.height - 70
                x: self.parent.x
                height: 80
                width: 80

        Button:
            background_normal: "images/menu_button.png"
            pos_hint: {"x": 0.4, "y": 0}
            size_hint: 0.3,0.3
            pos_hint: {"x": 0.35}
            on_press:
                app.root.transition = SlideTransition(direction="right")
                app.root.current = "home"

<Level1intro>
    name: "level1intro"

    canvas:
        Rectangle:
            source: "images/background.png"
            size: self.size
    Image:
        source: "images/dialog.png"
        pos_hint: {"y": -0.35}
        size_hint: 0.7,1.0
    Label:
        font_size: 20
        color: 1,1,1,1
        pos_hint: {"x": -0.385, "y": -0.285}
        text: root.pName
    Label:
        font_size: 15
        color: 1,1,1,1
        pos_hint: {"x": -0.15, "y": -0.4}
        text: root.msg1
    Label:
        font_size: 15
        color: 0.7,0.8,1,1
        pos_hint: {"x": 0.025, "y": -0.449}
        text: root.cont
        on_touch_down: 
            app.root.transition = FadeTransition()
            app.root.current = "level1"

<Level1>
    name: "level1"
    canvas:
        Rectangle:
            source: "images/background.png"
            size: self.size

    Button:
        text: ">"
        size_hint: 0.1,0.1
        pos_hint: {"x":0.9, "y":0.0}
        on_press:
            root.goright()
        on_release:
            root.stopright()
    Button:
        text: "<"
        size_hint: 0.1,0.1
        pos_hint: {"x": 0.0, "y": 0.0}
        on_press:
            root.posx = root.posx-1

    Image:
        id: char
        source: "images/idle1.png"
        size: self.size
        pos: root.posx,root.posy

感谢您的宝贵时间和帮助。 Gerrit 兰

//我将“i”更改为“self.i”,但并没有解决问题。

最佳答案

我为您创建了一个简单的示例,展示了如何通过按下按钮移动角色(在本例中为 elf warrior level 1):

#!/usr/bin/env python3.5
# -*- coding: utf-8 -*-
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.floatlayout import FloatLayout
from kivy.clock import mainthread, Clock

gui = '''
Root:
    orientation: 'vertical'

    arena: arena
    control_button: control_button

    Arena:
        id: arena

    Button
        id: control_button
        size_hint_y: None
        height: dp(50)
        text: 'move'


<Arena@FloatLayout>:
    player: player

    Button:
        id: player
        pos: 150, 300
        text: 'elf warrior\\nlevel 1'
        size_hint: None, None
        size: 100, 100
'''


class Root(BoxLayout):

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        @mainthread
        def job():
            self.control_button.bind(on_press=self._on_press)
            self.control_button.bind(on_release=self._on_release)

        job()

    def _on_press(self, button):
        self.arena.start_movement()

    def _on_release(self, button):
        self.arena.stop_movement()


class Arena(FloatLayout):

    def start_movement(self):
        Clock.schedule_interval(self._move_right, 0.01)

    def stop_movement(self):
        Clock.unschedule(self._move_right)

    def _move_right(self, dt):
        self.player.x += 1


class Test(App):

    def build(self):
        return Builder.load_string(gui)


Test().run()

关于android - KIVY - Python 在按下按钮时继续执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38578280/

有关android - KIVY - Python 在按下按钮时继续执行的更多相关文章

  1. python - 如何使用 Ruby 或 Python 创建一系列高音调和低音调的蜂鸣声? - 2

    关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。

  2. ruby-openid:执行发现时未设置@socket - 2

    我在使用omniauth/openid时遇到了一些麻烦。在尝试进行身份验证时,我在日志中发现了这一点:OpenID::FetchingError:Errorfetchinghttps://www.google.com/accounts/o8/.well-known/host-meta?hd=profiles.google.com%2Fmy_username:undefinedmethod`io'fornil:NilClass重要的是undefinedmethodio'fornil:NilClass来自openid/fetchers.rb,在下面的代码片段中:moduleNetclass

  3. ruby - Chef 执行非顺序配方 - 2

    我遵循了教程http://gettingstartedwithchef.com/,第1章。我的运行list是"run_list":["recipe[apt]","recipe[phpap]"]我的phpapRecipe默认Recipeinclude_recipe"apache2"include_recipe"build-essential"include_recipe"openssl"include_recipe"mysql::client"include_recipe"mysql::server"include_recipe"php"include_recipe"php::modul

  4. ruby - 即使失败也继续进行多主机测试 - 2

    我已经构建了一些serverspec代码来在多个主机上运行一组测试。问题是当任何测试失败时,测试会在当前主机停止。即使测试失败,我也希望它继续在所有主机上运行。Rakefile:namespace:specdotask:all=>hosts.map{|h|'spec:'+h.split('.')[0]}hosts.eachdo|host|begindesc"Runserverspecto#{host}"RSpec::Core::RakeTask.new(host)do|t|ENV['TARGET_HOST']=hostt.pattern="spec/cfengine3/*_spec.r

  5. ruby - 为什么 Ruby 的 each 迭代器先执行? - 2

    我在用Ruby执行简单任务时遇到了一件奇怪的事情。我只想用每个方法迭代字母表,但迭代在执行中先进行:alfawit=("a".."z")puts"That'sanalphabet:\n\n#{alfawit.each{|litera|putslitera}}"这段代码的结果是:(缩写)abc⋮xyzThat'sanalphabet:a..z知道为什么它会这样工作或者我做错了什么吗?提前致谢。 最佳答案 因为您的each调用被插入到在固定字符串之前执行的字符串文字中。此外,each返回一个Enumerable,实际上您甚至打印它。试试

  6. ruby - 继续,未定义 callcc 方法 - 2

    我想学习一些关于Continuation的知识,使用callcc方法从一些文章中键入几个示例,但我遇到了错误:NoMethodError:undefinedmethod`callcc'formain:Objectfrom(pry):2:in`'没有文章提到包含延续库。那么如何解决这个问题呢?谢谢编辑:ruby1.9.2p290(2011-07-09修订版32553)[x86_64-linux] 最佳答案 您需要要求“继续”。require'continuation' 关于ruby-继续,

  7. Python 相当于 Perl/Ruby ||= - 2

    这个问题在这里已经有了答案:关闭10年前。PossibleDuplicate:Pythonconditionalassignmentoperator对于这样一个简单的问题表示歉意,但是谷歌搜索||=并不是很有帮助;)Python中是否有与Ruby和Perl中的||=语句等效的语句?例如:foo="hey"foo||="what"#assignfooifit'sundefined#fooisstill"hey"bar||="yeah"#baris"yeah"另外,类似这样的东西的通用术语是什么?条件分配是我的第一个猜测,但Wikipediapage跟我想的不太一样。

  8. ruby - 检查是否通过 require 执行或导入了 Ruby 程序 - 2

    如何检查Ruby文件是否是通过“require”或“load”导入的,而不是简单地从命令行执行的?例如:foo.rb的内容:puts"Hello"bar.rb的内容require'foo'输出:$./foo.rbHello$./bar.rbHello基本上,我想调用bar.rb以不执行puts调用。 最佳答案 将foo.rb改为:if__FILE__==$0puts"Hello"end检查__FILE__-当前ruby​​文件的名称-与$0-正在运行的脚本的名称。 关于ruby-检查是否

  9. java - 什么相当于 ruby​​ 的 rack 或 python 的 Java wsgi? - 2

    什么是ruby​​的rack或python的Java的wsgi?还有一个路由库。 最佳答案 来自Python标准PEP333:Bycontrast,althoughJavahasjustasmanywebapplicationframeworksavailable,Java's"servlet"APImakesitpossibleforapplicationswrittenwithanyJavawebapplicationframeworktoruninanywebserverthatsupportstheservletAPI.ht

  10. 华为OD机试用Python实现 -【明明的随机数】 2023Q1A - 2

    华为OD机试题本篇题目:明明的随机数题目输入描述输出描述:示例1输入输出说明代码编写思路最近更新的博客华为od2023|什么是华为od,od薪资待遇,od机试题清单华为OD机试真题大全,用Python解华为机试题|机试宝典【华为OD机试】全流程解析+经验分享,题型分享,防作弊指南华为o

随机推荐