Amazing-Python-Scripts

Форк
0
190 строк · 6.3 Кб
1
from tkinter import *
2
from tkinter import font
3

4
# Constants
5
TOLERANCE = 8
6
CELL_SIZE = 40
7
OFFSET = 10
8
CIRCLE_RADIUS = 5
9
DOT_OFFSET = OFFSET + CIRCLE_RADIUS
10
GAME_HEIGHT = 400
11
GAME_WIDTH = 400
12

13
# Player Class
14

15

16
class Player:
17
    def __init__(self, name, color="#00BFFF"):  # Blue color
18
        self.score = 0
19
        self.text_var = StringVar()
20
        self.name = name
21
        self.color = color
22

23
    def update(self):
24
        self.text_var.set(f"{self.name}: {self.score}")
25

26

27
# Main Frame Class
28
class DotConnectFrame(Frame):
29
    def __init__(self, master):
30
        Frame.__init__(self, master)
31

32
        # Fonts
33
        self.title_font = font.Font(
34
            self, name="TitleFont", family="Arial", weight="bold", size=36)
35

36
        # Info Frame
37
        self.info_frame = Frame(self, bg="#333333")  # Dark gray background
38
        self.players = [Player("Player A", "#00BFFF"), Player(
39
            "Player B", "#00FF00")]  # Blue and Green colors
40
        self.info_frame.players = [Label(self.info_frame, textvariable=i.text_var, bg="#FFFFFF", fg="#333333",
41
                                         font="Arial 20 bold") for i in self.players]  # White text on dark gray background
42
        for i in self.info_frame.players:
43
            i.grid()
44
        self.info_frame.grid(row=0, column=0, columnspan=2, pady=10)
45

46
        # Canvas
47
        # Dark gray background
48
        self.canvas = Canvas(self, height=GAME_HEIGHT,
49
                             width=GAME_WIDTH, bg="#333333")
50
        self.canvas.bind("<Button-1>", lambda e: self.click(e))
51
        self.canvas.grid(row=1, column=0, padx=10)
52

53
        # Dots
54
        self.dots = [[self.canvas.create_oval(CELL_SIZE*i+OFFSET, CELL_SIZE*j+OFFSET, CELL_SIZE*i+OFFSET+2*CIRCLE_RADIUS,
55
                                              CELL_SIZE*j+OFFSET+2*CIRCLE_RADIUS, fill="#000000") for j in range(10)] for i in range(10)]  # Black dots
56
        self.lines = []
57

58
        # Reset Game Button
59
        self.reset_button = Button(self, text="Reset Game", command=self.reset_game,
60
                                   font="Arial 14 bold", bg="#FF0000", fg="#000000")  # Red button with white text
61
        self.reset_button.grid(row=2, column=0, pady=10)
62

63
        self.turn = self.players[0]
64
        self.update_players()
65

66
        self.grid()
67

68
    def update_players(self):
69
        for player in self.players:
70
            player.update()
71

72
    def click(self, event):
73
        x, y = event.x, event.y
74
        orientation = self.check_proximity(x, y)
75

76
        if orientation:
77
            if self.line_exists(x, y, orientation):
78
                return
79
            line = self.create_line(x, y, orientation)
80
            score = self.update_score(line)
81
            if score:
82
                self.turn.score += score
83
                self.turn.update()
84
                self.check_game_over()
85
            else:
86
                index = self.players.index(self.turn)
87
                self.turn = self.players[1 - index]
88
            self.lines.append(line)
89

90
    def create_line(self, x, y, orientation):
91
        start_x = CELL_SIZE * ((x - OFFSET) // CELL_SIZE) + DOT_OFFSET
92
        start_y = CELL_SIZE * ((y - OFFSET) // CELL_SIZE) + DOT_OFFSET
93
        tmp_x = (x - OFFSET) // CELL_SIZE
94
        tmp_y = (y - OFFSET) // CELL_SIZE
95

96
        if orientation == "horizontal":
97
            end_x = start_x + CELL_SIZE
98
            end_y = start_y
99
        else:
100
            end_x = start_x
101
            end_y = start_y + CELL_SIZE
102

103
        return self.canvas.create_line(start_x, start_y, end_x, end_y, width=2, fill=self.turn.color)
104

105
    def update_score(self, line):
106
        score = 0
107
        x0, y0, x1, y1 = self.canvas.coords(line)
108
        if x0 == x1:  # Vertical line
109
            mid_x = x0
110
            mid_y = (y0 + y1) / 2
111
            pre = (x0 - CELL_SIZE / 2, mid_y)
112
            post = (x0 + CELL_SIZE / 2, mid_y)
113
        elif y0 == y1:  # Horizontal line
114
            mid_x = (x0 + x1) / 2
115
            mid_y = y0
116
            pre = (mid_x, y0 - CELL_SIZE / 2)
117
            post = (mid_x, y0 + CELL_SIZE / 2)
118

119
        if len(self.find_lines(pre)) == 3:
120
            self.fill_box(pre)
121
            score += 1
122
        if len(self.find_lines(post)) == 3:
123
            self.fill_box(post)
124
            score += 1
125
        return score
126

127
    def find_lines(self, coords):
128
        x, y = coords
129
        if x < 0 or x > GAME_WIDTH:
130
            return []
131
        if y < 0 or y > GAME_WIDTH:
132
            return []
133

134
        lines = [x for x in self.canvas.find_enclosed(
135
            x - CELL_SIZE, y - CELL_SIZE, x + CELL_SIZE, y + CELL_SIZE) if x in self.lines]
136
        return lines
137

138
    def fill_box(self, coords):
139
        x, y = coords
140
        self.canvas.create_text(x, y, text=self.turn.name,
141
                                fill=self.turn.color, font="Arial 5 bold")
142

143
    def check_proximity(self, x, y):
144
        x -= OFFSET
145
        y -= OFFSET
146
        dx = x - (x // CELL_SIZE) * CELL_SIZE
147
        dy = y - (y // CELL_SIZE) * CELL_SIZE
148

149
        if abs(dx) < TOLERANCE:
150
            if abs(dy) < TOLERANCE:
151
                return None
152
            else:
153
                return "vertical"
154
        elif abs(dy) < TOLERANCE:
155
            return "horizontal"
156
        else:
157
            return None
158

159
    def line_exists(self, x, y, orientation):
160
        id_ = self.canvas.find_closest(x, y, halo=TOLERANCE)[0]
161
        if id_ in self.lines:
162
            return True
163
        else:
164
            return False
165

166
    def check_game_over(self):
167
        total = sum([player.score for player in self.players])
168
        if total == 81:
169
            self.canvas.create_text(GAME_WIDTH / 2, GAME_HEIGHT / 2, text="GAME OVER", font=self.title_font, fill="#888888",
170
                                    justify=CENTER)
171

172
    def reset_game(self):
173
        self.canvas.delete("all")
174
        self.lines = []
175
        for i in range(10):
176
            for j in range(10):
177
                self.dots[i][j] = self.canvas.create_oval(CELL_SIZE * i + OFFSET, CELL_SIZE * j + OFFSET, CELL_SIZE * i + OFFSET + 2 * CIRCLE_RADIUS,
178
                                                          CELL_SIZE * j + OFFSET + 2 * CIRCLE_RADIUS, fill="#000000")
179
        for player in self.players:
180
            player.score = 0
181
            player.update()
182
        self.turn = self.players[0]
183

184

185
# Main Tkinter Window
186
main_window = Tk()
187
main_window.title("Dot Connect")
188
main_window.config(bg="#000000")
189
main_window.frame = DotConnectFrame(main_window)
190
main_window.mainloop()
191

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.