Python Forum

Full Version: Lambda seems to call expression 1 extra time every time it's called.
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Pages: 1 2
Move the player move button's connect out of the diceroll method, only connect once.
(May-18-2019, 08:16 AM)Yoriz Wrote: [ -> ]Move the player move button's connect out of the diceroll method, only connect once.

I should have thought of that! That has almost fixed my problem, however, 'self.move_players' is called with the old value not the new one.
Here is my new 'diceRoll':
def diceRoll(self, argument):
        temp = 0
        rollT = Settings.ROLL_TIME
        self.roll.setEnabled(False)
        while(temp <= rollT):
            yield ((temp * 0.02) + 0.05)
            img = random.choice(self.images)
            spaces = int(img[0:1])
            pixmap = QPixmap(img)
            self.image.setPixmap(pixmap)
            self.vbox2.addWidget(self.image)
            temp += 1
        self.move.setEnabled(True)
        print(spaces)
        a = lambda: self.move_players("P1" if self.currPl == 1 else "P2", spaces)
        if(self.notCalled):
            self.move.clicked.connect(a)
            self.notCalled = False
When player 1 rolls and they get a 4, for instance, it 'calls self.move_players' with the arguments of 'P1' and 4. Then player 2 rolls a 6 and 'self.move_players' is called withe the arguments 'P2' and 4. Not 6, 4. Even though spaces equals 6, it still uses player 1's value of 4. This is similar to what I described in my original post.
With all the prints, here is the wrong output:
Output:
1 P1 1 3 P2 1
and here is the output I should get
Output:
1 P1 1 3 P2 3
Just a slight difference.

D

EDIT: after rolling the dice more that two times, I can see that for every player, it uses the first value that was rolled. For instance, if player 1 rolls a 5 on the first go, every player, every go will move 5 spaces, no matter what they roll.
The self.move.clicked.connect doesn't need to be in diceRoll at all, place it in the setup code not the event code, just like you have self.roll.clicked.connect
players does not need passing to the method self.move_players it can access the current player directly from self.currPl
spaces can be set as an instance variable in diceRoll, self.move_players can then access the current spaces directly from self.spaces

Remove the lambda, remove the parameters from self.move_players and connect directly to self.move_players.
It will now be connected with no out of date arguments as it gets the current values itself at the point the button is clicked.
Finally! I did what you suggested and moved it out of the diceRoll function and into the dice function, and also use a variable self.spaces, again, like you suggested, to update the players position.

Thank you all for the help!
Dream
Pages: 1 2