generated from mwc/lab_dice
A problem I can solve using classes is simulating a deck of cards for a card game. Each card could be an object with attributes like its suit and its value. A separate class called Deck could hold all the cards, shuffle them, and deal them to players. This setup would make it easier to model real game situations like Blackjack or Poker, since each player could also be a class with their own hand of cards.
62 lines
1.3 KiB
Python
62 lines
1.3 KiB
Python
from die import Die
|
|
from tqdm import tqdm
|
|
|
|
class FiveDice:
|
|
def __init__(self):
|
|
self.dice = [Die() for number in range(5)]
|
|
|
|
def roll(self):
|
|
for die in self.dice:
|
|
die.roll()
|
|
return self.faces()
|
|
|
|
def faces(self):
|
|
return [die.face for die in self.dice]
|
|
|
|
def all_ones(self):
|
|
for face in self.faces():
|
|
if face != 1:
|
|
return False
|
|
return True
|
|
|
|
def is_three_of_a_kind(self):
|
|
faces = self.faces()
|
|
for value in range(1,7):
|
|
if faces.count(value) >= 3:
|
|
return True
|
|
return False
|
|
|
|
def is_four_of_a_kind(self):
|
|
faces = self.faces()
|
|
for value in range(1,7):
|
|
if faces.count(value) >= 4:
|
|
return True
|
|
return False
|
|
|
|
dice = FiveDice()
|
|
successes = 0
|
|
trials = 1000000
|
|
for trial in tqdm(range(trials)):
|
|
dice.roll()
|
|
if dice.all_ones():
|
|
successes += 1
|
|
|
|
print("All ones probability:",successes/trials)
|
|
|
|
successes = 0
|
|
for trial in tqdm(range(trials)):
|
|
dice.roll()
|
|
if dice.is_three_of_a_kind():
|
|
successes += 1
|
|
print("Three-of-a-kind probability:", successes/trials)
|
|
|
|
successes = 0
|
|
for trial in tqdm(range(trials)):
|
|
dice.roll()
|
|
if dice.is_four_of_a_kind():
|
|
successes += 1
|
|
print("Four-of-a-kind probability:", successes/trials)
|
|
|
|
|
|
|