vendredi 24 juillet 2020

Guessing game using random with two players

I am writing a programme to allow two players taking turns in reducing the random number by guessing any number. For example. The hidden random number is 40, player 1 enter 4, the remainder will be 36..then player 2 turns and so on. The player who leaves 1 as a remaining win. and the player who takes the last 1 loss. The programme is running but I can improve it better

  import random
  def userstart():
  global thisturn #define the variables that will need to be accessed from 
  multiple functions
  global user1
  global user2

  user1=input(print("Enter first player’s name:"))
  user2=input(print("Enter second player’s name: "))
  thisturn=input(print("Who is starting now?: ")) #assign which player to start now
  begin(thisturn, ran_val)

def begin(thisturn, ran_val):
  print("Alright,",thisturn)
  userinput=int(input("Enter number of counter to remove;1 or 2 or 3?:"))
  #take user input and call check input function
  checkiput(ran_val, userinput) 

def checkiput(ran_val, userinput):
  #check if the input is 1,2, or 3 then call calculate() function 
  if userinput==1:calculate(ran_val, userinput)
  elif userinput==2:calculate(ran_val, userinput)
  elif userinput==3:calculate(ran_val, userinput)

def calculate(ran_val, userinput):
  #deduct the user input number from the secret random number
  new_val=ran_val-userinput #assign the result to new variable
  print("amount remain is:", new_val) #this is just for the programmer to follow if this stage is passed
  checknew_val(new_val)

def checknew_val(new_val):#report the result
  while new_val>1:
    ran_val=new_val
    switchuser(thisturn,user1,user2)
    userstart(ran_val)
  if new_val==0:
    print("You took the last counter, you lost!")
    exit()
  elif new_val==1:
    print("There is one counter left, you win!")
    exit()

def switchuser(thisturn,user1,user2):
  #switch between players
  if thisturn==user1:
    thisturn=user2
    print("Now its ",thisturn,"round")
  if thisturn==user2:
    thisturn=user1
    print("Now its ",thisturn,"round")
  begin(thisturn,ran_val)

def main():
  global ran_val #define it as global to be accessible from other function without the need to call the whole function
  ran_val=random.randint(10,50)
  userstart()



Aucun commentaire:

Enregistrer un commentaire