Python Guess‑the‑Word (Hangman) Game Implementation
This article presents a complete Python implementation of a guess‑the‑word (Hangman) game, explaining its mechanics, providing detailed source code, and offering a simplified version for readers to learn basic programming concepts and game logic.
This article provides a full Python implementation of a guess‑the‑word (Hangman) game, describing the game flow, user interaction, and win/lose conditions.
The program randomly selects a word from a predefined list, displays blanks for each letter, tracks correct and incorrect guesses, limits the number of attempts, and allows the player to replay the game.
Key functions include getWord for selecting a random word, display for showing the current game state, getLetter for handling user input, and playAgain for restarting the session.
Full source code for the main version:
from random import *
words = 'tiger lion wolf elephant zebra ducksheep rabbit mouse'.split
def getWord(wordList):
n = randint(0, len(wordList)-1)
return wordList[n]
def display(word, wrongLetters, rightLetters, chance):
print('你还有{:n}次机会'.format(chance).center(40,'-'))
print('已经猜错的字母:' + wrongLetters)
print()
blanks = '_' * len(word)
for i in range(len(word)):
if word[i] in rightLetters:
blanks = blanks[:i] + word[i] + blanks[i+1:]
for i in blanks:
print(i + ' ', end='')
print()
print()
def getLetter(alreadyGuessed):
while True:
print('请输入一个可能的字母:')
guess = input()
guess = guess.lower()
if guess[0] in alreadyGuessed:
print('你已经猜过这个字母了!')
elif guess[0] not in 'qwertyuiopasdfghjklzxcvbnm':
print('请输入英文字母!(a-z)')
else:
return guess[0]
def playAgain():
print('是否在玩一次?(y/n)')
s = input()
s = s.lower()
if s[0] == 'y':
return 1
return 0
# 游戏初始化
wrongLetters = ''
rightLetters = ''
word = getWord(words)
chance = 6 # 初始为6次机会
done = False
while True:
display(word, wrongLetters, rightLetters, chance)
guess = getLetter(wrongLetters + rightLetters)
if guess in word:
rightLetters = rightLetters + guess
foundAll = True
for i in range(len(word)):
if word[i] not in rightLetters:
foundAll = False
break
if foundAll:
print('你真棒,这个单词就是' + word + ',你赢了!')
done = True
else:
wrongLetters = wrongLetters + guess
chance = chance - 1
if chance == 0:
display(word, wrongLetters, rightLetters, chance)
print("你已经没有机会了!你一共猜错了" + str(len(wrongLetters)) + "次,猜对了" + str(len(rightLetters)) + "次,正确的单词是:" + word)
done = True
if done:
if playAgain():
wrongLetters = ''
rightletters = ''
word = getWord(words)
chance = 6 # 初始为6次机会
done = 0
else:
breakA simplified version of the game is also provided, showing random word selection, user input handling, and win/lose logic in a more compact form.
import random
WORDS = ("math","english","china","history")
right = 'Y'
print("欢迎参加猜单词游戏!")
while right == 'Y' or right == 'y':
word = random.choice(WORDS)
correct = word
newword = ''
while word:
pos = random.randrange(len(word))
newword += word[pos]
word = word[:pos] + word[(pos+1):]
print("你要猜测的单词为:", newword)
guess = input("请输入你的答案:")
count = 1
while count < 5:
if guess != correct:
guess = input("输入的单词错误,请重新输入:")
count += 1
else:
print("输入的单词正确,正确单词为:", correct)
break
if count == 5:
print("您已猜错5次,正确的单词为:", correct)
right = input("是否继续,Y/N:")Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.