Advertisement
Sasha2001

Game of dice

May 27th, 2019
134
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.50 KB | None | 0 0
  1. from random import randint         #Import randint that belong to random numbers
  2. import pprint                      #To print dictionary better
  3.  
  4. #Creating variables
  5. players = ("player" , "computer")  #stores all player names
  6. active_player = randint(0, 1)      #number for the player in turn
  7. #Dictionary that stores all dice in the game
  8. game = {"player" : {"active" :[], "saved" : []}, "computer" : {"active" : [], "saved" : []}}
  9. def player_score(d):
  10.     """
  11.    a funktion that calculates the result for a player
  12.    :param d:   Dictionary with two lists, active and saved
  13.    :return:    The sum of the dice's value in both lists
  14.    """
  15. def change_active_player(save=False):
  16.     global active_player  # Telling that we want to use active_player inside the function
  17.     if save:
  18.       # .extend allows us to add a list to another
  19.      game[players[active_player]]['saved'].extend(game[players[active_player]]['active'])
  20.     # Empty the active list
  21.     game[players[active_player]]['active'] = []
  22.  
  23.     # Change aktive player, can be written: active_player (active_player + 1) % 2
  24. if active_player == 1:          #If the value for avtive_player is 1---
  25.         active_player = 0           #...set it to 0
  26. else:                           #...otherwise
  27.         active_player = 1           #...set it to 1
  28. print("Player changes")
  29. def standings():
  30.     """
  31.    Prints the stance
  32.    :return:    strict with the stand
  33.    """
  34.     s = "{} has hit {} (sum {} point)".format(players[active_player],
  35.                                               game[players[active_player]]['active'], sum(game[players[active_player]]['active']))
  36.     s += "\nTotal you have {} points and the computer has {} points".format(player_score(game['player']),
  37.                                                                             player_score(game['computer']))
  38.     return s
  39.  
  40. #prints the welcome message
  41. input("""#######################################
  42. # Welcome to the dice game of 40 #
  43. #######################################
  44. Game of 40 is a dice game where you first have to reach at least 40 points.
  45. If you hit a six, you lose the points you have not saved and the tour goes
  46. over to the opponent. You can save your points at any time and let the luck
  47. go over to the opponent.
  48. The player who starts the game is: {}
  49. Press enter to start the game.""".format(players[active_player]))
  50.  
  51. #Run n endless loop
  52. while True:
  53.    
  54.     #Rolls a dice
  55.     dice = randint(1,6)
  56.  
  57.     #Prints the value of the dice
  58.     print("\nDice value: {}".format(dice))
  59.  
  60.     #If dice value is 6
  61.     if dice == 6:
  62.         change_active_player()
  63.     else:
  64.         # Stores the dice in the active player list
  65.         game[players[active_player]]["active"].append(dice)
  66.  
  67.         if active_player == 1:                         #If the value for active_player is 1...
  68.             active_player = 0                          #...Set it to 0
  69.         else:                                          #...otherwise
  70.             active_player = 1                          #...set it to 1
  71.         print("Player changed")
  72.  
  73.     # Prints the stand
  74.     print(standings())
  75.  
  76.     # Prints whose turn it is to play.
  77.     print("Player to hit: {}".format(players[active_player]))
  78.  
  79.     # Logic for the different players
  80.     if players[active_player] == 'computer':            #Computer playes
  81.         #If the computer has more than two dice in its active-list...
  82.         if len(game[players[active_player]]['active']) > 2:
  83.             change_active_player(True)                  #...then these must be saved and the turn goes to the player
  84.         else:
  85.             input("Press to display the computers next dice")
  86.     else:                                               # Player playes
  87.      input("Press enter to hit a dice again")
  88. else:
  89.     while True:
  90.         val = input("Choose [K] to throw th dice again or [S] to save your dices: ")
  91.         if val.upper() == 'K' :                     #Hit the dice
  92.             break
  93.         elif val.upper() == 'S':                    #Save your dice
  94.             change_active_player(True)              #To save dice and leave the turn
  95.             break
  96.         else:
  97.             print("Incorrect entry, try again")
  98.         # Prints game
  99.         #pprint.pprint(game)
  100.  
  101.         #Prints whose turn it is to play
  102.         print("Player to hit: {}".format(players[active_player]))
  103.  
  104.         #Wait for input before running the loop again
  105.         input("Press enter to hit a dice again.")
  106.  
  107.         #If someone has scored more than 39 then they have won...
  108.         if player_score(game['player']) > 39 or player_score(game['computer']) > 39:
  109.             break          #...Break loop
  110.         #prints game
  111.         pprint.pprint(game)
  112.  
  113.         #Wait for input before we run the loop again
  114.         input("Press the entrance button to roll a dice")
  115.         #The game ends and winner is played
  116.         #Check first who won, since no one can get at least 40, we know someone has won
  117.         if player_score(game['player']) > player_score(game['computer']):
  118.             print("Congratulations! you have beaten your computer with {} vs {} points.".format(player_score(game['player']),
  119.                                                                                                                 player_score(game['computer'])))
  120.         else:
  121.             print("You have lost to the computer with {} vs {} points.".format(player_score(game['computer']),
  122.                                                                                 player_score(game['player'])))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement