import tkinter as tk
from random import randint
from typing import Callable
class ClickerGame:
def __init__(self, master: tk.Tk, width: int = 400, height: int = 400):
self.master = master
self.master.title("Clicker Game")
self.canvas = tk.Canvas(self.master, width=width, height=height)
self.canvas.pack()
self.width = width
self.height = height
self.score = 0
self.time_limit = 2000 # 2 seconds
self.button = None
self.timer_id = None
self.score_display = None
self.create_score_display()
self.start_game()
def create_score_display(self) -> None:
self.score_display = self.canvas.create_text(
self.width // 2, 20, text=f"Score: {self.score}", font=("Arial", 16)
)
def start_game(self) -> None:
self.create_button()
self.schedule_game_over()
def create_button(self) -> None:
x, y = self.get_random_position()
self.button = self.canvas.create_oval(
x - 25, y - 25, x + 25, y + 25, fill="red", tags="button"
)
self.canvas.tag_bind("button", "", self.on_button_click)
def get_random_position(self) -> tuple[int, int]:
return randint(25, self.width - 25), randint(25, self.height - 25)
def on_button_click(self, event: tk.Event) -> None:
self.score += 1
self.update_score_display()
self.move_button()
self.reset_timer()
def move_button(self) -> None:
x, y = self.get_random_position()
self.canvas.coords(self.button, x - 25, y - 25, x + 25, y + 25)
def update_score_display(self) -> None:
self.canvas.itemconfig(self.score_display, text=f"Score: {self.score}")
def schedule_game_over(self) -> None:
self.cancel_timer()
self.timer_id = self.master.after(self.time_limit, self.game_over)
def reset_timer(self) -> None:
self.cancel_timer()
self.schedule_game_over()
def cancel_timer(self) -> None:
if self.timer_id:
self.master.after_cancel(self.timer_id)
self.timer_id = None
def game_over(self) -> None:
self.canvas.delete("all")
self.canvas.create_text(
self.width // 2,
self.height // 2,
text=f"Game Over!\nFinal Score: {self.score}",
font=("Arial", 20),
justify=tk.CENTER,
)
def main() -> None:
root = tk.Tk()
game = ClickerGame(root)
root.mainloop()
if __name__ == "__main__":
main()
В данном коде если ты не успел нажать за 2 секунды игра окончится.
и этот интервал можно менять под свой таймер
self.time_limit = 2000 # 2 seconds