21 Number game in Python

Last Updated : 11 Dec, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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.


Previous Article
Next Article

Similar Reads

Python implementation of automatic Tic Tac Toe game using random number
Tic-tac-toe is a very popular game, so let's implement an automatic Tic-tac-toe game using Python. The game is automatically played by the program and hence, no user input is needed. Still, developing an automatic game will be lots of fun. Let's see how to do this. NumPy and random Python libraries are used to build this game. Instead of asking the
5 min read
Number Guessing Game Using Python Tkinter Module
Number Guessing Game using the Python Tkinter module is a simple game that involves guessing a randomly generated number. The game is developed using the Tkinter module, which provides a graphical user interface for the game. The game has a start button that starts the game and a text entry field where the user can enter their guess. The game also
5 min read
Number Guessing Game Using Python Streamlit Library
The game will pick a number randomly from 1 to 100 and the player needs to guess the exact number guessed by calculating the hint. The player will get 7 chances to guess the number and for every wrong guess game will tell you if the number is more or less or you can take a random hint to guess the number like (2+2=?, 3*3=?) to guess the number. In
5 min read
Number guessing game in Python 3 and C
Most of the geeks from a CS (Computer Science) background, think of their very first project after doing a Programming Language. Here, you will get your very first project and the basic one, in this article. Task: Below are the steps: Build a Number guessing game, in which the user selects a range.Let's say User selected a range, i.e., from A to B,
7 min read
PyQt5 - Number Guessing Game
In this article we will see how we can create a number guessing name using PyQt5. The Number guessing game is all about guessing the number randomly chosen by the computer in the given number of chances. Below is how game will look like GUI implementation steps 1. Create a head label to show the game name, set its alignment font and color 2. Create
4 min read
Color game using Tkinter in Python
TKinter is widely used for developing GUI applications. Along with applications, we can also use Tkinter GUI to develop games. Let's try to make a game using Tkinter. In this game player has to enter color of the word that appears on the screen and hence the score increases by one, the total time to play this game is 30 seconds. Colors used in this
4 min read
Rock, Paper, Scissor game - Python Project
In this article, we will see how we can create a rock paper and scissor game using Tkinter. Rock paper scissor is a hand game usually played between two people, in which each player simultaneously forms one of the three shapes with an outstretched hand. These shapes are “rock”, “paper”, and “scissors”. Game Winner Conditions Let there be a Player w
15+ min read
Python | Program to implement simple FLAMES game
Python is a multipurpose language and one can do literally anything with it. Python can also be used for game development. Let’s create a simple FLAMES game without using any external game libraries like PyGame. FLAMES is a popular game named after the acronym: Friends, Lovers, Affectionate, Marriage, Enemies, Sibling. This game does not accurately
6 min read
Python | Simple FLAMES game using Tkinter
Prerequisites: Introduction to TkinterProgram to implement simple FLAMES game Python offers multiple options for developing a GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with Tkinter outputs the fastest and e
5 min read
Python | Pokémon Training Game
Problem : You are a Pokémon trainer. Each Pokémon has its own power, described by a positive integer value. As you travel, you watch Pokémon and you catch each of them. After each catch, you have to display maximum and minimum powers of Pokémon caught so far. You must have linear time complexity. So sorting won't help here. Try having minimum extra
1 min read
Mastermind Game using Python
Given the present generation's acquaintance with gaming and its highly demanded technology, many aspire to pursue the idea of developing and advancing it further. Eventually, everyone starts at the beginning. Mastermind is an old code-breaking game played by two players. The game goes back to the 19th century and can be played with paper and pencil
8 min read
Introduction to pyglet library for game development in Python
Pyglet is easy to use but powerful library for developing visually rich GUI applications like games, multimedia etc on Windows, Mac OS and Linux. This library is created purely in Python and it supports many features like windowing, user interface event handling, Joysticks, OpenGL graphics, loading images, and videos, and playing sounds and music.
2 min read
Tic Tac Toe Game using PyQt5 in Python
In this article , we will see how we can create a Tic Tac Toe game using PyQt5. Tic-tac-toe, noughts, and crosses, or Xs and Os is a paper-and-pencil game for two players, X and O, who take turns marking the spaces in a 3×3 grid. The player who succeeds in placing three of their marks in a horizontal, vertical, or diagonal row is the winner. Below
5 min read
Create a Simple Two Player Game using Turtle in Python
Prerequisites: Turtle Programming in Python TurtleMove game is basically a luck-based game. In this game two-players (Red & Blue), using their own turtle (object) play the game. How to play The game is played in the predefined grid having some boundaries. Both players move the turtle for a unit distance.Now both players flip the coin:if HEAD, t
4 min read
Snake Water Gun game using Python and C
Snake Water Gun is one of the famous two-player game played by many people. It is a hand game in which the player randomly chooses any of the three forms i.e. snake, water, and gun. Here, we are going to implement this game using python. This python project is to build a game for a single player that plays with the computer Following are the rules
8 min read
Tic Tac Toe game with GUI using tkinter in Python
Tic-tac-toe (American English), noughts and crosses (British English), or Xs and Os is a paper-and-pencil game for two players, X and O, who take turns marking the spaces in a 3×3 grid. The player who succeeds in placing three of their marks in a horizontal, vertical, or diagonal row is the winner. tkinter Python library is used to create the GUI.
15+ min read
Quote Guessing Game using Web Scraping in Python
Prerequisite: BeautifulSoup Installation In this article, we will scrape a quote and details of the author from this site http//quotes.toscrape.com using python framework called BeautifulSoup and develop a guessing game using different data structures and algorithm. The user will be given 4 chances to guess the author of a famous quote, In every ch
3 min read
Python - Cows and Bulls game
Cows and Bulls is a pen and paper code-breaking game usually played between 2 players. In this, a player tries to guess a secret code number chosen by the second player. The rules are as follows: A player will create a secret code, usually a 4-digit number. This number should have no repeated digits.Another player makes a guess (4 digit number) to
3 min read
Game of Craps in Python
In this article, we are going to discuss how to create the Game of Craps using Python. Rules of the game: Two dices are required to play and a player rolls two six-sided dice and adds the numbers rolled together.If on the first roll a player encounters a total of 7 or 11 the player automatically wins, and if the player rolls a total of 2, 3, or 12
5 min read
Python - MCQ Quiz Game using Tkinter
Prerequisite: Python GUI – tkinter Python provides a standard GUI framework Tkinter which is used to develop fast and easy GUI applications. Here we will be developing a simple multiple-choice quiz in python with GUI. We will be creating a multiple choice quiz in Python with Tkinter. First, we will create a library named Quiz in the directory of yo
6 min read
KBC game using Python
In this article, we will make a KBC game with almost all the features in CLI(Command Line Interface) mode using Python. Features of the game:Random questions every timeFour lifelinesAudience Poll50:50Double dipFlip the questionMade with the help of Matplotlib and NumPy libraries of python.Bar graph for audience poll lifelineRules to play the game:T
15 min read
Python Arcade - Adding Bullets in Game
In this article, we will learn how to add bullets to a game in Arcade using Python. Adding Bullet In this example, we are going to add bullets to the screen. For this, we will use some functions: draw_text(): This function is used to draw text to the screen using Pyglet’s label. Syntax: arcade.draw_text(text, x, y, color, size, width, align, font_n
4 min read
Higher-Lower Game with Python
In this article, we will be looking at the way to design a game in which the user has to guess which has a higher number of followers and it displays the scores. Game Play:The name of some Instagram accounts will be displayed, you have to guess which has a higher number of followers by typing in the name of that account. Make sure you type the name
8 min read
Snake Game Using Tkinter - Python
For many years, players all across the world have cherished the iconic video game Snake. The player controls a snake that crawls around the screen while attempting to consume food, avoiding obstacles or running into its own tail. It is a straightforward but addictive game. The snake lengthens each time it consumes food, and the player must control
12 min read
Brick Breaker Game In Python using Pygame
Brick Breaker is a 2D arcade video game developed in the 1990s. The game consists of a paddle/striker located at the bottom end of the screen, a ball, and many blocks above the striker. The basic theme of this game is to break the blocks with the ball using the striker. The score is calculated by the number of blocks broken and each time the player
14 min read
Dice game using Turtle in Python
Dice Roll Game using python turtleThe simple python program implements the rolling of dice using the turtle library and random module of python. The turtle library is used to draw graphics and animations on the screen, while the random library is used to generate random numbers and random selections that can be used to control the behavior of the t
3 min read
Automate Chrome Dino Game using Python
For this article, we will be building a Python bot that can play the "Chrome Dino Offline Game". Chrome dino is a dinosaur game that launches itself on your web browser when there is no internet connection. For the introduction of the game, the dinosaur has to jump to avoid the approaching cactus or duck to avoid the bird. The first fundamental ste
7 min read
Blackjack console game using Python
Blackjack is a popular two-player card game that is played with a deck of standard playing cards around the world in casinos. The main criteria for winning this game are chance and strategy. The challenge of this game is to get as close to 21 points as possible without exceeding them. That is why it is also known as Twenty-One. In this article, we
6 min read
Create Bingo Game Using Python
A card with a grid of numbers on it is used to play the popular dice game of bingo. Players check off numbers on their cards when they are selected at random by a caller, competing to be the first to mark off all of their numbers in a particular order. We'll examine how to utilise Python to create a simple bingo game in this lesson. The following i
9 min read
A Game of Anagrams in Python
Project idea:The aim of this project is to create a game in python in which the user is presented with an anagram of a word and has to guess the right word within a limited number of attempts. Features of Project: The user is given a fixed number of attempts to guess the correct word. The number of attempts is dependent on the length of the word.Af
4 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg