# Привязка метода on_closing к событию закрытия окна
self.root.protocol("WM_DELETE_WINDOW", self.on_closing)
# Инициализаия атрибутов аймера и уведомлй
self.timer_id = None # {{ Иницилиция timer_id }}
self.notification_after_id = None # {{ Инициализация notification_after_id }}
# Загрузка рекордов
self.highscores = load_highscores()
# Настройка стилей
style = ttk.Style()
style.theme_use('clam') # Изменено на более современную тему
style.configure("Header.TFrame", background="#34495e") # {{ Добавлен стиль я Header.TFrame }}
style.configure("TLabel", font=("Segoe UI", 12), background="#2c3e50", foreground="#ecf0f1", padding=5)
style.configure("Title.TLabel", font=("Segoe UI", 24, "bold"), background="#34495e", foreground="#e74c3c", padding=10)
style.configure("TButton", font=("Segoe UI", 12, "bold"), padding=10, relief="raised", borderwidth=2, focuscolor='none')
style.configure("TRadiobutton", font=("Segoe UI", 12), background="#2c3e50", foreground="#ecf0f1", padding=5)
# Добавьте этот код в начало файла
python_paths = [
r"C:\Users\Егор\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Python 3.9\python.exe", # Исправленный путь
r"C:\Users\Егор\AppData\Local\Programs\Python\Python39\python.exe",
r"C:\Python39\python.exe",
"python.exe" # Попытка использовать Python из системного PATH
]
def find_python():
for path in python_paths:
if os.path.exists(path):
return path
return None
python_exe = find_python()
if python_exe is None:
print("Ошибка: Python не найден. Пожалуйста, убедитесь, что Python установлен и добавлен в PATH.")
print("Доступные пути:")
for path in python_paths:
print(f"- {path} {'(существует)' if os.path.exists(path) else '(не существует)'}")
sys.exit(1)
print(f"Используется Python: {python_exe}")
if sys.executable.endswith('pythonw.exe'):
subprocess.Popen([python_exe] + sys.argv)
sys.exit()
# Добавляем код отладки
print("Python executable:", python_exe)
print("Python version:", sys.version)
print("Current working directory:", os.getcwd())
print("Script location:", os.path.dirname(os.path.abspath(__file__)))
# Настройка логирования
logging.basicConfig(filename='game.log', level=logging.INFO,
format='%(asctime)s:%(levelname)s:%(message)s')
HIGHSCORES_FILE = "highscores.json"
def load_highscores():
if not os.path.exists(HIGHSCORES_FILE):
return {}
try:
with open(HIGHSCORES_FILE, "r", encoding="utf-8") as file:
data = json.load(file)
# Преобразуем записи, хранящиеся как int, в dict
for level, record in data.items():
if isinstance(record, int):
data[level] = {"name": "Игрок", "attempts": record} # {{ Преобразование int в dict }}
return data
except json.JSONDecodeError:
# Если файл повреждён, ерезаписываем е
return {}
def save_highscores(highscores):
with open(HIGHSCORES_FILE, "w", encoding="utf-8") as file:
json.dump(highscores, file, ensure_ascii=False, indent=4)
class Thermometer(tk.Canvas):
def __init__(self, master, **kwargs):
super().__init__(master, **kwargs)
self.configure(bg='#2c3e50', highlightthickness=0)
self.width = kwargs.get('width', 80)
self.height = kwargs.get('height', 300)
self.create_thermometer()
def create_thermometer(self):
# Фон термометра
self.create_rectangle(0, 0, self.width, self.height, fill='#34495e', outline='')
# Основа термометра
self.create_rounded_rectangle(self.width*0.2, self.height*0.1,
self.width*0.8, self.height*0.9,
radius=self.width*0.3, fill='#ecf0f1')
# Колба термометра
self.create_oval(self.width*0.2, self.height*0.8,
self.width*0.8, self.height*0.95,
fill='#e74c3c', outline='')
# Шкала
for i in range(5):
y = self.height*0.2 + i * (self.height*0.6) / 4
self.create_line(self.width*0.35, y, self.width*0.65, y, fill='#7f8c8d')
# Декоративные элементы
self.create_text(self.width/2, self.height*0.05, text="🔥", font=("Arial", 20), fill='#e74c3c')
self.create_text(self.width/2, self.height*0.98, text="❄", font=("Arial", 20), fill='#3498db')
# Ртутный столбик
self.mercury = self.create_rectangle(self.width*0.35, self.height*0.85,
self.width*0.65, self.height*0.85,
fill='#e74c3c', outline='')
def set_temperature(self, value, victory=False):
# value должно быть от 0 до 1
height = self.height * 0.65 * value
y = self.height * 0.85 - height
self.coords(self.mercury, self.width*0.35, y, self.width*0.65, self.height*0.85)
# Изменение цвета в зависимости от значения или победы
if victory:
color = '#2ecc71' # Зеленый для победы
else:
if value < 0.3:
color = '#3498db' # Холодный синий
elif value < 0.7:
color = '#f1c40f' # Теплый желтый
else:
color = '#e74c3c' # Горячий красный
self.itemconfig(self.mercury, fill=color)
def create_rounded_rectangle(self, x1, y1, x2, y2, radius=25, **kwargs):
points = [x1+radius, y1,
x1+radius, y1,
x2-radius, y1,
x2-radius, y1,
x2, y1,
x2, y1+radius,
x2, y1+radius,
x2, y2-radius,
x2, y2-radius,
x2, y2,
x2-radius, y2,
x2-radius, y2,
x1+radius, y2,
x1+radius, y2,
x1, y2,
x1, y2-radius,
x1, y2-radius,
x1, y1+radius,
x1, y1+radius,
x1, y1]
return self.create_polygon(points, **kwargs, smooth=True)
class GuessNumberApp:
def __init__(self, root):
print("Initializing GuessNumberApp") # Отладочное сообщение
self.root = root
self.root.title("Угадай число")
self.root.geometry("800x600") # {{ Увеличена ширина окна для размещения термометра }}
self.root.resizable(False, False)
# Привязка метода on_closing к событию закрытия окна
self.root.protocol("WM_DELETE_WINDOW", self.on_closing)
# Инициализаия атрибутов аймера и уведомлй
self.timer_id = None # {{ Иницилиция timer_id }}
self.notification_after_id = None # {{ Инициализация notification_after_id }}
# Загрузка рекордов
self.highscores = load_highscores()
# Настройка стилей
style = ttk.Style()
style.theme_use('clam') # Изменен на более современную тему
style.configure("Header.TFrame", background="#34495e") # {{ Добавлен стиль я Header.TFrame }}
style.configure("TLabel", font=("Segoe UI", 12), background="#2c3e50", foreground="#ecf0f1", padding=5)
style.configure("Title.TLabel", font=("Segoe UI", 24, "bold"), background="#34495e", foreground="#e74c3c", padding=10)
style.configure("TButton", font=("Segoe UI", 12, "bold"), padding=10, relief="raised", borderwidth=2, focuscolor='none')
style.configure("TRadiobutton", font=("Segoe UI", 12), background="#2c3e50", foreground="#ecf0f1", padding=5)
# Добавьте этот код в начало файла
python_paths = [
r"C:\Users\Егор\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Python 3.9\python.exe", # Исправленный путь
r"C:\Users\Егор\AppData\Local\Programs\Python\Python39\python.exe",
r"C:\Python39\python.exe",
"python.exe" # Попытка использовать Python из системного PATH
]
def find_python():
for path in python_paths:
if os.path.exists(path):
return path
return None
python_exe = find_python()
if python_exe is None:
print("Ошибка: Python не найден. Пожалуйста, убедитесь, что Python установлен и добавлен в PATH.")
print("Доступные пути:")
for path in python_paths:
print(f"- {path} {'(существует)' if os.path.exists(path) else '(не существует)'}")
sys.exit(1)
print(f"Используется Python: {python_exe}")
if sys.executable.endswith('pythonw.exe'):
subprocess.Popen([python_exe] + sys.argv)
sys.exit()
# Добавляем код отладки
print("Python executable:", python_exe)
print("Python version:", sys.version)
print("Current working directory:", os.getcwd())
print("Script location:", os.path.dirname(os.path.abspath(__file__)))
# Настройка логирования
logging.basicConfig(filename='game.log', level=logging.INFO,
format='%(asctime)s:%(levelname)s:%(message)s')
HIGHSCORES_FILE = "highscores.json"
def load_highscores():
if not os.path.exists(HIGHSCORES_FILE):
return {}
try:
with open(HIGHSCORES_FILE, "r", encoding="utf-8") as file:
data = json.load(file)
# Преобразуем записи, хранящиеся как int, в dict
for level, record in data.items():
if isinstance(record, int):
data[level] = {"name": "Игрок", "attempts": record} # {{ Преобразование int в dict }}
return data
except json.JSONDecodeError:
# Если файл повреждён, ерезаписываем е
return {}
def save_highscores(highscores):
with open(HIGHSCORES_FILE, "w", encoding="utf-8") as file:
json.dump(highscores, file, ensure_ascii=False, indent=4)
class Thermometer(tk.Canvas):
def __init__(self, master, **kwargs):
super().__init__(master, **kwargs)
self.configure(bg='#2c3e50', highlightthickness=0)
self.width = kwargs.get('width', 80)
self.height = kwargs.get('height', 300)
self.create_thermometer()
def create_thermometer(self):
# Фон термометра
self.create_rectangle(0, 0, self.width, self.height, fill='#34495e', outline='')
# Основа термометра
self.create_rounded_rectangle(self.width*0.2, self.height*0.1,
self.width*0.8, self.height*0.9,
radius=self.width*0.3, fill='#ecf0f1')
# Колба термометра
self.create_oval(self.width*0.2, self.height*0.8,
self.width*0.8, self.height*0.95,
fill='#e74c3c', outline='')
# Шкала
for i in range(5):
y = self.height*0.2 + i * (self.height*0.6) / 4
self.create_line(self.width*0.35, y, self.width*0.65, y, fill='#7f8c8d')
# Декоративные элементы
self.create_text(self.width/2, self.height*0.05, text="🔥", font=("Arial", 20), fill='#e74c3c')
self.create_text(self.width/2, self.height*0.98, text="❄", font=("Arial", 20), fill='#3498db')
# Ртутный столбик
self.mercury = self.create_rectangle(self.width*0.35, self.height*0.85,
self.width*0.65, self.height*0.85,
fill='#e74c3c', outline='')
def set_temperature(self, value, victory=False):
# value должно быть от 0 до 1
height = self.height * 0.65 * value
y = self.height * 0.85 - height
self.coords(self.mercury, self.width*0.35, y, self.width*0.65, self.height*0.85)
# Изменение цвета в зависимости от значения или победы
if victory:
color = '#2ecc71' # Зеленый для победы
else:
if value < 0.3:
color = '#3498db' # Холодный синий
elif value < 0.7:
color = '#f1c40f' # Теплый желтый
else:
color = '#e74c3c' # Горячий красный
self.itemconfig(self.mercury, fill=color)
def create_rounded_rectangle(self, x1, y1, x2, y2, radius=25, **kwargs):
points = [x1+radius, y1,
x1+radius, y1,
x2-radius, y1,
x2-radius, y1,
x2, y1,
x2, y1+radius,
x2, y1+radius,
x2, y2-radius,
x2, y2-radius,
x2, y2,
x2-radius, y2,
x2-radius, y2,
x1+radius, y2,
x1+radius, y2,
x1, y2,
x1, y2-radius,
x1, y2-radius,
x1, y1+radius,
x1, y1+radius,
x1, y1]
return self.create_polygon(points, **kwargs, smooth=True)
class GuessNumberApp:
def __init__(self, root):
print("Initializing GuessNumberApp") # Отладочное сообщение
self.root = root
self.root.title("Угадай число")
self.root.geometry("800x600") # {{ Увеличена ширина окна для размещения термометра }}
self.root.resizable(False, False)
# Привязка метода on_closing к событию закрытия окна
self.root.protocol("WM_DELETE_WINDOW", self.on_closing)
# Инициализаия атрибутов аймера и уведомлй
self.timer_id = None # {{ Иницилиция timer_id }}
self.notification_after_id = None # {{ Инициализация notification_after_id }}
# Загрузка рекордов
self.highscores = load_highscores()
# Настройка стилей
style = ttk.Style()
style.theme_use('clam') # Изменен на более современную тему
style.configure("Header.TFrame", background="#34495e") # {{ Добавлен стиль я Header.TFrame }}
style.configure("TLabel", font=("Segoe UI", 12), background="#2c3e50", foreground="#ecf0f1", padding=5)
style.configure("Title.TLabel", font=("Segoe UI", 24, "bold"), background="#34495e", foreground="#e74c3c", padding=10)
style.configure("TButton", font=("Segoe UI", 12, "bold"), padding=10, relief="raised", borderwidth=2, focuscolor='none')
style.configure("TRadiobutton", font=("Segoe UI", 12), background="#2c3e50", foreground="#ecf0f1", padding=5)
# Добавьте этот код в начало файла
python_paths = [
r"C:\Users\Егор\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Python 3.9\python.exe", # Исправленный путь
r"C:\Users\Егор\AppData\Local\Programs\Python\Python39\python.exe",
r"C:\Python39\python.exe",
"python.exe" # Попытка использовать Python из системного PATH
]
def find_python():
for path in python_paths:
if os.path.exists(path):
return path
return None
python_exe = find_python()
if python_exe is None:
print("Ошибка: Python не найден. Пожалуйста, убедитесь, что Python установлен и добавлен в PATH.")
print("Доступные пути:")
for path in python_paths:
print(f"- {path} {'(существует)' if os.path.exists(path) else '(не существует)'}")
sys.exit(1)
print(f"Используется Python: {python_exe}")
if sys.executable.endswith('pythonw.exe'):
subprocess.Popen([python_exe] + sys.argv)
sys.exit()
# Добавляем код отладки
print("Python executable:", python_exe)
print("Python version:", sys.version)
print("Current working directory:", os.getcwd())
print("Script location:", os.path.dirname(os.path.abspath(__file__)))
# Настройка логирования
logging.basicConfig(filename='game.log', level=logging.INFO,
format='%(asctime)s:%(levelname)s:%(message)s')
HIGHSCORES_FILE = "highscores.json"
def load_highscores():
if not os.path.exists(HIGHSCORES_FILE):
return {}
try:
with open(HIGHSCORES_FILE, "r", encoding="utf-8") as file:
data = json.load(file)
# Преобразуем записи, хранящиеся как int, в dict
for level, record in data.items():
if isinstance(record, int):
data[level] = {"name": "Игрок", "attempts": record} # {{ Преобразование int в dict }}
return data
except json.JSONDecodeError:
# Если файл повреждён, ерезаписываем е
return {}
def save_highscores(highscores):
with open(HIGHSCORES_FILE, "w", encoding="utf-8") as file:
json.dump(highscores, file, ensure_ascii=False, indent=4)
class Thermometer(tk.Canvas):
def __init__(self, master, **kwargs):
super().__init__(master, **kwargs)
self.configure(bg='#2c3e50', highlightthickness=0)
self.width = kwargs.get('width', 80)
self.height = kwargs.get('height', 300)
self.create_thermometer()
def create_thermometer(self):
# Фон термометра
self.create_rectangle(0, 0, self.width, self.height, fill='#34495e', outline='')
# Основа термометра
self.create_rounded_rectangle(self.width*0.2, self.height*0.1,
self.width*0.8, self.height*0.9,
radius=self.width*0.3, fill='#ecf0f1')
# Колба термометра
self.create_oval(self.width*0.2, self.height*0.8,
self.width*0.8, self.height*0.95,
fill='#e74c3c', outline='')
# Шкала
for i in range(5):
y = self.height*0.2 + i * (self.height*0.6) / 4
self.create_line(self.width*0.35, y, self.width*0.65, y, fill='#7f8c8d')
# Декоративные элементы
self.create_text(self.width/2, self.height*0.05, text="🔥", font=("Arial", 20), fill='#e74c3c')
self.create_text(self.width/2, self.height*0.98, text="❄", font=("Arial", 20), fill='#3498db')
# Ртутный столбик
self.mercury = self.create_rectangle(self.width*0.35, self.height*0.85,
self.width*0.65, self.height*0.85,
fill='#e74c3c', outline='')
def set_temperature(self, value, victory=False):
# value должно быть от 0 до 1
height = self.height * 0.65 * value
y = self.height * 0.85 - height
self.coords(self.mercury, self.width*0.35, y, self.width*0.65, self.height*0.85)
# Изменение цвета в зависимости от значения или победы
if victory:
color = '#2ecc71' # Зеленый для победы
else:
if value < 0.3:
color = '#3498db' # Холодный синий
elif value < 0.7:
color = '#f1c40f' # Теплый желтый
else:
color = '#e74c3c' # Горячий красный
self.itemconfig(self.mercury, fill=color)
def create_rounded_rectangle(self, x1, y1, x2, y2, radius=25, **kwargs):
points = [x1+radius, y1,
x1+radius, y1,
x2-radius, y1,
x2-radius, y1,
x2, y1,
x2, y1+radius,
x2, y1+radius,
x2, y2-radius,
x2, y2-radius,
x2, y2,
x2-radius, y2,
x2-radius, y2,
x1+radius, y2,
x1+radius, y2,
x1, y2,
x1, y2-radius,
x1, y2-radius,
x1, y1+radius,
x1, y1+radius,
x1, y1]
return self.create_polygon(points, **kwargs, smooth=True)
class GuessNumberApp:
def __init__(self, root):
print("Initializing GuessNumberApp") # Отладочное сообщение
self.root = root
self.root.title("Угадай число")
self.root.geometry("800x600") # {{ Увеличена ширина окна для размещения термометра }}
self.root.resizable(False, False)
# Привязка метода on_closing к событию закрытия окна
self.root.protocol("WM_DELETE_WINDOW", self.on_closing)
# Инициализаия атрибутов аймера и уведомлй
self.timer_id = None # {{ Иницилиция timer_id }}
self.notification_after_id = None # {{ Инициализация notification_after_id }}
# Загрузка рекордов
self.highscores = load_highscores()
# Настройка стилей
style = ttk.Style()
style.theme_use('clam') # Изменен на более современную тему
style.configure("Header.TFrame", background="#34495e") # {{ Добавлен стиль я Header.TFrame }}
style.configure("TLabel", font=("Segoe UI", 12), background="#2c3e50", foreground="#ecf0f1", padding=5)
style.configure("Title.TLabel", font=("Segoe UI", 24, "bold"), background="#34495e", foreground="#e74c3c", padding=10)
style.configure("TButton", font=("Segoe UI", 12, "bold"), padding=10, relief="raised", borderwidth=2, focuscolor='none')
style.configure("TRadiobutton", font=("Segoe UI", 12), background="#2c3e50", foreground="#ecf0f1", padding=5)
# Добавьте этот код в начало файла
python_paths = [
r"C:\Users\Егор\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Python 3.9\python.exe", # Исправленный путь
r"C:\Users\Егор\AppData\Local\Programs\Python\Python39\python.exe",
r"C:\Python39\python.exe",
"python.exe" # Попытка использовать Python из системного PATH
]
def find_python():
for path in python_paths:
if os.path.exists(path):
return path
return None
python_exe = find_python()
if python_exe is None:
print("Ошибка: Python не найден. Пожалуйста, убедитесь, что Python установлен и добавлен в PATH.")
print("Доступные пути:")
for path in python_paths:
print(f"- {path} {'(существует)' if os.path.exists(path) else '(не существует)'}")
sys.exit(1)
print(f"Используется Python: {python_exe}")
if sys.executable.endswith('pythonw.exe'):
subprocess.Popen([python_exe] + sys.argv)
sys.exit()
# Добавляем код отладки
print("Python executable:", python_exe)
print("Python version:", sys.version)
print("Current working directory:", os.getcwd())
print("Script location:", os.path.dirname(os.path.abspath(__file__)))
# Настройка логирования
logging.basicConfig(filename='game.log', level=logging.INFO,
format='%(asctime)s:%(levelname)s:%(message)s')
HIGHSCORES_FILE = "highscores.json"
def load_highscores():
if not os.path.exists(HIGHSCORES_FILE):
return {}
try:
with open(HIGHSCORES_FILE, "r", encoding="utf-8") as file:
data = json.load(file)
# Преобразуем записи, хранящиеся как int, в dict
for level, record in data.items():
if isinstance(record, int):
data[level] = {"name": "Игрок", "attempts": record} # {{ Преобразование int в dict }}
return data
except json.JSONDecodeError:
# Если файл повреждён, ерезаписываем е
return {}
def save_highscores(highscores):
with open(HIGHSCORES_FILE, "w", encoding="utf-8") as file:
json.dump(highscores, file, ensure_ascii=False, indent=4)
class Thermometer(tk.Canvas):
def __init__(self, master, **kwargs):
super().__init__(master, **kwargs)
self.configure(bg='#2c3e50', highlightthickness=0)
self.width = kwargs.get('width', 80)
self.height = kwargs.get('height', 300)
self.create_thermometer()
def create_thermometer(self):
# Фон термометра
self.create_rectangle(0, 0, self.width, self.height, fill='#34495e', outline='')
# Основа термометра
self.create_rounded_rectangle(self.width*0.2, self.height*0.1,
self.width*0.8, self.height*0.9,
radius=self.width*0.3, fill='#ecf0f1')
# Колба термометра
self.create_oval(self.width*0.2, self.height*0.8,
self.width*0.8, self.height*0.95,
fill='#e74c3c', outline='')
# Шкала
for i in range(5):
y = self.height*0.2 + i * (self.height*0.6) / 4
self.create_line(self.width*0.35, y, self.width*0.65, y, fill='#7f8c8d')
# Декоративные элементы
self.create_text(self.width/2, self.height*0.05, text="🔥", font=("Arial", 20), fill='#e74c3c')
self.create_text(self.width/2, self.height*0.98, text="❄", font=("Arial", 20), fill='#3498db')
# Ртутный столбик
self.mercury = self.create_rectangle(self.width*0.35, self.height*0.85,
self.width*0.65, self.height*0.85,
fill='#e74c3c', outline='')
def set_temperature(self, value, victory=False):
# value должно быть от 0 до 1
height = self.height * 0.65 * value
y = self.height * 0.85 - height
self.coords(self.mercury, self.width*0.35, y, self.width*0.65, self.height*0.85)
# Изменение цвета в зависимости от значения или победы
if victory:
color = '#2ecc71' # Зеленый для победы
else:
if value < 0.3:
color = '#3498db' # Холодный синий
elif value < 0.7:
color = '#f1c40f' # Теплый желтый
else:
color = '#e74c3c' # Горячий красный
self.itemconfig(self.mercury, fill=color)
def create_rounded_rectangle(self, x1, y1, x2, y2, radius=25, **kwargs):
points = [x1+radius, y1,
x1+radius, y1,
x2-radius, y1,
x2-radius, y1,
x2, y1,
x2, y1+radius,
x2, y1+radius,
x2, y2-radius,
x2, y2-radius,
x2, y2,
x2-radius, y2,
x2-radius, y2,
x1+radius, y2,
x1+radius, y2,
x1, y2,
x1, y2-radius,
x1, y2-radius,
x1, y1+radius,
x1, y1+radius,
x1, y1]
return self.create_polygon(points, **kwargs, smooth=True)
class GuessNumberApp:
def __init__(self, root):
print("Initializing GuessNumberApp") # Отладочное сообщение
self.root = root
self.root.title("Угадай число")
self.root.geometry("800x600") # {{ Увеличена ширина окна для размещения термометра }}
self.root.resizable(False, False)
# Привязка метода on_closing к событию закрытия окна
self.root.protocol("WM_DELETE_WINDOW", self.on_closing)
# Инициализаия атрибутов аймера и уведомлй
self.timer_id = None # {{ Иницилиция timer_id }}
self.notification_after_id = None # {{ Инициализация notification_after_id }}
# Загрузка рекордов
self.highscores = load_highscores()
# Настройка стилей
style = ttk.Style()
style.theme_use('clam') # Изменен на более современную тему
style.configure("Header.TFrame", background="#34495e") # {{ Добавлен стиль я Header.TFrame }}
style.configure("TLabel", font=("Segoe UI", 12), background="#2c3e50", foreground="#ecf0f1", padding=5)
style.configure("Title.TLabel", font=("Segoe UI", 24, "bold"), background="#34495e", foreground="#e74c3c", padding=10)
style.configure("TButton", font=("Segoe UI", 12, "bold"), padding=10, relief="raised", borderwidth=2, focuscolor='none')
style.configure("TRadiobutton", font=("Segoe UI", 12), background="#2c3e50", foreground="#ecf0f1", padding=5)
# Добавьте этот код в начало файла
python_paths = [
r"C:\Users\Егор\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Python 3.9\python.exe", # Исправленный путь
r"C:\Users\Егор\AppData\Local\Programs\Python\Python39\python.exe",
r"C:\Python39\python.exe",
"python.exe" # Попытка использовать Python из системного PATH
]
def find_python():
for path in python_paths:
if os.path.exists(path):
return path
return None
python_exe = find_python()
if python_exe is None:
print("Ошибка: Python не найден. Пожалуйста, убедитесь, что Python установлен и добавлен в PATH.")
print("Доступные пути:")
for path in python_paths:
print(f"- {path} {'(существует)' if os.path.exists(path) else '(не существует)'}")
sys.exit(1)
print(f"Используется Python: {python_exe}")
if sys.executable.endswith('pythonw.exe'):
subprocess.Popen([python_exe] + sys.argv)
sys.exit()
# Добавляем код отладки
print("Python executable:", python_exe)
print("Python version:", sys.version)
print("Current working directory:", os.getcwd())
print("Script location:", os.path.dirname(os.path.abspath(__file__)))
# Настройка логирования
logging.basicConfig(filename='game.log', level=logging.INFO,
format='%(asctime)s:%(levelname)s:%(message)s')
HIGHSCORES_FILE = "highscores.json"
def load_highscores():
if not os.path.exists(HIGHSCORES_FILE):
return {}
try:
with open(HIGHSCORES_FILE, "r", encoding="utf-8") as file:
data = json.load(file)
# Преобразуем записи, хранящиеся как int, в dict
for level, record in data.items():
if isinstance(record, int):
data[level] = {"name": "Игрок", "attempts": record} # {{ Преобразование int в dict }}
return data
except json.JSONDecodeError:
# Если файл повреждён, ерезаписываем е
return {}
def save_highscores(highscores):
with open(HIGHSCORES_FILE, "w", encoding="utf-8") as file:
json.dump(highscores, file, ensure_ascii=False, indent=4)
class Thermometer(tk.Canvas):
def __init__(self, master, **kwargs):
super().__init__(master, **kwargs)
self.configure(bg='#2c3e50', highlightthickness=0)
self.width = kwargs.get('width', 80)
self.height = kwargs.get('height', 300)
self.create_thermometer()
def create_thermometer(self):
# Фон термометра
self.create_rectangle(0, 0, self.width, self.height, fill='#34495e', outline='')
# Основа термометра
self.create_rounded_rectangle(self.width*0.2, self.height*0.1,
self.width*0.8, self.height*0.9,
radius=self.width*0.3, fill='#ecf0f1')
# Колба термометра
self.create_oval(self.width*0.2, self.height*0.8,
self.width*0.8, self.height*0.95,
fill='#e74c3c', outline='')
# Шкала
for i in range(5):
y = self.height*0.2 + i * (self.height*0.6) / 4
self.create_line(self.width*0.35, y, self.width*0.65, y, fill='#7f8c8d')
# Декоративные элементы
self.create_text(self.width/2, self.height*0.05, text="🔥", font=("Arial", 20), fill='#e74c3c')
self.create_text(self.width/2, self.height*0.98, text="❄", font=("Arial", 20), fill='#3498db')
# Ртутный столбик
self.mercury = self.create_rectangle(self.width*0.35, self.height*0.85,
self.width*0.65, self.height*0.85,
fill='#e74c3c', outline='')
def set_temperature(self, value, victory=False):
# value должно быть от 0 до 1
height = self.height * 0.65 * value
y = self.height * 0.85 - height
self.coords(self.mercury, self.width*0.35, y, self.width*0.65, self.height*0.85)
# Изменение цвета в зависимости от значения или победы
if victory:
color = '#2ecc71' # Зеленый для победы
else:
if value < 0.3:
color = '#3498db' # Холодный синий
elif value < 0.7:
color = '#f1c40f' # Теплый желтый
else:
color = '#e74c3c' # Горячий красный
self.itemconfig(self.mercury, fill=color)
def create_rounded_rectangle(self, x1, y1, x2, y2, radius=25, **kwargs):
points = [x1+radius, y1,
x1+radius, y1,
x2-radius, y1,
x2-radius, y1,
x2, y1,
x2, y1+radius,
x2, y1+radius,
x2, y2-radius,
x2, y2-radius,
x2, y2,
x2-radius, y2,
x2-radius, y2,
x1+radius, y2,
x1+radius, y2,
x1, y2,
x1, y2-radius,
x1, y2-radius,
x1, y1+radius,
x1, y1+radius,
x1, y1]
return self.create_polygon(points, **kwargs, smooth=True)
class GuessNumberApp:
def __init__(self, root):
print("Initializing GuessNumberApp") # Отладочное сообщение
self.root = root
self.root.title("Угадай число")
self.root.geometry("800x600") # {{ Увеличена ширина окна для размещения термометра }}
self.root.resizable(False, False)
# Привязка метода on_closing к событию закрытия окна
self.root.protocol("WM_DELETE_WINDOW", self.on_closing)
# Инициализаия атрибутов аймера и уведомлй
self.timer_id = None # {{ Иницилиция timer_id }}
self.notification_after_id = None # {{ Инициализация notification_after_id }}
# Загрузка рекордов
self.highscores = load_highscores()
# Настройка стилей
style = ttk.Style()
style.theme_use('clam') # Изменен на более современную тему
style.configure("Header.TFrame", background="#34495e") # {{ Добавлен стиль я Header.TFrame }}
style.configure("TLabel", font=("Segoe UI", 12), background="#2c3e50", foreground="#ecf0f1", padding=5)
style.configure("Title.TLabel", font=("Segoe UI", 24, "bold"), background="#34495e", foreground="#e74c3c", padding=10)
style.configure("TButton", font=("Segoe UI", 12, "bold"), padding=10, relief="raised", borderwidth=2, focuscolor='none')
style.configure("TRadiobutton", font=("Segoe UI", 12), background="#2c3e50", foreground="#ecf0f1", padding=5)
# Добавьте этот код в начало файла
python_paths = [
r"C:\Users\Егор\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Python 3.9\python.exe", # Исправленный путь
r"C:\Users\Егор\AppData\Local\Programs\Python\Python39\python.exe",
r"C:\Python39\python.exe",
"python.exe" # Попытка использовать Python из системного PATH
]
def find_python():
for path in python_paths:
if os.path.exists(path):
return path
return None
python_exe = find_python()
if python_exe is None:
print("Ошибка: Python не найден. Пожалуйста, убедитесь, что Python установлен и добавлен в PATH.")
print("Доступные пути:")
for path in python_paths:
print(f"- {path} {'(существует)' if os.path.exists(path) else '(не существует)'}")
sys.exit(1)
print(f"Используется Python: {python_exe}")
if sys.executable.endswith('pythonw.exe'):
subprocess.Popen([python_exe] + sys.argv)
sys.exit()
# Добавляем код отладки
print("Python executable:", python_exe)
print("Python version:", sys.version)
print("Current working directory:", os.getcwd())
print("Script location:", os.path.dirname(os.path.abspath(__file__)))
# Настройка логирования
logging.basicConfig(filename='game.log', level=logging.INFO,
format='%(asctime)s:%(levelname)s:%(message)s')
HIGHSCORES_FILE = "highscores.json"
def load_highscores():
if not os.path.exists(HIGHSCORES_FILE):
return {}
try:
with open(HIGHSCORES_FILE, "r", encoding="utf-8") as file:
data = json.load(file)
# Преобразуем записи, хранящиеся как int, в dict
for level, record in data.items():
if isinstance(record, int):
data[level] = {"name": "Игрок", "attempts": record} # {{ Преобразование int в dict }}
return data
except json.JSONDecodeError:
# Если файл повреждён, ерезаписываем е
return {}
def save_highscores(highscores):
with open(HIGHSCORES_FILE, "w", encoding="utf-8") as file:
json.dump(highscores, file, ensure_ascii=False, indent=4)
class Thermometer(tk.Canvas):
def __init__(self, master, **kwargs):
super().__init__(master, **kwargs)
self.configure(bg='#2c3e50', highlightthickness=0)
self.width = kwargs.get('width', 80)
self.height = kwargs.get('height', 300)
self.create_thermometer()
def create_thermometer(self):
# Фон термометра
self.create_rectangle(0, 0, self.width, self.height, fill='#34495e', outline='')
# Основа термометра
self.create_rounded_rectangle(self.width*0.2, self.height*0.1,
self.width*0.8, self.height*0.9,
radius=self.width*0.3, fill='#ecf0f1')
# Колба термометра
self.create_oval(self.width*0.2, self.height*0.8,
self.width*0.8, self.height*0.95,
fill='#e74c3c', outline='')
# Шкала
for i in range(5):
y = self.height*0.2 + i * (self.height*0.6) / 4
self.create_line(self.width*0.35, y, self.width*0.65, y, fill='#7f8c8d')
# Декоративные элементы
self.create_text(self.width/2, self.height*0.05, text="🔥", font=("Arial", 20), fill='#e74c3c')
self.create_text(self.width/2, self.height*0.98, text="❄", font=("Arial", 20), fill='#3498db')
# Ртутный столбик
self.mercury = self.create_rectangle(self.width*0.35, self.height*0.85,
self.width*0.65, self.height*0.85,
fill='#e74c3c', outline='')
def set_temperature(self, value, victory=False):
# value должно быть от 0 до 1
height = self.height * 0.65 * value
y = self.height * 0.85 - height
self.coords(self.mercury, self.width*0.35, y, self.width*0.65, self.height*0.85)
# Изменение цвета в зависимости от значения или победы
if victory:
color = '#2ecc71' # Зеленый для победы
else:
if value < 0.3:
color = '#3498db' # Холодный синий
elif value < 0.7:
color = '#f1c40f' # Теплый желтый
else:
color = '#e74c3c' # Горячий красный
self.itemconfig(self.mercury, fill=color)
def create_rounded_rectangle(self, x1, y1, x2, y2, radius=25, **kwargs):
points = [x1+radius, y1,
x1+radius, y1,
x2-radius, y1,
x2-radius, y1,
x2, y1,
x2, y1+radius,
x2, y1+radius,
x2, y2-radius,
x2, y2-radius,
x2, y2,
x2-radius, y2,
x2-radius, y2,
x1+radius, y2,
x1+radius, y2,
x1, y2,
x1, y2-radius,
x1, y2-radius,
x1, y1+radius,
x1, y1+radius,
x1, y1]
return self.create_polygon(points, **kwargs, smooth=True)
class GuessNumberApp:
def __init__(self, root):
print("Initializing GuessNumberApp") # Отладочное сообщение
self.root = root
self.root.title("Угадай число")
self.root.geometry("800x600") # {{ Увеличена ширина окна для размещения термометра }}
self.root.resizable(False, False)
# Привязка метода on_closing к событию закрытия окна
self.root.protocol("WM_DELETE_WINDOW", self.on_closing)
# Инициализаия атрибутов аймера и уведомлй
self.timer_id = None # {{ Иницилиция timer_id }}
self.notification_after_id = None # {{ Инициализация notification_after_id }}
# Загрузка рекордов
self.highscores = load_highscores()
# Настройка стилей
style = ttk.Style()
style.theme_use('clam') # Изменен на более современную тему
style.configure("Header.TFrame", background="#34495e") # {{ Добавлен стиль я Header.TFrame }}
style.configure("TLabel", font=("Segoe UI", 12), background="#2c3e50", foreground="#ecf0f1", padding=5)
style.configure("Title.TLabel", font=("Segoe UI", 24, "bold"), background="#34495e", foreground="#e74c3c", padding=10)
style.configure("TButton", font=("Segoe UI", 12, "bold"), padding=10, relief="raised", borderwidth=2, focuscolor='none')
style.configure("TRadiobutton", font=("Segoe UI", 12), background="#2c3e50", foreground="#ecf0f1", padding=5)
# Добавьте этот код в начало файла
python_paths = [
r"C:\Users\Егор\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Python 3.9\python.exe", # Исправленный путь
r"C:\Users\Егор\AppData\Local\Programs\Python\Python39\python.exe",
r"C:\Python39\python.exe",
"python.exe" # Попытка использовать Python из системного PATH
]
def find_python():
for path in python_paths:
if os.path.exists(path):
return path
return None
python_exe = find_python()
if python_exe is None:
print("Ошибка: Python не найден. Пожалуйста, убедитесь, что Python установлен и добавлен в PATH.")
print("Доступные пути:")
for path in python_paths:
print(f"- {path} {'(существует)' if os.path.exists(path) else '(не существует)'}")
sys.exit(1)
print(f"Используется Python: {python_exe}")
if sys.executable.endswith('pythonw.exe'):
subprocess.Popen([python_exe] + sys.argv)
sys.exit()
# Добавляем код отладки
print("Python executable:", python_exe)
print("Python version:", sys.version)
print("Current working directory:", os.getcwd())
print("Script location:", os.path.dirname(os.path.abspath(__file__)))
# Настройка логирования
logging.basicConfig(filename='game.log', level=logging.INFO,
format='%(asctime)s:%(levelname)s:%(message)s')
HIGHSCORES_FILE = "highscores.json"
def load_highscores():
if not os.path.exists(HIGHSCORES_FILE):
return {}
try:
with open(HIGHSCORES_FILE, "r", encoding="utf-8") as file:
data = json.load(file)
# Преобразуем записи, хранящиеся как int, в dict
for level, record in data.items():
if isinstance(record, int):
data[level] = {"name": "Игрок", "attempts": record} # {{ Преобразование int в dict }}
return data
except json.JSONDecodeError:
# Если файл повреждён, ерезаписываем е
return {}
def save_highscores(highscores):
with open(HIGHSCORES_FILE, "w", encoding="utf-8") as file:
json.dump(highscores, file, ensure_ascii=False, indent=4)
class Thermometer(tk.Canvas):
def __init__(self, master, **kwargs):
super().__init__(master, **kwargs)
self.configure(bg='#2c3e50', highlightthickness=0)
self.width = kwargs.get('width', 80)
self.height = kwargs.get('height', 300)
self.create_thermometer()
def create_thermometer(self):
# Фон термометра
self.create_rectangle(0, 0, self.width, self.height, fill='#34495e', outline='')
# Основа термометра
self.create_rounded_rectangle(self.width*0.2, self.height*0.1,
self.width*0.8, self.height*0.9,
radius=self.width*0.3, fill='#ecf0f1')
# Колба термометра
self.create_oval(self.width*0.2, self.height*0.8,
self.width*0.8, self.height*0.95,
fill='#e74c3c', outline='')
# Шкала
for i in range(5):
y = self.height*0.2 + i * (self.height*0.6) / 4
self.create_line(self.width*0.35, y, self.width*0.65, y, fill='#7f8c8d')
# Декоративные элементы
self.create_text(self.width/2, self.height*0.05, text="🔥", font=("Arial", 20), fill='#e74c3c')
self.create_text(self.width/2, self.height*0.98, text="❄", font=("Arial", 20), fill='#3498db')
# Ртутный столбик
self.mercury = self.create_rectangle(self.width*0.35, self.height*0.85,
self.width*0.65, self.height*0.85,
fill='#e74c3c', outline='')
def set_temperature(self, value, victory=False):
# value должно быть от 0 до 1
height = self.height * 0.65 * value
y = self.height * 0.85 - height
self.coords(self.mercury, self.width*0.35, y, self.width*0.65, self.height*0.85)
# Изменение цвета в зависимости от значения или победы
if victory:
color = '#2ecc71' # Зеленый для победы
else:
if value < 0.3:
color = '#3498db' # Холодный синий
elif value < 0.7:
color = '#f1c40f' # Теплый желтый
else:
color = '#e74c3c' # Горячий красный
self.itemconfig(self.mercury, fill=color)
def create_rounded_rectangle(self, x1, y1, x2, y2, radius=25, **kwargs):
points = [x1+radius, y1,
x1+radius, y1,
x2-radius, y1,
x2-radius, y1,
x2, y1,
x2, y1+radius,
x2, y1+radius,
x2, y2-radius,
x2, y2-radius,
x2, y2,
x2-radius, y2,
x2-radius, y2,
x1+radius, y2,
x1+radius, y2,
x1, y2,
x1, y2-radius,
x1, y2-radius,
x1, y1+radius,
x1, y1+radius,
x1, y1]
return self.create_polygon(points, **kwargs, smooth=True)
class GuessNumberApp:
new_text = message
self.notification_label.config(text=new_text)
self.notification_frame.grid() # Показываем фрейм уведомлений
self.notification_after_id = self.root.after(duration, self.hide_notification)
def hide_notification(self):
print("DEBUG: Вызов hide_notification") # Отладочное сообщение
self.notification_frame.grid_remove() # Скрываем фрейм уведомлений
self.notification_label.config(text="")
self.notification_after_id = None
def safe_update(self, widget, method, *args, **kwargs):
try:
getattr(widget, method)(*args, **kwargs)
except tk.TclError:
# Окно было закрыто, игнорируем ошибку
pass