G Ang
G Ang

Reputation: 25

Execute function upon initiation of screen in Kivy

I'm trying to execute a function (self.bomb) automatically when the screen changes from Screen 1 (ComputerScreen) to Screen 2 (PlayerScreen) as shown below. The screen changes with the code self.manager.current = "player".

class ComputerScreen(Screen):
    def __init__(self, **kwargs):
        super(ComputerScreen, self).__init__(**kwargs)
        self.comgrid = comgrid()
        self.add_widget(self.comgrid)


    def shoot(self):
        shootsub_x = self.shootxinput.text,
        shootsub_y = self.shootyinput.text,
        shootsub_z = self.shootdepthinput.text,
        while True:
            try:
                shootsub_x = int(shootsub_x[0])
                try:
                    shootsub_y = str(shootsub_y[0]).upper()
                    try:
                        shootsub_z = int(shootsub_z[0])
                        break
                    except:
                        showpopup("z error")
                        print("try")
                except:
                    showpopup("y error")
            except:
                showpopup("x error")
        if shootsub_x not in range(1, 11):
            showpopup("x error")
        elif shootsub_y not in sub_ydict:
            showpopup("y error")
        elif shootsub_z not in sub_zdict:
            showpopup("z error")
            print("z not in dict")
        else:
            target = sub_ydict[shootsub_y] + shootsub_x + sub_zdict[shootsub_z]
            shots = explosion(target)
            for i in shots:
                if i in computerlist:
                    computerlist.remove(i)
                if comgrid_dict[i] == "clear.png":
                    comgrid_dict[i] = "cross.png"
                elif comgrid_dict[i] == "clear_ship.png":
                    comgrid_dict[i] = "explosion.png"
                else:
                    pass
            self.comgrid.update()
            Clock.schedule_once(self.check_game, 1)

    def check_game(self,instance):
        if updategame():
            game_status = True
            self.show = popup_game()
            self.show.label.text = "Computer's turn to make a move..."
            self.popupWindow = Popup(title="Computer's Turn", content=self.show, size_hint=(0.5, 0.4),
                                pos_hint={'x': 0.25, 'y': 0.3})
            self.popupWindow.open()
            Clock.schedule_once(self.computerturn, 2)
        else:
            self.show = popup_game()
            self.show.label.text = "You have eliminated your opponent!"
            popupWindow = Popup(title="You win!", content=self.show, size_hint=(0.5, 0.4),
                                pos_hint={'x': 0.25, 'y': 0.3})
            popupWindow.open()
            Clock.schedule_once(self.end_game, 2)

    def computerturn(self,instance):
        self.manager.current = "player"
        self.popupWindow.dismiss()
        game_status = True

    def end_game(self,instance):
        self.manager.current = "main"





class PlayerScreen(Screen):
    def __init__(self, **kwargs):
        super(PlayerScreen, self).__init__(**kwargs)
        self.gamegrid = gamegrid()
        self.add_widget(self.gamegrid)
        if game_status:
            self.bomb()

    def bomb(self):
        target = random.choice(range(1, 200))
        shots = explosion(target)
        for i in shots:
            if i in playerlist:
                playerlist.remove(i)
                game_dict[i] = "explosion.png"
                print(playerlist)
            if game_dict[i] == "clear.png":
                game_dict[i] = "cross.png"
        self.gamegrid.update()
        status = False
        Clock.schedule_once(self.check_game, 3)

    def check_game(self, instance):
        if updategame():
            self.manager.current = "computer"
        else:
            self.show = popup_game()
            self.show.label.text = "Your opponent exploded your ships!"
            popupWindow = Popup(title="You lose!", content=self.show, size_hint=(0.5, 0.4),
                                pos_hint={'x': 0.25, 'y': 0.3})
            popupWindow.open()
            Clock.schedule_once(self.end_game, 2)

    def end_game(self,instance):
        self.manager.current = "main"

I added the if game_status: line, because without it, when the app starts up, the screen changes to PlayerScreen immediately, skipping the previous few screens.

Upvotes: 0

Views: 384

Answers (1)

Pieter-Jan
Pieter-Jan

Reputation: 540

To execute a function upon entering a new Screen, you can try to add the following method to that Screen:

def on_enter():

This method will be triggered when the Screen is displayed.

So in your case, maybe try to replace def bomb(self) with def on_enter(self):. And also replace self.bomb() with self.on_enter(). Let me know if it worked.

Upvotes: 1

Related Questions