The Wayback Machine - https://web.archive.org/web/20241001235455/https://www.geeksforgeeks.org/python-cows-and-bulls-game/
Open In App

Python – Cows and Bulls game

Last Updated : 24 Jan, 2021
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 crack the secret number. Upon making a guess, 2 hints will be provided- Cows and Bulls.
  • Bulls indicate the number of correct digits in the correct position and cows indicates the number of correct digits in the wrong position. For example, if the secret code is 1234 and the guessed number is 1246 then we have 2 BULLS (for the exact matches of digits 1 and 2) and 1 COW (for the match of digit 4 in the wrong position)
  • The player keeps on guessing until the secret code is cracked. The player who guesses in the minimum number of tries wins.

Explanation:

Let’s see a sample run for better understanding.

Secret Code: 3768

Guess: 1234
Response: 0 bulls, 1 cow
Guess: 5678
Response: 1 bull, 2 cows
Guess: 1678
Response: 1 bull, 2 cows
Guess: 3678
Response: 2 bulls, 2 cows
Guess: 3148
Response: 2 bulls, 0 cows
Guess: 3768
You guessed right!

Approach:

To create this game in Python, the computer generates a secret code and the user will have to guess the code. Break it down into these blocks:

  • Generate a secret code- Generate a random 4-digit number and check that it does not have any repeated digits.
  • Generate hint or response- Take the generated 4-digit secret number and the guessed number (input). Find the common digits with exact matches (bulls) and the common digits in the wrong position (cows). Repeat with each guess until you have 4 bulls (an exact match) or you run out of tries.

Constraint: The secret code and the guessed code should be of 4-digits (between 1000 and 9999) and have no repeated numbers.

Program:

Python




# Import required module
import random 
  
# Returns list of digits 
# of a number
def getDigits(num):
    return [int(i) for i in str(num)]
      
  
# Returns True if number has 
# no duplicate digits 
# otherwise False      
def noDuplicates(num):
    num_li = getDigits(num)
    if len(num_li) == len(set(num_li)):
        return True
    else:
        return False
  
  
# Generates a 4 digit number 
# with no repeated digits    
def generateNum():
    while True:
        num = random.randint(1000,9999)
        if noDuplicates(num):
            return num
  
  
# Returns common digits with exact 
# matches (bulls) and the common 
# digits in wrong position (cows)
def numOfBullsCows(num,guess):
    bull_cow = [0,0]
    num_li = getDigits(num)
    guess_li = getDigits(guess)
      
    for i,j in zip(num_li,guess_li):
          
        # common digit present
        if j in num_li:
          
            # common digit exact match
            if j == i:
                bull_cow[0] += 1
              
            # common digit match but in wrong position
            else:
                bull_cow[1] += 1
                  
    return bull_cow
      
      
# Secret Code
num = generateNum()
tries =int(input('Enter number of tries: '))
  
# Play game until correct guess 
# or till no tries left
while tries > 0:
    guess = int(input("Enter your guess: "))
      
    if not noDuplicates(guess):
        print("Number should not have repeated digits. Try again.")
        continue
    if guess < 1000 or guess > 9999:
        print("Enter 4 digit number only. Try again.")
        continue
      
    bull_cow = numOfBullsCows(num,guess)
    print(f"{bull_cow[0]} bulls, {bull_cow[1]} cows")
    tries -=1
      
    if bull_cow[0] == 4:
        print("You guessed right!")
        break
else:
    print(f"You ran out of tries. Number was {num}")


Output:



Previous Article
Next Article

Similar Reads

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
Create a 2D Game with Python and the Arcade Library
We have a task to create a 2D game with Python and the Arcade library. In this article, we will demonstrate how to create a 2D game using Python and the Arcade library. What is Arcade Library?The Arcade library in Python is a modern framework designed for creating 2D games and graphical applications. It provides a user-friendly and intuitive interf
7 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
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
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
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 variatio
11 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
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
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
Conway's Game Of Life (Python Implementation)
Conways's Game Of Life is a Cellular Automation Method created by John Conway. This game was created with Biology in mind but has been applied in various fields such as Graphics, terrain generation,etc.. The "game" is a zero-player game, meaning that its evolution is determined by its initial state, requiring no further input. One interacts with th
5 min read
Python Game Development Libraries
Python, with its simplicity and versatility, has become a favorite among developers for various applications, including game development. Thanks to its rich ecosystem of libraries and frameworks, creating games with Python has never been easier. In this article, we'll delve into some of the top Python game development frameworks and provide an over
5 min read
Practice Tags :