Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Making a dice
#1
Hi guys,

for some homework I have to write a code for a dice that can't roll the same value back to back.
So: if on turn 1 the dice throws a 3
then on turn 2 the dice CANT roll a 3
but on turn 3 the dice CAN roll a 3 again.

Thanks in advance guys!
Reply
#2
Compare the last value of the dice with the current number and if it's not equal, set the last value to the current number and return the value.

from random import randint


class Dice:
    def __init__(self):
        self.last = None
    def __call__(self):
        while True:
            number = randint(1,6)
            if number != self.last:
                self.last = number
                return number

dice = Dice()
print([dice() for _ in range(20)])
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#3
Thanks !!
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020