Я пытаюсь сделать игру на kivy и у меня возникла проблема. Игрок открывает приложение и видит кнопку "Play". Он нажимает и играет. Победив/проиграв он снова возвращается на этот экран.
Я написал два приложения, которые запускают друг друга. Но при повторном вызове игры возникает ошибка "The file C:\проекты PyCharm\pythonProject\pong.kv is loaded multiples times, you might have unwanted behaviors" и интерфейс отображается неправильно.
Подскажите, пожалуйста, способ решения этой проблемы. Спасибо!
Мой код:
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.widget import Widget
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.button import Button
from kivy.properties import (
NumericProperty, ReferenceListProperty, ObjectProperty
)
from kivy.vector import Vector
from kivy.clock import Clock
result = None
class PongPaddle(Widget):
score = NumericProperty(0)
def bounce_ball(self, ball):
if self.collide_widget(ball):
vx, vy = ball.velocity
offset = (self.center_y - ball.center_y) / 50
bounced = Vector(-1 * vx, vy)
vel = bounced * 1.0 # ускорение
ball.velocity = vel.x, vel.y - offset
class PongBall(Widget):
velocity_x = NumericProperty(0)
velocity_y = NumericProperty(0)
velocity = ReferenceListProperty(velocity_x, velocity_y)
def move(self):
self.pos = Vector(*self.velocity) + self.pos
class PongGame(Widget):
ball = ObjectProperty(None)
player1 = ObjectProperty(None)
player2 = ObjectProperty(None)
ball_speed = 4
bot_speed = ball_speed / 4
sec = 0
last_x = None
label = Label()
global clock
def serve_ball(self, vel=(ball_speed, random.randint(-10, 10))):
self.ball.center = self.center
self.ball.velocity = vel
def update(self, dt):
self.ball.move()
global result
global app
global play
# bounce of paddles
self.player1.bounce_ball(self.ball)
self.player2.bounce_ball(self.ball)
if self.player2.center_y < self.ball.center_y:
self.player2.center_y += self.bot_speed
elif self.player2.center_y > self.ball.center_y:
self.player2.center_y -= self.bot_speed
# bounce ball off bottom or top
if (self.ball.y < self.y) or (self.ball.top > self.top):
self.ball.velocity_y *= -1
# went of to a side to score point?
if self.ball.x < self.x + 0: # победа бота
print(self.ball.x, self.x)
self.player2.score += 1
if self.player2.score >= 5:
clock.cancel()
result = "bot"
app.pause()
self._press()
play = Play()
play.run()
self.serve_ball(vel=(self.ball_speed, random.randint(-10, 10)))
if self.ball.x > self.width - 50: # победа игрока
print(self.ball.x, self.width)
self.player1.score += 1
if self.player1.score >= 0:
clock.cancel()
result = "win"
app.stop()
self._press()
play = Play()
play.run()
self.serve_ball(vel=(-self.ball_speed, random.randint(-10, 10)))
self.bot_speed += 0.25
def on_touch_move(self, touch):
self.player1.center_y = touch.y
def _press(self, *args):
self.player2.score = 0
self.player1.score = 0
class PongApp(App):
def build(self):
game = PongGame()
game.serve_ball()
global clock
clock = Clock.schedule_interval(game.update, 1.0 / 120.0)
return game
class Play(App):
def build(self):
layout = FloatLayout()
label = Label(
text=f'You {result}!' if result is not None else "",
size_hint=(.5, .5),
pos_hint={'x': .25, 'y': .5},
)
layout.add_widget(label)
button = Button(
text='Play',
size_hint=(.3, .1),
pos_hint={'x': .35, 'y': .3},
)
button.bind(on_press=game)
layout.add_widget(button)
return layout
def game(instance=None):
print(instance)
global app
try:
global play
play.stop()
except Exception as e:
pass
app = PongApp()
app.run()
if __name__ == "__main__":
play = Play()
play.run()