为什么我的简单tictactoe应用在Android上启动后立即崩溃?

时间:2019-02-18 17:40:14

标签: android python kivy

我无法在Android上运行我的应用。

我使用python和kivy开发了一个简单的tictactoe应用程序。当我使用PC上的命令提示符运行应用程序时,它运行良好,但是当我使用builozer版本0.37构建apk并将其安装在手机上时,它立即崩溃。我曾经尝试过构建一个“ hello world”应用程序,并且效果很好。所以我对可能是什么问题感到很困惑。我正在使用Kivy版本1.10.1。我在Galaxy S7上运行了该应用程序(不知道是否有帮助)。我为我的草率代码预先表示歉意,我仍然是应用程序开发的新手,这是我的第一个完整应用程序。请注意,我之前仅使用python 3进行编程,当我尝试在spec文件中指定python 3时,构建过程失败,因此我将其更改为hostpython 2(也许是引起问题的原因)

非常感谢您提供的任何帮助。

这是我的python代码

from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.gridlayout import GridLayout
from kivy.uix.popup import Popup
from kivy.uix.floatlayout import FloatLayout
from kivy.properties import BooleanProperty, ObjectProperty, StringProperty
from kivy.graphics.vertex_instructions import (Line, Ellipse, Rectangle)
from kivy.graphics.context_instructions import Color
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.core.window import Window
import random

# I set a global variable because I don't know how to change another screen/class variable using the first screen

aioption = BooleanProperty(False)

class WelcomeScreen(Screen):

    def __init__(self):
    super(WelcomeScreen, self).__init__()
    self.set_aioption()

    def set_aioption(self):
    button = self.ids.ai_button
    button.bind(on_press = self.option_true)

    def option_true(self, *args):
    global aioption
    aioption = True
    # for debugging porpuses
    print('success in changing global variable')

class WinnerPopup(Popup):
    pass


class GameScreen(Screen):
    #defining all variables we need

    global aioption
    turn = 1
    checking_threshold = 0
    isX = BooleanProperty(False)
    isO = BooleanProperty(False)
    result = StringProperty('')
    # this checks if a button is used or not
    isavail = BooleanProperty(True)
    haswon = BooleanProperty(False)

    def drawX(self, button):
        # creates the X sign
        with self.canvas.after:
            Color(0,0,0.5,1)
            Line(points = [button.x, button.y, button.x+button.width, button.y+button.height], width = 0.03*button.width)
            Line(points = [button.x+button.width, button.y, button.x, button.y+button.height], width = 0.03*button.width)

    def drawO(self, button):
        #draws the O sign
        with self.canvas.after:
            Color(0.5,0,0,1)
            Line(width = 0.03*button.width, circle = (button.center_x, button.center_y, min(button.width, button.height)
                / 2))

    def winning(self, result):

    #handles popup at the end

    box = BoxLayout(orientation = 'vertical')
    play_btn = Button(text= 'play again', font_size = '20sp')
    exit_btn = Button(text = 'exit', font_size = '20sp')
    winner_label = Label(text= result,
                         font_size= '30sp')
    wp = WinnerPopup(title = 'Winner',
                     id = 'mypopup'
                     , size_hint_y = None, size_hint_x= None
                     , size=(0.5*self.width, 0.5*self.height),
                     auto_dismiss = False)

    play_btn.bind(on_press = self.reset_game)
    play_btn.bind(on_press = self.change_welcome)
    play_btn.bind(on_press = wp.dismiss)
    exit_btn.bind(on_press = self.exit_app)
    wp.add_widget(box)
    box.add_widget(winner_label)
    box.add_widget(play_btn)
    box.add_widget(exit_btn)

    wp.open()

    def exit_app(self, *args):
    App.get_running_app().stop()
    Window.close()

    def change_welcome(self, *args):
    self.manager.current = 'welcomescreen'

    def check_winner(self):
    b1 = self.ids.button1
    b2 = self.ids.button2
    b3 = self.ids.button3
    b4 = self.ids.button4
    b5 = self.ids.button5
    b6 = self.ids.button6
    b7 = self.ids.button7
    b8 = self.ids.button8
    b9 = self.ids.button9

    #checks for winning conditions

    if ((b1.isX == True and b2.isX == True and b3.isX == True)
    or (b1.isX == True and b4.isX == True and b7.isX == True)
    or (b1.isX == True and b5.isX == True and b9.isX == True)
    or (b2.isX == True and b5.isX == True and b8.isX == True)
    or (b3.isX == True and b6.isX == True and b9.isX == True)
    or (b4.isX == True and b5.isX == True and b6.isX == True)
    or (b7.isX == True and b8.isX == True and b9.isX == True)
    or (b3.isX == True and b5.isX == True and b7.isX == True)):

        self.haswon = True
        self.result = "X's won"
        self.winning(self.result)

    elif ((b1.isO == True and b2.isO == True and b3.isO == True)
    or (b1.isO == True and b4.isO == True and b7.isO == True)
    or (b1.isO == True and b5.isO == True and b9.isO == True)
    or (b2.isO == True and b5.isO == True and b8.isO == True)
    or (b3.isO == True and b6.isO == True and b9.isO == True)
    or (b4.isO == True and b5.isO == True and b6.isO == True)
    or (b7.isO == True and b8.isO == True and b9.isO == True)
    or (b3.isO == True and b5.isO == True and b7.isO == True)):

        self.haswon = True
        self.result = "O's won"
        self.winning(self.result)

    elif self.checking_threshold >= 8:

        self.result = 'it is a draw'
        self.winning(self.result)

    def reset_game(self, *args):
    self.turn = 1
    self.checking_threshold = 0
    self.result = ''
    self.haswon = False
    global aioption
    aioption = False
    for i in range(1,10):
        self.ids[f'button{i}'].isX = False
        self.ids[f'button{i}'].isO = False
        self.ids[f'button{i}'].isavail = True

    self.canvas.after.clear()

    #fake AI, just chooses a random postition
    def ai_engine(self, *args):
    label = self.ids.game_label
    flag = False
    while flag == False and self.turn % 2 == 0:        
        random_int = random.randint(1, 9)
        button = self.ids[f'button{random_int}']

        if button.isavail == True:
            button.isO = True
            label.text = "it's X's turn"
            label.color = [0,0,0.5,1]
            self.drawO(button)
            flag = True
            self.turn += 1
            button.isavail = False
            self.checking_threshold += 1


    # condition that changes the game mode                
    def sign(self, button):
    if aioption == True:
        label = self.ids.game_label
        #makes sure match cant go on when game is over
        if self.haswon != True:
            if button.isavail == True:
                if self.turn % 2 != 0:
                    self.drawX(button)
                    label.text = "it's AI's turn"
                    label.color = [0.5,0,0,1]
                    button.isX = True
                    self.turn += 1
                    button.isavail = False
                    self.checking_threshold += 1
                    self.ai_engine()

                if self.checking_threshold >= 3:
                    self.check_winner()



            else: 
                print('the button is not available')
    else:
        label = self.ids.game_label
        if self.haswon != True:
            if button.isavail == True:
                if self.turn % 2 != 0:
                    self.drawX(button)
                    label.text = "it's O's turn"
                    label.color = [0.5,0,0,1]
                    button.isX = True
                else:
                    button.isO = True
                    label.text = "it's X's turn"
                    label.color = [0,0,0.5,1]
                    self.drawO(button)

                if self.checking_threshold >= 4:
                    self.check_winner()

                button.isavail = False
                self.turn += 1
                self.checking_threshold += 1


            else: 
                print('the button is not available')


class TicTacToe2App(App):
    def build(self):
    sm = ScreenManager()
    sm.add_widget(WelcomeScreen())
    sm.add_widget(GameScreen(name = 'gamescreen'))
    return sm

if __name__ == '__main__':
    TicTacToe2App().run()

这是我的kv文件:

<Button>:
    isX: False
    isO: False
    isavail: True


<WelcomeScreen>:
    name: 'welcomescreen'
    BoxLayout:
    orientation: 'vertical'
    FloatLayout:
        size_hint: None, None
        size:root.width, 0.4*root.height

        canvas:
            Color:
                rgba: 1,1,1,0.5
            Rectangle:
                pos: self.pos
                size: self.size
        Label:
            size_hint: None, None
            text: 'Welcome to TicTacToe'
            center: self.parent.center
            font_size: '50sp'
            size: self.texture_size
    FloatLayout:
        BoxLayout:
            center: self.parent.center
            orientation: 'vertical'
            Button:
                id: human_button
                size_hint: None, None
                size: 0.2*root.width, 0.1*root.height
                text: '1 vs 1'
                font_size: '20sp'
                on_press: app.root.current = 'gamescreen'
            Button:
                id: ai_button
                size_hint: None, None
                size: 0.2*root.width, 0.1*root.height
                text: '1 vs Bot'
                font_size: '20sp'
                on_press: app.root.current = 'gamescreen'
                on_press: root.aioption = True
<GameScreen>:
    name: 'gamescreen'
    BoxLayout:
    orientation: 'vertical'
    FloatLayout:
        id: myfloat
        size_hint_y: None
        height: 0.2*root.height
        Label:
            id: game_label
            center: self.parent.center
            size_hint_x: None
            width: 0.8*root.width
            color: 0,0,1,0.85
            text: "X's turn"
            font_size: '35sp'

    GridLayout:
        id: mygrid
        cols: 3
        rows: 3
        padding: 0.05*root.width
        spacing: 0.02*root.width
        Button:
            id: button1
            background_color: 0,0,0,0

            canvas:
                Color:
                    rgba: 1,1,1,0.8
                Rectangle:
                    pos: (self.width + self.x), (root.y+0.025*root.width)
                    size: (0.02*root.width), (mygrid.height-0.05*root.width)
            on_press: root.sign(self)
        Button:
            id: button2
            background_color: 0,0,0,0

            canvas:
                Color:
                    rgba: 1,1,1,0.8
                Rectangle:
                    pos: (self.width + self.x), (root.y+0.025*root.width)
                    size: (0.02*root.width), (mygrid.height-0.05*root.width)
            on_press: root.sign(self)
        Button:
            id: button3
            background_color: 0,0,0,0

            on_press: root.sign(self)
            canvas:
                Color:
                    rgba: 1,0,1,1
        Button:
            id: button4
            background_color: 0,0,0,0

            on_press: root.sign(self)
            canvas:
                Color:
                    rgba: 1,1,1,0.8
                Rectangle:
                    pos: (root.x + 0.025*root.width) , (self.y + self.height)
                    size: (mygrid.width - 0.05*root.width) , (0.02*root.width)
                Rectangle:
                    pos: (root.x + 0.025*root.width) , (self.y - 0.02*root.width)
                    size: (mygrid.width - 0.05*root.width) , (0.02*root.width)
        Button:
            id: button5
            background_color: 0,0,0,0

            on_press: root.sign(self)
            canvas:
                Color:
                    rgba: 1,0,0,1
        Button:
            id: button6
            background_color: 0,0,0,0

            on_press: root.sign(self)
            canvas:
                Color:
                    rgba: 1,0,0,1
        Button:
            id: button7 
            background_color: 0,0,0,0

            on_press: root.sign(self)
            canvas:
                Color:
                    rgba: 1,0,0,1
        Button:
            id: button8
            background_color: 0,0,0,0

            on_press: root.sign(self)
            canvas:
                Color:
                    rgba: 1,0,0,1
        Button:
            id: button9
            background_color: 0,0,0,0

            on_press: root.sign(self)
            canvas:
                Color:
                    rgba: 1,0,0,1

这是我的buildozer规格文件:

[app]

# (str) Title of your application
title = Tic Tac Toe

# (str) Package name
package.name = myapp

# (str) Package domain (needed for android/ios packaging)
package.domain = com.mydomain

# (str) Source code where the main.py live
source.dir = .

# (list) Source files to include (let empty to include all the files)
source.include_exts = py,kv

# (list) List of inclusions using pattern matching
#source.include_patterns = assets/*,images/*.png

# (list) Source files to exclude (let empty to not exclude anything)
#source.exclude_exts = spec

# (list) List of directory to exclude (let empty to not exclude anything)
#source.exclude_dirs = tests, bin

# (list) List of exclusions using pattern matching
#source.exclude_patterns = license,images/*/*.jpg

# (str) Application versioning (method 1)
version = 0.1

# (str) Application versioning (method 2)
# version.regex = __version__ = ['"](.*)['"]
# version.filename = %(source.dir)s/main.py

# (list) Application requirements
# comma separated e.g. requirements = sqlite3,kivy
requirements = hostpython2,kivy

# (str) Custom source folders for requirements
# Sets custom source for any requirements with recipes
# requirements.source.kivy = ../../kivy

# (list) Garden requirements
#garden_requirements =

# (str) Presplash of the application
#presplash.filename = %(source.dir)s/data/presplash.png

# (str) Icon of the application
#icon.filename = %(source.dir)s/data/icon.png

# (str) Supported orientation (one of landscape, portrait or all)
orientation = all

# (list) List of service to declare
#services = NAME:ENTRYPOINT_TO_PY,NAME2:ENTRYPOINT2_TO_PY

#
# OSX Specific
#

#
# author = © Copyright Info

# change the major version of python used by the app
osx.python_version = 3

# Kivy version to use
osx.kivy_version = 1.10.1
#
# Android specific
#

# (bool) Indicate if the application should be fullscreen or not
fullscreen = 1

# (string) Presplash background color (for new android toolchain)
# Supported formats are: #RRGGBB #AARRGGBB or one of the following names:
# red, blue, green, black, white, gray, cyan, magenta, yellow, lightgray,
# darkgray, grey, lightgrey, darkgrey, aqua, fuchsia, lime, maroon, navy,
# olive, purple, silver, teal.
#android.presplash_color = #FFFFFF

# (list) Permissions
#android.permissions = INTERNET

# (int) Android API to use
#android.api = 19

# (int) Minimum API required
#android.minapi = 9

# (int) Android SDK version to use
#android.sdk = 20

# (str) Android NDK version to use
#android.ndk = 9c

# (bool) Use --private data storage (True) or --dir public storage (False)
#android.private_storage = True

# (str) Android NDK directory (if empty, it will be automatically downloaded.)
android.ndk_path = /home/kivy/Downloads/android-ndk-r13b/

# (str) Android SDK directory (if empty, it will be automatically downloaded.)
#android.sdk_path =

# (str) ANT directory (if empty, it will be automatically downloaded.)
#android.ant_path =

# (bool) If True, then skip trying to update the Android sdk
# This can be useful to avoid excess Internet downloads or save time
# when an update is due and you just want to test/build your package
# android.skip_update = False

# (str) Android entry point, default is ok for Kivy-based app
#android.entrypoint = org.renpy.android.PythonActivity

# (list) Pattern to whitelist for the whole project
#android.whitelist =

# (str) Path to a custom whitelist file
#android.whitelist_src =

# (str) Path to a custom blacklist file
#android.blacklist_src =

# (list) List of Java .jar files to add to the libs so that pyjnius can access
# their classes. Don't add jars that you do not need, since extra jars can slow
# down the build process. Allows wildcards matching, for example:
# OUYA-ODK/libs/*.jar
#android.add_jars = foo.jar,bar.jar,path/to/more/*.jar

# (list) List of Java files to add to the android project (can be java or a
# directory containing the files)
#android.add_src =

# (list) Android AAR archives to add (currently works only with sdl2_gradle
# bootstrap)
#android.add_aars =

# (list) Gradle dependencies to add (currently works only with sdl2_gradle
# bootstrap)
#android.gradle_dependencies =

# (list) Java classes to add as activities to the manifest.
#android.add_activites = com.example.ExampleActivity

# (str) python-for-android branch to use, defaults to stable
#p4a.branch = stable

# (str) OUYA Console category. Should be one of GAME or APP
# If you leave this blank, OUYA support will not be enabled
#android.ouya.category = GAME

# (str) Filename of OUYA Console icon. It must be a 732x412 png image.
#android.ouya.icon.filename = %(source.dir)s/data/ouya_icon.png

# (str) XML file to include as an intent filters in <activity> tag
#android.manifest.intent_filters =

# (str) launchMode to set for the main activity
#android.manifest.launch_mode = standard

# (list) Android additional libraries to copy into libs/armeabi
#android.add_libs_armeabi = libs/android/*.so
#android.add_libs_armeabi_v7a = libs/android-v7/*.so
#android.add_libs_x86 = libs/android-x86/*.so
#android.add_libs_mips = libs/android-mips/*.so

# (bool) Indicate whether the screen should stay on
# Don't forget to add the WAKE_LOCK permission if you set this to True
#android.wakelock = False

# (list) Android application meta-data to set (key=value format)
#android.meta_data =

# (list) Android library project to add (will be added in the
# project.properties automatically.)
#android.library_references =

# (str) Android logcat filters to use
#android.logcat_filters = *:S python:D

# (bool) Copy library instead of making a libpymodules.so
#android.copy_libs = 1

# (str) The Android arch to build for, choices: armeabi-v7a, arm64-v8a, x86
android.arch = armeabi-v7a

#
# Python for android (p4a) specific
#

# (str) python-for-android git clone directory (if empty, it will be automatically cloned from github)
#p4a.source_dir =

# (str) The directory in which python-for-android should look for your own build recipes (if any)
#p4a.local_recipes =

# (str) Filename to the hook for p4a
#p4a.hook =

# (str) Bootstrap to use for android builds
# p4a.bootstrap = sdl2

# (int) port number to specify an explicit --port= p4a argument (eg for bootstrap flask)
#p4a.port =


#
# iOS specific
#

# (str) Path to a custom kivy-ios folder
#ios.kivy_ios_dir = ../kivy-ios

# (str) Name of the certificate to use for signing the debug version
# Get a list of available identities: buildozer ios list_identities
#ios.codesign.debug = "iPhone Developer: <lastname> <firstname> (<hexstring>)"

# (str) Name of the certificate to use for signing the release version
#ios.codesign.release = %(ios.codesign.debug)s


[buildozer]

# (int) Log level (0 = error only, 1 = info, 2 = debug (with command output))
log_level = 2

# (int) Display warning if buildozer is run as root (0 = False, 1 = True)
warn_on_root = 1

# (str) Path to build artifact storage, absolute or relative to spec file
build_dir = /build/myapp

# (str) Path to build output (i.e. .apk, .ipa) storage
# bin_dir = ./bin

#    -----------------------------------------------------------------------------
#    List as sections
#
#    You can define all the "list" as [section:key].
#    Each line will be considered as a option to the list.
#    Let's take [app] / source.exclude_patterns.
#    Instead of doing:
#
#[app]
#source.exclude_patterns = license,data/audio/*.wav,data/images/original/*
#
#    This can be translated into:
#
#[app:source.exclude_patterns]
#license
#data/audio/*.wav
#data/images/original/*
#


#    -----------------------------------------------------------------------------
#    Profiles
#
#    You can extend section / key with a profile
#    For example, you want to deploy a demo version of your application without
#    HD content. You could first change the title to add "(demo)" in the name
#    and extend the excluded directories to remove the HD content.
#
#[app@demo]
#title = My Application (demo)
#
#[app:source.exclude_patterns@demo]
#images/hd/*
#
#    Then, invoke the command line with the "demo" profile:
#
#buildozer --profile demo android debug

这是到adb logcat输出的链接(我使用此语句adb logcat | findstr com.example.package过滤了输出):

https://github.com/theyoungthunder/app-logcat-output/blob/master/logcat%20output.txt

1 个答案:

答案 0 :(得分:0)

Python 3

您的应用在使用Android 5.0.1版的Acer平板电脑上运行良好。该apk文件是在Xubuntu 18.04 Bionic Beaver上使用Buildozer 0.39,Python 3,Kivy 1.10.1和Cython 0.28.6构建的。

Python 2

您的应用无法在Python 2上运行。失败是由于使用了Python 3字符串格式。

Python2 - SyntaxError

解决方案

升级Buildozer

pip install --upgrade buildozer

buildozer.spec

# (list) Application requirements
# comma seperated e.g. requirements = sqlite3,kivy
requirements = python3,kivy

Ubuntu 18.04(64位)上的Android

sudo pip install --upgrade cython==0.28.6
sudo dpkg --add-architecture i386
sudo apt update
sudo apt install build-essential ccache git libncurses5:i386 libstdc++6:i386 libgtk2.0-0:i386 libpangox-1.0-0:i386 libpangoxft-1.0-0:i386 libidn11:i386 python2.7 python2.7-dev openjdk-8-jdk unzip zlib1g-dev zlib1g:i386

Ubuntu 16.04(64位)上的Android

sudo pip install --upgrade cython==0.21
sudo dpkg --add-architecture i386
sudo apt-get update
sudo apt-get install build-essential ccache git libncurses5:i386 libstdc++6:i386 libgtk2.0-0:i386 libpangox-1.0-0:i386 libpangoxft-1.0-0:i386 libidn11:i386 python2.7 python2.7-dev openjdk-8-jdk unzip zlib1g-dev zlib1g:i386