Hello Python Lovers!
Today I will teach you how to make a simple word guessing game using the Python programming language. The game is based on the computer choosing a random word and the user trying to guess the word.
First, we need to create a word list using the Python programming language. We will randomly select a word from this list and give the user a chance to guess the word.
First, we include the random module in our project. This module will help us generate random numbers and select random items.
Now, let's define a function to select a random word:
def word_choice():
words = ["python", "computer", "programming", "data", "developer", "artificial", "intelligence"]
return random.choice(words)
With this function, we create an array of words and randomly select a word from this array. We then return the selected word.
Next, we will create a function to get the user's guesses:
This function takes a letter input from the user and returns the value.
Now, let's define a function to display the predicted letters:
def show_word(word, predicted_predicted_letters):
letter_list = [letter if letter in predicted_predicted_letters else "_" for letter in word]
return " ".join(letter_list)
This function shows the letters that the user has guessed correctly, while it converts the letters that have not yet been guessed to "_".
Now, let's create a function to start the game:
def game():
word = word_choice()
predicted_predicted_letters = set()
guess_right = 6
while guess_right > 0:
guess = input_guess()
guessed_edited_letters.add(guess)
if guess not in word:
guess_right -= 1
print(f "Wrong guess! You have one guess left: {guess_right}")
else:
print("Correct guess!")
print(show_word(word, predicted_predicted_letters))
if "_" not in show_word(word, predicted_predicted_letters):
print("Congratulations, you guessed the word correctly!")
break
else:
print(f "Unfortunately you are out of guesses. The correct word is: {word}")
if __name__ == "__main__":
game()
Display More
We start our game with these functions. We take the user's guesses, check the accuracy of the guesses and print the results on the screen. Since the guessing right is limited, we check whether the user was successful or not and print the result on the screen.
In this content, I have explained a simple word guessing game in Python step by step. These examples will help you practice and have fun while learning Python programming language.
By trying this game, you can better understand basic concepts in Python such as loops, conditions, and string operations. You can also modify the code to suit your needs to create more complex games. You can also share your version here if you like. If you have any questions or suggestions, you can ask them under this topic.
Thank you for reading and good work!