DEV Community

Orion
Orion

Posted on

Hangman Code :P

My first basic not so good project..

But I did learn a few things...

Things I think I'll remember from now on...
json.load()
choice() method (random module)
system() method (os module)
sleep() method (time module)
sort() method for lists
isalpha() method
count() method
index() method

words.json is a file which consists of words.

import random import json import os import time with open("words.json") as words_list: words=json.load(words_list) word=random.choice(words).upper() chances=5 guesses=list() g_word='-'*len(word) while chances>0: os.system("clear") print("Word: {}".format(g_word)) print("Guessed Letters: {}".format(' '.join(guesses))) print("Chances: {}".format(chances)) guess=input("Guess a letter: ").upper() if not guess.isalpha() or len(guess)!=1 or guess in guesses: print("Invalid Input. Try Again.") time.sleep(1) continue guesses.append(guess) guesses.sort() if guess not in word: print("Wrong Guess...") chances=chances-1 time.sleep(1) continue if guess in word: g_word=''.join([letter if letter in guesses else '-' for letter in word]) print("Right On!") time.sleep(0.5) if g_word == word: print("Word: {}".format(g_word)) print("You Won!") time.sleep(1) exit(0) print("\nYou lost! Better luck next time.") print("The key was: {}".format(word)) 
Enter fullscreen mode Exit fullscreen mode

Top comments (0)