Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- """
- JOGO TIP-TAP-TOE (JOGO DA VELHA) UTILIZANDO A GUI TKINTER
- Author: Janes Roberto
- """
- from tkinter import *
- from tkinter import messagebox
- # Inicio da Classe
- class TipTapToe( Frame ):
- """
- Metodo construtor da Classe.
- Define os elementos da janela principal e inicia o programa
- """
- def __init__(self):
- # Cria nossa janela principal
- self.window = Tk()
- self.window.title('TIP TAP TOE TABAJARA')
- # Inicializa algumas variaveis de controle
- self.rodadaJogador = 1 # controla de quem e a rodada
- self.clickedOpt = "" # guada o valor da label clicada
- self.listaGames = list(range(1, 10)) # gera uma lista para controlar a marcacao do jogo
- self.ganhou = False # guarda o status da jogada
- # cria os frames do jogo
- self.framePlacar = Frame(self.window, bg="white", height=100, width=400)
- self.frameGame = Frame(self.window, bg="yellow", height=250, width=400)
- self.frameInfo = Frame(self.window, bg="black", height=100, width=400)
- # monta o frame 1 - Placar
- self.labelP1 = Label(self.framePlacar, text='P1 ', font=('Helvetica', 32), fg='red')
- self.pointsP1 = StringVar()
- self.pointsP1.set("0")
- self.placarP1 = Label(self.framePlacar, width=2, font=('Terminal', 32), fg='yellow', bg='black', textvariable=self.pointsP1, justify='center')
- self.labelVs = Label(self.framePlacar, text='x', font=('Helvetica', 18), fg='black', width=6)
- self.labelP2 = Label(self.framePlacar, text=' P2', font=('Helvetica', 32), fg='blue')
- self.pointsP2 = StringVar()
- self.pointsP2.set("0")
- self.placarP2 = Label(self.framePlacar, width=2, font=('Terminal', 32), fg='yellow', bg='black', textvariable=self.pointsP2, justify='center')
- # organiza widgets do placar na grid
- self.labelP1.grid(row=0, column=0, sticky=W)
- self.placarP1.grid(row=0, column=1, sticky=W)
- self.labelVs.grid(row=0, column=2, sticky=W)
- self.placarP2.grid(row=0, column=3, sticky=W)
- self.labelP2.grid(row=0, column=4, sticky=W)
- # monta o frame 2 - tabuleiro do jogo
- #variaveis das labels que sao alteradas dinamicamente ao se clicar na label
- self.charGame1 = StringVar()
- self.charGame2 = StringVar()
- self.charGame3 = StringVar()
- self.charGame4 = StringVar()
- self.charGame5 = StringVar()
- self.charGame6 = StringVar()
- self.charGame7 = StringVar()
- self.charGame8 = StringVar()
- self.charGame9 = StringVar()
- # labels que formam o tabuleiro do jogo
- self.labelGame1 = Label(self.frameGame, font=('Helvetica', 32), text=' ', fg='blue', width=6, justify='center', relief='groove', height='2', textvariable=self.charGame1)
- self.labelGame2 = Label(self.frameGame, font=('Helvetica', 32), text=' ', fg='blue', width=6, justify='center', relief='groove', height='2', textvariable=self.charGame2)
- self.labelGame3 = Label(self.frameGame, font=('Helvetica', 32), text=' ', fg='blue', width=6, justify='center', relief='groove', height='2', textvariable=self.charGame3)
- self.labelGame4 = Label(self.frameGame, font=('Helvetica', 32), text=' ', fg='blue', width=6, justify='center', relief='groove', height='2', textvariable=self.charGame4)
- self.labelGame5 = Label(self.frameGame, font=('Helvetica', 32), text=' ', fg='blue', width=6, justify='center', relief='groove', height='2', textvariable=self.charGame5)
- self.labelGame6 = Label(self.frameGame, font=('Helvetica', 32), text=' ', fg='blue', width=6, justify='center', relief='groove', height='2', textvariable=self.charGame6)
- self.labelGame7 = Label(self.frameGame, font=('Helvetica', 32), text=' ', fg='blue', width=6, justify='center', relief='groove', height='2', textvariable=self.charGame7)
- self.labelGame8 = Label(self.frameGame, font=('Helvetica', 32), text=' ', fg='blue', width=6, justify='center', relief='groove', height='2', textvariable=self.charGame8)
- self.labelGame9 = Label(self.frameGame, font=('Helvetica', 32), text=' ', fg='blue', width=6, justify='center', relief='groove', height='2', textvariable=self.charGame9)
- # Cria o vinculo das labels a uma funcao com o evento "clique do 1o botao do mouse"
- self.labelGame1.bind("<Button-1>", self.MarcarOpcao)
- self.labelGame2.bind("<Button-1>", self.MarcarOpcao)
- self.labelGame3.bind("<Button-1>", self.MarcarOpcao)
- self.labelGame4.bind("<Button-1>", self.MarcarOpcao)
- self.labelGame5.bind("<Button-1>", self.MarcarOpcao)
- self.labelGame6.bind("<Button-1>", self.MarcarOpcao)
- self.labelGame7.bind("<Button-1>", self.MarcarOpcao)
- self.labelGame8.bind("<Button-1>", self.MarcarOpcao)
- self.labelGame9.bind("<Button-1>", self.MarcarOpcao)
- # organiza widgets do tabuleiro na grid
- self.labelGame1.grid(row=0, column=0, sticky=W)
- self.labelGame2.grid(row=0, column=1, sticky=W)
- self.labelGame3.grid(row=0, column=2, sticky=W)
- self.labelGame4.grid(row=1, column=0, sticky=W)
- self.labelGame5.grid(row=1, column=1, sticky=W)
- self.labelGame6.grid(row=1, column=2, sticky=W)
- self.labelGame7.grid(row=2, column=0, sticky=W)
- self.labelGame8.grid(row=2, column=1, sticky=W)
- self.labelGame9.grid(row=2, column=2, sticky=W)
- # monta o frame 3 - rodape
- # variavel dinamica para guardar as mensagens da jogada no rodape
- self.varInfo = StringVar()
- self.varInfo.set('Rodada do Jogador 1')
- # Label do rodape
- self.labelInfo = Label(self.frameInfo, font=('Terminal', 12), textvariable=self.varInfo, justify='center', bg='black', fg='yellow', width='38', pady='4')
- self.labelInfo.pack(fill=X, expand=1)
- # Empacota os frames na janela principal
- self.framePlacar.pack()
- self.frameGame.pack()
- self.frameInfo.pack()
- # Criando um loop eterno (basicamente um "while True" por debaixo dos panos pra abrir nossa janela)
- self.window.mainloop()
- """
- Metodo responsavel por mostrar a marcacao do jogador no tabuleiro ao clicar nele.
- """
- def MarcarOpcao(self, event):
- # pega o label clicado pelo jogador
- self.clickedOpt = event.widget.winfo_name()
- # Estes blocos verificam qual label foi clicada pelo jogador, marcando "x" ou "o" de aordo com o jogador da rodada
- # tambem guarda a opcao na lista de jogadas que e usada para ver se ha uma jogada vencedora
- # Por fim, altera a cor do texto de acordo com o jogador da rodada ("x" sempre vermelho e "o" sempre azul)
- if self.clickedOpt == '!label' and self.charGame1.get() == '':
- self.charGame1.set('X') if self.rodadaJogador == 1 else self.charGame1.set('O')
- self.listaGames[0] = 'X' if self.rodadaJogador == 1 else 'O'
- self.labelGame1.config(fg='red') if self.rodadaJogador == 1 else self.labelGame1.config(fg='blue')
- self.VerificaSeGanhou()
- elif self.clickedOpt == '!label2' and self.charGame2.get() == '':
- self.charGame2.set('X') if self.rodadaJogador == 1 else self.charGame2.set('O')
- self.listaGames[1] = 'X' if self.rodadaJogador == 1 else 'O'
- self.labelGame2.config(fg='red') if self.rodadaJogador == 1 else self.labelGame2.config(fg='blue')
- self.VerificaSeGanhou()
- elif self.clickedOpt == '!label3' and self.charGame3.get() == '':
- self.charGame3.set('X') if self.rodadaJogador == 1 else self.charGame3.set('O')
- self.listaGames[2] = 'X' if self.rodadaJogador == 1 else 'O'
- self.labelGame3.config(fg='red') if self.rodadaJogador == 1 else self.labelGame3.config(fg='blue')
- self.VerificaSeGanhou()
- elif self.clickedOpt == '!label4' and self.charGame4.get() == '':
- self.charGame4.set('X') if self.rodadaJogador == 1 else self.charGame4.set('O')
- self.listaGames[3] = 'X' if self.rodadaJogador == 1 else 'O'
- self.labelGame4.config(fg='red') if self.rodadaJogador == 1 else self.labelGame4.config(fg='blue')
- self.VerificaSeGanhou()
- elif self.clickedOpt == '!label5' and self.charGame5.get() == '':
- self.charGame5.set('X') if self.rodadaJogador == 1 else self.charGame5.set('O')
- self.listaGames[4] = 'X' if self.rodadaJogador == 1 else 'O'
- self.labelGame5.config(fg='red') if self.rodadaJogador == 1 else self.labelGame5.config(fg='blue')
- self.VerificaSeGanhou()
- elif self.clickedOpt == '!label6' and self.charGame6.get() == '':
- self.charGame6.set('X') if self.rodadaJogador == 1 else self.charGame6.set('O')
- self.listaGames[5] = 'X' if self.rodadaJogador == 1 else 'O'
- self.labelGame6.config(fg='red') if self.rodadaJogador == 1 else self.labelGame6.config(fg='blue')
- self.VerificaSeGanhou()
- elif self.clickedOpt == '!label7' and self.charGame7.get() == '':
- self.charGame7.set('X') if self.rodadaJogador == 1 else self.charGame7.set('O')
- self.listaGames[6] = 'X' if self.rodadaJogador == 1 else 'O'
- self.labelGame7.config(fg='red') if self.rodadaJogador == 1 else self.labelGame7.config(fg='blue')
- self.VerificaSeGanhou()
- elif self.clickedOpt == '!label8' and self.charGame8.get() == '':
- self.charGame8.set('X') if self.rodadaJogador == 1 else self.charGame8.set('O')
- self.listaGames[7] = 'X' if self.rodadaJogador == 1 else 'O'
- self.labelGame8.config(fg='red') if self.rodadaJogador == 1 else self.labelGame8.config(fg='blue')
- self.VerificaSeGanhou()
- elif self.clickedOpt == '!label9' and self.charGame9.get() == '':
- self.charGame9.set('X') if self.rodadaJogador == 1 else self.charGame9.set('O')
- self.listaGames[8] = 'X' if self.rodadaJogador == 1 else 'O'
- self.labelGame9.config(fg='red') if self.rodadaJogador == 1 else self.labelGame9.config(fg='blue')
- self.VerificaSeGanhou()
- """
- Metodo responsavel por verificar se ja ha uma jogada vencedora
- """
- def VerificaSeGanhou(self):
- # define as possibilidades para vencer uma rodada. Inicialmente todas as possibilidades sao falsas
- # Quando temos uma jogada vencedora, a variavel desta sequencia recebe True
- game1 = self.listaGames[0] == self.listaGames[1] == self.listaGames[2] # primeira linha
- game2 = self.listaGames[3] == self.listaGames[4] == self.listaGames[5] # segunda linha
- game3 = self.listaGames[6] == self.listaGames[7] == self.listaGames[8] # terceira linha
- game4 = self.listaGames[0] == self.listaGames[3] == self.listaGames[6] # primeira coluna
- game5 = self.listaGames[1] == self.listaGames[4] == self.listaGames[7] # segunda coluna
- game6 = self.listaGames[2] == self.listaGames[5] == self.listaGames[8] # terceira coluna
- game7 = self.listaGames[0] == self.listaGames[4] == self.listaGames[8] # primeira diagonal
- game8 = self.listaGames[2] == self.listaGames[4] == self.listaGames[6] # segunda diagonal
- # adiciona estas possibilidades numa lista
- checaGames = [game1, game2, game3, game4, game5, game6, game7, game8]
- # itera a lista para verificar se ha uma rodada vitoriosa (True)
- for possibilidade in checaGames:
- if possibilidade == True:
- self.ganhou = True
- # Se encontrar uma possibilidade vitoriosa, chama a funcao para declarar o vencedor
- # caso contrario, altera o turno para o outro jogador e continua o jogo
- if self.ganhou:
- self.TemosUmVencedor()
- else:
- self.alterarodada()
- """
- Metodo chamado quando um jogador ganha a partida
- """
- def TemosUmVencedor(self):
- self.ganhou = True
- mensagem = ' O Jogador ' + str(self.rodadaJogador) + ' venceu! Parabéns!'
- self.varInfo.set(mensagem)
- self.MarcarPonto()
- self.DialogoJogo(mensagem)
- """
- Metodo responsavel por marcar o ponto no placar do jogador vencedor
- """
- def MarcarPonto(self):
- if self.rodadaJogador == 1:
- valor = int(self.pointsP1.get())
- valor = valor + 1
- self.pointsP1.set(valor)
- elif self.rodadaJogador == 2:
- valor = int(self.pointsP2.get())
- valor = valor + 1
- self.pointsP2.set(valor)
- """
- Metodo responsavel por alterar a rodada entre os jogadores
- """
- def alterarodada(self):
- if self.rodadaJogador == 1:
- self.rodadaJogador = 2
- self.varInfo.set('Rodada do Jogador 2')
- else:
- self.rodadaJogador = 1
- self.varInfo.set('Rodada do Jogador 1')
- """
- Metodo responsavel por exibir a caixa de dialogo no final das partidas
- """
- def DialogoJogo(self, mensagem):
- # exibe a caixa de dialogo e recebe a opcao escolhida pelos jogadores (True ou False)
- resp = messagebox.askretrycancel(title='Temos um vencedor!', message=mensagem)
- # se o jogador escolher "Repetir", reinicia o jogo. Se escolher cancelar, fecha o jogo
- if resp == True:
- self.ReiniciarGame()
- else:
- self.window.quit()
- """
- Metodo que reinicia a partida, zerando as variaveis para uma nova rodasa
- """
- def ReiniciarGame(self):
- self.rodadaJogador = 1 # volta a rodada ao jogador 1
- self.listaGames = list(range(1, 10)) # recria a lista de possibilidades
- self.ganhou = False
- self.varInfo.set('Rodada do Jogador 1')
- # Limpa o tabuleiro com as marcações "x" e "o"
- self.charGame1.set('')
- self.charGame2.set('')
- self.charGame3.set('')
- self.charGame4.set('')
- self.charGame5.set('')
- self.charGame6.set('')
- self.charGame7.set('')
- self.charGame8.set('')
- self.charGame9.set('')
- # FIM DA CLASSE TIPTAPTOE
- # Instancia a classe e inicia o jogo! LET'S PLAY!
- TipTapToe()
Advertisement
Add Comment
Please, Sign In to add comment