Amazing-Python-Scripts
121 строка · 3.1 Кб
1import pygame
2import math
3import random
4
5# setup display
6pygame.init()
7WIDTH, HEIGHT = 800, 500
8win = pygame.display.set_mode((WIDTH, HEIGHT))
9pygame.display.set_caption("Hangman Game")
10
11# button variables
12radius = 20
13gap = 15
14letters = []
15startx = round((WIDTH - (radius * 2 + gap) * 13) / 2)
16starty = 400
17A = 65
18for i in range(26):
19x = startx + gap * 2 + ((radius * 2 + gap) * (i % 13))
20y = starty + ((i//13) * (gap + radius * 2))
21letters.append([x, y, chr(A+i), True])
22
23# load images
24images = []
25for i in range(7):
26img = pygame.image.load("./Hangman-Game/hangman" + str(i) + ".png")
27images.append(img)
28
29# game variables
30hangman_status = 0
31with open("./Hangman-Game/words.txt", 'r') as f:
32content = f.read()
33list_of_words = content.split(",")
34word = random.choice(list_of_words).upper()
35guessed = []
36
37# colors
38white = (255, 255, 255)
39BLACK = (0, 0, 0)
40BLUE = (180, 219, 251)
41PINK = (232, 90, 202)
42
43# fonts
44LETTER_FONTS = pygame.font.SysFont('comicsans', 40)
45WORD_FONTS = pygame.font.SysFont('comicsans', 60)
46TITLE_FONTS = pygame.font.SysFont('comicsans', 70)
47
48
49def draw():
50win.fill(BLUE)
51# draw title
52text = TITLE_FONTS.render("HANGMAN GAME", 1, BLACK)
53win.blit(text, (WIDTH/2 - text.get_width()/2, 20))
54# draw word
55display_word = ""
56for i in word:
57if i in guessed:
58display_word += i + " "
59else:
60display_word += "_ "
61
62text = WORD_FONTS.render(display_word, 1, BLACK)
63win.blit(text, (400, 200))
64# draw buttons
65for i in letters:
66x, y, ltr, visible = i
67if visible:
68pygame.draw.circle(win, BLACK, (x, y), radius, 3)
69text = LETTER_FONTS.render(ltr, 1, BLACK)
70win.blit(text, (x - text.get_width()/2, y - text.get_height()/2))
71win.blit(images[hangman_status], (150, 100))
72pygame.display.update()
73
74# win/loose msg printing msg on screen
75
76
77def display_message(message):
78pygame.time.delay(1000)
79win.fill(PINK)
80text = WORD_FONTS.render(message, 1, BLACK)
81win.blit(text, (WIDTH/2 - text.get_width() /
822, HEIGHT/2 - text.get_height()/2))
83pygame.display.update()
84pygame.time.delay(3000)
85
86
87# setup game loop
88FPS = 60
89clock = pygame.time.Clock()
90run = True
91while run:
92clock.tick(FPS)
93draw()
94for i in pygame.event.get():
95if i.type == pygame.QUIT:
96run = False
97if i.type == pygame.MOUSEBUTTONDOWN:
98m_x, m_y = pygame.mouse.get_pos()
99for i in letters:
100x, y, ltr, visible = i
101if visible:
102dis = math.sqrt((x - m_x)**2 + (y - m_y)**2)
103if dis < radius:
104i[3] = False
105guessed.append(ltr)
106if ltr not in word:
107hangman_status += 1
108draw()
109# checking for winner
110won = True
111for i in word:
112if i not in guessed:
113won = False
114break
115if won:
116display_message("Wohooo...!! You Won!")
117break
118if hangman_status == 6:
119display_message(f"Oopss..!! It was {word} You Lost!")
120break
121pygame.quit()
122