Skip to content

Module quickpython.examples.hangman

/games/hangman.py

Copyright (c) 2019 ShineyDev

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

View Source
"""

/games/hangman.py

    Copyright (c) 2019 ShineyDev

    Licensed under the Apache License, Version 2.0 (the "License");

    you may not use this file except in compliance with the License.

    You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software

    distributed under the License is distributed on an "AS IS" BASIS,

    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

    See the License for the specific language governing permissions and

    limitations under the License.

"""

__authors__ = [("shineydev", "contact@shiney.dev")]

__maintainers__ = [("shineydev", "contact@shiney.dev")]

__version_info__ = (1, 0, 0, "final", 0)

__version__ = "{0}.{1}.{2}{3}{4}".format(

    *[str(n)[0] if (i == 3) else str(n) for (i, n) in enumerate(__version_info__)]

)

import os

import random

import pyfiglet

HANGMAN = [

    """

\t-----

\t|   |

\t|

\t|

\t|

\t|

\t|

\t|

\t|

\t--------

    """,

    """

\t-----

\t|   |

\t|   0

\t|

\t|

\t|

\t|

\t|

\t|

\t--------

    """,

    """

\t-----

\t|   |

\t|   0

\t|  -+-

\t|

\t|

\t|

\t|

\t|

\t--------

    """,

    """

\t-----

\t|   |

\t|   0

\t| /-+-

\t|

\t|

\t|

\t|

\t|

\t--------

    """,

    """

\t-----

\t|   |

\t|   0

\t| /-+-\\

\t|

\t|

\t|

\t|

\t|

\t--------

    """,

    """

\t-----

\t|   |

\t|   0

\t| /-+-\\

\t|   |

\t|

\t|

\t|

\t|

\t--------

    """,

    """

\t-----

\t|   |

\t|   0

\t| /-+-\\

\t|   |

\t|   |

\t|

\t|

\t|

\t--------

    """,

    """

\t-----

\t|   |

\t|   0

\t| /-+-\\

\t|   |

\t|   |

\t|  |

\t|

\t|

\t--------

    """,

    """

\t-----

\t|   |

\t|   0

\t| /-+-\\

\t|   |

\t|   |

\t|  |

\t|  |

\t|

\t--------

    """,

    """

\t-----

\t|   |

\t|   0

\t| /-+-\\

\t|   |

\t|   |

\t|  | |

\t|  |

\t|

\t--------

    """,

    """

\t-----

\t|   |

\t|   0

\t| /-+-\\

\t|   |

\t|   |

\t|  | |

\t|  | |

\t|

\t--------

    """,

]

class Hangman:

    def __init__(self):

        """

        initializes a `Hangman` object

        """

        pass

    def game(self):

        """

        starts the game

        """

        self.message = ""

        lives = 11

        word = [character.upper() for character in random.choice(WORDS)]

        word_hidden = ["_" for character in word]

        guessed = []

        while (lives != 0) and ("_" in word_hidden):

            cls()

            print(HANGMAN[-lives])

            print()

            if guessed:

                print(" ".join(guessed))

                print()

            print("".join(word_hidden))

            print()

            if self.message:

                print(self.message)

                print()

                self.message = ""

            else:

                print("you have {0} attempt{1} remaining".format(lives, "" if lives == 1 else "s"))

                print()

            letter = input("choose a letter;\n> ").upper()

            if not letter:

                continue

            elif not len(letter) == 1:

                self.message = "too many letters"

                continue

            elif not letter.isalpha():

                self.message = "that is not a letter"

                continue

            elif letter in guessed:

                self.message = "you've already guessed that letter"

                continue

            guessed.append(letter)

            if letter not in word:

                lives -= 1

                continue

            for i in range(len(word)):

                if letter == word[i]:

                    word_hidden[i] = letter

        cls()

        print(HANGMAN[-lives])

        print()

        if guessed:

            print(" ".join(guessed))

            print()

        print("".join(word_hidden))

        print()

        if lives == 0:

            print("you lose")

            print("the word was {0}".format("".join(word)))

        else:

            print("you win")

    def start(self):

        """

        calls `self.game` in a 'would you like to play again?' loop

        """

        choice = "y"

        while choice.startswith("y"):

            cls()

            print(pyfiglet.figlet_format("Hangman"))

            print()

            input("enter to play\nctrl + c to quit to main menu\n\n")

            self.game()

            choice = input("\nwould you like to play again?\n> ").strip()

WORDS = """aa

ab

ad

ag

ah

ai

am

an

as

at

aw

ax

ay

ba

be

bi

bo

by

da

do

dy

ee

eh

el

em

en

er

ex

fa

ga

gi

go

ha

he

hi

ho

id

if

in

io

is

it

ka

ki

la

li

lo

ma

me

mo

my

no

of

oh

oi

ok

on

op

or

ou

ow

ox

oz

pa

pi

re

so

te

to

uh

um

up

us

wa

we

ye

yo

act

add

age

ago

aid

aim

air

all

and

any

arm

art

ask

bad

bag

ban

bar

bay

bed

bet

bid

big

bin

bit

box

boy

bus

but

buy

bye

can

cap

car

cat

cow

cry

cup

cut

dad

day

die

dig

dog

dot

dry

due

dvd

dye

ear

eat

egg

end

etc

eye

fan

far

fat

fee

few

fit

fix

flu

fly

for

fry

fun

fur

gap

gas

get

god

gun

guy

hat

her

hip

his

hit

hot

how

ice

ill

ink

jam

job

joy

key

kid

lab

law

lay

leg

let

lid

lie

lip

lot

low

mad

map

may

mix

mrs

net

new

nor

not

now

nut

odd

off

oil

old

one

our

out

owe

own

pan

pay

pen

per

pet

pig

pin

pop

pot

pub

put

raw

red

rid

rob

rub

run

say

sea

see

set

sew

sex

she

shy

sir

sit

six

sky

son

sum

sun

tap

tax

tea

ten

the

tie

tin

tip

toe

ton

too

top

toy

try

two

use

van

via

war

way

web

wet

who

why

win

yes

yet

you

able

acid

aged

ally

also

area

arms

army

atom

aunt

away

baby

back

bake

ball

band

bank

base

bath

beak

bear

beat

beef

beer

bell

belt

bend

bent

best

bike

bill

bird

bite

blow

blue

boat

body

boil

bomb

bone

book

boot

bore

born

boss

both

bowl

burn

bury

bush

busy

cake

call

calm

camp

card

care

case

cash

cast

cell

cent

chat

chew

chin

chip

chop

city

clap

club

coal

coat

code

coin

cold

come

cook

cool

cope

copy

core

cost

crop

curb

cure

curl

damp

dare

dark

data

date

dead

deaf

deal

dear

debt

deep

deny

desk

diet

dirt

disc

dish

disk

door

down

drag

draw

drop

drug

drum

dull

dump

dust

duty

each

earn

ease

east

easy

edge

else

euro

even

ever

evil

exam

exit

face

fact

fail

fair

fall

fame

farm

fast

fear

feed

feel

file

fill

film

find

fine

fire

firm

fish

five

flag

flat

flow

fold

food

foot

fork

form

four

free

from

fuel

full

fund

gain

game

gate

gear

gift

girl

give

glad

glue

goal

gold

good

grab

gram

grey

grow

hair

half

hall

hand

hang

hard

harm

hate

have

head

heal

hear

heat

heel

hell

help

here

hero

hers

hide

high

hill

hire

hold

hole

holy

home

hook

hope

horn

host

hour

huge

hunt

hurt

idea

inch

into

iron

item

join

joke

july

jump

june

just

keen

keep

kick

kill

kind

king

kiss

knee

knit

knot

know

lack

lady

lake

lamp

land

lane

last

late

lazy

lead

leaf

lean

left

lend

less

life

lift

like

line

link

list

live

load

loan

lock

long

look

lord

lose

loss

lost

loud

love

luck

lump

lung

mail

main

make

male

mall

many

mark

mass

mate

meal

mean

meat

meet

melt

menu

mere

mess

mild

mile

milk

mind

mine

miss

mood

moon

more

most

move

much

must

nail

name

navy

near

neat

neck

need

nest

news

next

nice

nine

none

nose

note

obey

once

only

onto

open

ours

oven

over

pace

pack

page

pain

pair

pale

park

part

pass

past

path

peak

pick

pile

pill

pink

pint

pipe

pity

plan

play

plot

plug

plus

poem

pole

pool

poor

port

pose

post

pour

pray

pull

pure

push

quit

race

rail

rain

rank

rare

rate

read

real

rear

rely

rent

rest

rice

rich

ride

ring

rise

risk

road

rock

role

roll

roof

room

root

rope

rude

ruin

rule

rush

sack

safe

sail

sale

salt

same

sand

save

seal

seat

seed

seek

seem

self

sell

send

ship

shoe

shop

shot

show

shut

sick

side

sign

silk

sing

sink

site

size

skin

slip

slow

snow

soap

sock

soft

soil

some

song

soon

sore

sort

soul

soup

sour

spin

spot

star

stay

step

stir

stop

such

suck

suit

sure

swim

tail

take

talk

tall

tank

tape

task

taxi

team

tear

tell

tend

tent

term

test

text

than

that

them

then

they

thin

this

thus

tidy

till

time

tiny

tire

tone

tool

tour

town

trap

tree

trip

true

tube

tune

turn

twin

type

tyre

ugly

undo

unit

upon

urge

used

user

vary

vast

very

view

vote

wage

wait

wake

walk

wall

want

warm

warn

wash

wave

weak

wear

week

well

west

what

when

whom

wide

wife

wild

will

wind

wine

wing

wire

wise

wish

with

wood

wool

word

work

wrap

zero

zone

about

above

abuse

actor

adapt

admit

adopt

adult

after

again

agent

agree

ahead

alarm

alive

allow

alone

along

aloud

alter

amaze

among

amuse

anger

angle

angry

ankle

annoy

apart

apple

apply

april

argue

arise

armed

arrow

aside

avoid

awake

award

aware

awful

badly

based

basic

basis

beach

beard

begin

below

birth

black

blade

blame

blank

blind

block

blood

board

bored

bound

brain

brand

brave

bread

break

breed

brick

brief

bring

broad

brown

brush

build

bunch

burnt

burst

buyer

cable

candy

carry

catch

cause

cease

chain

chair

chart

chase

cheap

cheat

check

cheek

chest

chief

child

civil

claim

class

clean

clear

clerk

click

climb

clock

close

cloth

cloud

coach

coast

cough

could

count

court

cover

crack

craft

crash

crazy

cream

crime

crisp

cross

crowd

crown

cruel

crush

curly

curve

cycle

daily

dance

death

decay

delay

depth

diary

dirty

doubt

dozen

draft

drama

dream

dress

drink

drive

drunk

dying

early

earth

eight

elbow

elect

email

empty

enemy

enjoy

enter

entry

equal

error

essay

event

every

exact

exist

extra

faint

faith

false

fancy

fault

fence

fetch

fever

field

fifth

fifty

fight

final

first

fixed

flame

flash

flesh

float

flood

floor

flour

focus

force

forty

found

frame

fresh

front

fruit

fully

funny

giant

glass

glove

goods

grade

grain

grand

grant

grass

grave

great

green

group

guard

guess

guest

guide

habit

happy

heart

heavy

hello

hence

hobby

horse

hotel

house

human

hurry

ideal

image

imply

index

inner

issue

jeans

jelly

joint

judge

juice

knife

knock

label

large

later

laugh

layer

learn

least

leave

legal

lemon

level

light

limit

litre

local

logic

loose

lorry

lover

loyal

lucky

lunch

magic

major

march

marry

match

maybe

mayor

means

media

metal

metre

might

minor

mixed

model

money

month

moral

motor

mount

mouse

mouth

movie

music

naked

nerve

never

newly

niece

night

ninth

noise

noisy

north

novel

nurse

occur

ocean

oddly

offer

often

onion

order

organ

other

ought

outer

owner

paint

panel

pants

paper

party

pause

peace

penny

phase

phone

photo

piano

piece

pilot

pitch

place

plain

plane

plant

plate

point

pound

power

press

price

pride

prime

print

prior

prize

proof

proud

prove

punch

pupil

queen

quick

quiet

quite

quote

radio

raise

range

rapid

reach

react

ready

refer

relax

reply

rider

right

rival

river

rough

round

route

royal

ruler

rural

sadly

salad

salty

sauce

scale

scare

scene

score

screw

sense

serve

seven

shade

shake

shall

shame

shape

share

sharp

shave

sheep

sheet

shelf

shell

shift

shine

shiny

shirt

shock

shoot

short

shout

sight

silly

since

sixth

sixty

skill

skirt

sleep

slice

slide

slope

small

smart

smash

smell

smile

smoke

snake

solid

solve

sorry

sound

south

space

spare

speak

speed

spell

spend

spice

spicy

spite

split

spoil

spoon

sport

spray

staff

stage

stair

stamp

stand

stare

start

state

steal

steam

steel

steep

steer

stick

stiff

still

sting

stock

stone

store

storm

story

stove

strip

study

stuff

style

sugar

swear

sweat

sweep

sweet

swell

swing

table

taste

teach

tenth

thank

their

theme

there

thick

thief

thing

think

third

three

throw

thumb

tight

tired

title

today

tonne

tooth

topic

total

touch

tough

towel

tower

trace

track

trade

train

treat

trend

trial

trick

truck

truly

trust

truth

twice

twist

uncle

under

union

unite

until

upper

upset

urban

usual

valid

value

video

virus

visit

vital

voice

waist

waste

watch

water

weigh

wheel

where

which

while

white

whole

whose

width

woman

world

worry

worse

worst

worth

would

wound

wrist

write

wrong

young

yours

youth

abroad

absent

absorb

accent

accept

access

accuse

across

action

active

actual

adjust

admire

advert

advice

advise

affair

affect

afford

afraid

agency

allied

almost

always

amazed

amount

amused

animal

annual

answer

anyone

anyway

appeal

appear

around

arrest

arrive

artist

asleep

aspect

assist

assume

assure

attach

attack

attend

august

author

autumn

battle

beauty

become

before

behalf

behave

behind

belief

belong

beside

better

beyond

bitter

blonde

border

boring

borrow

bother

bottle

bottom

branch

breast

breath

bridge

bright

broken

bubble

budget

bullet

butter

button

called

calmly

camera

cancel

cancer

cannot

career

carpet

carrot

castle

centre

chance

change

charge

cheese

cheque

choice

choose

church

cinema

circle

clever

client

closed

closet

coffee

coldly

colour

column

comedy

commit

common

cooker

cookie

corner

cotton

county

couple

course

cousin

create

credit

crisis

curved

custom

damage

dancer

danger

debate

decade

decide

deeply

defeat

defend

define

degree

demand

depend

derive

desert

design

desire

detail

device

devote

dinner

direct

divide

doctor

dollar

double

drawer

driver

during

easily

editor

effect

effort

eighth

eighty

either

eleven

emerge

empire

employ

enable

ending

energy

engage

engine

enough

ensure

entire

escape

estate

except

excite

excuse

expand

expect

expert

export

expose

extend

extent

factor

fairly

family

famous

farmer

fasten

father

faucet

favour

fellow

female

figure

finely

finger

finish

firmly

flight

flower

flying

follow

forest

forget

formal

former

fourth

freely

freeze

friday

fridge

friend

frozen

future

gallon

gamble

garage

garden

gather

gentle

gently

global

govern

ground

growth

guilty

hammer

handle

happen

hardly

hatred

health

heaven

height

highly

hollow

honest

honour

horror

humour

hungry

ignore

impact

import

impose

income

indeed

indoor

infect

inform

injure

injury

insect

insert

inside

insist

insult

intend

invent

invest

invite

island

itself

jacket

junior

kindly

labour

latest

latter

launch

lawyer

leader

league

length

lesson

letter

likely

liquid

listen

little

lively

living

locate

lonely

loudly

lovely

mainly

manage

manner

market

master

matter

medium

member

memory

mental

merely

method

midday

middle

minute

mirror

mobile

modern

moment

monday

mostly

mother

motion

moving

murder

muscle

museum

myself

narrow

nation

nature

nearby

nearly

neatly

needle

nephew

nicely

ninety

nobody

normal

notice

number

object

obtain

occupy

offend

office

online

openly

oppose

option

orange

origin

output

packet

palace

parent

partly

pencil

people

pepper

period

permit

person

petrol

phrase

planet

player

please

plenty

pocket

poetry

poison

police

policy

polish

polite

potato

powder

praise

prayer

prefer

pretty

priest

prince

prison

profit

prompt

proper

public

punish

purely

purple

pursue

racing

rarely

rather

reader

really

reason

recall

recent

reckon

record

reduce

reform

refuse

regard

region

regret

reject

relate

relief

remain

remark

remind

remote

remove

rented

repair

repeat

report

rescue

resist

resort

result

retain

retire

return

reveal

review

revise

reward

rhythm

riding

rubber

rudely

ruined

rumour

runner

safely

safety

sailor

salary

sample

saving

scared

scheme

school

scream

screen

search

season

second

secret

sector

secure

select

senate

senior

series

settle

severe

sewing

sexual

shadow

shaped

should

shower

signal

silent

silver

simple

simply

singer

single

sister

sleeve

slight

slowly

smooth

social

softly

source

speech

spider

spirit

spoken

spread

spring

square

stable

statue

status

steady

sticky

strain

stream

street

stress

strict

strike

string

stripe

stroke

strong

studio

stupid

sudden

suffer

suited

summer

sunday

supply

surely

survey

switch

symbol

system

tablet

tackle

target

thanks

theirs

theory

thirty

though

thread

threat

throat

ticket

tiring

toilet

tomato

tongue

travel

tunnel

twelve

twenty

unable

unfair

unique

united

unkind

unless

unlike

unload

untidy

upside

upward

urgent

useful

valley

varied

victim

vision

volume

waiter

wallet

wander

warmth

wealth

weapon

weekly

weight

widely

wildly

window

winner

winter

within

wonder

wooden

worker

writer

yellow

abandon

ability

absence

account

achieve

acquire

actress

address

advance

against

airport

alarmed

alcohol

already

amazing

amusing

analyse

ancient

angrily

annoyed

another

anxiety

anxious

anybody

appoint

approve

arrange

arrival

article

ashamed

attempt

attract

average

awfully

awkward

baggage

balance

bandage

bargain

barrier

battery

because

bedroom

believe

beneath

benefit

betting

between

bicycle

billion

biology

biscuit

breathe

briefly

broadly

brother

cabinet

camping

capable

capital

captain

capture

careful

ceiling

central

century

certain

chamber

channel

chapter

charity

cheaply

chemist

chicken

citizen

classic

clearly

climate

closely

clothes

collect

college

combine

comfort

command

comment

company

compare

compete

complex

concept

concern

concert

conduct

confine

confirm

confuse

connect

consist

consult

contact

contain

content

contest

context

control

convert

cooking

correct

cottage

council

counter

country

courage

covered

cracked

crowded

crucial

culture

curious

current

curtain

customs

cycling

dancing

declare

decline

defence

delight

deliver

dentist

deposit

depress

deserve

despite

destroy

develop

devoted

diagram

diamond

digital

discuss

disease

disgust

dislike

dismiss

display

disturb

divorce

drawing

dressed

driving

eastern

economy

edition

educate

elderly

elegant

element

emotion

engaged

enquiry

entitle

equally

evening

exactly

examine

example

excited

exclude

exhibit

expense

explain

explode

explore

express

extreme

factory

failure

faintly

farming

farther

fashion

feather

feature

federal

feeling

fifteen

finally

finance

fishing

flavour

flooded

folding

foreign

forever

forgive

formula

fortune

forward

freedom

freshly

funeral

further

garbage

general

genuine

goodbye

gradual

grammar

gravely

greatly

grocery

happily

harmful

healthy

hearing

heating

heavily

helpful

herself

highway

himself

history

holiday

housing

however

hundred

hunting

husband

illegal

illness

imagine

immoral

impress

improve

include

indoors

initial

injured

install

instead

involve

january

jealous

jointly

journey

justice

justify

killing

kitchen

knitted

lacking

largely

leading

leather

lecture

legally

library

licence

license

lightly

limited

locally

located

logical

loosely

luggage

machine

manager

married

massive

maximum

meaning

measure

medical

meeting

mention

message

million

mineral

minimum

missing

mistake

mixture

monitor

morally

morning

musical

mystery

natural

neither

nervous

network

noisily

nothing

nowhere

nuclear

observe

obvious

october

offence

offense

officer

opening

operate

opinion

opposed

outdoor

outline

outside

overall

package

painful

painter

partner

passage

passing

patient

pattern

payment

pension

perfect

perform

perhaps

physics

picture

plastic

pleased

pointed

popular

possess

precise

predict

prepare

present

pretend

prevent

primary

printer

private

problem

proceed

process

produce

product

program

project

promise

promote

propose

protect

protest

proudly

provide

publish

purpose

qualify

quality

quarter

quickly

quietly

railway

rapidly

reading

reality

realize

receipt

receive

recover

reflect

refusal

regular

related

relaxed

release

remains

removal

replace

request

require

reserve

resolve

respect

respond

restore

retired

reverse

rightly

roughly

rounded

routine

rubbish

running

sadness

sailing

satisfy

science

scratch

section

senator

serious

servant

service

session

seventh

seventy

several

shallow

sharply

shelter

shocked

shortly

silence

similar

sincere

singing

sixteen

skilful

skilled

smoking

society

soldier

somehow

someone

speaker

special

squeeze

station

steeply

stiffly

stomach

strange

stretch

striped

student

subject

succeed

success

suggest

summary

support

suppose

surface

surname

survive

suspect

swallow

sweater

swollen

teacher

tension

theatre

thickly

thirsty

thought

through

tightly

tonight

totally

tourist

towards

trading

traffic

trouble

tuesday

twelfth

twisted

typical

unhappy

uniform

unknown

unlucky

unusual

upwards

useless

usually

variety

various

vehicle

venture

version

victory

village

violent

visible

visitor

walking

warning

washing

weather

website

wedding

weekend

welcome

western

whereas

whether

whisper

whistle

whoever

willing

winning

without

witness

working

worried

worship

wounded

writing

written

wrongly

absolute

academic

accident

accurate

actively

activity

actually

addition

adequate

advanced

aircraft

alarming

alphabet

although

ambition

analysis

announce

annoying

annually

anything

anywhere

apparent

approach

approval

argument

artistic

attached

attitude

attorney

audience

backward

bacteria

bathroom

birthday

bitterly

brightly

building

business

campaign

capacity

careless

category

ceremony

chairman

cheerful

chemical

climbing

clothing

collapse

coloured

commonly

complain

complete

computer

conclude

concrete

confined

conflict

confront

confused

congress

consider

constant

consumer

continue

contract

contrast

convince

coughing

covering

creature

criminal

critical

cultural

cupboard

customer

daughter

december

decision

decorate

decrease

definite

delicate

delivery

describe

deserted

detailed

directly

director

disabled

disagree

disaster

discount

discover

dissolve

distance

district

division

divorced

document

domestic

dominate

downward

dramatic

economic

educated

eighteen

election

electric

elevator

eleventh

emphasis

employee

employer

engineer

enormous

entirely

entrance

envelope

estimate

everyone

evidence

exchange

exciting

exercise

expected

facility

faithful

familiar

farthest

february

festival

fiftieth

fighting

finished

flooding

football

forecast

formally

formerly

fortieth

fourteen

frequent

friendly

frighten

function

gambling

gasoline

generate

generous

governor

grandson

grateful

harmless

headache

hesitate

homework

honestly

hospital

humorous

identify

identity

incident

increase

indicate

indirect

industry

infected

informal

innocent

instance

intended

interest

interior

internal

internet

interval

involved

irritate

keyboard

kilogram

kindness

knitting

language

location

magazine

maintain

majority

marriage

matching

material

medicine

mentally

midnight

military

minister

ministry

minority

mistaken

moreover

mountain

movement

multiply

musician

national

negative

nineteen

nonsense

normally

northern

november

occasion

occupied

official

opponent

opposing

opposite

ordinary

organize

original

outdoors

overcome

painting

parallel

passport

patience

peaceful

personal

persuade

physical

planning

platform

pleasant

pleasing

pleasure

politely

politics

position

positive

possible

possibly

powerful

practice

practise

pregnant

premises

prepared

presence

preserve

pressure

previous

princess

printing

priority

prisoner

probable

probably

producer

progress

promptly

properly

property

proposal

prospect

provided

publicly

purchase

quantity

question

railroad

reaction

recently

regional

register

relation

relative

relaxing

relevant

religion

remember

repeated

research

resident

resource

response

restrict

revision

romantic

saturday

schedule

scissors

secretly

security

sensible

sentence

separate

severely

sexually

shocking

shooting

shopping

shoulder

sideways

sixtieth

slightly

smoothly

socially

software

solution

somebody

somewhat

southern

specific

spelling

standard

steadily

straight

stranger

strategy

strength

stressed

strictly

striking

strongly

struggle

suddenly

suitable

suitcase

superior

surprise

surround

swearing

swelling

swimming

sympathy

teaching

tendency

terrible

terribly

thinking

thirteen

thorough

thousand

threaten

thursday

together

tomorrow

training

transfer

triangle

tropical

trousers

ultimate

umbrella

unfairly

universe

unlikely

unsteady

upstairs

vacation

valuable

vertical

violence

weakness

whatever

whenever

wherever

withdraw

worrying

wrapping

yourself

abandoned

accompany

according

advantage

adventure

advertise

affection

afternoon

agreement

alcoholic

alongside

ambulance

anxiously

apartment

apologize

approving

assistant

associate

attempted

attention

authority

automatic

available

awkwardly

backwards

basically

beautiful

beginning

behaviour

boyfriend

breakfast

breathing

brilliant

broadcast

calculate

candidate

cardboard

carefully

celebrate

certainly

challenge

character

chemistry

chocolate

cigarette

classroom

colleague

committee

community

complaint

concerned

condition

confident

confusing

confusion

connected

conscious

construct

container

continent

correctly

criterion

criticism

criticize

curiously

currently

dangerous

delighted

departure

depressed

desperate

determine

different

difficult

direction

disappear

discovery

disgusted

dishonest

downwards

drugstore

education

effective

efficient

eightieth

elsewhere

embarrass

emergency

emotional

emphasize

encounter

encourage

enjoyable

enjoyment

entertain

equipment

essential

establish

everybody

excellent

exception

excluding

executive

existence

expensive

explosion

extension

extensive

extremely

favourite

fifteenth

financial

following

furniture

generally

gentleman

genuinely

geography

gradually

guarantee

happiness

highlight

household

hundredth

illegally

imaginary

immediate

impatient

important

impressed

inability

including

infection

influence

initially

institute

insulting

insurance

intention

interpret

interrupt

interview

introduce

invention

irritated

jewellery

judgement

justified

kilometre

knowledge

landscape

machinery

marketing

meanwhile

milligram

millionth

motorbike

naturally

necessary

neighbour

nervously

newspaper

ninetieth

objective

obviously

o�clock

offensive

operation

organized

otherwise

ourselves

packaging

passenger

perfectly

performer

permanent

photocopy

poisonous

political

pollution

potential

practical

precisely

president

primarily

principle

privately

procedure

professor

programme

promotion

pronounce

providing

publicity

qualified

realistic

reception

recognize

recommend

recording

reduction

reference

regarding

regularly

religious

remaining

represent

reproduce

satisfied

scientist

secondary

secretary

selection

sensitive

separated

september

seriously

seventeen

signature

similarly

sincerely

situation

skilfully

something

sometimes

somewhere

specially

spiritual

statement

strangely

structure

substance

suffering

supporter

surprised

suspicion

technical

technique

telephone

temporary

therefore

thickness

thirtieth

timetable

tradition

transform

translate

transport

traveller

treatment

twentieth

typically

uncertain

underwear

unusually

unwilling

upsetting

variation

vegetable

violently

virtually

wednesday

willingly

wonderful

yesterday

absolutely

acceptable

accidental

accurately

additional

adequately

admiration

afterwards

aggressive

altogether

anticipate

apparently

appearance

appreciate

artificial

assistance

associated

atmosphere

attraction

attractive

background

carelessly

centimetre

chairwoman

cheerfully

collection

commercial

commission

commitment

comparison

completely

complicate

concerning

conclusion

conference

confidence

connection

constantly

continuous

contribute

controlled

convenient

convention

decoration

decorative

definitely

definition

deliberate

department

depressing

determined

dictionary

difference

difficulty

disappoint

disapprove

discipline

discussion

disgusting

distribute

disturbing

downstairs

eighteenth

electrical

electronic

employment

enthusiasm

equivalent

especially

eventually

everything

everywhere

exaggerate

excitement

exhibition

experience

experiment

expression

faithfully

foundation

fourteenth

frequently

friendship

frightened

generation

generously

girlfriend

government

grandchild

historical

horizontal

illustrate

importance

impossible

impression

impressive

indication

indirectly

individual

industrial

inevitable

inevitably

infectious

ingredient

initiative

instrument

interested

investment

invitation

irritating

journalist

laboratory

literature

management

membership

millimetre

motorcycle

mysterious

nineteenth

noticeable

officially

opposition

originally

parliament

particular

permission

personally

philosophy

photograph

physically

pleasantly

politician

population

possession

preference

presumably

previously

production

profession

proportion

protection

publishing

punishment

reasonable

reasonably

regulation

relatively

remarkable

remarkably

repeatedly

reputation

resistance

restaurant

restricted

retirement

revolution

ridiculous

satisfying

scientific

separately

separation

seventieth

specialist

substitute

successful

sufficient

suggestion

surprising

suspicious

technology

television

themselves

thirteenth

thoroughly

thousandth

throughout

ultimately

underneath

understand

underwater

unemployed

unexpected

unfriendly

university

unpleasant

achievement

acknowledge

advertising

alternative

anniversary

application

appointment

appropriate

approximate

arrangement

association

beautifully

businessman

calculation

celebration

certificate

combination

comfortable

comfortably

communicate

competition

competitive

complicated

concentrate

confidently

consequence

contrasting

countryside

demonstrate

description

desperately

destruction

development

differently

disapproval

dishonestly

distinguish

effectively

efficiently

electricity

embarrassed

emotionally

engineering

entertainer

environment

essentially

exaggerated

examination

expectation

experienced

explanation

fashionable

frightening

fundamental

grandfather

grandmother

grandparent

hairdresser

imagination

immediately

implication

importantly

improvement

independent

information

institution

instruction

intelligent

interesting

investigate

involvement

manufacture

mathematics

measurement

necessarily

observation

opportunity

outstanding

partnership

performance

permanently

personality

photography

politically

possibility

potentially

practically

preparation

publication

recognition

requirement

reservation

responsible

restriction

significant

substantial

supermarket

surrounding

sympathetic

temperature

temporarily

threatening

traditional

translation

transparent

unconscious

underground

unfortunate

unimportant

unnecessary

unwillingly

accidentally

alphabetical

artificially

artistically

circumstance

congratulate

conservative

considerable

considerably

construction

contemporary

continuously

contribution

conventional

conversation

deliberately

disadvantage

disagreement

disappointed

disapproving

distribution

dramatically

embarrassing

entertaining

enthusiastic

increasingly

independence

intelligence

interruption

introduction

manufacturer

nevertheless

occasionally

organization

particularly

photographer

presentation

professional

refrigerator

relationship

satisfaction

specifically

successfully

sufficiently

surprisingly

surroundings

unacceptable

uncontrolled

unemployment

unexpectedly

unreasonable

unsuccessful

accommodation

advertisement

alternatively

approximately

automatically

communication

concentration

consideration

determination

disappointing

embarrassment

encouragement

entertainment

environmental

extraordinary

granddaughter

independently

international

investigation

manufacturing

neighbourhood

pronunciation

qualification

significantly

substantially

traditionally

uncomfortable

understanding

unfortunately

alphabetically

characteristic

congratulation

disappointment

interpretation

representative

responsibility

transportation

enthusiastically""".split(

    "\n"

)

if __name__ == "__main__":

    game = Hangman()

    game.start()

Variables

HANGMAN
WORDS

Classes

Hangman

class Hangman(

)
View Source
class Hangman:

    def __init__(self):

        """

        initializes a `Hangman` object

        """

        pass

    def game(self):

        """

        starts the game

        """

        self.message = ""

        lives = 11

        word = [character.upper() for character in random.choice(WORDS)]

        word_hidden = ["_" for character in word]

        guessed = []

        while (lives != 0) and ("_" in word_hidden):

            cls()

            print(HANGMAN[-lives])

            print()

            if guessed:

                print(" ".join(guessed))

                print()

            print("".join(word_hidden))

            print()

            if self.message:

                print(self.message)

                print()

                self.message = ""

            else:

                print("you have {0} attempt{1} remaining".format(lives, "" if lives == 1 else "s"))

                print()

            letter = input("choose a letter;\n> ").upper()

            if not letter:

                continue

            elif not len(letter) == 1:

                self.message = "too many letters"

                continue

            elif not letter.isalpha():

                self.message = "that is not a letter"

                continue

            elif letter in guessed:

                self.message = "you've already guessed that letter"

                continue

            guessed.append(letter)

            if letter not in word:

                lives -= 1

                continue

            for i in range(len(word)):

                if letter == word[i]:

                    word_hidden[i] = letter

        cls()

        print(HANGMAN[-lives])

        print()

        if guessed:

            print(" ".join(guessed))

            print()

        print("".join(word_hidden))

        print()

        if lives == 0:

            print("you lose")

            print("the word was {0}".format("".join(word)))

        else:

            print("you win")

    def start(self):

        """

        calls `self.game` in a 'would you like to play again?' loop

        """

        choice = "y"

        while choice.startswith("y"):

            cls()

            print(pyfiglet.figlet_format("Hangman"))

            print()

            input("enter to play\nctrl + c to quit to main menu\n\n")

            self.game()

            choice = input("\nwould you like to play again?\n> ").strip()

Methods

game
def game(
    self
)

starts the game

View Source
    def game(self):

        """

        starts the game

        """

        self.message = ""

        lives = 11

        word = [character.upper() for character in random.choice(WORDS)]

        word_hidden = ["_" for character in word]

        guessed = []

        while (lives != 0) and ("_" in word_hidden):

            cls()

            print(HANGMAN[-lives])

            print()

            if guessed:

                print(" ".join(guessed))

                print()

            print("".join(word_hidden))

            print()

            if self.message:

                print(self.message)

                print()

                self.message = ""

            else:

                print("you have {0} attempt{1} remaining".format(lives, "" if lives == 1 else "s"))

                print()

            letter = input("choose a letter;\n> ").upper()

            if not letter:

                continue

            elif not len(letter) == 1:

                self.message = "too many letters"

                continue

            elif not letter.isalpha():

                self.message = "that is not a letter"

                continue

            elif letter in guessed:

                self.message = "you've already guessed that letter"

                continue

            guessed.append(letter)

            if letter not in word:

                lives -= 1

                continue

            for i in range(len(word)):

                if letter == word[i]:

                    word_hidden[i] = letter

        cls()

        print(HANGMAN[-lives])

        print()

        if guessed:

            print(" ".join(guessed))

            print()

        print("".join(word_hidden))

        print()

        if lives == 0:

            print("you lose")

            print("the word was {0}".format("".join(word)))

        else:

            print("you win")
start
def start(
    self
)

calls self.game in a 'would you like to play again?' loop

View Source
    def start(self):

        """

        calls `self.game` in a 'would you like to play again?' loop

        """

        choice = "y"

        while choice.startswith("y"):

            cls()

            print(pyfiglet.figlet_format("Hangman"))

            print()

            input("enter to play\nctrl + c to quit to main menu\n\n")

            self.game()

            choice = input("\nwould you like to play again?\n> ").strip()