Last active
January 21, 2016 03:29
-
-
Save eyohansa/6922cd77485eafceaefe to your computer and use it in GitHub Desktop.
A simulation of dice game where players race to empty their bowl of dice.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# author: Eric Yohansa | |
import random | |
NUM_OF_PLAYERS = 4 | |
NUM_OF_DICE = 6 | |
class Game(): | |
def __init__(self): | |
self.players = [] | |
self.winners = [] | |
self.round = 0 | |
for i in range(0, NUM_OF_PLAYERS): | |
self.players.append(Player("Player {0}".format(i + 1))) | |
def run(self): | |
while len(self.winners) == 0: | |
self.begin_round() | |
print("\n") | |
self.process_round() | |
self.post_process() | |
print("After dice removed/moved:") | |
for player in self.players: | |
print(player.get_dice_string()) | |
print("\n") | |
print("Winners: " + ', '.join('{0}'.format(winner) for winner in self.winners)) | |
def begin_round(self): | |
self.round += 1 | |
print("Round {0} \n".format(self.round)) | |
print("After dice rolled:") | |
for player in self.players: | |
player.roll() | |
print(player.get_dice_string()) | |
def process_round(self): | |
for idx, player in enumerate(self.players): | |
dice = player.process() | |
if player.dice_count <= 0: | |
self.winners.append(player) | |
next_index = idx + 1 if idx < len(self.players) - 1 else 0 | |
self.players[next_index].add_dice_to_buffer(dice) | |
def post_process(self): | |
for player in self.players: | |
player.add_dice() | |
class Player(): | |
def __init__(self, name): | |
self.name = name | |
self.dice = [] | |
self.add_buffer = 0 | |
self.dice_count = NUM_OF_DICE | |
def roll(self): | |
self.dice.clear() | |
for i in range(0, self.dice_count): | |
top = random.randint(1, 6) | |
self.dice.append(top) | |
def process(self): | |
dice_to_pass = 0 | |
for d in self.dice: | |
if d == 6: | |
self.dice_count -= 1 | |
elif d == 1: | |
self.dice_count -= 1 | |
dice_to_pass += 1 | |
self.dice = list(filter(lambda x: x != 6 and x != 1, self.dice)) | |
return dice_to_pass | |
def add_dice(self): | |
self.dice_count += self.add_buffer | |
for i in range(0, self.add_buffer): | |
self.dice.append(1) | |
self.add_buffer = 0 | |
def add_dice_to_buffer(self, count): | |
self.add_buffer = count | |
def get_dice_string(self): | |
return self.name + ": " + ', '.join("{0}".format(number) for number in self.dice) | |
def __str__(self): | |
return self.name | |
if __name__ == '__main__': | |
game = Game() | |
game.run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment