Created
February 14, 2025 10:40
-
-
Save kksudo/7be5aad95297edc26d7ba624ad9739a8 to your computer and use it in GitHub Desktop.
Ilia-PY
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from tkinter import * | |
| from tkinter import messagebox | |
| from random import randint | |
| # Определяем начальную точку русского алфавита | |
| st = ord('А') | |
| # метод при нажатии на клавишу, для десктопа | |
| def pressKey(event): | |
| global st | |
| ch = event.char.upper() | |
| if len(ch) == 0: | |
| return | |
| if ch == "Ё": | |
| codeBtn = 6 # Учитываем Ё в алфавите | |
| else: | |
| codeBtn = ord(ch) - st | |
| if 0 <= codeBtn <= 32: | |
| pressLetter(codeBtn) | |
| # обновляем информацию об очках | |
| def updateInfo(): | |
| scoreLabel["text"] = f"Ваши очки: {score}" | |
| topScoreLabel["text"] = f"Лучший результат: {topScore}" | |
| userTryLabel["text"] = f"Осталось попыток: {userTry} " | |
| # сохраняет в файл очки пользователя | |
| def saveTopScore(): | |
| global topScore | |
| topScore = score | |
| try: | |
| with open("topchik.dat", "w", encoding="utf-8") as f: | |
| f.write(str(topScore)) | |
| except BaseException: | |
| messagebox.showinfo("Возникла ошибка") | |
| # возвращает максимальное значение очков из файла | |
| def getTopScore(): | |
| try: | |
| with open("topchik.dat", "r", encoding="utf-8") as f: | |
| m = int(f.readline()) | |
| except BaseException: | |
| m = 0 | |
| return m | |
| # Загружаем слова в список | |
| def getWordsFromFile(): | |
| ret = [] | |
| try: | |
| with open("words.dat", "r", encoding="utf-8") as f: | |
| for l in f.readlines(): | |
| l = l.strip() | |
| ret.append(l) | |
| except BaseException: | |
| print("Проблема с файлом") | |
| quit(0) | |
| return ret | |
| # словарь | |
| dictionary = getWordsFromFile() | |
| # начало нового раунда | |
| def startNewRound(): | |
| global wordStar, wordComp, userTry | |
| wordComp = dictionary[randint(0, len(dictionary) - 1)] | |
| wordStar = "*" * len(wordComp) | |
| wordLabel["text"] = wordStar | |
| wordLabel.place(x=WIDTH // 2 - wordLabel.winfo_reqwidth() // 2, y=150) | |
| for i in range(32): | |
| btn[i]["text"] = chr(st + i) | |
| btn[i]["state"] = "normal" | |
| userTry = 10 | |
| updateInfo() | |
| # сравниваем строки и считаем сколько символов различаются | |
| def compareWord(s1, s2): | |
| res = 0 | |
| for i in range(len(s1)): | |
| if s1[i] != s2[i]: | |
| res += 1 | |
| return res | |
| def getWordStar(ch): | |
| ret = "" | |
| for i in range(len(wordComp)): | |
| if wordComp[i] == ch: | |
| ret += ch | |
| else: | |
| ret += wordStar[i] | |
| return ret | |
| # При нажатии мышкой на кнопку | |
| def pressLetter(n): | |
| global wordStar, score, userTry | |
| btn[n]["text"] = "." | |
| btn[n]["state"] = "disabled" | |
| oldWordStar = wordStar | |
| wordStar = getWordStar(chr(st + n)) | |
| count = compareWord(wordStar, oldWordStar) | |
| wordLabel["text"] = wordStar | |
| if count > 0: | |
| score += count * 5 | |
| else: | |
| score -= 6 | |
| if score < 0: | |
| score = 0 | |
| userTry -= 1 | |
| updateInfo() | |
| if wordComp == wordStar: | |
| score += score // 2 | |
| updateInfo() | |
| if score > topScore: | |
| messagebox.showinfo( | |
| "Поздравляю!", | |
| f"Рекорд! Угадано слово: {wordComp}! Нажмите Ok для продолжения игры") | |
| saveTopScore() | |
| else: | |
| messagebox.showinfo( | |
| "Отлично!", | |
| f"Слово угадано: {wordComp}! Продолжаем играть дальше!") | |
| startNewRound() | |
| elif userTry <= 0: | |
| messagebox.showinfo("Увы", "Отведенное количество попыток закончено!") | |
| quit(0) | |
| if btn[n]["text"] == ".": | |
| return 0 | |
| # mainloop | |
| root = Tk() | |
| root.resizable(False, False) | |
| root.title("Угадай слово") | |
| root.bind("<Key>", pressKey) | |
| WIDTH = 720 | |
| HEIGHT = 1600 | |
| SCR_WIDTH = root.winfo_screenwidth() | |
| SCR_HEIGHT = root.winfo_screenheight() | |
| POS_X = SCR_WIDTH // 2 - WIDTH // 2 | |
| POS_Y = SCR_HEIGHT // 2 - HEIGHT // 2 | |
| root.geometry(f"{WIDTH}x{HEIGHT}+{POS_X}+{POS_Y}") | |
| wordLabel = Label(font="consolas 35") | |
| scoreLabel = Label(font="consolas 16") | |
| topScoreLabel = Label(font="consolas 16") | |
| userTryLabel = Label(font="consolas 16") | |
| scoreLabel.place(x=10, y=650) | |
| topScoreLabel.place(x=10, y=680) | |
| userTryLabel.place(x=10, y=710) | |
| score = 0 | |
| topScore = getTopScore() | |
| userTry = 10 | |
| btn = [] | |
| for i in range(32): | |
| btn.append(Button(text=chr(st + i), width=1, font="consolas 16")) | |
| btn[i].place(x=10 + (i % 11) * 60, y=400 + i // 11 * 60) | |
| btn[i]["command"] = lambda x=i: pressLetter(x) | |
| wordComp = "" | |
| wordStar = "" | |
| startNewRound() | |
| root.mainloop() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment