Сегодня я буду обмениваться советами по созданию игры «Угадать номер» с языком программирования Python.
Давайте начнем !
👉 Импортируйте случайные модуль, чтобы случайным образом генерировать цифры в игре.
import random
💡 Введите бесконечный цикл.
👉 Создайте случайное число, инициализируйте шансы на ноль.
while True: print("\nN U M B E R G U E S S I N G G A M E") print("\nYou have 10 chances to guess the number.") # randint function to generate the random number between 1 to 100 number = random.randint(1, 100) """ number of chances to be given to the user to guess the number or it is the inputs given by user into input box here number of chances are 10 """ chances = 0 print("Guess a number (1 - 100):")
👉 Добавьте a Wime Loop, чтобы подсчитать количество используемых шансов и возьмите вход от пользователя.
# While loop to count the number of chances while chances < 10: # Enter a number between 1 to 100 guess = int(input())
👉 Соответственно вводится пользователь с номером угада.
# Compare the user entered number with the number to be guessed if guess == number: """ if number entered by user is same as the generated number by randint function then break from loop using loop control statement "break" """ print("Congratulation YOU WON!!!") break # Check if the user entered number is smaller than the generated number elif guess < number: print("Your guess was too low: Guess a number higher than", guess) # The user entered number is greater than the generated number else: print("Your guess was too high: Guess a number lower than", guess)
👉 Увеличьте значение переменных шансов по одному в то время, когда пользователь будет использовать один шанс за раз.
# Increase the value of chance by 1 as 1 chance is used chances += 1
👉 Убедитесь, что пользователь определил номер или нет.
# Check whether the user guessed the correct number if not chances < 10: print("YOU LOSE!!! The number is", number)
👉 Задайте вопрос воспроизведения и нарушите бесконечный цикл.
ans=input("Do you want to play again (y/n) : ") if ans != 'y' : break
Вот и все! Разве это не так просто? Вы также можете ссылаться на мой репо GitHub:
Divyakelaskar/Угадка-номер
Простая терминальная игра в Python.
Простая терминальная игра в Python.
Попробуйте!
Оригинал: “https://dev.to/divyakelaskar/guess-the-number-with-python-k97”