Skip to content

Instantly share code, notes, and snippets.

@mohitkh7
Created August 9, 2021 11:31
Show Gist options
  • Save mohitkh7/41654de9ffed314574f557a4a46b630a to your computer and use it in GitHub Desktop.
Save mohitkh7/41654de9ffed314574f557a4a46b630a to your computer and use it in GitHub Desktop.
"Game of Dice" is a CLI based game written in python language.
"""
The Game of Dice
The "Game of Dice" is a game where two players roll 6 faced dice in a round-robin fashion.
Each time a player rolls the dice their points increase by the number (1 to 6) achieved by the
roll. The first player to accumulate M points wins the game.
created by - Mohit Khandelwal ([email protected])
"""
import random
import time
class Game:
PLAYER_COUNT = 2
MAX_TURNS = 10
def __init__(self, target):
self.target = target
self.turn = None
self.winner = None
self.init_players()
self.assign_turn()
def init_players(self):
self.players = []
for p_id in range(Game.PLAYER_COUNT):
name = input("Enter player %d name : " % (p_id + 1))
self.players.append(Player(name))
def assign_turn(self):
self.turn = random.randint(0, len(self.players) - 1)
def next_turn(self):
if self.turn is None:
self.assign_turn()
self.turn = (self.turn + 1) % len(self.players)
def play(self):
for turn in range(Game.MAX_TURNS):
curr_player = self.players[self.turn]
dice_value = curr_player.take_turn()
if self.is_any_player_won():
break
if dice_value == 6:
print("Since %s got 6 in this throw, player gets one more roll chance" % curr_player.name)
else:
self.next_turn()
def is_any_player_won(self):
for player in self.players:
if player.score >= self.target:
self.winner = player
return True
return False
def display_result(self):
if self.winner:
print("%s Won !!!" % (self.winner.name))
else:
print("Too many turns and yet no winner. Aborting game.")
class Player:
def __init__(self, name):
self.name = name
self.score = 0
self.dice = Dice()
def update_score(self, value):
self.score += value
def take_turn(self):
input("\n%s's turn. press Enter to roll a dice." % (self.name))
dice_value = self.dice.roll()
self.update_score(dice_value)
print("Dice value: %d, %s's total score is: %d" % (dice_value, self.name, self.score))
return dice_value
class Dice:
POSSIBLE_SCORE = [1, 2, 3, 4, 5, 6]
def roll(self):
print("Rolling Dice ...")
time.sleep(1)
return random.choice(self.POSSIBLE_SCORE)
def main():
print("Welcome to The Game of Dice")
target_point = int(input("Enter points to accumulate : "))
game = Game(target_point)
game.play()
game.display_result()
print("Game End. Thanks for playing :)")
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment