Amazing-Python-Scripts

Форк
0
221 строка · 7.1 Кб
1
# -*- coding: utf-8 -*-
2
"""
3
Tic Toe Using pygame , numpy and sys with Graphical User Interface
4
"""
5
import pygame
6
import sys
7
from pygame.locals import *
8
import numpy as np
9
# ------
10
# constants
11
# -------
12
width = 800
13
height = 800
14
# row and columns
15
board_rows = 3
16
board_columns = 3
17
cross_width = 25
18
square_size = width//board_columns
19
# colors in RGB format
20
line_Width = 15
21
red = (255, 0, 0)
22
bg_color = (28, 170, 156)
23
line_color = (23, 145, 135)
24
circle_color = (239, 231, 200)
25
cross_color = (66, 66, 66)
26
space = square_size//4
27
# circle
28
circle_radius = square_size//3
29
circle_width = 14
30
pygame.init()
31
screen = pygame.display.set_mode((height, width))
32
pygame.display.set_caption('Tic Tac Toe!')
33
screen.fill(bg_color)
34
# color to display restart
35
white = (255, 255, 255)
36
green = (0, 255, 0)
37
blue = (0, 0, 128)
38

39
font = pygame.font.Font('freesansbold.ttf', 25)
40

41
# create a text suface object,
42
# on which text is drawn on it.
43
text = font.render('Press R to restart', True, green, blue)
44

45
Won = font.render(" Won", True, blue, green)
46
leave = font.render("Press X to Exit", True, white, red)
47
# create a rectangular object for the
48
# text surface object
49
leaveRect = text.get_rect()
50
textRect = text.get_rect()
51
winRect = Won.get_rect()
52
winRect.center = (100, 30)
53
textRect.center = (width-400, 30)
54
leaveRect.center = (width-120, 30)
55
board = np.zeros((board_rows, board_columns))
56
# print(board)
57
# pygame.draw.line( screen ,red ,(10,10),(300,300),10)
58

59

60
def draw_figures():
61
    for row in range(board_rows):
62
        for col in range(board_columns):
63
            if board[row][col] == 1:
64
                pygame.draw.circle(screen, circle_color, (int(col*square_size + square_size//2), int(
65
                    row*square_size + square_size//2)), circle_radius, circle_width)
66
            elif board[row][col] == 2:
67
                pygame.draw.line(screen, cross_color, (col*square_size + space, row*square_size + square_size -
68
                                 space), (col*square_size+square_size - space, row*square_size + space), cross_width)
69
                pygame.draw.line(screen, cross_color, (col*square_size + space, row*square_size + space),
70
                                 (col*square_size + square_size - space, row*square_size + square_size - space), cross_width)
71

72

73
def draw_lines():
74
    pygame.draw.line(screen, line_color, (0, square_size),
75
                     (width, square_size), line_Width)
76
    # 2nd horizontal line
77
    pygame.draw.line(screen, line_color, (0, 2*square_size),
78
                     (width, 2*square_size), line_Width)
79
    # 1st verticle
80
    pygame.draw.line(screen, line_color, (square_size, 0),
81
                     (square_size, height), line_Width)
82
    # 2nd verticle
83
    pygame.draw.line(screen, line_color, (2*square_size, 0),
84
                     (2*square_size, height), line_Width)
85

86
# To mark which square player has chosen
87

88

89
def mark_square(row, col, player):
90
    board[row][col] = player
91

92
# TO check the availablity of a square
93

94

95
def available_square(row, col):
96
    return board[row][col] == 0
97

98
# check board full or not
99

100

101
def is_board_full():
102
    k = False
103
    for row in range(board_rows):
104
        for col in range(board_columns):
105
            if board[row][col] == 0:
106
                k = False
107
            else:
108
                k = True
109
    return k
110

111

112
def check_win(player):
113
    # check verticle win
114
    for col in range(board_columns):
115
        if board[0][col] == player and board[1][col] == player and board[2][col] == player:
116
            draw_vertical_winning_line(col, player)
117
            return True
118
    # check Horizontal win
119
    for row in range(board_rows):
120
        if board[row][0] == player and board[row][1] == player and board[row][2] == player:
121
            draw_horizontal_winning_line(row, player)
122
            return True
123
    # check for asc win
124
    if board[2][0] == player and board[1][1] == player and board[0][2] == player:
125
        draw_asc_diagonal(player)
126
        return True
127
    if board[0][0] == player and board[1][1] == player and board[2][2] == player:
128
        draw_des_diagonal(player)
129
        return True
130

131

132
def draw_horizontal_winning_line(row, player):
133
    posY = row*square_size + square_size//2
134

135
    if (player == 1):
136
        color = circle_color
137
    else:
138
        color = cross_color
139

140
    pygame.draw.line(screen, color, (15, posY), (width-15, posY), 15)
141

142

143
def draw_vertical_winning_line(col, player):
144
    posX = col*square_size + square_size//2
145
    if (player == 1):
146
        color = circle_color
147
    else:
148
        color = cross_color
149
    pygame.draw.line(screen, color, (posX, 15), (posX, width-15), 15)
150

151

152
def draw_asc_diagonal(player):
153
    if (player == 1):
154
        color = circle_color
155
    else:
156
        color = cross_color
157
    pygame.draw.line(screen, color, (15, height-15), (width-15, 15), 15)
158

159

160
def draw_des_diagonal(player):
161
    if (player == 1):
162
        color = circle_color
163
    else:
164
        color = cross_color
165
    pygame.draw.line(screen, color, (15, 15), (width-15, height-15), 15)
166

167

168
def restart():
169
    screen.fill(bg_color)
170
    draw_lines()
171
    player = 1
172
    for row in range(board_rows):
173
        for col in range(board_columns):
174
            board[row][col] = 0
175

176

177
draw_lines()
178
# player
179
player = 1
180
game_over = False
181
while True:  # main game loop
182
    for event in pygame.event.get():  # constantly looks for the event
183
        if event.type == pygame.QUIT:  # if user clicks exit pygame.QUIT and sys exits
184
            pygame.quit()
185
            sys.exit()
186
        board_full = is_board_full()
187
        if board_full and not game_over:
188
            Won = font.render("    It's a Tie    ", True, blue, green)
189
            screen.blit(Won, winRect)
190
            screen.blit(text, textRect)
191
            screen.blit(leave, leaveRect)
192
        if event.type == pygame.MOUSEBUTTONDOWN and not game_over:
193
            mouseX = event.pos[0]  # x
194
            mouseY = event.pos[1]  # y
195
            clicked_row = int(mouseY // square_size)
196
            clicked_column = int(mouseX // square_size)
197
            if available_square(clicked_row, clicked_column):
198
                mark_square(clicked_row, clicked_column, player)
199
                if (check_win(player)):
200
                    game_over = True
201
                    Won = font.render("Player"+str(player) +
202
                                      " Won ", True, blue, green)
203
                    screen.blit(Won, winRect)
204
                    screen.blit(text, textRect)
205
                    screen.blit(leave, leaveRect)
206
                player = player % 2 + 1
207
                if not game_over and not board_full:
208
                    Won = font.render("Player"+str(player) +
209
                                      " Turn ", True, blue, green)
210
                    screen.blit(Won, winRect)
211
                draw_figures()
212
        # to restart the game
213
        if event.type == pygame.KEYDOWN:
214
            if event.key == pygame.K_r:
215
                restart()
216
                game_over = False
217
            elif event.key == pygame.K_x:
218
                pygame.quit()
219
                sys.exit()
220
                # print(board)
221
    pygame.display.update()
222

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

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

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

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