Program Designer

Hangman Game Code

Only editable by group admins

  • Last updated December 8, 2016 at 4:53 AM
  • Evidence visible to public
This is your hangman.py file containing the Python code for your game.

All posted evidence

Hangman Game

#Trent Cimina
#Hangman

import random
from tkinter import *

def draw_gallows():
  #Draw Gallows
    c.create_line(100,800, 500,800, width=10)
    c.create_line(100,800, 100,900, width=10)
    c.create_line(500,800, 500,900, width=10)
    c.create_line(300,800, 300,200, width=10)
    c.create_line(300,200, 500,200, 500,300, width=10)
def draw_head():
    c.create_oval(450,300, 550,400, width=5)
def draw_torso():
    c.create_line(500,400, 500,600, width=5)
def draw_rightleg():
    c.create_line(500,600, 425,700, width=5)
def draw_leftleg():
    c.create_line(500,600, 575,700, width=5)
def draw_rightarm():
    c.create_line(500,450, 425,400, width=5)
def draw_leftarm():
    c.create_line(500,450, 575,400, width=5)
def lines():
  #Underlines for the letters
  	x = 60
    counter = 0
    while counter < len(puzzle):
        if puzzle[counter] in legal_chars:
            c.create_line(x,100, (x+10), 100)
            x = x + 10
            counter = counter + 1
        elif puzzle[counter] == "'":
            c.create_text(x,70, text = puzzle[counter])
            x = x + 10
            counter = counter + 1
        else:
            c.create_text(x,100,text = puzzle[counter])
            x = x + 10
            counter = counter + 1
def read_phrase():
  #This generates the puzzle / secret phrase
    f = open('hangman.txt')
    selected_line = random.randrange(0, 370) #change this to a random value between 0 and 370
    for i in range(selected_line-1):
      	f.readline()
    puzzle = f.readline()
    f.close()
    return puzzle
  
def handle_keypress(event):
  	global mistake
  	global right_time
  	global number_of_letter
  	if event.char in legal_chars:
    	for i in range(len(secret_phrase)):
      	if event.char == secret_phrase[i]:
        	c.create_text(200+i*20, 100, text=event.char)
        	right_time +=1
        if right_time == number_of_letter:
            c.create_text(1000, 300, text="Congrats! Winner!")
            main_window.after(2000,main_window.destroy)
  	if event.char in legal_chars:
    	if event.char not in secret_phrase:
      	mistake +=1
      	wrong()
      	c.create_text(1000+mistake*20, 100, text=event.char)
      
def wrong():
  	if mistake == 1:
    	draw_head()
  	if mistake == 2:
    	draw_torso()
  	if mistake == 3:
    	draw_rightarm()
    if mistake == 4:
    	draw_leftarm()
  	if mistake == 5:
    	draw_rightleg()
  	if mistake == 6:
    	draw_leftleg()
    	c.create_text(1000, 300, text="Aw! Game Over!")
    	for i in range (len(secret_phrase)):
      	if secret_phrase[i] in legal_chars:
        	c.create_text(204+i*20, 105, text=secret_phrase[i])
    	main_window.after(2000,main_window.destroy)
              
legal_chars = 'abcdefghijklmnopqrstuvwxyz'
secret_phrase = read_phrase()

main_window = Tk()
main_window.title("Hangman")

c = Canvas(main_window, width=1200, height=1200)
c.pack()
c.bind('<Key>', handle_keypress)
c.focus_set()

number_of_letter = 0
right_time = 0
mistake = 0
lines()
draw_gallows()
mainloop()
ciminat99 Almost 9 years ago

Hangman code

#Shaunak Lavande, Mods 15-16
#This program allows the user to play hangman

from tkinter import *
import random

legal_chars = 'abcdefghijklmnopqrstuvwxyz'
used = ""
wrong = 0
done = False


def read_phrase():
    '''This function generates the phrase for the game'''
    f = open('hangman.txt')
    selected_line = random.randrange(0, 371)
    for i in range(selected_line-1):
        f.readline()                
    puzzle = f.readline()
    f.close()
    return puzzle.lower()


def draw_gallows():
    '''This function draws the gallows'''
    c.create_line(300,315,380,315,fill='red',width=4)
    c.create_line(340,315,340,90, fill='red',width=4)
    c.create_line(340,90,395,90,fill='red',width=4)
    c.create_line(395,90,395,115,fill='red',width=4)
def head():
    '''This function draws the head'''
    c.create_oval(375,115,415,155)

def body():
    '''This function draws the body'''
    c.create_line(395,155,395,240)

def left_arm():
    '''This function draws the left arm'''
    c.create_line(395,177,365,215)

def right_arm():
    '''This function draws the right arm'''
    c.create_line(395,177,425,215)

def left_leg():
    '''This function draws the left leg'''
    c.create_line(395,240,375,280)

def right_leg():
    '''This function draws the right leg'''
    c.create_line(395,240,415,280)
def handle_keypress(event):
    '''This function is used to mark the characters the player picks.
Also, it asks if the player wants to continue playing or not.'''
    global used_letters
    global wrong
    global done
    yee = set(puzzle)
    wee = set()
    if done == False:
        if event.char in puzzle:
           if event.char in legal_chars and event.char not in used_letters:
                for i in range(len(puzzle)):
                    if event.char == puzzle[i]:
                        c.create_text(10+i*20, 395, text=event.char)
                        used_letters += str(event.char)
                        wee = set(used_letters)
        elif event.char in legal_chars and event.char in used_letters:
                print("Character is used. Try another one")            
        elif event.char not in puzzle:
            if event.char in legal_chars:
               wrong = wrong + 1
               print("You got " + str(wrong) +" characters wrong")
               man()
            elif event.char not in legal_chars:
                print("This character is illegal, please try again")
        if (yee & set(legal_chars)) - wee == set():
            print("You won!")
            done = True
    if done == True:
        c.create_text(300,600, text = "Would you like to play again?(Please press 'y' for yes and 'n' for no)")
        if event.char == "y":
            game_setup()
        elif event.char == "n":
            c.create_text(300,450, text = "Thanks for playing")



def draw_lines():
    '''This function draws the lines for the characters'''
    x = 5
    number_of_tries = 0
    while number_of_tries < len(puzzle):
        if puzzle[number_of_tries] in legal_chars:
            c.create_line(x,400, (x+10), 400)
            x = x + 20
            number_of_tries = number_of_tries + 1
        elif puzzle[number_of_tries] == "'":
            c.create_text(x,380, text = puzzle[number_of_tries])
            x = x + 20
            number_of_tries = number_of_tries + 1
        else:
            c.create_text(x,400,text = puzzle[number_of_tries])
            x = x + 20
            number_of_tries = number_of_tries + 1

def man():
    '''This program makes the dead hangman depending on how many characters the player got wrong'''
    global wrong
    global done
    if done == False:
       if wrong == 1:
           head()
       elif wrong == 2:
           body()
       elif wrong == 3:
           left_arm()
       elif wrong == 4:
           right_arm()
       elif wrong == 5:
           left_leg()
       elif wrong == 6:
           right_leg()
           print("You lost, the phrase is:" +str(puzzle))
           done = True
    elif done == True:
        c.create_text(300,500, text = "Would you like to play again?(Please press 'y' for yes and 'n' for no)")
        if event.char == "y":
            game_setup()
        elif event.char == "n":
            c.create_text(300,550, text = "Thank you for playing")

def setup():
    '''This function sets the game'''
    global puzzle
    global done
    global used_letters
    global wrong
    c.create_rectangle(0,0, 900,900, fill="green")
    puzzle = read_phrase()
    draw_lines()
    draw_gallows()
    done = False
    used_letters = ""
    wrong = 0
    

main_window = Tk()
main_window.title("Hangman Game by Shaunak Lavande")
c = Canvas(main_window, width=900, height=900)
c.pack()
c.bind('<Key>', handle_keypress)
c.focus_set()

setup()

mainloop()
shaunakl123 Almost 9 years ago

Hangman Assignment Code

#Simon Ren
#This program plays the Hangman Game
import random
from tkinter import *

def read_phrase():
    ''' Generates a phrase to be used in the puzzle'''
    f = open('hangman.txt')
    selected_line = random.randrange(0,371) #change this to a random value between 0 and 370
    for i in range(selected_line-1):
        f.readline() #skip over the lines till we get to the selected line
    puzzle = f.readline()
    f.close()
    return puzzle

def draw_gallows():
    ''' Draws the gallows for the Hangman game '''
    c.create_line(0, 600, 80, 600)
    c.create_line(40, 600, 40, 300)
    c.create_line(40, 300, 120, 300)
    c.create_line(120, 300, 120, 350)

def draw_head():
    ''' Draws the head of the Hangman'''
    c.create_oval(80, 350, 160, 430)

def draw_body():
    ''' Draws the body of the Hangman '''
    c.create_line(120, 430, 120, 520)

def draw_arm1():
    ''' Draws the left arm of the Hangman '''
    c.create_line(100, 490, 120, 460)

def draw_arm2():
    ''' Draws the right arm of the Hangman '''
    c.create_line(140, 490, 120, 460)

def draw_leg1():
    ''' Draws the left leg of the Hangman '''
    c.create_line(100, 540, 120, 520)

def draw_leg2():
    ''' Draws the right leg of the Hangman '''
    c.create_line(120, 520, 140, 540)

def mistake():
    ''' Draws the corresponding body part for each mistake the user makes
        If the body is completely drawn, displays a Lose message '''
    if incorrect < 7:
        if incorrect == 1:
            draw_head()
        elif incorrect == 2:
            draw_body()
        elif incorrect == 3:
            draw_leg1()
        elif incorrect == 4:
            draw_leg2()
        elif incorrect == 5:
            draw_arm1()
        elif incorrect == 6:
            draw_arm2()
            c.create_text(350, 450, text="Lost :(")
            c.create_text(350, 350, text=secret_phrase)
    
     
def handle_keypress(event):
    ''' Allows the program to respond to keystrokes
        Creates the inputed character in the correct location
        If the phrase is completed, displays a Win message '''
    global correct
    global incorrect
    if event.char in legal_chars:
        for i in range(len(secret_phrase)):
            if event.char == secret_phrase[i]:
                c.create_text(16 + i*20, 35, text=event.char)
                correct += 1
        if correct == letternum:
            c.create_text(350, 450, text="Winner!  :)")
    if event.char in legal_chars:
        if event.char not in secret_phrase:
            incorrect += 1
            mistake()
            c.create_text(100 + incorrect*20, 150, text=event.char)

def blanks():
    ''' Draws the blanks for the phrase that the useer must complete '''
    global letternum
    for i in range(len(secret_phrase)):
        if secret_phrase[i] in legal_chars:
            c.create_line(15+i*20, 45, 25+i*20, 45)
            letternum += 1
        else:
            c.create_text(15 + i*20, 35, text=secret_phrase[i])

        




read_phrase()
letternum = 0
correct = 0
incorrect = 0
legal_chars = 'abcdefghijklmnopqrstuvwxyz'
secret_phrase = read_phrase()
secret_phrase = secret_phrase.lower()

main_window = Tk()
main_window.title("Hangman")
    
c = Canvas(main_window, width=800, height=800)
c.pack()
c.bind('<Key>', handle_keypress)
c.focus_set()
draw_gallows()
blanks()


mainloop()
simonren Almost 9 years ago

Hangman Code

#Shreyas Vivek
#Hangman game

from tkinter import *
import random

characters = 'abcdefghijklmnopqrstuvwxyz'
used_characters = ""
wrong = 0
done = False

def phrase():
    '''This function generates the phrase for the game'''
    f = open('hangman.txt')
    selected_line = random.randrange(0,370)
    for i in range(selected_line-1):
        f.readline()                                        
    puzzle = f.readline()
    f.close()
    return puzzle.lower()

def gallows():
    '''This function draws the gallows'''
    c.create_line(385,360, 385,135,fill="white",width=2)
    c.create_line(440,135, 440,160,fill="white",width=2)
    c.create_line(385,135, 440,135,fill="white",width=2)
    c.create_line(345,360, 425,360,fill="white",width=2)

def head():
    '''Draws the head'''
    c.create_oval(420,160, 460,200,fill="white",width=2)

def body():
    '''Draws the body'''
    c.create_line(440,200, 440,285,fill="white",width=2)

def right_arm():
    '''Draws the right arm'''
    c.create_line(440,222, 470,260,fill="white",width=2)


def left_arm():
    '''Draws the left arm'''
    c.create_line(440,222, 410, 260,fill="white",width=2)

def right_leg():
    '''Draws the right leg'''
    c.create_line(440,285, 460, 325,fill="white",width=2)


def left_leg():
    '''Draws the left leg'''
    c.create_line(440,285, 420, 325,fill="white",width=2)


def handle_keypress(event):
    '''This function writes down the charcter in the space if its presnt in the phrase,
recognizes if it isnt present and draws a body part, and notifys the user if it is an illegal character '''
    global used_characters
    global wrong
    global done
    p = set(puzzle)
    pu = set()
    if done == False:
        if event.char in puzzle:
           if event.char in characters and event.char not in used_characters:
                for i in range(len(puzzle)):
                    if event.char == puzzle[i]:
                        c.create_text(10+i*20, 395, text=event.char, fill="white",width=2)
                        used_characters += str(event.char)
                        pu = set(used_characters)
        elif event.char in characters and event.char in used_characters:
                print("You have already used this character! Try again!")            
        elif event.char not in puzzle:
            if event.char in characters:
               wrong = wrong + 1
               print("That is your " + str(wrong) +" character wrong")
               man()
            elif event.char not in characters:
                print("You cannot use this character becuase it  is illegal! Try again!")
        if (p & set(characters)) - pu == set():
            c.create_text(300,450, fill="white", text = "Winner!",width=2)
            done = True
    if done == True:
        c.create_text(300,500, fill="white", text = "Are you done or ready for more? (click y to play again or n to leave the game)")
        if event.char == "y":
            setup()
        elif event.char == "n":
            c.create_text(300,550, fill="white", text = "See you later!",width=2)

def lines():
    '''Draws the lines for the characters'''
    x = 5
    tries = 0
    while tries < len(puzzle):
        if puzzle[tries] in characters:
            c.create_line(x,400, (x+10), 400, fill="white",width=2)
            x = x + 20
            tries = tries + 1
        elif puzzle[tries] == "'":
            c.create_text(x,380, text = puzzle[tries])
            x = x + 20
            tries = tries + 1
        else:
            c.create_text(x,400,text = puzzle[tries])
            x = x + 20
            tries = tries + 1

def man():
    '''This draws the hangman whenever the user inputs a wrong character'''
    global wrong
    global done
    if done == False:
       if wrong == 1:
            head()
       elif wrong == 2:
            body()
       elif wrong == 3:
            left_arm()
       elif wrong == 4:
            right_arm()
       elif wrong == 5:
            left_leg()
       elif wrong == 6:
            right_leg()
            print("Loser! The correct phrase was:" +str(puzzle))
            done = True
    elif done == True:
        c.create_text(300,500, text = "Are you done or ready for more? (click y to play again or n to leave the game)",width=2)
        if event.char == "y":
            setup()
        elif event.char == "n":
            c.create_text(300,550, text = "See you later!",width=2)

def setup():
    '''This function sets up the game'''
    global puzzle
    global done
    global used_characters
    global wrong
    c.create_rectangle(0,0, 1000,1000, fill="black")
    puzzle = phrase()
    lines()
    gallows()
    done = False
    used_characters = ""
    wrong = 0
    

main_window = Tk()
main_window.title("Hangman Game-Shreyas Vivek")
c = Canvas(main_window, width=1000, height=1000)
c.pack()
c.bind('<Key>', handle_keypress)
c.focus_set()
setup()

mainloop()
shreyas_vivek Almost 9 years ago

You need to copy the text document path in order to use random

import random
from tkinter import *
phrase_list = []
phrase = ""
window = Tk()
window.title("stuff")
canvas = Canvas(window, width = 1000, height = 800)
canvas.pack()
phrase = "jojojojojo"
test_string = ""
legal_char = "abcdefghijklmnopqrstuvwxyz"
part_number = 0
game_over = False

def dead():
    #resets the game when it's over
    global game_over, part_number
    game_over = True
    for x in range(len(phrase)):
        canvas.create_text(500 - 5*len(phrase)+(x*10), 647, text = phrase[x], tag = "text", fill = "red")
    print("oh, too bad, you lose try again!!!")
    part_number = -1
def drawbodypart():
    #draws the person
    global part_number
    if(part_number == 0):
        canvas.create_oval(650, 200, 750, 300, tag = "person")
    if(part_number == 1):
        canvas.create_oval(675, 220, 690, 235, tag = "person")
    if(part_number == 2):
        canvas.create_oval(710, 220, 725, 235, tag = "person")
    if(part_number == 3):
        canvas.create_line(675, 265, 725, 265, tag = "person")
    if(part_number == 4):
        canvas.create_line(700, 300, 700, 500, tag = "person")
    if(part_number == 5):
        canvas.create_line(650, 400, 750, 400, tag = "person")
    if(part_number == 6):
        canvas.create_line(700, 500, 650, 570, tag = "person")
    if(part_number == 7):
        canvas.create_line(700, 500, 750, 570, tag = "person")
        dead()
    part_number += 1
    
def test_letter(character):
    #checks the letter inputted
    global legal_char, game_over, test_string
    y = 0
    if game_over:
        initialize()
    else:
        if(character.char in legal_char):
            for x in range(len(phrase)):
                if(character.char == phrase[x]):
                    canvas.create_text(500 - 5*len(phrase)+(x*10), 647, text = character.char, tag = "text")
                    test_string += character.char
                    y = 1
            legal_char = legal_char.replace(character.char, "")
            canvas.create_text((ord(character.char)-97) * 10 + 300, 750, text = "X", fill = "red", tag = "text")
            if(y == 0):
                drawbodypart()
            else:
                y = 0
                if(len(test_string) == len(phrase.replace(" ",""))):
                    print("yey, u win. press a letter to keep playing")
                    game_over = True
                
        
def initialize():
    #initializes the game
    canvas.delete("person", "text")
    global legal_char, game_over, test_string, phrase, part_number
    part_number = 0
    game_over = False
    legal_char = "abcdefghijklmnopqrstuvwxyz"
    phrase = input("Hangman phrase (hide this from the player): ").lower()
    if(phrase.lower() == "random"):
        phrase = phrase_list[random.randrange(len(phrase_list))].lower()
    else:
        for x in range(len(phrase.replace(" ",""))):
            if(phrase.replace(" ","")[x] not in legal_char):
                print("That phrase has an illegal character in it!!! (press a letter to try again)")
                game_over = True
    canvas.create_line(400, 600, 600, 600)
    canvas.create_line(500, 600, 500, 100, 700, 100, 700, 200)
    canvas.bind("<Key>", test_letter)
    canvas.focus_set()
    test_string = ""
    for x in range(len(phrase)):
        if(" " != phrase[x]):
            canvas.create_text(500 - 5*len(phrase)+(x*10), 650,text = "_", tag = "text")
        else:
            canvas.create_text(500 - 5*len(phrase)+(x*10), 650,text = " ", tag = "text")
    for x in range(26):
        canvas.create_text(x * 10 + 300, 750, text = chr(x+65), tag = "text")

def main():
    #just main
    with open("/Users/burts/Desktop/Kappa/CopyPathnameHere.txt", 'r') as file:
        for line in file:
            phrase_list.append(line[:-1])        
    initialize()
    mainloop()
main()

drmrcool Almost 9 years ago

My python hangman game program.

#Ethan Bowman
#Hangman Game
from tkinter import*
import random
import sys
import os


legal_char = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
punctuation = " ' " 

def read_phrase():#Choses one random phrase
    global puzzle
    f = open('hangman.txt')
    selected_line = random.randrange(0, 370)
    for i in range(selected_line-1):
        f.readline()
    puzzle = f.readline()
    f.close()
read_phrase()

secret_phrase = puzzle.lower()

def num_characters(): #Counts the number of characters in the phrase
    global total
    for o in range(len(secret_phrase)):
        if secret_phrase[o] in legal_char:
            total = total + 1
    return total

def draw_game(): #Draws gallows and letter underlining
    a = 0
    for i in range (len(secret_phrase)):
        if secret_phrase[i] in legal_char:
            c.create_line (250-(len(secret_phrase)*2.5)+(15*a), 550,  260 - (len(secret_phrase)*2.5) + (15*a), 550)
        if secret_phrase[i] in punctuation:
            c.create_text(253 - (len(secret_phrase)*2.5) +i*15.1, 540, text=secret_phrase[i])
        a = a + 1
    c.create_line(250, 450,  550, 450,)
    c.create_line(400, 450,  400, 100,  325, 100,  325, 120)

def handle_keypress(event): #Processes user input
    global b
    global t
    global tot_chars
    if event.char in legal_char:
        if event.char not in tot_chars:
            for i in range(len(secret_phrase)):
                if event.char == secret_phrase[i]:
                    c.create_text(253 - (len(secret_phrase)*2.5) +i*15.1, 540, text=event.char)
                    t = t + 1
                    if t == total:
                        c.create_text(500, 250, text="You Win!")
                        end_of_game()
            if event.char not in secret_phrase:
                c.create_text(253 + b, 600, text=event.char)
                draw_body()
                b = b + 12
            tot_chars = tot_chars + event.char
    if event.char == " ":
        python = sys.executable
        os.execl(python, python, * sys.argv)
    
def draw_body(): #Draws new body part each time called 
    global n
    if n == 1:
        #Draw head
        c.create_oval(295, 120,  355, 180 )
        n = n + 1
        return
    if n == 2:
        #Draw body
        c.create_line(325, 180,  325, 300)
        n = n + 1
        return
    if n == 3:
        #Draw left leg
        c.create_line(325, 300,  275, 370)
        n = n + 1
        return
    if n == 4:
        #Draw right leg
        c.create_line(325, 300,  375, 370)
        n = n + 1
        return
    if n == 5:
        #Draw right arm
        c.create_line(325, 200, 375, 250)
        n = n + 1
        return
    if n == 6:
        #Draw left arm
        c.create_line(325, 200, 275, 250)
        c.create_text(500, 250, text="You Loose!")
        end_of_game()

def end_of_game(): #Completes puzzle and finishes game
    for i in range(len(secret_phrase)):
        if secret_phrase[i] not in tot_chars:
            c.create_text(253 - (len(secret_phrase)*2.5) +i*15.1, 540, text=secret_phrase[i])
    c.create_text(550, 320, text="Press space bar to continue")

      
n = 1
b = 0
t = 0
tot_chars = " "
total = 0

main_window = Tk()
main_window.title("hangman")

c = Canvas(main_window, width=800, height = 800)
c.pack()
c.bind('<Key>', handle_keypress)
c.focus_set()
draw_game()
num_characters()

mainloop()
ethanb Almost 9 years ago

This is my hangman program.

#Alex Majkic, Mods 3-4
#This program allows the user to play hangman

from tkinter import *
import random

legal_chars = 'abcdefghijklmnopqrstuvwxyz'
used_letters = ""
wrong = 0
done = False

def draw_gallows():
    '''This function draws the gallows'''
    c.create_line(335,350, 415,350)
    c.create_line(375,350, 375,125)
    c.create_line(375,125, 430,125)
    c.create_line(430,125, 430,150)

def draw_head():
    '''This function draws the head'''
    c.create_oval(410,150, 450,190)

def draw_body():
    '''This function draws the body'''
    c.create_line(430,190, 430,275)

def draw_l_arm():
    '''This function draws the left arm'''
    c.create_line(430,212, 400, 250)

def draw_r_arm():
    '''This function draws the right arm'''
    c.create_line(430,212, 460,250)

def draw_l_leg():
    '''This function draws the left leg'''
    c.create_line(430,275, 410, 315)

def draw_r_leg():
    '''This function draws the right leg'''
    c.create_line(430,275, 450, 315)

def read_phrase():
    '''This function generates the phrase for the game'''
    f = open('hangman371.txt')
    selected_line = random.randrange(0, 371)
    for i in range(selected_line-1):
        f.readline()                                        #skip over the lines till we get to the selected line
    puzzle = f.readline()
    f.close()
    return puzzle.lower()

def handle_keypress(event):
    '''This function makes the letters appear on the screen
    and notes whether or not the player has chosen a correct character
    event = when the player types a character'''
    global used_letters
    global wrong
    global done
    ps = set(puzzle)
    uls = set()
    if done == False:
        if event.char in puzzle:
           if event.char in legal_chars and event.char not in used_letters:
                for i in range(len(puzzle)):
                    if event.char == puzzle[i]:
                        c.create_text(10+i*20, 395, text=event.char)
                        used_letters += str(event.char)
                        uls = set(used_letters)
        elif event.char in legal_chars and event.char in used_letters:
                print("This character has already been used, please try again")            
        elif event.char not in puzzle:
            if event.char in legal_chars:
               wrong = wrong + 1
               print("You have gotten " + str(wrong) +" characters wrong")
               man()
            elif event.char not in legal_chars:
                print("This character is an illegal character, please try again")
        if (ps & set(legal_chars)) - uls == set():
            print("You win!")
            done = True
    if done == True:
        c.create_text(300,500, text = "Would you like to play again?(Please press 'y' for yes and 'n' for no)")
        if event.char == "y":
            game_setup()
        elif event.char == "n":
            c.create_text(300,550, text = "Thank you for playing")

def draw_lines():
    '''This function draws the lines for the characters'''
    x = 5
    counter = 0
    while counter < len(puzzle):
        if puzzle[counter] in legal_chars:
            c.create_line(x,400, (x+10), 400)
            x = x + 20
            counter = counter + 1
        elif puzzle[counter] == "'":
            c.create_text(x,380, text = puzzle[counter])
            x = x + 20
            counter = counter + 1
        else:
            c.create_text(x,400,text = puzzle[counter])
            x = x + 20
            counter = counter + 1

def man():
    '''This program forms the hangman based on how many characters the character has gotten wrong'''
    global wrong
    global done
    if done == False:
       if wrong == 1:
            draw_head()
       elif wrong == 2:
            draw_body()
       elif wrong == 3:
            draw_l_arm()
       elif wrong == 4:
            draw_r_arm()
       elif wrong == 5:
            draw_l_leg()
       elif wrong == 6:
            draw_r_leg()
            print("You lose, the puzzle was:" +str(puzzle))
            done = True
    elif done == True:
        c.create_text(300,500, text = "Would you like to play again?(Please press 'y' for yes and 'n' for no)")
        if event.char == "y":
            game_setup()
        elif event.char == "n":
            c.create_text(300,550, text = "Thank you for playing")

def game_setup():
    '''This function sets up the game'''
    global puzzle
    global done
    global used_letters
    global wrong
    c.create_rectangle(0,0, 800,750, fill="white")
    puzzle = read_phrase()
    draw_lines()
    draw_gallows()
    done = False
    used_letters = ""
    wrong = 0
    

main_window = Tk()
main_window.title("Hangman")
c = Canvas(main_window, width=800, height=750)
c.pack()
c.bind('<Key>', handle_keypress)
c.focus_set()

game_setup()

mainloop()
majkica Almost 9 years ago

...

#Vivian Li
#Hangman Game
import random
import tkinter
master = tkinter.Tk()
master.title("Hangman Game")
screen = tkinter.Canvas(master,width = 600, height = 600)
screen.pack()
puzzles = ""
pressable_char = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
wrong_guess = 0
correct_characters = []
def draw_screen(puzzle):
    """Draws the hangman screen"""
    x_cord = 300 -10*(len(puzzle)/2)
    x_cord2 = 40
    for x in puzzles:
        if x == " ":
            x_cord += 10
        elif x == ",":
            screen.create_line(x_cord+3,501,x_cord,503)
            x_cord += 12
        elif x == "'":
            screen.create_line(x_cord+3,493,x_cord,495)
            x_cord += 12
        elif x == "-":
            screen.create_line(x_cord,503,x_cord+5,503)
            x_cord+=10
        elif x.lower() in 'abcdefghijklmnopqrstuvwxyz':
            screen.create_line(x_cord, 500, x_cord + 5, 500)
            x_cord += 10
    for x in 'abcdefghijklmnopqrstuvwxyz':
        screen.create_text(x_cord2, 550, text=x.upper(), tag="letter")
        x_cord2 += 20
    screen.create_line(150,450,450,450)
    screen.create_line(300, 450, 300, 100,400,100,400,150)
def read_phrase():
    """Chooses a random phrase to guess"""
    #copy the hangman371 to the desktop
    f = open('/Users/liv/Desktop/hangman371.txt')
    selected_line = random.randrange(0,370)
    for i in range(selected_line+1):
        f.readline()
    puzzle = f.readline()
    f.close()
    return puzzle
def play_again():
    """Resets the screen to play again"""
    global pressable_char
    global wrong_guess
    global correct_characters
    global puzzles
    screen.delete("all")
    pressable_char = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
    wrong_guess = 0
    correct_characters = []
    puzzles = read_phrase()
    draw_screen(puzzles)
def draw_man():
    """When the guess is wrong, draws a body part, and if the man is dead, tells the player what letters they missed"""
    global screen
    global wrong_guess
    global puzzles
    global pressable_char
    x_cord = 300 -10*(len(puzzles)/2)
    wrong_guess += 1
    if wrong_guess == 1:
        screen.create_oval(375,150,425,200,tag="man")
    elif wrong_guess == 2:
        screen.create_line(400,200,400,350, tag="man")
    elif wrong_guess == 3:
        screen.create_line(400,250,350,300,tag="man")
    elif wrong_guess == 4:
        screen.create_line(400,250,450,300,tag="man")
    elif wrong_guess == 5:
        screen.create_line(400,350, 450,400,tag="man")
    elif wrong_guess == 6:
        screen.create_line(400,350,350,400,tag="man")
    elif wrong_guess == 7:
        screen.create_line(400,300,475,350,tag='man')
        for i in range(len(puzzles)):
            for x in pressable_char:
                if x == puzzles[i].lower():
                    screen.create_text(x_cord+3.5 + i*10,493, text=x, fill="red")
        if tkinter.messagebox.askyesno("Game Over","Do you want to play again?") == True:
            play_again()
def check_win():
    """Checks if the play won"""
    global puzzles
    global correct_characters
    puzzlesi = len(puzzles) - puzzles.count(" ") - puzzles.count("'")-puzzles.count(",")
    correct = 0
    for x in puzzles.lower():
        if x in correct_characters:
            correct += 1
    if correct >= puzzlesi -1:
        if tkinter.messagebox.askyesno("You Won","Do you want to play again?") == True:
            play_again()
def handle_keypress(event):
    """When a key is pressed, runs the key to see if it is in the word, and removes it from pressable characters"""
    global pressable_char
    global puzzles
    global correct_characters
    global screen
    x_cord = 300 -10*(len(puzzles)/2)
    x_cord2 = 40
    if event.char in pressable_char:
        for i in range(len(puzzles)):
            if event.char == puzzles[i].lower():
                screen.create_text(x_cord+3.5 + i*10,493, text=event.char)
                correct_characters.append(event.char)
        pressable_char.remove(event.char)
        screen.delete("letter")
        for x in pressable_char:
            screen.create_text(x_cord2, 550, text=x.upper(),tag="letter")
            x_cord2 += 20
        if (event.char not in puzzles.lower()) and (event.char in 'abcdefjhijklmnopqrstuvwxyz'):
            draw_man()
    else:
        message = tkinter.messagebox.showinfo("Invalid Character", "The character you have guessed either has been guessed before or isn't a valid character")
    check_win()
puzzles = read_phrase()
screen.bind('<Key>', handle_keypress)
screen.focus_set()
draw_screen(puzzles)
tenshiri About 9 years ago

This program sets up a game of hangman.

#Brooke Christiansen
#HANGMAN program

from tkinter import *
from random import *
from time import sleep

legal_chars = 'abcdefghijklmnopqrstuvwxyz'
used_char = ''
wrong_answerz = 0
right_answerz = 0
len_of_puzzle = 0
done = False

def intro():
    c.create_text(400,100,text='ready to die?', font = ('LCDMono2',30))

def draw_gallows():
    '''draws the gallows for the man'''
    c.create_line(90,60,90,20,200,20,200,400, width="10", fill = 'red')
    c.create_line(60,400,340,400, width="10",fill = 'red')

def read_phrase():
    '''picks a random phrase'''
    f = open('hangman.txt')
    selected_line = randrange(0,370) #changed this to a random value between 0 and 370
    for i in range(selected_line-1):
        f.readline() #skip over the lines till we get to the selected line
    puzzle = f.readline()
    f.close()
    strpuzzle = str(puzzle)
    l_puzzle= strpuzzle.lower()
    return l_puzzle

def draw_word_lines(puzzle):
    '''draws the areas for characters
    puzzle - the given phrase'''
    global len_of_puzzle
    
    for i in range(len(puzzle)):
        if puzzle[i] in legal_chars:
            c.create_line(15+i*25,490,(15+(i)*25)+8,490)
            len_of_puzzle += 1
        else:
            c.create_text(20+i*25,480,text=puzzle[i])

def handle_keypress(event):
    '''creates the spacing for correct letters
    event - if keyboard is used'''
    global wrong_answerz,right_answerz, len_of_puzzle, used_char, done
    if done:
        main_window.destroy()
    elif event.char not in used_char:
        used_char += event.char
        if event.char in legal_chars:
            for i in range(len(puzzle)):
                if event.char == puzzle[i]:
                    c.create_text(20+i*25,480,text=event.char, font = ('LCDMono2',30))
                    right_answerz = right_answerz + 1
                    if wrong_answerz < 7 and right_answerz == len_of_puzzle:
                        c.create_text(500,300,text="you miraculously didn't die.(press any character to quit)", font = ('LCDMono2',30))
                        done = True

        if event.char not in puzzle:
            wrong_answerz = wrong_answerz + 1
            wrong(wrong_answerz)
            c.create_text(500+wrong_answerz*25,200,text=event.char, font = ('LCDMono2',30))

def wrong(wrong_answerz):
    '''draws the hangman and tells you if you lost
    wrong_answerz - the amount of incorrect guesses'''
    global done
    if wrong_answerz == 1:
        c.create_oval(50,60,130,140)
    elif wrong_answerz == 2:
        c.create_line(90,140,90,250)
    elif wrong_answerz == 3:
        c.create_line(90,250,50,320)
    elif wrong_answerz == 4:
        c.create_line(90,250,130,320)
    elif wrong_answerz == 5:
        c.create_line(90,180,130,180)
    elif wrong_answerz == 6:
        c.create_line(90,180,50,180)
        c.create_text(500,300,text='you died. rip.(press any character to quit)', font = ('LCDMono2',30))
        done = True

        
main_window = Tk()
main_window.title("Brooke's hangman bonanza")
puzzle = read_phrase()

c = Canvas(main_window,width=1000, height=500)
c.pack()
c.bind('<Key>',handle_keypress)
c.focus_set()

intro()

draw_word_lines(puzzle)

draw_gallows()

mainloop()
christiansenb About 9 years ago