import random
import time
# Function to print the sticks
def sticks(times):
print("\nThere are " + str(times) + " sticks(s) left ")
print("! " * times)
def thinking():
print("Thinking", end=' ')
for i in range(0, 5):
print(' . ', end=' ')
time.sleep(.5)
# 1 is always a legal move, unless we already lost
def nim_minimal():
return 1
# Always return random number between 1 to 3
def nim_random(n):
print('"nim_random" is ', end=' ')
thinking()
return random.randint(1, min(n, 3))
# Always return Nim Best , Win Win condition
def nim_best(n):
nim_win = n % 4
print('"nim_best" is ', end=' ')
thinking()
if nim_win == 0:
return 1
else:
return nim_win
# Always Human
def nim_human(n):
while True: # get input until it's legal
taken = int(input('\n"nim_human" Please choose 1,2 or 3 sticks only : '))
# sticks(n)
if taken in range(1, min(n, 3) + 1):
return taken
print("Illegal move.")
# Players Pool
player_list = [nim_best, nim_minimal, nim_random, nim_human]
# transform into a dictionary with function name mapping to function
player_dict = {p.__name__: p for p in player_list}
# Function for player selection from the Players Pool
def player_slctn(plyr_num, plyr_dict):
while True:
player_name = input("Player - %d , Please choose (nim_best, nim_minimal, nim_random, nim_human) : " % plyr_num)
if player_name in plyr_dict:
break
else:
print("Invalid name!!! Please Try again \n")
return plyr_dict[player_name]
# Up to 2 Players Selection
def players_selecttion(plyr_dict):
players = []
while len(players) < 2:
players.append(player_slctn(len(players) + 1, plyr_dict))
return players
# game Controller
def game_ctrlr():
print(f"\n\t !!! Nim Game Menu !!!\n")
heap_size = int(input("Enter the number of sticks: "))
players = players_selecttion(player_dict)
while heap_size > 0:
player = players[0]
player_pick = player(heap_size)
print('\n"' + player.__name__ + '" has choosen ' + str(player_pick) + ' sticks!')
heap_size -= player_pick
sticks(heap_size)
players.reverse()
print("Congratulation *** " + players[1].__name__ + " is **** WINNER **** (◠‿◠ )")
# calling the Game Controller Function
game_ctrlr()
0 Comments