我的任务与Python / Kivy有关。 我需要使用各种纹理作为游戏块(即方形字段,40 x 40),具体取决于它们的类型。我尝试了最自然的方式,即将类型定义为对象属性,并测试.kv文件中的值。唉,该属性无法识别。 我很确定这很简单,而且是因为我对某些概念的误解。 Stil我无法从可用的文档中找到它。 提前谢谢你让我朝着正确的方向前进。
考虑以下示例代码。这是相当大的一块,但这是它完成运行的成本。
# Imports
from os import system as _system
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.graphics import Color
from kivy.properties import NumericProperty, ReferenceListProperty, ObjectProperty
from kivy.vector import Vector
from kivy.config import Config
from kivy.uix.image import Image
# Size of the map in memory
MAXX = 1001
MAXY = 150
# Size of the display, counted in blocks
MAXSCREENX = 91
MAXSCREENY = 60
# Single block size
BLOCK_SIZE = 40
# Global data structures
game_state = []
mapa = []
player_position = []
equipment = []
eye_direction = 0
# Various subclasees, because of different GIFs defined in the .ky file
class Block(Widget):
typ = NumericProperty(0)
class GameWidget(Widget):
xshift = NumericProperty(0)
yshift = NumericProperty(0)
class ExampleApp(App):
def build(self):
game = GameWidget()
game.xshift = 0
game.yshift = 0
game.screen_map = []
for i in range(MAXSCREENX):
for j in range(MAXSCREENY):
idx = i*MAXSCREENY + j
game.add_widget(Block(), idx)
game.children[idx].pos = (i * BLOCK_SIZE, j * BLOCK_SIZE)
game.children[idx].typ = 2
return game
if __name__ == '__main__':
# Set the window size
Config.set('graphics', 'width', str(MAXSCREENX * BLOCK_SIZE))
Config.set('graphics', 'height', str(MAXSCREENY * BLOCK_SIZE))
ExampleApp().run() # Launch the main application
附带的example.kv文件:
#:kivy 1.9.0
<Block>:
size: 40, 40
canvas:
Rectangle:
if self.typ == 2:
source: "Textures/Dirt.png"
pos: self.pos
size: 40, 40
唉,我收到以下错误:
kivy.lang.ParserException: Parser: File "C:\Moje\Example\example.kv", line 7:
...
5: canvas:
6: Rectangle:
>> 7: if self.typ == 2:
8: source: "Textures/Dirt.png"
9: pos: self.pos
答案 0 :(得分:2)
您在kv语言中使用Python表达式是不正确的。有关正确的语法,请参阅docs。具体来说,您需要在source:
Rectangle:
source: "Textures/Dirt.png" if root.typ == 2
pos: self.pos
size: 40, 40