Как написать виселицу на python

На чтение 6 мин Просмотров 3.4к. Опубликовано 28.03.2022

Содержание

  1. Введение
  2. Импорт модулей
  3. Написание кода
  4. Заключение

Введение

В этой статье напишем игру “Виселица” на python. Создание данной игры отлично подойдёт для тренировки начинающих python.

Правила создаваемой игры:

Программа загадывает слово, а игрок должен его угадать подбирая буквы. Если же игрок не угадал букву, то висельник с виселицей начинает всё больше прорисовываться, пока полностью не прорисуется. После прорисовки висельника с виселицей игрок проигрывает, если же игрок угадал слово до прорисовки, то он побеждает.

Импорт модулей

На самом деле нам понадобится всего один модуль, а именно модуль random из которого мы возьмём choice.

Импортируем:

from random import choice

Написание кода

Создадим кортеж, хранящий в себе этапы неверных предположений игрока:

HANGMAN = (
    """
     ------
     |    |
     |
     |
     |
     |
     |
    ----------
    """,
    """
     ------
     |    |
     |    O
     |
     |
     |
     |
    ----------
    """,
    """
     ------
     |    |
     |    O
     |    |
     | 
     |   
     |    
    ----------
    """,
    """
     ------
     |    |
     |    O
     |   /|
     |   
     |   
     |   
    ----------
    """,
    """
     ------
     |    |
     |    O
     |   /|\
     |   
     |   
     |     
    ----------
    """,
    """
     ------
     |    |
     |    O
     |   /|\
     |   /
     |   
     |    
    ----------
    """,
    """
     ------
     |    |
     |    O
     |   /|\
     |   / \
     |   
     |   
    ----------
    """
)

Создадим переменную max_wrong, хранящую в себе количество неверных предположений игрока:

max_wrong = len(HANGMAN) - 1

Далее создадим кортеж слов, загадываемых программой, одно из которых будет рандомно выбираться и сохраняться в переменную word:

WORDS = ("python", "игра", "программирование")  # Слова для угадывания

word = choice(WORDS)  # Слово, которое нужно угадать

Добавим ещё 2 переменных, хранящих чёрточки на каждую букву в слове и количество неверных предположений, а так же список угаданных букв:

so_far = "_" * len(word)  # Одна черточка для каждой буквы в слове, которое нужно угадать
wrong = 0  # Количество неверных предположений, сделанных игроком
used = []  # Буквы уже угаданы

Создадим цикл, который будет работать до тех пор, пока число максимальных ошибок не превысит количество имеющихся попыток и пока слово не будет угадано:

while wrong < max_wrong and so_far != word:
    print(HANGMAN[wrong])  # Вывод висельника по индексу
    print("nВы использовали следующие буквы:n", used)
    print("nНа данный момент слово выглядит так:n", so_far)

В цикле добавим переменную, в которую игрок будет вводить предполагаемые буквы:

guess = input("nnВведите свое предположение: ")  # Пользователь вводит предполагаемую букву

В основном цикле while создадим ещё один цикл, который проверяет, вводилась ли данная буква игроком ранее:

    while guess in used:
        print("Вы уже вводили букву", guess)  # Если буква уже вводилась ранее, то выводим соответствующее сообщение
        guess = input("Введите свое предположение: ")  # Пользователь вводит предполагаемую букву

Если буква не вводилась ранее, то она добавится в основном цикле в список used:

used.append(guess)  # В список использованных букв добавляется введённая буква

В основном цикле создаём условие, проверяющее есть ли введённая буква в загаданном слове:

    if guess in word:  # Если введённая буква есть в загаданном слове, то выводим соответствующее сообщение
        print("nДа!", guess, "есть в слове!")
        new = ""
        for i in range(len(word)):  # В цикле добавляем найденную букву в нужное место
            if guess == word[i]:
                new += guess
            else:
                new += so_far[i]
        so_far = new

    else:
        print("nИзвините, буквы "" + guess + "" нет в слове.")  # Если буквы нет, то выводим соответствующее сообщение
        wrong += 1

Последнее условие, которое находится после цикла проверяет, превышено ли количество ошибок:

if wrong == max_wrong:  # Если игрок превысил кол-во ошибок, то его повесили
    print(HANGMAN[wrong])
    print("nТебя повесили!")
else:  # Если кол-во ошибок не превышено, то игрок выиграл
    print("nВы угадали слово!")

И в конце кода будет выводиться загаданное слово:

print("nЗагаданное слово было "" + word + '"')

Весь код:

from random import choice

HANGMAN = (
    """
     ------
     |    |
     |
     |
     |
     |
     |
    ----------
    """,
    """
     ------
     |    |
     |    O
     |
     |
     |
     |
    ----------
    """,
    """
     ------
     |    |
     |    O
     |    |
     | 
     |   
     |    
    ----------
    """,
    """
     ------
     |    |
     |    O
     |   /|
     |   
     |   
     |   
    ----------
    """,
    """
     ------
     |    |
     |    O
     |   /|\
     |   
     |   
     |     
    ----------
    """,
    """
     ------
     |    |
     |    O
     |   /|\
     |   /
     |   
     |    
    ----------
    """,
    """
     ------
     |    |
     |    O
     |   /|\
     |   / \
     |   
     |   
    ----------
    """
)

max_wrong = len(HANGMAN) - 1
WORDS = ("python", "игра", "программирование")  # Слова для угадывания

word = choice(WORDS)  # Слово, которое нужно угадать
so_far = "_" * len(word)  # Одна черточка для каждой буквы в слове, которое нужно угадать
wrong = 0  # Количество неверных предположений, сделанных игроком
used = []  # Буквы уже угаданы

while wrong < max_wrong and so_far != word:
    print(HANGMAN[wrong])  # Вывод висельника по индексу
    print("nВы использовали следующие буквы:n", used)
    print("nНа данный момент слово выглядит так:n", so_far)

    guess = input("nnВведите свое предположение: ")  # Пользователь вводит предполагаемую букву

    while guess in used:
        print("Вы уже вводили букву", guess)  # Если буква уже вводилась ранее, то выводим соответствующее сообщение
        guess = input("Введите свое предположение: ")  # Пользователь вводит предполагаемую букву

    used.append(guess)  # В список использованных букв добавляется введённая буква

    if guess in word:  # Если введённая буква есть в загаданном слове, то выводим соответствующее сообщение
        print("nДа!", guess, "есть в слове!")
        new = ""
        for i in range(len(word)):  # В цикле добавляем найденную букву в нужное место
            if guess == word[i]:
                new += guess
            else:
                new += so_far[i]
        so_far = new

    else:
        print("nИзвините, буквы "" + guess + "" нет в слове.")  # Если буквы нет, то выводим соответствующее сообщение
        wrong += 1

if wrong == max_wrong:  # Если игрок превысил кол-во ошибок, то его повесили
    print(HANGMAN[wrong])
    print("nТебя повесили!")
else:  # Если кол-во ошибок не превышено, то игрок выиграл
    print("nВы угадали слово!")

print("nЗагаданное слово было "" + word + '"')

Заключение

В данной статье мы написали игру “Виселица” на python. Игра довольно простая, но код объёмный, надеюсь Вам понравилась статья 🙂

Спасибо всем, кто читал, удачи Вам 😉

Темы рассматриваемые в этой главе:

  • Многострочные строки
  • Методы
  • Списки
  • Методы append() и reverse()
  • lower(), upper(), split(), startswitch() и endswitch() — методы работы со строками
  • Операторы in и not in
  • Функции range() и list()
  • Объявление del
  • Цикл for
  • Условие elif

В этой главе вы познакомитесь со множеством новых понятий. Но не волнуйтесь, мы подробно рассмотрим каждую новую инструкцию и вдоволь поэкспериментируем с ней в интерактивной оболочке. Вы узнаете о методах, которые являются функциями, привязанными к значениям. Также мы изучим новый тип цикла Python 3 — for и новый тип данных — list (список). Как только вы усвоите эти знания, код программы «Виселица» станет намного понятнее.

Исходный код игры «Виселица»

Код этой игры существенно больше тех, что мы изучали ранее. Но на самом деле, значительную часть кода программы занимают символьные рисунки виселицы. Наберите код программы в текстовом редакторе Python 3 и сохраните её под именем hangman.py

 
  1. import random
  2. HANGMANPICS = ['''
  3.
  4.    +---+
  5.    |   |
  6.        |
  7.        |
  8.        |
  9.        |
 10. =========''','''
 11.
 12.    +---+
 13.    |   |
 14.    O   |
 15.        |
 16.        |
 17.        |
 18. =========''','''
 19.
 20.    +---+
 21.    |   |
 22.    O   |
 23.    |   |
 24.        |
 25.        |
 26. =========''','''
 27.
 28.    +---+
 29.    |   |
 30     O   |
 31.   /|   |
 32.        |
 33.        |
 34. =========''','''
 35.
 36.    +---+
 37.    |   |
 38.    O   |
 39.   /|  |
 40.        |
 41.        |
 42. =========''','''
 43.
 44.    +---+
 45.    |   |
 46.    O   |
 47.   /|  |
 48.   /    |
 49.        |
 50. =========''','''
 51.
 52.    +---+
 53.    |   |
 54.    O   |
 55.   /|  |
 56.   /   |
 57.        |
 58. =========''']
 59.
 60. words = 'муравей бабуин барсук медведь бобр верблюд 
кошка моллюск кобра пума койот ворона олень собака осел 
утка орел хорек лиса лягушка коза гусь ястреб ящерица лама 
моль обезьяна лось мышь мул тритон выдра сова панда попугай 
голубь питон кролик баран крыса носорог лосось акула змея 
паук аист лебедь тигр жаба форель индейка черепаха ласка 
кит волк вомбат зебра'.split()
 61.
 62. def getRandomWord(wordList):
 63.     #Эта функция возвращает случайное слово, которое выбирает из заранее 
созданного списка
 64.     wordIndex = random.randint(0, len(wordList) - 1)
 65.     return wordList[wordIndex]
 66.
 67. def displayBoard(HANGMANPICS, missedletters, correctLetters,secretWord):
 68.     print(HANGMANPICS[len(missedLetters)])
 69.     print()
 70. 
 71.     print('Неправильные буквы:', end=' ')
 72.     for letter in missedLetters:
 73.         print(letter, end=' ')
 74.     print()
 75.
 76.     blanks = '*'*len(secretWord)
 77.     #Заменяем звездочки на правильно угаданные буквы
 78.     for i in range(len(secretWord)):
 79.         if secretWord[i] in correctLetters:
 80.             blanks = blanks[:i] + secretWord[i] + blanks[i+1:]
 81.     #Показываем загаданное слово с пробелами между букв
 82.     for letter in blanks: 
 83.         print(letter, end=' ')
 84.     print()
 85.
 86. def getGuess(alreadyGuessed):
 87.     #Возвращает букву, которую ввел игрок. Эта функция проверяет, что введена
 буква, а не какой-то другой символ
 88.     while True:
 89.     print('Введите букву')
 90.     guess = input()
 91.     guess = guess.lower()
 92.     if len(guess) != 1:
 93          print('Ваша буква:')
 94.     elif guess in alreadyGuessed:
 95.         print ('Вы уже пробовали эту букву. Выберите другую')
 96.     elif guess not in 'ёйцукенгшщзхъфывапролджэячсмитьбю':
 97.         print('Пожалуйста, введите букву кириллицы')
 98.     else:
 99.         return guess
100.
101. def playAgain():
102.     #Эта функция возвращает True если игрок решит сыграть еще раз. 
В противном случае возвращается False
103.     print('Хотите попробовать еще раз? ("Да" или "Нет")')
104.     return input().lower().startswith('д')
105.
106. print('В И С Е Л И Ц А')
107. missedLetters = ''
108. correctLetters = ''
109. secretWord = getRandomWord(words)
110. gameIsDone = False
111.
112. while True:
113.     displayBoard(HANGMANPICS, missedLetters, correctLetters, secretWord)
114.
115.     #Вычисляем количество букв, которые ввел игрок
116.
117.     guess = getGuess(missedLetters+correctLetters)
118.
119.     if guess in secretWord:
120.         correctLetters = correctLetters + guess
121.
122.         #Проверка условия победы игрока
123.         foundAllLetters = True
124.         for i in range(len(secretWord)):
125.             if secretWord[i] not in correctLetters:
126.                 foundAllLetters = False
127.                 break
128.         if foundAllLetters:
129.             print('Превосходно! Было загадано слово "'+secretWord+'"
! Вы победили!')
130.
131.             gameIsDone = True
132.     else:
133.         missedLetters = missedLetters+guess
134.
135.         #Проверка условия проигрыша игрока
136.         if len(missedLetters) == len(HANGMANPICS) - 1:
137.             displayBoard(HANGMANPICS, missedLetters, correctLetters, 
secretWord)
138.             print('У вас не осталось попыток!nПосле '+str(len(missedLetters))
+' ошибок и '+str(len(correctLetters))+'угаданных букв. Загаданное слово:'
+secretWord+'"')
139.             gameIsDone = True
140.     # Спрашиваем, хочет ли игрок сыграть еще раз.
141.
142.     if gameIsDone:
143.         if playAgain():
144.             missedLetters = ''
145.             correctLetters = ''
146.             gameIsDone = False
147.             secretWord = getRandomWord(words)
148.     else:
149.         break

Как всегда, если вам лень набирать программу, вы можете скачать готовый файл на странице «Загрузки«.

Обсудить на форуме.

Permalink

Cannot retrieve contributors at this time


This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters

Show hidden characters

HANGMAN = (
«»»
«»»,
«»»
———-
«»»,
«»»
|
|
|
|
|
|
|
|
———-
«»»,
«»»
|
|
|
|
|
|
|\
| \
———-
«»»,
«»»
———
|
|
|
|
|
|
|\
| \
———-
«»»,
«»»
———
| |
|
|
|
|
|
|\
| \
———-
«»»,
«»»
———
| |
| 0
| /X\
| / \
|
|
|\
| \
———-
«»»
)
max_wrong = len(HANGMAN) 1
words = {«УРОКИ»:«Что можно приготовить, но нельзя съесть?»,
«ШАХМАТИСТ»:«Кто ходит сидя?»,
«ДВЕРЬ»:«Кто приходит, кто уходит, все ее за ручку водят.»,
«ДОРОГА»:«Если б встала, до неба достала б.»,
«День»:«К вечеру умирает, по утру оживает.»,
«РАДИО»:«В Москве говорят, а у нас слышно.»,
«ВРЕМЯ»:«Без ног и без крыльев оно, быстро летит, не догонишь его.»,
«ТУАЛЕТНАЯ»:«Самая популярная бумага»,
«СЕКРЕТОМ»:«Чем можно поделиться только один раз?»}
import random
import os
key = random.choice(list(words.keys()))
length = «-«*len(key)
wrong = 0
used = []
while wrong<max_wrong and length!=key:
print(«Добро пожаловать в игру Виселица ^^»)
print(«Попробуй отгадать слово, которое я загадал ;)»)
print(«nВот тебе небольшая подсказка:nt«,words[key])
print(HANGMAN[wrong])
print(«Вы уже предлагали следующие буквы: «,used)
print(«Отгаданное вами в слове сейчас выглядит так: «,length,«n«)
guess = input(«Введите букву: «)
guess = guess.upper()
while guess in used:
print(«Вы уже вводили букву «,guess)
guess = input(«Введите другую букву: «)
guess = guess.upper()
used.append(guess)
if guess in key:
print(«Умница! Буква «,guess,» есть в слове!»)
new = «»
for i in range(len(key)):
if guess == key[i]:
new += guess
else:
new += length[i]
length = new
else:
print(«К сожалению буквы «,guess,» нет в слове.»)
wrong += 1
os.system(‘cls’)
if wrong == max_wrong:
print(«Вас повесили >_<«)
print(HANGMAN[wrong])
else:
print(«Уря! У тебя получилось!»)
print(«Вы предлагали следующие буквы: «,used)
print(«Отгаданное вами в слове выглядит так: «,length,«n«)
print(«Было загадано слово «,key)
input(«Нажмите Enter, чтобы выйти ;)»)

Онлайн-школа программирования “Пиксель” делится бесплатными уроками по созданию игр на языке Python (Питон, Пайтон). Небольшие проекты предназначены для того, чтобы познакомить детей с Питоном, научить их писать собственные программы и реализовывать свои идеи.

На этом уроке мы запрограмммируем игру “Виселица” с помощью Python. Смысл игры в том, чтобы угадать слово, выбранное компьютером случайно из определенного списка. Игрок, угадывающий слово, в качестве подсказки видит только гласные буквы. Давайте приступим к программированию.

Мы также подготовили подробную видеоинструкцию, ищите ее в конце материала.

игра виселица на питоне

Начало программирования игры на Python

Создаем python-файл под названием hangman.py. В переводе с англ. это значит “виселица”. Импортируем модуль random. Нам он понадобится для случайного выбора слова. Создаем функцию hangman. В функцию print поместим приветственное сообщение. Создадим список и поместим в него разные фрукты. Вы можете написать свой список. В переменную secret поместим то слово, которое должен угадать игрок. В модуле random есть функция choice, которая из списка, помещенного в скобки, выберет случайное значение. Таким образом компьютер случайным образом выбирает слово.

В переменную guesses поместим гласные буквы. Мы сделали это для того, чтобы игроку была предоставлена подсказка. Ему останется угадать только согласные буквы. В turns кладем число 5, означающее количество попыток у игрока. Запустим цикл while, который будет работать, пока у игрока не закончатся попытки.

создаем игру виселица python

Переменная missed будет означать количество пропусков. Пока поместим туда ноль. Запустим цикл for, перебирающий каждую букву в загаданной компьютером слове. Далее с помощью условия будем проверять, какую букву угадал игрок. Пока в guesses записаны гласные буквы, но потом запись будет удлиняться каждый ход, когда игрок пытается отгадать букву. В том месте, где буква не отгадана, будет стоять нижнее подчеркивание. К missed будет прибавлена единица, что означает наличие пропусков в слове.

Ниже добавим условие: если missed равен нулю, то игрок выиграл, а команда break завершает цикл принудительно. Другими словами, если пропусков в слове не осталось, то игрок побеждает. В переменную guess поместим input. В данной переменной будет храниться буква, которую напишет игрок в консоли. Затем эта буква присоединяется к переменной guesses. А переменная guesses каждую итерацию, то есть каждый раз, когда код повторяется, проверяется на наличие отгаданных букв.

Последнее условие будет на тот случай, если игрок не угадает букву. У переменной turns отнимаем единицу. Выводим сообщение в консоль. Сообщаем о количестве оставшихся попыток. Запишем на каждой строке условия, которые будут отрисовывать человечка на виселице. Если игрок увидит человечка полностью, то значит игра завершилась проигрышем. Обязательно выведем в консоль загаданное слово.

Выйдем из функции. В переменную ans по умолчанию поместим ответ “да”. Цикл while будет работать только в том случае, если ans будет равен “да”. В цикл помещаем функцию hangman. Как только функция прекращает работу, в консоль выводится сообщение, которое спрашивает игрока, желает ли он продолжить игру. Через консоль игрок дает ответ. Давайте проверим, как работает программа. Пойдем по тому сценарию, где игрок угадывает слово. А теперь не угадывает.

Если хотите создавать игры, используя язык программирования Python, то записывайтесь к нам на курсы и мы вас всему научим. Школа “Пиксель” обучает программированию на Python школьников от 10 до 14 лет.

как сделать игру виселица в питон

Игра “Виселица” на Python — полный код программы

import random

def hangman():

print (‘Привет! Добро пожаловать в игру Виселица’)

wordlist = [‘мандарин’, ‘яблоко’, ‘груша’, ‘виноград’, ‘апельсин’, ‘манго’]

secret = random.choice(wordlist)

guesses = ‘ауоыиэяюёе’

turns = 5

while turns > 0:

missed = 0

for letter in secret:

if letter in guesses:

print (letter,end=’ ‘)

else:

print (‘_’,end=’ ‘)

missed += 1

if missed == 0:

print (‘nТы выиграл!’)

break

guess = input(‘nНазови букву: ‘)

guesses += guess

if guess not in secret:

turns -= 1

print (‘Не угадал.’)

print (‘n’, ‘Осталось попыток: ‘, turns)

if turns < 5: print (‘n | ‘)

if turns < 4: print (‘ O ‘)

if turns < 3: print (‘ /| ‘)

if turns < 2: print (‘ | ‘)

if turns < 1: print (‘ / ‘)

if turns == 0: print (‘nnЭто слово: ‘, secret)

ans = ‘да’

while ans == ‘да’:

hangman()

print(‘Хочешь сыграть снова? (да или нет)’)

ans = input()

Видеоурок по созданию игры:

Improve Article

Save Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    Hangman Wiki:

    The origins of Hangman are obscure meaning not discovered, but it seems to have arisen in Victorian times, ” says Tony Augarde, author of The Oxford Guide to Word Games. The game is mentioned in Alice Bertha Gomme’s “Traditional Games” in 1894 under the name “Birds, Beasts and Fishes.” The rules are simple; a player writes down the first and last letters of a word and another player guesses the letters in between. In other sources, [where?] the game is called “Gallows”, “The Game of Hangin”, or “Hanger”. 

    Implementation:

    This is a simple Hangman game using Python programming language. Beginners can use this as a small project to boost their programming skills and understanding logic.  

    1. The Hangman program randomly selects a secret word from a list of secret words. The random module will provide this ability, so line 1 in program imports it.
    2. The Game: Here, a random word (a fruit name) is picked up from our collection and the player gets limited chances to win the game.
    3. When a letter in that word is guessed correctly, that letter position in the word is made visible. In this way, all letters of the word are to be guessed before all the chances are over. 
    4. For convenience, we have given length of word + 2 chances. For example, word to be guessed is mango, then user gets 5 + 2 = 7 chances, as mango is a five-letter word.

    Example

    Python

    import random

    from collections import Counter

    someWords =

    someWords = someWords.split(' ')

    word = random.choice(someWords)

    if __name__ == '__main__':

        print('Guess the word! HINT: word is a name of a fruit')

        for i in word:

            print('_', end=' ')

        print()

        playing = True

        letterGuessed = ''

        chances = len(word) + 2

        correct = 0

        flag = 0

        try:

            while (chances != 0) and flag == 0

                print()

                chances -= 1

                try:

                    guess = str(input('Enter a letter to guess: '))

                except:

                    print('Enter only a letter!')

                    continue

                if not guess.isalpha():

                    print('Enter only a LETTER')

                    continue

                else if len(guess) & gt

                1:

                    print('Enter only a SINGLE letter')

                    continue

                else if guess in letterGuessed:

                    print('You have already guessed that letter')

                    continue

                if guess in word:

                    k = word.count(guess)

                    for _ in range(k):

                        letterGuessed += guess 

                for char in word:

                    if char in letterGuessed and (Counter(letterGuessed) != Counter(word)):

                        print(char, end=' ')

                        correct += 1

                    else if (Counter(letterGuessed) == Counter(word)):

                        print(& quot

                               The word is: & quot

                               , end=' ')

                        print(word)

                        flag = 1

                        print('Congratulations, You won!')

                        break 

                        break 

                    else:

                        print('_', end=' ')

            if chances & lt

            = 0 and (Counter(letterGuessed) != Counter(word)):

                print()

                print('You lost! Try again..')

                print('The word was {}'.format(word))

        except KeyboardInterrupt:

            print()

            print('Bye! Try again.')

            exit()

    Output: 

    Please run the program on your terminal.  

    omkarpathak@omkarpathak-Inspiron-3542:~/Documents/
    Python-Programs$ python P37_HangmanGame.py 
    Guess the word! HINT: word is a name of a fruit
    _ _ _ _ _ 
    
    Enter a letter to guess: m
    _ _ m _ _ 
    Enter a letter to guess: o
    _ _ m o _ 
    Enter a letter to guess: l
    l _ m o _ 
    Enter a letter to guess: e
    l e m o _ 
    Enter a letter to guess: n
    l e m o n 
    Congratulations, You won!

    Code Explanation:

    1. The code starts by importing the random module.
    2. This module provides a way to generate random numbers.
    3. Next, the code creates someWords, which is a list of fruit names.
    4. The list is split into spaces using the string ‘ ‘, and then each space is replaced with a letter.
    5. Next, the code randomly selects a secret word from our someWords list.
    6. This word will be used as the input for the game later on.
    7. The next part of the code checks to see if the user has entered an alpha character (a letter that appears in front of other letters).
    8. If not, then they are asked to enter only a letter.
    9. If they enter an alpha character, then it’s assumed that they want to guess at another letter in word .
    10. So, this part of the code checks to see if guess matches one of the letters in word .
    11. If it does, then chances is updated and flag is set to 1 .
    12. Otherwise, chances is decreased by 1 and flag remains at 0 .
    13. The next part of the code tries to guess at another letter in word .
    14. If guess isn’t valid (i.e., it doesn’t match any of the letters in word ), then print() prints out all empty spaces for letters in word , and
    15. The code starts by importing the random module.
    16. This module provides us with a number of useful functions, one of which is the choice function.
    17. This function allows us to randomly choose a secret word from our list of words.
    18. Next, we create some variables which will be used throughout the program.
    19. These include someWords , word and letterGuessed .
    20. letterGuessed will store the letter guessed by the player, while chances will store the number of times that the player has correctly guessed the word so far.
    21. correct will keep track of how many letters have been guessed so far and flag will indicate whether or not the player has guessed the word correctly.
    22. We then start looping through our list of words and randomly choosing a secret word from it.

    Try it yourself Exercises: 

    • You can further enhance program by adding timer after every Guess
    • You can also give hints from the beginning to make the task a bit easier for user
    • You can also decrease the chance by one only if the player’s guess is WRONG. If the guess is right, 
      player’s chance is not reduced.

    This article is contributed by Omkar Pathak. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

    Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above.

    Improve Article

    Save Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    Hangman Wiki:

    The origins of Hangman are obscure meaning not discovered, but it seems to have arisen in Victorian times, ” says Tony Augarde, author of The Oxford Guide to Word Games. The game is mentioned in Alice Bertha Gomme’s “Traditional Games” in 1894 under the name “Birds, Beasts and Fishes.” The rules are simple; a player writes down the first and last letters of a word and another player guesses the letters in between. In other sources, [where?] the game is called “Gallows”, “The Game of Hangin”, or “Hanger”. 

    Implementation:

    This is a simple Hangman game using Python programming language. Beginners can use this as a small project to boost their programming skills and understanding logic.  

    1. The Hangman program randomly selects a secret word from a list of secret words. The random module will provide this ability, so line 1 in program imports it.
    2. The Game: Here, a random word (a fruit name) is picked up from our collection and the player gets limited chances to win the game.
    3. When a letter in that word is guessed correctly, that letter position in the word is made visible. In this way, all letters of the word are to be guessed before all the chances are over. 
    4. For convenience, we have given length of word + 2 chances. For example, word to be guessed is mango, then user gets 5 + 2 = 7 chances, as mango is a five-letter word.

    Example

    Python

    import random

    from collections import Counter

    someWords =

    someWords = someWords.split(' ')

    word = random.choice(someWords)

    if __name__ == '__main__':

        print('Guess the word! HINT: word is a name of a fruit')

        for i in word:

            print('_', end=' ')

        print()

        playing = True

        letterGuessed = ''

        chances = len(word) + 2

        correct = 0

        flag = 0

        try:

            while (chances != 0) and flag == 0

                print()

                chances -= 1

                try:

                    guess = str(input('Enter a letter to guess: '))

                except:

                    print('Enter only a letter!')

                    continue

                if not guess.isalpha():

                    print('Enter only a LETTER')

                    continue

                else if len(guess) & gt

                1:

                    print('Enter only a SINGLE letter')

                    continue

                else if guess in letterGuessed:

                    print('You have already guessed that letter')

                    continue

                if guess in word:

                    k = word.count(guess)

                    for _ in range(k):

                        letterGuessed += guess 

                for char in word:

                    if char in letterGuessed and (Counter(letterGuessed) != Counter(word)):

                        print(char, end=' ')

                        correct += 1

                    else if (Counter(letterGuessed) == Counter(word)):

                        print(& quot

                               The word is: & quot

                               , end=' ')

                        print(word)

                        flag = 1

                        print('Congratulations, You won!')

                        break 

                        break 

                    else:

                        print('_', end=' ')

            if chances & lt

            = 0 and (Counter(letterGuessed) != Counter(word)):

                print()

                print('You lost! Try again..')

                print('The word was {}'.format(word))

        except KeyboardInterrupt:

            print()

            print('Bye! Try again.')

            exit()

    Output: 

    Please run the program on your terminal.  

    omkarpathak@omkarpathak-Inspiron-3542:~/Documents/
    Python-Programs$ python P37_HangmanGame.py 
    Guess the word! HINT: word is a name of a fruit
    _ _ _ _ _ 
    
    Enter a letter to guess: m
    _ _ m _ _ 
    Enter a letter to guess: o
    _ _ m o _ 
    Enter a letter to guess: l
    l _ m o _ 
    Enter a letter to guess: e
    l e m o _ 
    Enter a letter to guess: n
    l e m o n 
    Congratulations, You won!

    Code Explanation:

    1. The code starts by importing the random module.
    2. This module provides a way to generate random numbers.
    3. Next, the code creates someWords, which is a list of fruit names.
    4. The list is split into spaces using the string ‘ ‘, and then each space is replaced with a letter.
    5. Next, the code randomly selects a secret word from our someWords list.
    6. This word will be used as the input for the game later on.
    7. The next part of the code checks to see if the user has entered an alpha character (a letter that appears in front of other letters).
    8. If not, then they are asked to enter only a letter.
    9. If they enter an alpha character, then it’s assumed that they want to guess at another letter in word .
    10. So, this part of the code checks to see if guess matches one of the letters in word .
    11. If it does, then chances is updated and flag is set to 1 .
    12. Otherwise, chances is decreased by 1 and flag remains at 0 .
    13. The next part of the code tries to guess at another letter in word .
    14. If guess isn’t valid (i.e., it doesn’t match any of the letters in word ), then print() prints out all empty spaces for letters in word , and
    15. The code starts by importing the random module.
    16. This module provides us with a number of useful functions, one of which is the choice function.
    17. This function allows us to randomly choose a secret word from our list of words.
    18. Next, we create some variables which will be used throughout the program.
    19. These include someWords , word and letterGuessed .
    20. letterGuessed will store the letter guessed by the player, while chances will store the number of times that the player has correctly guessed the word so far.
    21. correct will keep track of how many letters have been guessed so far and flag will indicate whether or not the player has guessed the word correctly.
    22. We then start looping through our list of words and randomly choosing a secret word from it.

    Try it yourself Exercises: 

    • You can further enhance program by adding timer after every Guess
    • You can also give hints from the beginning to make the task a bit easier for user
    • You can also decrease the chance by one only if the player’s guess is WRONG. If the guess is right, 
      player’s chance is not reduced.

    This article is contributed by Omkar Pathak. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

    Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above.

    сделать простую игру с палачом на языке программирования Python

    Всем привет! Сегодня я покажу вам, как сделать простую игру с палачом на языке программирования Python.

    План

    Наша игра «Виселица» должна делать следующее:

    Пусть пользователь угадывает символы для случайных слов

    Теперь вы можете начать думать о том, как это может работать в коде. Код должен будет сделать следующее:

    1. Используйте случайную библиотеку
    2. сделать входную переменную для имени пользователя и сказать привет
    3. составить список слов
    4. создать переменную, которая случайным образом выбирает слова из предыдущего списка
    5. предложить пользователю угадать символы
    6. создать переменную предположения
    7. создайте переменную поворотов и установите для нее любое число
    8. создать цикл while для поворотов, пока больше 0
    9. создать переменную в цикле while и вызвать ее не удалось и она равна 0
    10. создать цикл for внутри цикла while (для char в слове)
    11. создайте оператор if в цикле for (если char в предположениях), затем напечатайте его, иначе напечатайте «_» и увеличьте неудачную переменную на единицу
    12. создайте оператор if внутри цикла while для ошибки и установите для него значение 0, и если его истинная печать вы выиграете, напечатаете слово и прервете цикл while.
    13. создайте входную переменную для предположения, чтобы угадать символ
    14. сохранить каждый входной символ в переменной предположения
    15. создайте оператор if, если догадываетесь не в слове, затем уменьшите «повороты» на единицу и напечатайте неправильно и напечатайте количество ходов, оставшихся для пользователя
    16. если повороты = 0, вы проигрываете
    import random 
    # library that we use in order to choose  
    # on random words from a list of words 
      
    name = input("What is your name? ") 
    # Here the user is asked to enter the name first 
      
    print("Good Luck ! ", name) 
      
    words = ['rainbow', 'computer', 'science', 'programming',  
             'python', 'mathematics', 'player', 'condition',  
             'reverse', 'water', 'board', 'geeks']  
      
    # Function will choose one random 
    # word from this list of words 
    word = random.choice(words) 
      
      
    print("Guess the characters") 
      
    guesses = '' 
      
    # any number of turns can be used here 
    turns = 12
      
      
    while turns > 0: 
          
        # counts the number of times a user fails 
        failed = 0
          
        # all characters from the input 
        # word taking one at a time. 
        for char in word:  
              
            # comparing that character with 
            # the character in guesses 
            if char in guesses:  
                print(char) 
                  
            else:  
                print("_") 
                  
                # for every failure 1 will be 
                # incremented in failure 
                failed += 1
                  
      
        if failed == 0: 
            # user will win the game if failure is 0 
            # and 'You Win' will be given as output 
            print("You Win")  
              
            # this print the correct word 
            print("The word is: ", word)  
            break
          
        # if user has input the wrong alphabet then 
        # it will ask user to enter another alphabet 
        guess = input("guess a character:") 
          
        # every input character will be stored in guesses  
        guesses += guess  
          
        # check input with the character in word 
        if guess not in word: 
              
            turns -= 1
              
            # if the character doesn’t match the word 
            # then “Wrong” will be given as output  
            print("Wrong") 
              
            # this will print the number of 
            # turns left for the user 
            print("You have", + turns, 'more guesses') 
              
              
            if turns == 0: 
                print("You Loose")

    Вывод:

    What is your name? Gautam
    Good Luck!  Gautam
    Guess the characters
    _
    _
    _
    _
    _
    guess a character:g
    g
    _
    _
    _
    _
    guess a character:e
    g
    e
    e
    _
    _
    guess a character:k
    g
    e
    e
    k
    _
    guess a character:s
    g
    e
    e
    k
    s
    You Win
    The word is:  geeks

    Вывод

    Надеюсь, вы узнали что-то новое о программировании и решении задач, и следите за новостями.

    Понравилась статья? Поделить с друзьями:
  • Как написать вирусный пост вконтакте
  • Как написать вирусную программу троян
  • Как написать вирусную программу на python для новичка
  • Как написать вирус шутку
  • Как написать вирус шифровальщик