Saturday, December 28, 2024
Google search engine
HomeLanguages21 Number game in Python

21 Number game in Python

21, Bagram, or Twenty plus one is a game which progresses by counting up 1 to 21, with the player who calls “21” is eliminated. It can be played between any number of players. Implementation This is a simple 21 number game using Python programming language. The game illustrated here is between the player and the computer. There can be many variations in the game.

  • The player can choose to start first or second.
  • The list of numbers is shown before the Player takes his turn so that it becomes convenient.
  • If consecutive numbers are not given in input then the player is automatically disqualified.
  • The player loses if he gets the chance to call 21 and wins otherwise.

Winning against the computer can be possible by choosing to play second. The strategy is to call numbers till the multiple of 4 which would eventually lead to 21 on computer hence making the player the winner. 

Python3




# Python code to play 21 Number game
 
# returns the nearest multiple to 4
def nearestMultiple(num):
    if num >= 4:
        near = num + (4 - (num % 4))
    else:
        near = 4
    return near
 
def lose1():
    print ("\n\nYOU LOSE !")
    print("Better luck next time !")
    exit(0)
     
# checks whether the numbers are consecutive
def check(xyz):
    i = 1
    while i<len(xyz):
        if (xyz[i]-xyz[i-1])!= 1:
            return False
        i = i + 1
    return True
 
# starts the game
def start1():
    xyz = []
    last = 0
    while True:
        print ("Enter 'F' to take the first chance.")
        print("Enter 'S' to take the second chance.")
        chance = input('> ')
         
        # player takes the first chance
        if chance == "F":
            while True:
                if last == 20:
                    lose1()
                else:
                    print ("\nYour Turn.")
                    print ("\nHow many numbers do you wish to enter?")
                    inp = int(input('> '))
                     
                    if inp > 0 and inp <= 3:
                        comp = 4 - inp
                    else:
                        print ("Wrong input. You are disqualified from the game.")
                        lose1()
             
                    i, j = 1, 1
 
                    print ("Now enter the values")
                    while i <= inp:
                        a = input('> ')
                        a = int(a)
                        xyz.append(a)
                        i = i + 1
                     
                    # store the last element of xyz.
                    last = xyz[-1]
                     
                    # checks whether the input
                    # numbers are consecutive
                    if check(xyz) == True:
                        if last == 21:
                            lose1()
                             
                        else:
                            #"Computer's turn."
                            while j <= comp:
                                xyz.append(last + j)
                                j = j + 1
                            print ("Order of inputs after computer's turn is: ")
                            print (xyz)
                            last = xyz[-1]
                    else:
                        print ("\nYou did not input consecutive integers.")
                        lose1()
                         
        # player takes the second chance
        elif chance == "S":
            comp = 1
            last = 0
            while last < 20:
                #"Computer's turn"
                j = 1
                while j <= comp:
                    xyz.append(last + j)
                    j = j + 1
                print ("Order of inputs after computer's turn is:")
                print (xyz)
                if xyz[-1] == 20:
                    lose1()
                     
                else:
                    print ("\nYour turn.")
                    print ("\nHow many numbers do you wish to enter?")
                    inp = input('> ')
                    inp = int(inp)
                    i = 1
                    print ("Enter your values")
                    while i <= inp:
                        xyz.append(int(input('> ')))
                        i = i + 1
                    last = xyz[-1]
                    if check(xyz) == True:
                        # print (xyz)
                        near = nearestMultiple(last)
                        comp = near - last
                        if comp == 4:
                            comp = 3
                        else:
                            comp = comp
                    else:
                        # if inputs are not consecutive
                        # automatically disqualified
                        print ("\nYou did not input consecutive integers.")
                        # print ("You are disqualified from the game.")
                        lose1()
            print ("\n\nCONGRATULATIONS !!!")
            print ("YOU WON !")
            exit(0)
             
        else:
            print ("wrong choice")
                         
         
game = True   
while game == True:
        print ("Player 2 is Computer.")
        print("Do you want to play the 21 number game? (Yes / No)")
        ans = input('> ')
        if ans =='Yes':
            start1()
        else:
            print ("Do you want quit the game?(yes / no)")
            nex = input('> ')
            if nex == "yes":
                print ("You are quitting the game...")
                exit(0)
            elif nex == "no":
                print ("Continuing...")
            else:
                print ("Wrong choice")
                


Output:

Player 2 is Computer.
Do you want to start the game? (Yes/No)
> Yes
Enter 'F' to take the first chance.
Enter 'S' to take the second chance.
> S
Order of inputs after computer's turn is:
[1]

Your turn.

How many numbers do you wish to enter?
> 3
Enter your values
> 2
> 3
> 4
Order of inputs after computer's turn is:
[1, 2, 3, 4, 5, 6, 7]

Your turn.

How many numbers do you wish to enter?
> 1
Enter your values
> 8
Order of inputs after computer's turn is:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]

Your turn.

How many numbers do you wish to enter?
> 1
Enter your values
> 12
Order of inputs after computer's turn is:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]

Your turn.

How many numbers do you wish to enter?
> 1
Enter your values
> 16
Order of inputs after computer's turn is:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

Your turn.

How many numbers do you wish to enter?
> 1
Enter your values
> 20


CONGRATULATIONS!!!
YOU WON! 

Code Explanation:

  1. The code starts by creating an empty list, xyz.
  2. It then checks to see if the number 4 is in the list.
  3. If it is not, the code adds 4 to num and continues checking numbers.
  4. If num is equal to or greater than 4, the code calculates the nearest multiple of 4 and stores that value in near.
  5. The code then prints “YOU LOSE!”
  6. and ends the game.
  7. If num is not equal to or greater than 4, the code checks to see if xyz[i] – xyz[i-1] equals 1.
  8. If it does not, then i has incremented by 1 and check() returns False so last can be set to i instead of 0 (last = i).
  9. Otherwise, i has incremented by 1 and check() returns True so last can be set to i+1 instead of len(xyz)-1 (last = len(xyz)+1).
  10. The start() function starts the game by assigning xyz[] a new length of zero.
  11. This will cause last to always return 0 because there are no numbers yet in xyz[] .
  12. The code starts by creating an empty list, last in particular will keep track of the player’s score.
  13. Next, a while loop is started which will run until the user presses CTRL+C.
  14. This while loop will be responsible for playing the game.
  15. Inside the loop, xyz will be set to an empty list.
  16. The len function will be used to determine how many numbers are in xyz .
  17. Next, i will be set to 1 and it’ll start counting from 0 .
  18. The check function is then called which checks whether each number in xyz is consecutive.
  19. If it isn’t, false is returned and i is incremented by 1 .
  20. If all numbers are consecutive, then True is returned and i is reset to 1 .
  21. The code starts by asking the player for a number between 1 and 20.
  22. If the player enters a number that is not between 1 and 20, then the program prints “Your Turn.”
  23. The code then asks the player how many numbers they want to enter.
  24. If the player enters a number greater than 0 and less than 3, then the program calculates their chance of winning as 4 – input().
  25. If the player enters a number greater than 3, then their chance of winning is input().
  26. The if statement checks to see if last equals 20.
  27. If it does, then lose1() is called.
  28. Otherwise, print(“Your Turn.”)
  29. and ask for another number from the player.
  30. The while True: loop will keep running until either someone inputs a number other than “Your Turn” or last equals 20 again.
  31. In this loop, if last equals 20 again, then lose1() is called; otherwise, print(“\nHow many numbers do you wish to enter?”)
  32. and allow the player to enter another number.
  33. Inp is used in both if statements because it stores whatever was entered by the user (in this case, numbers).
  34. int(input(‘> ‘)) converts that string into an integer so that it can be
  35. The code will ask the player for a number between 0 and 3.
  36. If the number entered is greater than 0 but less than 3, then the code will check to see if the player has input 4 – the number they entered.
  37. If not, then the code will check to see if the player has input a number that equals 4.
  38. If so, then it will use that number as their comp value.
  39. If the player enters a number that does not equal 4, then they will be asked to enter another number.
  40. The game will keep track of how many numbers have been entered by the player and once they have input three numbers or more, it will declare them as losing and display an appropriate message on-screen.
  41. The code starts by initializing two variables, i and j.
  42. The code then prints a message telling the player that they are disqualified from the game because they entered an invalid input.
  43. Next, the code loops through the input string and assigns each character to a variable.
  44. The first loop checks whether each number is a consecutive sequence.
  45. If it is, then the code stores the last number in last variable and continues with the next loop.
  46. Otherwise, if check() returns True, then the player has entered an invalid input and loses 1 point.
  47. In this example, there are three possible outcomes of this game: (1) Player enters 21 as their input; (2) Player enters 22 as their input; or (3) Player enters any other valid input besides 21 or 22.
  48. In all three cases, if player loses due to an invalid input, they will be given a message indicating what happened and where to find more information about Python programming concepts.
  49. The code will check whether the input numbers are consecutive and, if they are, it will print “Wrong input.
  50. You are disqualified from the game.” If the input numbers are not consecutive, then it will print “Now enter the values” and ask the player to enter a number between 1 and 20.
  51. Once the player enters a number, it will append that number to xyz and increment i by 1.
  52. The last element of xyz will be stored in last and checked to see if it is equal to 21.
  53. If it is, then lose1() is called and the game is over.
  54. Otherwise, the game continues.
  55. The code starts by declaring two variables: comp and last.
  56. comp is a variable that stores the number of times the computer has turned, and last stores the number entered by the player.
  57. The code then declares two functions: lose1() and near.
  58. lose1() is a function that will be used to determine if the player has lost (i.e., if their input does not match any of the inputs in xyz).
  59. near is a function that will be used to determine whether or not there are any multiple matches for the player’s input (in other words, it will return the nearest multiple of 20).
  60. Next, the code sets up an infinite loop in which comp keeps track of how many times the computer has turned, and last keeps track of what was entered by the player.
  61. The while loop inside this loop checks to see if game is True (which it always is at first), and then it runs different parts of code based on that condition.
  62. First, if game is False (which means that someone else has won), then lose1() determines whether or not they have lost (by checking to see if their input matches any in xyz).
  63. If they have lost, then they exit out of this program with an
  64. The code will keep track of the order in which the players input integers.
  65. The player will have two chances to input integers.
  66. If they input consecutive integers, they are automatically declared the winner.
  67. If they make a mistake, they have a second chance to input integers.
  68. If they still make a mistake, they are disqualified from the game.
  69. If the player inputs incorrect values, their turn is over and the computer takes over again.
  70. The code also prints out congratulatory messages to the player once they win and displays an error message if there is a problem with playing the game.
     

Try it yourself as exercise:

  • You can further enhance program by increasing the number of players.
  • You can also use only even/odd numbers.
  • You can replace the numbers with binary number system.
  • You can add levels with variations in the game.
RELATED ARTICLES

Most Popular

Recent Comments