Python’s concise syntax and straightforward programming paradigm make it an excellent choice for creating quick and fun games. In this article, we’ll explore a simple Python game that can be implemented in just 10 lines of code.
The game we’ll build is a variation of the classic “Guess a Number” game. The computer will randomly select a number between 1 and 10, and the player will have to guess it. The player gets three chances to guess correctly.
Here’s the code for the game:
pythonimport random
secret_number = random.randint(1, 10)
guess_limit = 3
guess_count = 0
while guess_count < guess_limit:
guess = int(input("Guess a number between 1 and 10: "))
guess_count += 1
if guess == secret_number:
print("Congratulations, you guessed it!")
break
else:
print("Sorry, you've exceeded the number of guesses. The secret number was:", secret_number)
Let’s break down the code:
- We import the
random
module to generate a random number.
- We define the
secret_number
as a random integer between 1 and 10.
- We set the
guess_limit
to 3, indicating that the player has three chances to guess the number.
- We initialize the
guess_count
to 0 to track the number of guesses.
- We use a
while
loop that continues until the player guesses correctly or exceeds the guess limit.
- Inside the loop, we prompt the player for a guess using the
input()
function, convert it to an integer, and increment the guess_count
.
- If the player guesses correctly, we congratulate them and use the
break
statement to exit the loop.
- If the loop completes without a correct guess (i.e., the player exceeds the guess limit), we print a message indicating that they have exceeded the number of guesses and display the secret number.
This simple game demonstrates the power of Python’s concise syntax and the effectiveness of its built-in functions for creating engaging experiences. It’s a great starting point for beginners interested in learning more about programming and game development.