-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhangman.py
119 lines (96 loc) · 3.14 KB
/
hangman.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
import pygame
import math
import random
import os
pygame.init()
WIDTH, HEIGHT = 800, 500
win = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Hangman Game!")
RADIUS = 20
GAP = 15
letters = []
startx = round((WIDTH - (RADIUS * 2 + GAP) * 13) / 2)
starty = 400
A = 65
for i in range(26):
x = startx + GAP * 2 + ((RADIUS * 2 + GAP) * (i % 13))
y = starty + ((i // 13) * (GAP + RADIUS * 2))
letters.append([x, y, chr(A + i), True])
# fonts
LETTER_FONT = pygame.font.SysFont('comicsans', 40)
WORD_FONT = pygame.font.SysFont('comicsans', 60)
TITLE_FONT = pygame.font.SysFont('comicsans', 70)
# load images.
images = []
for i in range(7):
image = pygame.image.load(os.path.join("assets", "hangman") + str(i) + ".png")
images.append(image)
hangman_status = 0
words = ["PYTHON", "PYGAME", "HANGMAN", "GITHUB"]
word = random.choice(words)
guessed = []
WHITE = (255,255,255)
BLACK = (0,0,0)
def draw():
win.fill(WHITE)
text = TITLE_FONT.render("HANGMAN GAME!", 1, BLACK)
win.blit(text, (WIDTH/2 - text.get_width()/2, 20))
display_word = ""
for letter in word:
if letter in guessed:
display_word += letter + " "
else:
display_word += "_ "
text = WORD_FONT.render(display_word, 1, BLACK)
win.blit(text, (400, 200))
for letter in letters:
x, y, ltr, visible = letter
if visible:
pygame.draw.circle(win, BLACK, (x, y), RADIUS, 3)
text = LETTER_FONT.render(ltr, 1, BLACK)
win.blit(text, (x - text.get_width()/2, y - text.get_height()/2))
win.blit(images[hangman_status], (150, 100))
pygame.display.update()
def display_message(message):
pygame.time.delay(1000)
win.fill(WHITE)
text = WORD_FONT.render(message, 1, BLACK)
win.blit(text, (WIDTH/2 - text.get_width()/2, HEIGHT/2 - text.get_height()/2))
pygame.display.update()
pygame.time.delay(3000)
def main():
global hangman_status
FPS = 60
clock = pygame.time.Clock()
run = True
while run:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.MOUSEBUTTONDOWN:
m_x, m_y = pygame.mouse.get_pos()
for letter in letters:
x, y, ltr, visible = letter
if visible:
dis = math.sqrt((x - m_x)**2 + (y - m_y)**2)
if dis < RADIUS:
letter[3] = False
guessed.append(ltr)
if ltr not in word:
hangman_status += 1
draw()
won = True
for letter in word:
if letter not in guessed:
won = False
break
if won:
display_message("You WON!")
break
if hangman_status == 6:
display_message("You LOST!")
break
while True:
main()
pygame.quit()