This project contains a simple python script to play a terminal-based hangman game.
Run the script:
Source Code:
hangman.py
import random
from json import load
# function to randomly get one word from words.py and convert the word to uppercase
def get_word():
with open('words.json') as json_file:
data = load(json_file)
wordArray = data["word_list"]
word = random.choice(wordArray)
word = word.upper()
return word
# function to play the game
def play(word):
# intialise variable
word_completion = "_" * len(word) # generate a line to show the number of word
guessed = False # indicate the status of guess
guessed_letters = [] # store guessed letters
guessed_words = [] # store guessed words
tries = 6 # user have 6 times of wrong
# display message and the format of the hangman
print("Let's play Hangman!")
print(display_hangman(tries))
print(word_completion)
print("\n")
print("Length of the word: ", len(word))
print("\n")
# user can keep guessing when the tries is more than 0 and the answer is not found yet.
while not guessed and tries > 0:
# Display message and ask for user input and convert it into uppercase
guess = input("Please guess a letter or the word: ").upper()
# check the length of the user input and is it alpha or not
if len(guess) == 1 and guess.isalpha():
# display message when user guess the same letter twice
if guess in guessed_letters:
print("You already guessed the letter", guess)
# display message and deduct the tries when user guess the wrong letter
elif guess not in word:
print(guess, "is not in the word.")
tries -= 1
guessed_letters.append(guess)
# dispay message and store the letter when the user guess the correct letter
else:
print("Good job,", guess, "is in the word!")
guessed_letters.append(guess)
word_as_list = list(word_completion)
indices = [i for i, letter in enumerate(word) if letter == guess]
for index in indices:
word_as_list[index] = guess
# join the guess word in the word_completion
word_completion = "".join(word_as_list)
# if there is not blank space in word_completion change the status of guess to true
if "_" not in word_completion:
guessed = True
# check the length of the user input and is it alpha or not
elif len(guess) == len(word) and guess.isalpha():
# display message when user guess the same letter twice
if guess in guessed_words:
print("You already guessed the word", guess)
# display message and deduct the tries when user guess the wrong letter
elif guess != word:
print(guess, "is not the word.")
tries -= 1
guessed_words.append(guess)
# change the status of guess
else:
guessed = True
word_completion = word
# display error message for user
else:
print("Not a valid guess.")
# display the format of hangman each time of guess
print(display_hangman(tries))
print(word_completion)
print("\n")
print("Length of the word: ", len(word))
print("\n")
# if the variable of guess is true means user win the game
if guessed:
print("Congrats, you guessed the word! You win!")
# else means user lose the game.
else:
print("Sorry, you ran out of tries. The word was " + word + ". Maybe next time!")
# function to display the format of hangman
def display_hangman(tries):
stages = ["""
--------
| |
| 0
| \\|/
| |
| / \\
-
""",
"""
--------
| |
| 0
| \\|/
| |
| /
-
""",
"""
--------
| |
| 0
| \\|/
| |
|
-
""",
"""
--------
| |
| 0
| \\|
| |
|
-
""",
"""
--------
| |
| 0
| |
| |
|
-
""",
"""
--------
| |
| 0
|
|
|
-
""",
"""
--------
| |
|
|
|
|
-
"""
]
return stages[tries]
# main function to start the game
def main():
word = get_word()
play(word)
while input("Play Again? (Y/N): ").upper() == "Y":
word = get_word()
play(word)
if __name__ == "__main__":
main()
Code language: PHP (php)
words.json
{
"word_list" : [
"abandon",
"ability",
"abortion",
"above",
"abroad",
"absence",
"absolute",
"absorb",
"academic",
"accompany",
"accurate",
"achievement",
"acquire",
"action",
"addition",
"admire",
"adult",
"afford",
"afraid",
"afternoon",
"against",
"agent",
"agreement",
"agreement",
"almost",
"already",
"always",
"another",
"answer",
"apartment",
"apparently",
"appeal",
"appearance",
"apple",
"application",
"apply",
"appointment",
"appreciate",
"approach",
"appropriate",
"approval",
"approve",
"balance",
"ball",
"bank",
"barrel",
"barrier",
"baseball",
"basic",
"basketball",
"bathroom",
"battery",
"battle",
"beach",
"beautiful",
"bedroom",
"beginning",
"behavior",
"believe",
"belong",
"bench",
"birthday",
"breakfast",
"breathe",
"bridge",
"brilliant",
"brother",
"building",
"bullet",
"business",
"button",
"cabinet",
"cable",
"cake",
"calculate",
"call",
"camera",
"campaign",
"campus",
"cancer",
"candidate",
"capability",
"capacity",
"capital",
"captain",
"capture",
"carbon",
"career",
"carefully",
"carry",
"catch",
"category",
"celebrate",
"celebrity",
"center",
"century",
"ceremony",
"chairman",
"challenge",
"chamber",
"champion",
"championship",
"chance",
"channel",
"chapter",
"character",
"characteristic",
"charge",
"charity",
"chart",
"chase",
"cheap",
"check",
"cheese",
"chemical",
"chest",
"chicken",
"childhood",
"classroom",
"christmas",
"circle",
"citizen",
"climb",
"cloth",
"close",
"comfortable",
"comedy",
"combine",
"company",
"commander",
"communication",
"community",
"compare",
"competition",
"complain",
"comprehensive",
"conclude",
"confidence",
"confirm",
"connection",
"consider",
"constant",
"construction",
"contain",
"content",
"contact",
"control",
"convert",
"crowd",
"damage",
"dance",
"danger",
"dangerous",
"darkness",
"daughter",
"dealer",
"debate",
"decade",
"decide",
"decision",
"declare",
"decline",
"decrease",
"defeat",
"defend",
"defense",
"deficit",
"definition",
"degree",
"delivery",
"demand",
"democracy",
"demonstrate",
"department",
"dependent",
"depict",
"depression",
"describe",
"description",
"desert",
"deserve",
"design",
"designer",
"desire",
"desperate",
"despite",
"destroy",
"destruction",
"detect",
"determine",
"develop",
"development",
"device",
"dialogue",
"difference",
"difficulty",
"digital",
"dimension",
"direction",
"director",
"disability",
"disagree",
"disappear",
"disaster",
"discipline",
"discover",
"discrimination",
"discussion",
"disease",
"dismiss",
"display",
"distance",
"distinction",
"distinguish",
"distribute",
"diversity",
"division",
"doctor",
"domestic",
"dominant",
"double",
"draft",
"drawing",
"dream",
"dress",
"drink",
"drive",
"earnings",
"earth",
"eastern",
"economy",
"edition",
"editor",
"education",
"effective",
"efficiency",
"efficient",
"effort",
"eight",
"either",
"elderly",
"election",
"electricity",
"element",
"eliminate",
"elite",
"embrace",
"emergency",
"emission",
"emotion",
"emphasis",
"employee",
"empty",
"enable",
"encounter",
"encourage",
"enemy",
"energy",
"enforcement",
"engage",
"engine",
"engineer",
"enhance",
"enjoy",
"enormous",
"enough",
"ensure",
"enterprise",
"entertainment",
"entrance",
"environment",
"episode",
"equal",
"equipment",
"error",
"escape",
"especially",
"essay",
"essential",
"establish",
"estate",
"estimate",
"evaluation",
"event",
"eventually",
"everybody",
"everyday",
"everyone",
"everything",
"everywhere",
"evidence",
"evolution",
"evolve",
"exactly",
"examination",
"example",
"exceed",
"excellent",
"exception",
"exchange",
"exciting",
"executive",
"exercise",
"exhibition",
"existing",
"expansion",
"expectation",
"expensive",
"experience",
"experiment",
"expert",
"explanation",
"explode",
"explore",
"explosion",
"exposure",
"expression",
"extension",
"external",
"extra",
"extremely",
"fabric",
"facility",
"factor",
"factory",
"faculty",
"failure",
"fairly",
"faith",
"false",
"familiar",
"family",
"famous",
"fantasy",
"farmer",
"fashion",
"father",
"fault",
"favorite",
"feature",
"federal",
"feeling",
"fellow",
"female",
"fence",
"fiction",
"field",
"fifteen",
"fighter",
"figure",
"final",
"finance",
"finding",
"finger",
"finish",
"first",
"fishing",
"fitness",
"flame",
"flavor",
"flesh",
"flight",
"float",
"floor",
"flower",
"focus",
"follow",
"football",
"force",
"foreign",
"forest",
"forever",
"forget",
"formal",
"formula",
"fortune",
"forward",
"foundation",
"fourth",
"framework",
"freedom",
"freeze",
"frequency",
"fresh",
"friend",
"front",
"fruit",
"frustration",
"function",
"fundamental",
"funding",
"funeral",
"funny",
"furniture",
"furthermore",
"future",
"galaxy",
"gallery",
"garage",
"garden",
"garlic",
"gather",
"gender",
"general",
"generate",
"generation",
"genetic",
"gentleman",
"gently",
"gesture",
"ghost",
"giant",
"girlfriend",
"glance",
"glass",
"glove",
"golden",
"government",
"governor",
"graduate",
"grain",
"grand",
"grandfather",
"grandmother",
"grant",
"grass",
"grave",
"great",
"green",
"grocery",
"ground",
"group",
"growth",
"guarantee",
"guard",
"guess",
"guest",
"guideline",
"guilty",
"habitat",
"handful",
"handle",
"happen",
"happy",
"headline",
"headquarters",
"healthy",
"heart",
"heaven",
"heavy",
"height",
"helicopter",
"helpful",
"heritage",
"herself",
"highlight",
"highway",
"himself",
"history",
"holiday",
"homeless",
"honest",
"honey",
"honor",
"horizon",
"horror",
"horse",
"hospital",
"hotel",
"household",
"housing",
"however",
"human",
"humor",
"hundred",
"hungry",
"hunter",
"husband",
"hypothesis",
"ideal",
"identification",
"identity",
"ignore",
"illegal",
"illness",
"illustrate",
"image",
"imagination",
"immediately",
"immigration",
"impact",
"implement",
"implication",
"importance",
"impossible",
"impression",
"improvement",
"incentive",
"incident",
"include",
"income",
"incorporate",
"increase",
"incredible",
"indeed",
"independence",
"index",
"indicate",
"individual",
"industrial",
"infection",
"inflation",
"influence",
"information",
"ingredient",
"initial",
"injury",
"innocent",
"inquiry",
"inside",
"insight",
"insist",
"inspire",
"install",
"instance",
"instead",
"institution",
"instruction",
"instrument",
"insurance",
"intellectual",
"intelligence",
"intend",
"intense",
"intensity",
"intention",
"interaction",
"interest",
"international",
"interpretation",
"intervention",
"interview",
"introduction",
"invasion",
"investigation",
"investment",
"invite",
"involve",
"island",
"issue",
"itself",
"jacket",
"joint",
"journal",
"journey",
"judgment",
"juice",
"junior",
"justify",
"killer",
"kitchen",
"knife",
"knock",
"knowledge",
"label",
"labor",
"laboratory",
"landscape",
"language",
"large",
"later",
"latter",
"laugh",
"launch",
"lawsuit",
"lawyer",
"layer",
"leader",
"league",
"learning",
"least",
"leather",
"leave",
"legacy",
"legal",
"legend",
"legislation",
"legitimate",
"lemon",
"length",
"lesson",
"letter",
"level",
"liberal",
"library",
"license",
"lifestyle",
"lifetime",
"light",
"limitation",
"listen",
"literature",
"little",
"living",
"local",
"location",
"loose",
"lover",
"lower",
"lucky",
"lunch",
"machine",
"magazine",
"maintenance",
"majority",
"maker",
"makeup",
"management",
"manager",
"manner",
"manufacturing",
"margin",
"market",
"marriage",
"massive",
"master",
"match",
"material",
"matter",
"maybe",
"mayor",
"meaning",
"meanwhile",
"measurement",
"mechanism",
"media",
"medical",
"medication",
"medicine",
"medium",
"meeting",
"member",
"membership",
"memory",
"mental",
"mention",
"message",
"metal",
"meter",
"method",
"middle",
"might",
"military",
"million",
"minister",
"minority",
"minute",
"miracle",
"mirror",
"missile",
"mission",
"mistake",
"mixture",
"model",
"moderate",
"modern",
"modest",
"moment",
"money",
"monitor",
"month",
"moral",
"moreover",
"morning",
"mortgage",
"mother",
"motivation",
"motor",
"mount",
"mountain",
"mouse",
"mouth",
"movement",
"movie",
"multiple",
"murder",
"muscle",
"museum",
"music",
"mutual",
"myself",
"mystery",
"naked",
"narrative",
"narrow",
"national",
"native",
"natural",
"nature",
"nearby",
"necessary",
"negative",
"negotiate",
"negotiation",
"neighbor",
"neither",
"nervous",
"network",
"never",
"newspaper",
"night",
"nobody",
"noise",
"nomination",
"normal",
"north",
"nothing",
"notice",
"novel",
"nuclear",
"number",
"numerous",
"nurse",
"objective",
"obligation",
"observation",
"obtain",
"obviously",
"occasionally",
"occupation",
"occur",
"ocean",
"offensive",
"offer",
"office",
"often",
"ongoing",
"onion",
"online",
"opening",
"operation",
"opinion",
"opponent",
"opportunity",
"opposite",
"option",
"orange",
"order",
"ordinary",
"organic",
"organization",
"orientation",
"original",
"others",
"ourselves",
"outcome",
"outside",
"overall",
"overcome",
"overlook",
"owner",
"package",
"painful",
"painting",
"panel",
"paper",
"parent",
"parking",
"participant",
"participation",
"particular",
"partnership",
"party",
"passenger",
"passion",
"patch",
"patient",
"pattern",
"pause",
"payment",
"peace",
"penalty",
"people",
"pepper",
"perfect",
"performance",
"perhaps",
"period",
"permanent",
"permission",
"personality",
"personally",
"perspective",
"persuade",
"phenomenon",
"philosophy",
"phone",
"photograph",
"phrase",
"physical",
"piano",
"picture",
"piece",
"pilot",
"pitch",
"place",
"plane",
"planet",
"planning",
"plant",
"plastic",
"plate",
"platform",
"player",
"pleasure",
"plenty",
"pocket",
"poetry",
"point",
"police",
"policy",
"pollution",
"popular",
"population",
"porch",
"portion",
"portrait",
"portray",
"position",
"positive",
"possess",
"possibility",
"potato",
"potential",
"pound",
"poverty",
"powder",
"powerful",
"practical",
"prayer",
"precisely",
"predict",
"preference",
"pregnant",
"preparation",
"prescription",
"presentation",
"presidential",
"pressure",
"pretend",
"pretty",
"prevent",
"previously",
"price",
"pride",
"priest",
"primary",
"prime",
"principal",
"principle",
"print",
"priority",
"prisoner",
"privacy",
"private",
"probably",
"problem",
"procedure",
"process",
"produce",
"production",
"professional",
"profile",
"profit",
"program",
"project",
"prominent",
"promise",
"promote",
"prompt",
"proof",
"properly",
"property",
"proportion",
"proposal",
"prosecutor",
"prospect",
"protection",
"protein",
"protest",
"proud",
"provide",
"provision",
"psychology",
"public",
"publish",
"punishment",
"purchase",
"pursue",
"qualify",
"quality",
"quarter",
"question",
"quick",
"quiet",
"quite",
"quote",
"radical",
"radio",
"raise",
"range",
"rapid",
"rather",
"rating",
"ratio",
"reach",
"reaction",
"reader",
"ready",
"reality",
"realize",
"really",
"reason",
"recall",
"receive",
"recent",
"recipe",
"recognize",
"recommendation",
"record",
"recovery",
"recruit",
"reduction",
"reference",
"reflection",
"reform",
"refugee",
"refuse",
"regarding",
"regional",
"register",
"regular",
"reinforce",
"reject",
"relationship",
"relative",
"relax",
"release",
"relevant",
"relief",
"religion",
"religious",
"remaining",
"remarkable",
"remember",
"remind",
"remote",
"remove",
"repeat",
"replace",
"representative",
"reputation",
"request",
"requirement",
"research",
"resemble",
"reservation",
"resident",
"resistance",
"resolution",
"resolve",
"resort",
"resource",
"respect",
"responsibility",
"restaurant",
"restore",
"restriction",
"result",
"retain",
"retire",
"return",
"reveal",
"revenue",
"review",
"revolution",
"rhythm",
"rifle",
"right",
"river",
"romantic",
"rough",
"round",
"route",
"routine",
"running",
"rural",
"sacred",
"safety",
"salad",
"salary",
"sample",
"sanction",
"satellite",
"satisfaction",
"scale",
"scandal",
"scared",
"scenario",
"schedule",
"scheme",
"scholarship",
"science",
"scope",
"score",
"scream",
"screen",
"script",
"search",
"season",
"second",
"secretary",
"section",
"sector",
"secure",
"security",
"segment",
"seize",
"selection",
"senior",
"sensitive",
"sentence",
"separate",
"sequence",
"series",
"serious",
"service",
"session",
"setting",
"settle",
"seven",
"several",
"severe",
"sexual",
"shade",
"shadow",
"shake",
"shall",
"shape",
"share",
"sharp",
"sheet",
"shelf",
"shell",
"shelter",
"shift",
"shine",
"shirt",
"shock",
"shoot",
"shopping",
"shore",
"short",
"should",
"shoulder",
"shout",
"shower",
"shrug",
"sight",
"signal",
"significant",
"silence",
"silent",
"silver",
"similar",
"simple",
"simply",
"since",
"singer",
"single",
"sister",
"situation",
"skill",
"slave",
"sleep",
"slice",
"slide",
"slight",
"small",
"smart",
"smell",
"smile",
"smoke",
"smooth",
"soccer",
"social",
"society",
"software",
"solar",
"soldier",
"solid",
"solution",
"solve",
"somebody",
"somehow",
"someone",
"something",
"sometimes",
"somewhat",
"somewhere",
"sophisticated",
"sorry",
"sound",
"source",
"south",
"space",
"speaker",
"special",
"specialist",
"species",
"specific",
"speech",
"speed",
"spend",
"spirit",
"split",
"spokesman",
"sport",
"spread",
"spring",
"square",
"squeeze",
"stability",
"staff",
"stage",
"stair",
"stake",
"stand",
"standard",
"standing",
"stare",
"start",
"statement",
"station",
"statistics",
"status",
"steady",
"steal",
"steel",
"stick",
"still",
"stock",
"stomach",
"stone",
"storage",
"store",
"storm",
"story",
"straight",
"stranger",
"strategic",
"stream",
"street",
"strength",
"stress",
"stretch",
"strike",
"string",
"strip",
"stroke",
"strong",
"structure",
"struggle",
"student",
"studio",
"study",
"stuff",
"stupid",
"style",
"subject",
"submit",
"subsequent",
"substance",
"substantial",
"succeed",
"successful",
"sudden",
"suffer",
"sufficient",
"sugar",
"suggestion",
"suicide",
"summer",
"summit",
"supporter",
"suppose",
"surface",
"surgery",
"surprise",
"surround",
"survey",
"survival",
"suspect",
"sustain",
"swear",
"sweep",
"sweet",
"swing",
"switch",
"symbol",
"symptom",
"system",
"table",
"tablespoon",
"tactic",
"talent",
"target",
"taste",
"taxpayer",
"teacher",
"teaspoon",
"technical",
"technique",
"technology",
"teenager",
"telephone",
"telescope",
"television",
"temperature",
"temporary",
"tendency",
"tennis",
"tension",
"terrible",
"territory",
"testimony",
"thank",
"theater",
"their",
"theme",
"themselves",
"theory",
"therapy",
"therefore",
"these",
"thick",
"thing",
"thinking",
"third",
"thirty",
"those",
"though",
"thought",
"thousand",
"threaten",
"three",
"throat",
"throughout",
"throw",
"ticket",
"tight",
"tissue",
"title",
"tobacco",
"today",
"together",
"tomato",
"tomorrow",
"tongue",
"tonight",
"tooth",
"topic",
"total",
"touch",
"tough",
"tourist",
"tournament",
"toward",
"tower",
"trace",
"track",
"trade",
"traditional",
"traffic",
"tragedy",
"trail",
"train",
"transfer",
"transform",
"transformation",
"transition",
"translate",
"transportation",
"travel",
"treatment",
"treaty",
"tremendous",
"trend",
"trial",
"tribe",
"trick",
"troop",
"trouble",
"truck",
"truly",
"trust",
"truth",
"tunnel",
"twelve",
"twenty",
"twice",
"typical",
"ultimate",
"unable",
"uncle",
"under",
"understand",
"unfortunately",
"uniform",
"union",
"unique",
"universal",
"universe",
"university",
"unknown",
"unless",
"unlike",
"until",
"unusual",
"upper",
"urban",
"useful",
"usually",
"utility",
"vacation",
"valley",
"valuable",
"variable",
"variation",
"variety",
"various",
"vegetable",
"vehicle",
"venture",
"version",
"versus",
"vessel",
"veteran",
"victim",
"victory",
"video",
"viewer",
"village",
"violation",
"virtually",
"virtue",
"virus",
"visible",
"visitor",
"vital",
"voice",
"volume",
"volunteer",
"vulnerable",
"wander",
"warning",
"waste",
"watch",
"water",
"wealthy",
"weapon",
"weather",
"wedding",
"weekend",
"weekly",
"weight",
"welcome",
"welfare",
"western",
"whatever",
"wheel",
"whenever",
"whether",
"which",
"while",
"whisper",
"white",
"whole",
"whose",
"widespread",
"willing",
"window",
"winner",
"winter",
"wisdom",
"withdraw",
"within",
"without",
"witness",
"woman",
"wonderful",
"wooden",
"worker",
"workshop",
"world",
"worried",
"worth",
"would",
"wound",
"write",
"wrong",
"yellow",
"yesterday",
"yield",
"young",
"yourself",
"youth"]}
Code language: JSON / JSON with Comments (json)