-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhangman_curses.py
126 lines (104 loc) · 4.26 KB
/
hangman_curses.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
120
121
122
123
124
125
126
from unicurses import *
import argparse
from random import choice
import string
def get_args():
p = argparse.ArgumentParser(
prog='hangman.py',
description='Игра виселица (балда)',
epilog='(с) Александр Килинкаров'
)
p.add_argument('-c', default=10, type=int, help='всего сколько ошибок можно допустить')
p.add_argument('-f', required=True, help='имя файла со словами (слова по одному в строке)')
return p.parse_args()
def prepare(filename='russian_nouns.txt'):
try:
with open(filename, 'r', encoding='utf-8') as f:
word = choice([word.lower().strip() for word in f if word.strip()])
except FileNotFoundError:
print('Нет такого файла')
exit()
except PermissionError:
print('Невозможно прочесть файл')
exit()
except:
print('Что-то пошло не так')
exit()
tablo = list('*' * len(word))
return word, tablo
def hangman(tries_count=5, filename='russian_nouns.txt'):
word, tablo = prepare(filename=filename)
alpha = string.digits + string.ascii_lowercase + 'абвгдеёжзийклмнопрстуфхцчшщъыьэюя'
used_letters = []
tries = 0
while tries < tries_count:
wborder(stdscr, 0)
mvaddstr(3, 5, f'Игра Виселица', A_BOLD | color_pair(1))
mvaddstr(5, 5, f'Ошибок {tries}/{tries_count}')
mvaddstr(6, 5, '0 - слово целиком, или буква (Escape - выход)')
if used_letters:
mvaddstr(7, 5, 'Использованные буквы: ' + ', '.join(used_letters))
mvaddstr(ROWS//2, COLS//2 - len(word)//2, ''.join(tablo))
refresh()
k = get_wch()
# Check Esc or Alt
if k == 27:
# Esc or Alt
# Don't need to wait for another key
# If it was Alt then curses has already sent the other key
# If it was Escape key, -1 is sent
nodelay(stdscr, True)
x = getch()
if x == -1: # Escape
exit()
nodelay(stdscr, False)
answer = chr(k).lower()
if answer not in alpha:
continue
used_letters.append(answer)
if answer == '0':
clear()
wborder(stdscr, 0)
mvaddstr(3, 5, f'Игра Виселица', A_BOLD | color_pair(1))
mvaddstr(ROWS//2, COLS//2 - len(word)//2, ''.join(tablo))
mvaddstr(ROWS//2 + 1, COLS//2 - len(word)//2, 'Назови слово: ')
curs_set(1)
echo()
refresh()
u_word = getstr().lower().strip()
if u_word == word:
tablo = [i for i in word]
break
else:
u_letter = answer
if u_letter in word:
for i in range(len(word)):
if word[i] == u_letter:
tablo[i] = word[i]
if '*' not in tablo:
break
else:
tries += 1
clear()
clear()
wborder(stdscr, 0)
mvaddstr(3, 5, f'Игра Виселица', A_BOLD | color_pair(1))
msg = ('Ты проиграл!', 2) if '*' in tablo else ('Ты выиграл!', 1)
mvaddstr(5, 5, f'Ошибок {tries}/{tries_count}')
mvaddstr(ROWS//2-1, COLS//2 - len(word)//2, f'Загаданное слово: {word}')
mvaddstr(ROWS//2, COLS//2 - len(word)//2, msg[0], A_BOLD | color_pair(msg[1]))
mvaddstr(ROWS//2+1, COLS//2 - len(word)//2, 'Нажми enter для выхода...')
curs_set(0)
refresh()
if __name__ == '__main__':
stdscr = initscr()
ROWS, COLS = getmaxyx(stdscr)
noecho()
curs_set(0)
start_color()
init_pair(1, COLOR_GREEN, COLOR_BLACK)
init_pair(2, COLOR_RED, COLOR_BLACK)
args = get_args()
hangman(tries_count=args.c, filename=args.f)
getch()
endwin()