I'm trying kivy and I'm having some problems. I'm working on a game project based on a github repository I found and I'm trying to create a racing game. My current problem is that I can't seem to add keyboard events at all. I've searched the internet and haven't managed to adapt the game to this. Could someone please help me?
I've already managed to put in a road, a car and some buttons. There are 6 buttons in total that do things when pressed with the mouse. As for their functionality, 4 of them move the car and the other 2 increase and decrease its speed. At the moment, my main problem, as mentioned above, is being able to move the car with kivy keyboard events.
This is my main.py code:
class CarGame(FloatLayout):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.speed_factor = 10
screen_height = Window.size[1]
with self.canvas.after:
self.car = Rectangle(source='READYGOredcar.png', size=[58, 104], pos=[10, (screen_height / 2) - 50])
def go_left(self):
x, y = self.car.pos
if x > 0:
x -= dp(self.speed_factor)
self.car.pos = [x, y]
def go_right(self):
x, y = self.car.pos
screen_width = Window.size[0]
car_width = self.car.size[0]
if x < screen_width - car_width:
x += dp(self.speed_factor)
self.car.pos = [x, y]
def go_up(self):
x, y = self.car.pos
screen_height = Window.size[1]
if y < screen_height * 0.65:
y += dp(self.speed_factor)
self.car.pos = [x, y]
def go_down(self):
x, y = self.car.pos
screen_height = Window.size[1]
if y > screen_height * 0.18:
y -= dp(self.speed_factor)
self.car.pos = [x, y]
def speed_up(self):
if self.speed_factor < 100:
self.speed_factor += 5
def speed_down(self):
if self.speed_factor > 5:
self.speed_factor -= 5
class MainApp(App):
def build(self):
return Builder.load_file('main.kv')
if __name__ == "__main__":
MainApp().run()
This is my main.kv code:
<CtrlBtn@Button>
size_hint: [None, None]
size: ['35dp', '35dp']
CarGame:
Image:
source: 'rszd-newroad.jpg'
allow_stretch: False
keep_ratio: True
CtrlBtn:
text: "L"
pos_hint: {'x': 0.05, 'y': 0.03}
on_press: root.go_left()
CtrlBtn:
text: "R"
pos_hint: {'x': 0.15, 'y': 0.03}
on_press: root.go_right()
CtrlBtn:
text: "U"
pos_hint: {'x': 0.25, 'y': 0.03}
on_press: root.go_up()
CtrlBtn:
text: "D"
pos_hint: {'x': 0.35, 'y': 0.03}
on_press: root.go_down()
CtrlBtn:
text: "Speed Up"
size: ['100dp', '20dp']
pos_hint: {'x': 0.85, 'y': 0.01}
on_press: root.speed_up()
CtrlBtn:
text: "Speed Down"
size: ['100dp', '20dp']
pos_hint: {'x': 0.85, 'y': 0.05}
on_press: root.speed_down()