【发布时间】:2020-12-01 15:33:58
【问题描述】:
我对编程很陌生,刚刚在大学里参加了一个介绍性研讨会,我应该用 Python 编写一个小应用程序。为此,我想使用 Kivy,但我被卡住了。 我有一个文本文件,其中应包含问题、可能的答案以及考虑用户选择的答案应该去哪里:
0|"Will you rather do A or B?"|"A"|"B"|1|2
1|"Congrats, you chose A. Now go to B."|"Go to B"|"Go to B"|2|2
2|"That's B. Incredible. Want to discover C?"|"Yes."|"Stay here."|3|6
3|Wow, C is so cool, isn't it? There's also a D.|D? Crazy!|Boring. Go back.|4|0
4|Welcome to the depths of D. You are curious, aren't you?|Yep.|Nope.|5|0
5|Cool. There's nothing else here.|There must be.|Knew it.|4|0
6|Surprise! You should really discover C.|Alright.|Is there a D?|3|4
现在我希望游戏转到相应的行,替换显示的文本并继续。从理论上讲,这有点像我的代码(如果它搞砸了,我很抱歉,正如我所说,我是这个主题的新手):
import kivy
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.gridlayout import GridLayout
from kivy.uix.button import Button
with open('try.txt') as t:
Lines = t.readlines()
first_line = Lines[0].strip()
x = first_line.split("|")
answer_b = int(x[5])
class MyGrid(GridLayout):
def __init__(self, **kwargs):
super(MyGrid, self).__init__(**kwargs)
self.cols = 1
self.inside = GridLayout()
self.inside.cols = 2
self.btna = Button(text=x[2])
self.btna.bind(on_press=self.a)
self.inside.add_widget(self.btna)
self.btnb = Button(text=x[3])
self.btnb.bind(on_press=self.b)
self.inside.add_widget(self.btnb)
self.main_text = Label(text=x[1])
self.add_widget(self.main_text)
self.add_widget(self.inside)
def a(self, instance):
answer_a = int(x[4])
next_line_a = Lines[answer_a].strip()
print(next_line_a)
print(answer_a)
x = next_line_a.split("|")
self.main_text.text = x[1]
self.btna.text = x[2]
self.btnb.text = x[3]
self.btna.bind(on_press=self.a)
def b(self, instance):
next_line_b = Lines[answer_b].strip()
print(next_line_b)
print(answer_b)
x = next_line_b.split("|")
self.main_text.text = x[1]
self.btna.text = x[2]
self.btnb.text = x[3]
class Game(App):
def build(self):
return MyGrid()
if __name__ == '__main__':
Game().run()
问题是它停留在我定义的第一行,我真的不知道如何解决这个问题。我想我首先用第一行定义 x ,然后用相应的新行重新定义 x 。但是 next_line 和 x 变量都相互依赖——我尝试了两种不同的方法来回答 a 和 b,但两者都不起作用。 B 将不断地取 first_line-x,A 告诉我在赋值之前引用了 x。 如果有人能帮助我摆脱困惑,那就太好了,因为我尝试的一切都没有成功...... 谢谢!
【问题讨论】:
标签: python kivy text-based