Let’s create a step-by-step guide for building a simple 21 Number game in Python. This game, also known as “21,” “Bagram,” or “Twenty plus one,” progresses by counting up from 1 to 21. The player who calls “21” is eliminated. It can be played between any number of players. In the example below, we’ll illustrate the game between the player and the computer.
Step 1: Define a Function to Find the Nearest Multiple of 4
We’ll need a function that returns the nearest multiple of 4 for a given number. This will help us determine the computer’s moves.
Python
def nearest_multiple(num): if num >= 4: return num + (4 - (num % 4)) else: return 4
AI-generated code. Review and use carefully. More info on FAQ.
Step 2: Implement the Game Logic
- Player Takes the First Chance:
- The player can choose to start first.
- The player enters how many numbers they wish to input (between 1 and 3).
- The computer calculates the remaining numbers to complete the set of 4.
- The player inputs consecutive integers.
- The game continues until the player reaches 21 or makes an incorrect move.
- Player Takes the Second Chance:
- The player can choose to play second.
- The computer starts by adding numbers to the sequence.
- The player then enters their numbers.
- The game continues until the player reaches 21 or makes an incorrect move.
Final Code:
Python
def check_consecutive(lst): for i in range(1, len(lst)): if lst[i] - lst[i - 1] != 1: return False return True def lose(): print("\n\nYOU LOSE!") print("Better luck next time!") exit(0) def play_game(): xyz = [] last = 0 while True: print("Enter 'F' to take the first chance.") print("Enter 'S' to take the second chance.") chance = input('> ') if chance == "F": while True: if last == 20: lose() else: print("\nYour Turn.") inp = int(input("How many numbers do you wish to enter? ")) if 0 < inp <= 3: comp = 4 - inp else: print("Wrong input. You are disqualified from the game.") lose() print("Now enter the values:") for _ in range(inp): a = int(input('> ')) xyz.append(a) last = a if check_consecutive(xyz): if last == 21: lose() else: while comp > 0: xyz.append(last + comp) comp -= 1 print("Order of inputs after computer's turn:") print(xyz) last = xyz[-1] else: print("\nYou did not input consecutive integers.") lose() elif chance == "S": comp = 1 while last < 20: while comp > 0: xyz.append(last + comp) comp -= 1 print("Order of inputs after computer's turn:") print(xyz) print("\nYour turn.") inp = int(input("How many numbers do you wish to enter? ")) for _ in range(inp): xyz.append(int(input('> '))) last = xyz[-1] if check_consecutive(xyz): near = nearest_multiple(last) comp = near - last if comp == 4: comp = 3 else: print("\nYou did not input consecutive integers.") lose() print("\n\nCONGRATULATIONS!!! You've won!") if __name__ == "__main__": play_game()
Written by: Piyush Patil
Feel free to customize the game further or add additional features. Happy coding! 😊