Example #1
0
    def __init__(self, parent, *args, **kwargs):
        super().__init__(parent, *args, **kwargs)
        self.parent = parent
        self.parent.title("TIC TAC TOE")
        self.width = 400
        self.height = 300
        self.tablero = TicTacToe()  #variable para tablero
        self.parent.config(cursor='arrow')
        self.x_cordinate = int((self.parent.winfo_screenwidth() / 2) -
                               (self.width / 2))
        self.y_cordinate = int((self.parent.winfo_screenheight() / 2) -
                               (self.height / 2))
        self.parent.geometry(
            '%dx%d+%d+%d' %
            (self.width, self.height, self.x_cordinate, self.y_cordinate))
        self.parent.resizable(False, False)
        self.parent.configure(background='beige')

        self.FrameCentral = tk.Frame(master=self.parent,
                                     width=self.width,
                                     height=self.height,
                                     bg='beige')
        self.FrameCentral.grid_propagate(0)
        self.FrameCentral.config(cursor='arrow')
        self.FrameCentral.place(x=0, y=0)
        self.principal()
Example #2
0
    def __init__(self, size):
        self.size = size
        self.game = TicTacToe(size)
        self.root = self.create_root_window()
        self.grid = self.create_grid()

        b = Button(self.root, text=":)", command=self.on_click_new_game)
        b.grid(row=self.size, column=1)
Example #3
0
 def __init__(self):
     self.surface = WINDOW
     self.width = WIDTH
     self.height = HEIGHT
     self.rows = 3
     self.color = colors['white']
     self.game = TicTacToe()
     self.winner = None
     self.font = 'century gothic'
     self.font_name = pygame.font.match_font(self.font, 1)
Example #4
0
    def __init__(self, size):
        self.size = size
        self.game = TicTacToe(size)
        self.root = self.create_root_window()
        self.grid = self.create_grid()

        b = Button(self.root, text=":)",
                   command=self.on_click_new_game)
        b.grid(row=self.size, column=1)
Example #5
0
class TicTacToeTk:
    def __init__(self, size):
        self.size = size
        self.game = TicTacToe(size)
        self.root = self.create_root_window()
        self.grid = self.create_grid()

        b = Button(self.root, text=":)", command=self.on_click_new_game)
        b.grid(row=self.size, column=1)

    def run(self):
        self.root.mainloop()

    def create_root_window(self):
        root = Tk()
        root.resizable(width=FALSE, height=FALSE)
        return root

    def create_grid(self):
        grid = [[StringVar() for j in range(self.size)]
                for i in range(self.size)]

        colors = ["white", "gray"]

        for i in range(self.size):
            for j in range(self.size):
                label = Label(self.root,
                              bg=colors[(i + j) % 2],
                              fg=colors[(i + j + 1) % 2],
                              height=3,
                              width=8,
                              textvariable=grid[i][j])
                label.bind('<Button-1>',
                           lambda event, r=i, c=j: self.on_click_cell(r, c))

                label.grid(row=i, column=j)

        return grid

    def on_click_new_game(self):
        self.game.reset()
        self.update_view()

    def on_click_cell(self, row, column):
        self.game.click(row, column)
        self.update_view()
        winner = self.game.get_winner()
        if winner != 0:
            tkMessageBox.showinfo("Winner",
                                  "Player %d is the winner!" % winner)
        elif not self.game.have_empty_cell():
            tkMessageBox.showinfo("Draw", "Game ended without a winner!")

    def update_view(self):
        for i in range(self.size):
            for j in range(self.size):
                if self.game.board[i][j] != '.':
                    self.grid[i][j].set(self.game.board[i][j])
                else:
                    self.grid[i][j].set('')
Example #6
0
class Grid:
    squares = [
        [(0, 0, 200, 200), (200, 0, 200, 200), (400, 0, 200, 200)],
        [(0, 200, 200, 200), (200, 200, 200, 200), (400, 200, 200, 200)],
        [(0, 400, 200, 200), (200, 400, 200, 200), (400, 400, 200, 200)],
    ]

    def __init__(self):
        self.surface = WINDOW
        self.width = WIDTH
        self.height = HEIGHT
        self.rows = 3
        self.color = colors['white']
        self.game = TicTacToe()
        self.winner = None
        self.font = 'century gothic'
        self.font_name = pygame.font.match_font(self.font, 1)

    def draw(self):
        space = self.width // self.rows
        x = 0
        y = 0
        for line in range(self.rows):
            x += space
            y += space
            pygame.draw.line(self.surface, self.color, (x, 0), (x, self.width),
                             3)
            pygame.draw.line(self.surface, self.color, (0, y),
                             (self.height, y), 3)

    def get_hovered_square(self):
        x, y = pygame.mouse.get_pos()
        if 0 < x < 200:
            c = 0
        elif 200 < x < 400:
            c = 1
        elif 400 < x < 600:
            c = 2
        else:
            c = None

        if 0 < y < 200:
            r = 0
        elif 200 < y < 400:
            r = 1
        elif 400 < y < 600:
            r = 2
        else:
            r = None

        if r is not None and c is not None:
            square = self.squares[r][c]
            if self.game.is_valid_move(
                    r, c) and self.game.check_for_winner() is None:
                pygame.draw.rect(self.surface, colors['green'], square)
            return square, (r, c)

    def draw_text(self, text, size, color, x, y):
        font = pygame.font.Font(self.font_name, size)
        text_surface = font.render(text, True, color)
        text_rect = text_surface.get_rect()
        text_rect.center = (x, y)
        self.surface.blit(text_surface, text_rect)

    def draw_moves(self):
        for r in range(3):
            for c in range(3):
                player = self.game.board[r][c]
                if player != 0:
                    square = self.squares[r][c]
                    x, y = square[0] + 100, square[1] + 100
                    if player == 1:
                        color = colors['blue']
                    else:
                        color = colors['red']
                    self.draw_text(self.game.symbols[player], 120, color, x, y)

    def draw_winning_line(self):
        if self.game.check_for_winner(
        ) is not None and self.game.check_for_winner() != 'tie':
            line, place = self.game.winning_line
            if line == 'row':
                y = (place * 200) + 100
                pygame.draw.line(self.surface, (173, 0, 173), (35, y),
                                 (self.width - 35, y), 15)
            if line == 'column':
                x = (place * 200) + 100
                pygame.draw.line(self.surface, colors['purple'], (x, 35),
                                 (x, self.height - 35), 15)
            if line == 'diagonal':
                if place == 1:
                    start = (35, 35)
                    end = (self.width - 35, self.height - 35)
                else:
                    start = (self.width - 35, 35)
                    end = (35, self.height - 35)
                pygame.draw.line(self.surface, colors['purple'], start, end,
                                 15)

    def make_move(self):
        return_val = self.get_hovered_square()
        if return_val is not None and self.game.check_for_winner() is None:
            active_square, (r, c) = return_val
            self.game.make_move(r, c)

    def announce_winner_terminal(self):
        self.winner = self.game.check_for_winner()
        if self.winner == 'tie':
            print("It's a tie")
            print("to play again press space")
            print('to exit press esc')
        elif self.winner:
            print(
                f"The winner is player {self.winner} -> ({self.game.symbols[self.winner]})"
            )
            print("to play again press space")
            print('to exit press esc')

    def announcement_bg(self):
        s = pygame.Surface((540, 140))
        s.set_alpha(100)
        s.fill(colors['purple'])
        self.surface.blit(s, (30, 230))

    def announce_winner(self):
        self.winner = self.game.check_for_winner()
        if self.winner == 'tie':
            self.announcement_bg()
            self.draw_text("It's a tie", 40, colors['green'], 300, 255)
            self.draw_text("to play again press space", 40, colors['green'],
                           300, 300)
            self.draw_text("to exit press esc", 40, colors['green'], 300, 345)

        elif self.winner:
            self.announcement_bg()
            self.draw_text(
                f"The winner is player {self.winner} -> {self.game.symbols[self.winner]}",
                40, colors['green'], 300, 255)
            self.draw_text("to play again press space", 40, colors['green'],
                           300, 300)
            self.draw_text("to exit press esc", 40, colors['green'], 300, 345)

    def reset(self):
        del self.game
        self.game = TicTacToe()
Example #7
0
 def reset(self):
     del self.game
     self.game = TicTacToe()
Example #8
0
class TicTacToeTk:
    def __init__(self, size):
        self.size = size
        self.game = TicTacToe(size)
        self.root = self.create_root_window()
        self.grid = self.create_grid()

        b = Button(self.root, text=":)",
                   command=self.on_click_new_game)
        b.grid(row=self.size, column=1)

    def run(self):
        self.root.mainloop()

    def create_root_window(self):
        root = Tk()
        root.resizable(width=FALSE, height=FALSE)
        return root

    def create_grid(self):
        grid = [[
            StringVar() for j in range(self.size)
        ] for i in range(self.size)]

        colors = ["white", "gray"]

        for i in range(self.size):
            for j in range(self.size):
                label = Label(self.root,
                              bg=colors[(i + j) % 2],
                              fg=colors[(i + j + 1) % 2],
                              height=3, width=8,
                              textvariable=grid[i][j])
                label.bind('<Button-1>',
                           lambda event, r=i, c=j: self.on_click_cell(r, c))

                label.grid(row=i, column=j)

        return grid

    def on_click_new_game(self):
        self.game.reset()
        self.update_view()

    def on_click_cell(self, row, column):
        self.game.click(row, column)
        self.update_view()
        winner = self.game.get_winner()
        if winner != 0:
            tkMessageBox.showinfo("Winner",
                                  "Player %d is the winner!" % winner)
        elif not self.game.have_empty_cell():
            tkMessageBox.showinfo("Draw",
                                  "Game ended without a winner!")

    def update_view(self):
        for i in range(self.size):
            for j in range(self.size):
                if self.game.board[i][j] != '.':
                    self.grid[i][j].set(self.game.board[i][j])
                else:
                    self.grid[i][j].set('')
Example #9
0
class MainWindow(tk.Frame):
    def __init__(self, parent, *args, **kwargs):
        super().__init__(parent, *args, **kwargs)
        self.parent = parent
        self.parent.title("TIC TAC TOE")
        self.width = 400
        self.height = 300
        self.tablero = TicTacToe()  #variable para tablero
        self.parent.config(cursor='arrow')
        self.x_cordinate = int((self.parent.winfo_screenwidth() / 2) -
                               (self.width / 2))
        self.y_cordinate = int((self.parent.winfo_screenheight() / 2) -
                               (self.height / 2))
        self.parent.geometry(
            '%dx%d+%d+%d' %
            (self.width, self.height, self.x_cordinate, self.y_cordinate))
        self.parent.resizable(False, False)
        self.parent.configure(background='beige')

        self.FrameCentral = tk.Frame(master=self.parent,
                                     width=self.width,
                                     height=self.height,
                                     bg='beige')
        self.FrameCentral.grid_propagate(0)
        self.FrameCentral.config(cursor='arrow')
        self.FrameCentral.place(x=0, y=0)
        self.principal()

    def principal(self):
        ####################################################################################
        ###################### USO DE OPERADORES DE TRASNFORMACIÓN #########################
        ####################################################################################
        self.vaciarFrameReactiveX(self.FrameCentral)
        self.fuente.subscribe(lambda x: print("objeto eliminado"))
        self.CreateLabel(self.FrameCentral, "TIC TAC TOE", 50, 200,
                         Font(family="Helvetica", size=15, weight="bold"),
                         'beige')
        self.CreateImage(self.FrameCentral, 'tic_128.png', 50, 75, 125, 125)
        self.nameJugador = tk.Entry(self.FrameCentral,
                                    justify=tk.CENTER,
                                    width=30)
        self.CreateButton(self.FrameCentral, 'SALIR', 200, 175, 16, 1, 'BLUE',
                          'WHITE', self.salirJuego)
        self.CreateButton(self.FrameCentral, 'JUGAR', 200, 125, 16, 1, 'GREEN',
                          'WHITE', self.empiezaJuego)
        self.CreateLabel(self.FrameCentral, 'Ingresa nombre del jugador', 100,
                         10, Font(family="Helvetica", size=12,
                                  weight="bold"), 'beige')
        self.nameJugador.place(x=110, y=50)

    def salirJuego(self):
        cuadro = messagebox.askyesno(message="¿Desea salir?",
                                     title="Fin del juego")
        if cuadro:
            ####################################################################################
            ###################### USO DE OPERADORES DE TRASNFORMACIÓN #########################
            ####################################################################################
            self.vaciarFrameReactiveX(self.FrameCentral)
            self.fuente.subscribe(lambda x: print("objeto eliminado"))
            self.parent.quit()

    def CreateLabel(self, window, text, row, col, font, bg):
        tk.Label(window, text=text, font=font, bg=bg).place(x=row, y=col)

    def CreateButton(self,
                     window,
                     text,
                     x,
                     y,
                     w,
                     h,
                     bg,
                     fg,
                     action,
                     textvar=None):
        if textvar is None:
            tk.Button(window,
                      text=text,
                      command=action,
                      width=w,
                      height=h,
                      bg=bg,
                      fg=fg).place(x=x, y=y)
        else:
            return tk.Button(window,
                             textvariable=textvar,
                             command=action,
                             width=w,
                             height=h,
                             bg=bg,
                             fg=fg).place(x=x, y=y)

    def CreateImage(self, window, path, x, y, width, height):
        img = Image.open(path)
        img = img.resize((width, height), Image.ANTIALIAS)
        img = ImageTk.PhotoImage(img)
        panel = tk.Label(window, image=img, bg="beige")
        panel.image = img
        panel.place(y=y, x=x)

        ####################################################################################
        ######### Vaciar frame con observadores y operador de transformación ###############
        ####################################################################################
    def vaciarFrameReactiveX(self, frame):
        self.fuente = rx.from_list(frame.winfo_children()).pipe(
            op.map(self.VaciarFrame))
        frame.pack_forget()

    def VaciarFrame(self, widget):
        widget.destroy()

    def EnviarJugadaJugador(self, fil, col):
        #print(fil, col)
        tablero_aux = self.tablero.jugadaUsuario(fil, col, self.turno)
        if tablero_aux is None:
            messagebox.showinfo(message="Casilla llena",
                                title="Seleccione otra casilla")
        elif tablero_aux == -1:
            actualiza = {
                'Key': 'Empate',
                'valor': self.estadisticas['Empate'] + 1
            }
            self.tablero.actualizarEstadistica(self.name, actualiza)
            self.empiezaDeNuevo('Empate!!')
        else:
            self.text_jugada[fil][col].set(self.turno)
            i, j, computador = self.tablero.jugadaComputador(self.turno)
            self.text_jugada[i][j].set(computador)
            if self.tablero.alguienGano(self.turno):
                #ganó el usuario
                messagebox.showinfo(message="Felicidades, has ganado!",
                                    title="Ganador")
                actualiza = {
                    'Key': 'Ganadas',
                    'valor': self.estadisticas['Ganadas'] + 1
                }
                self.tablero.actualizarEstadistica(self.name, actualiza)
                self.empiezaDeNuevo('Ganador!!')
            if self.tablero.alguienGano(self.tablero.cambiarFicha(self.turno)):
                #ganó el computador
                messagebox.showinfo(message="Has perdido. Intentalo de nuevo",
                                    title="Perdida")
                actualiza = {
                    'Key': 'Perdidas',
                    'valor': self.estadisticas['Perdidas'] + 1
                }
                self.tablero.actualizarEstadistica(self.name, actualiza)
                self.empiezaDeNuevo('Perdida')

    def empiezaDeNuevo(self, titulo):
        respuesta = messagebox.askyesno(message="¿Desea empezar de nuevo?",
                                        title=titulo)
        self.tablero.formateaTablero()
        self.formateaTableroBotones()
        if respuesta:
            self.empiezaJuego()
        else:
            self.principal()

    def formateaTableroBotones(self):

        for i in range(0, len(self.text_jugada)):
            for j in range(0, len(self.text_jugada)):
                self.text_jugada[i][j].set("")

    def FrameJugeo(self):
        self.CreateLabel(
            self.FrameCentral,
            'Es el turno de {} con ficha: {}'.format(str(self.name),
                                                     self.turno), 100, 10,
            Font(family="Helvetica", size=12, weight="bold"), 'beige')
        self.tablero_botones = [[None, None, None], [None, None, None],
                                [None, None, None]]
        self.text_jugada = [[None, None, None], [None, None, None],
                            [None, None, None]]
        self.CreateButton(self.FrameCentral, 'Juego nuevo', 200, 100, 16, 1,
                          'GREEN', 'WHITE',
                          partial(self.empiezaDeNuevo, 'Juego nuevo'))
        self.CreateButton(self.FrameCentral, 'Salir', 200, 150, 16, 1, 'BLUE',
                          'WHITE', self.principal)

        ## Crear visualización de estadisticas

        var = tk.StringVar()
        self.estadisticas = self.tablero.leerEstadisticas(self.name)
        variablePrueba = ''
        var.set('')
        for clave, valor in self.estadisticas.items():
            variablePrueba += "%s: %s    " % (clave, valor)
        var.set(variablePrueba)
        l = tk.Label(self.FrameCentral,
                     textvariable=var,
                     justify=tk.LEFT,
                     font=Font(family="Helvetica", size=10, weight="normal"),
                     wraplength=398,
                     bg='beige')
        l.place(x=40, y=225)

        for i in range(0, 3):
            for j in range(0, 3):
                self.text_jugada[i][j] = tk.StringVar()
                self.text_jugada[i][j].set('')
                self.tablero_botones[i][j] = self.CreateButton(
                    self.FrameCentral, '', 50 + (j * 45), 75 + (i * 40), 5, 2,
                    'WHITE', 'BLACK', partial(self.EnviarJugadaJugador, i,
                                              j), self.text_jugada[i][j])
        if self.turno == 'O':
            fil, col, computador = self.tablero.jugadaComputador(self.turno)
            self.text_jugada[fil][col].set(computador)

    def empiezaJuego(self):
        try:
            self.name = self.nameJugador.get()
        except:
            pass
        if self.name.isspace() or self.name == '':
            messagebox.showinfo(message="Ingrese nombre del jugador",
                                title="Jugador")
            self.nameJugador.config(state=tk.NORMAL)
            self.nameJugador.delete(0, tk.END)
        else:
            ####################################################################################
            ###################### USO DE OPERADORES DE TRASNFORMACIÓN #########################
            ####################################################################################
            self.vaciarFrameReactiveX(self.FrameCentral)
            self.fuente.subscribe(lambda x: print("objeto eliminado"))
            self.turno = "X" if messagebox.askyesno(
                message="¿Desea empezar primero?",
                title="Orden de participación") else "O"
            self.FrameJugeo()