Guest User

Tip Tap Toe (Jogo da Velha)

a guest
Aug 8th, 2019
672
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 14.15 KB | None | 0 0
  1. """
  2. JOGO TIP-TAP-TOE (JOGO DA VELHA) UTILIZANDO A GUI TKINTER
  3. Author: Janes Roberto
  4. """
  5. from tkinter import *
  6. from tkinter import messagebox
  7.  
  8. # Inicio da Classe
  9. class TipTapToe( Frame ):
  10.     """
  11.    Metodo construtor da Classe.
  12.    Define os elementos da janela principal e inicia o programa
  13.    """
  14.     def __init__(self):
  15.         # Cria nossa janela principal
  16.         self.window = Tk()
  17.         self.window.title('TIP TAP TOE TABAJARA')
  18.  
  19.         # Inicializa algumas variaveis de controle
  20.         self.rodadaJogador = 1 # controla de quem e a rodada
  21.         self.clickedOpt = "" # guada o valor da label clicada
  22.         self.listaGames = list(range(1, 10)) # gera uma lista para controlar a marcacao do jogo
  23.         self.ganhou = False # guarda o status da jogada
  24.  
  25.  
  26.         # cria os frames do jogo
  27.         self.framePlacar = Frame(self.window, bg="white", height=100, width=400)
  28.         self.frameGame = Frame(self.window, bg="yellow", height=250, width=400)
  29.         self.frameInfo = Frame(self.window, bg="black", height=100, width=400)
  30.  
  31.         # monta o frame 1 - Placar
  32.         self.labelP1 = Label(self.framePlacar, text='P1 ', font=('Helvetica', 32), fg='red')
  33.         self.pointsP1 = StringVar()
  34.         self.pointsP1.set("0")
  35.         self.placarP1 = Label(self.framePlacar, width=2, font=('Terminal', 32), fg='yellow', bg='black', textvariable=self.pointsP1, justify='center')
  36.  
  37.         self.labelVs = Label(self.framePlacar, text='x', font=('Helvetica', 18), fg='black', width=6)
  38.  
  39.         self.labelP2 = Label(self.framePlacar, text=' P2', font=('Helvetica', 32), fg='blue')
  40.         self.pointsP2 = StringVar()
  41.         self.pointsP2.set("0")
  42.         self.placarP2 = Label(self.framePlacar, width=2, font=('Terminal', 32), fg='yellow', bg='black', textvariable=self.pointsP2, justify='center')
  43.  
  44.         # organiza widgets do placar na grid
  45.         self.labelP1.grid(row=0, column=0, sticky=W)
  46.         self.placarP1.grid(row=0, column=1, sticky=W)
  47.         self.labelVs.grid(row=0, column=2, sticky=W)
  48.         self.placarP2.grid(row=0, column=3, sticky=W)
  49.         self.labelP2.grid(row=0, column=4, sticky=W)
  50.  
  51.         # monta o frame 2 - tabuleiro do jogo
  52.         #variaveis das labels que sao alteradas dinamicamente ao se clicar na label
  53.         self.charGame1 = StringVar()
  54.         self.charGame2 = StringVar()
  55.         self.charGame3 = StringVar()
  56.         self.charGame4 = StringVar()
  57.         self.charGame5 = StringVar()
  58.         self.charGame6 = StringVar()
  59.         self.charGame7 = StringVar()
  60.         self.charGame8 = StringVar()
  61.         self.charGame9 = StringVar()
  62.  
  63.         # labels que formam o tabuleiro do jogo
  64.         self.labelGame1 = Label(self.frameGame, font=('Helvetica', 32), text=' ', fg='blue', width=6, justify='center', relief='groove', height='2', textvariable=self.charGame1)
  65.         self.labelGame2 = Label(self.frameGame, font=('Helvetica', 32), text=' ', fg='blue', width=6, justify='center', relief='groove', height='2', textvariable=self.charGame2)
  66.         self.labelGame3 = Label(self.frameGame, font=('Helvetica', 32), text=' ', fg='blue', width=6, justify='center', relief='groove', height='2', textvariable=self.charGame3)
  67.         self.labelGame4 = Label(self.frameGame, font=('Helvetica', 32), text=' ', fg='blue', width=6, justify='center', relief='groove', height='2', textvariable=self.charGame4)
  68.         self.labelGame5 = Label(self.frameGame, font=('Helvetica', 32), text=' ', fg='blue', width=6, justify='center', relief='groove', height='2', textvariable=self.charGame5)
  69.         self.labelGame6 = Label(self.frameGame, font=('Helvetica', 32), text=' ', fg='blue', width=6, justify='center', relief='groove', height='2', textvariable=self.charGame6)
  70.         self.labelGame7 = Label(self.frameGame, font=('Helvetica', 32), text=' ', fg='blue', width=6, justify='center', relief='groove', height='2', textvariable=self.charGame7)
  71.         self.labelGame8 = Label(self.frameGame, font=('Helvetica', 32), text=' ', fg='blue', width=6, justify='center', relief='groove', height='2', textvariable=self.charGame8)
  72.         self.labelGame9 = Label(self.frameGame, font=('Helvetica', 32), text=' ', fg='blue', width=6, justify='center', relief='groove', height='2', textvariable=self.charGame9)
  73.  
  74.         # Cria o vinculo das labels a uma funcao com o evento "clique do 1o botao do mouse"
  75.         self.labelGame1.bind("<Button-1>", self.MarcarOpcao)
  76.         self.labelGame2.bind("<Button-1>", self.MarcarOpcao)
  77.         self.labelGame3.bind("<Button-1>", self.MarcarOpcao)
  78.         self.labelGame4.bind("<Button-1>", self.MarcarOpcao)
  79.         self.labelGame5.bind("<Button-1>", self.MarcarOpcao)
  80.         self.labelGame6.bind("<Button-1>", self.MarcarOpcao)
  81.         self.labelGame7.bind("<Button-1>", self.MarcarOpcao)
  82.         self.labelGame8.bind("<Button-1>", self.MarcarOpcao)
  83.         self.labelGame9.bind("<Button-1>", self.MarcarOpcao)
  84.  
  85.         # organiza widgets do tabuleiro na grid
  86.         self.labelGame1.grid(row=0, column=0, sticky=W)
  87.         self.labelGame2.grid(row=0, column=1, sticky=W)
  88.         self.labelGame3.grid(row=0, column=2, sticky=W)
  89.         self.labelGame4.grid(row=1, column=0, sticky=W)
  90.         self.labelGame5.grid(row=1, column=1, sticky=W)
  91.         self.labelGame6.grid(row=1, column=2, sticky=W)
  92.         self.labelGame7.grid(row=2, column=0, sticky=W)
  93.         self.labelGame8.grid(row=2, column=1, sticky=W)
  94.         self.labelGame9.grid(row=2, column=2, sticky=W)
  95.  
  96.         # monta o frame 3 - rodape
  97.         # variavel dinamica para guardar as mensagens da jogada no rodape
  98.         self.varInfo = StringVar()
  99.         self.varInfo.set('Rodada do Jogador 1')
  100.  
  101.         # Label do rodape
  102.         self.labelInfo = Label(self.frameInfo, font=('Terminal', 12), textvariable=self.varInfo, justify='center', bg='black', fg='yellow', width='38', pady='4')
  103.         self.labelInfo.pack(fill=X, expand=1)
  104.  
  105.         # Empacota os frames na janela principal
  106.         self.framePlacar.pack()
  107.         self.frameGame.pack()
  108.         self.frameInfo.pack()
  109.  
  110.         # Criando um loop eterno (basicamente um "while True" por debaixo dos panos pra abrir nossa janela)
  111.         self.window.mainloop()
  112.  
  113.     """
  114.    Metodo responsavel por mostrar a marcacao do jogador no tabuleiro ao clicar nele.    
  115.    """
  116.     def MarcarOpcao(self, event):
  117.         # pega o label clicado pelo jogador
  118.         self.clickedOpt = event.widget.winfo_name()
  119.  
  120.         # Estes blocos verificam qual label foi clicada pelo jogador, marcando "x" ou "o" de aordo com o jogador da rodada
  121.         # tambem guarda a opcao na lista de jogadas que e usada para ver se ha uma jogada vencedora
  122.         # Por fim, altera a cor do texto de acordo com o jogador da rodada ("x" sempre vermelho e "o" sempre azul)
  123.         if self.clickedOpt == '!label' and self.charGame1.get() == '':
  124.             self.charGame1.set('X') if self.rodadaJogador == 1 else self.charGame1.set('O')
  125.             self.listaGames[0] = 'X' if self.rodadaJogador == 1 else 'O'
  126.             self.labelGame1.config(fg='red') if self.rodadaJogador == 1 else self.labelGame1.config(fg='blue')
  127.             self.VerificaSeGanhou()
  128.         elif self.clickedOpt == '!label2' and self.charGame2.get() == '':
  129.             self.charGame2.set('X') if self.rodadaJogador == 1 else self.charGame2.set('O')
  130.             self.listaGames[1] = 'X' if self.rodadaJogador == 1 else 'O'
  131.             self.labelGame2.config(fg='red') if self.rodadaJogador == 1 else self.labelGame2.config(fg='blue')
  132.             self.VerificaSeGanhou()
  133.         elif self.clickedOpt == '!label3' and self.charGame3.get() == '':
  134.             self.charGame3.set('X') if self.rodadaJogador == 1 else self.charGame3.set('O')
  135.             self.listaGames[2] = 'X' if self.rodadaJogador == 1 else 'O'
  136.             self.labelGame3.config(fg='red') if self.rodadaJogador == 1 else self.labelGame3.config(fg='blue')
  137.             self.VerificaSeGanhou()
  138.         elif self.clickedOpt == '!label4' and self.charGame4.get() == '':
  139.             self.charGame4.set('X') if self.rodadaJogador == 1 else self.charGame4.set('O')
  140.             self.listaGames[3] = 'X' if self.rodadaJogador == 1 else 'O'
  141.             self.labelGame4.config(fg='red') if self.rodadaJogador == 1 else self.labelGame4.config(fg='blue')
  142.             self.VerificaSeGanhou()
  143.         elif self.clickedOpt == '!label5' and self.charGame5.get() == '':
  144.             self.charGame5.set('X') if self.rodadaJogador == 1 else self.charGame5.set('O')
  145.             self.listaGames[4] = 'X' if self.rodadaJogador == 1 else 'O'
  146.             self.labelGame5.config(fg='red') if self.rodadaJogador == 1 else self.labelGame5.config(fg='blue')
  147.             self.VerificaSeGanhou()
  148.         elif self.clickedOpt == '!label6' and self.charGame6.get() == '':
  149.             self.charGame6.set('X') if self.rodadaJogador == 1 else self.charGame6.set('O')
  150.             self.listaGames[5] = 'X' if self.rodadaJogador == 1 else 'O'
  151.             self.labelGame6.config(fg='red') if self.rodadaJogador == 1 else self.labelGame6.config(fg='blue')
  152.             self.VerificaSeGanhou()
  153.         elif self.clickedOpt == '!label7' and self.charGame7.get() == '':
  154.             self.charGame7.set('X') if self.rodadaJogador == 1 else self.charGame7.set('O')
  155.             self.listaGames[6] = 'X' if self.rodadaJogador == 1 else 'O'
  156.             self.labelGame7.config(fg='red') if self.rodadaJogador == 1 else self.labelGame7.config(fg='blue')
  157.             self.VerificaSeGanhou()
  158.         elif self.clickedOpt == '!label8' and self.charGame8.get() == '':
  159.             self.charGame8.set('X') if self.rodadaJogador == 1 else self.charGame8.set('O')
  160.             self.listaGames[7] = 'X' if self.rodadaJogador == 1 else 'O'
  161.             self.labelGame8.config(fg='red') if self.rodadaJogador == 1 else self.labelGame8.config(fg='blue')
  162.             self.VerificaSeGanhou()
  163.         elif self.clickedOpt == '!label9' and self.charGame9.get() == '':
  164.             self.charGame9.set('X') if self.rodadaJogador == 1 else self.charGame9.set('O')
  165.             self.listaGames[8] = 'X' if self.rodadaJogador == 1 else 'O'
  166.             self.labelGame9.config(fg='red') if self.rodadaJogador == 1 else self.labelGame9.config(fg='blue')
  167.             self.VerificaSeGanhou()
  168.  
  169.     """
  170.    Metodo responsavel por verificar se ja ha uma jogada vencedora    
  171.    """
  172.     def VerificaSeGanhou(self):
  173.  
  174.         # define as possibilidades para vencer uma rodada. Inicialmente todas as possibilidades sao falsas
  175.         # Quando temos uma jogada vencedora, a variavel desta sequencia recebe True
  176.         game1 = self.listaGames[0] == self.listaGames[1] == self.listaGames[2] # primeira linha
  177.         game2 = self.listaGames[3] == self.listaGames[4] == self.listaGames[5] # segunda linha
  178.         game3 = self.listaGames[6] == self.listaGames[7] == self.listaGames[8] # terceira linha
  179.         game4 = self.listaGames[0] == self.listaGames[3] == self.listaGames[6] # primeira coluna
  180.         game5 = self.listaGames[1] == self.listaGames[4] == self.listaGames[7] # segunda coluna
  181.         game6 = self.listaGames[2] == self.listaGames[5] == self.listaGames[8] # terceira coluna
  182.         game7 = self.listaGames[0] == self.listaGames[4] == self.listaGames[8] # primeira diagonal
  183.         game8 = self.listaGames[2] == self.listaGames[4] == self.listaGames[6] # segunda diagonal
  184.  
  185.         # adiciona estas possibilidades numa lista
  186.         checaGames = [game1, game2, game3, game4, game5, game6, game7, game8]
  187.  
  188.         # itera a lista para verificar se ha uma rodada vitoriosa (True)
  189.         for possibilidade in checaGames:
  190.             if possibilidade == True:
  191.                self.ganhou = True
  192.  
  193.         # Se encontrar uma possibilidade vitoriosa, chama a funcao para declarar o vencedor
  194.         # caso contrario, altera o turno para o outro jogador e continua o jogo
  195.         if self.ganhou:
  196.             self.TemosUmVencedor()
  197.         else:
  198.             self.alterarodada()
  199.  
  200.  
  201.     """
  202.    Metodo chamado quando um jogador ganha a partida    
  203.    """
  204.     def TemosUmVencedor(self):
  205.         self.ganhou = True
  206.         mensagem = ' O Jogador ' + str(self.rodadaJogador) + ' venceu! Parabéns!'
  207.         self.varInfo.set(mensagem)
  208.         self.MarcarPonto()
  209.         self.DialogoJogo(mensagem)
  210.  
  211.  
  212.     """
  213.    Metodo responsavel por marcar o ponto no placar do jogador vencedor    
  214.    """
  215.     def MarcarPonto(self):
  216.         if self.rodadaJogador == 1:
  217.             valor = int(self.pointsP1.get())
  218.             valor = valor + 1
  219.             self.pointsP1.set(valor)
  220.         elif self.rodadaJogador == 2:
  221.             valor = int(self.pointsP2.get())
  222.             valor = valor + 1
  223.             self.pointsP2.set(valor)
  224.  
  225.  
  226.     """
  227.    Metodo responsavel por alterar a rodada entre os jogadores  
  228.    """
  229.     def alterarodada(self):
  230.         if self.rodadaJogador == 1:
  231.             self.rodadaJogador = 2
  232.             self.varInfo.set('Rodada do Jogador 2')
  233.         else:
  234.             self.rodadaJogador = 1
  235.             self.varInfo.set('Rodada do Jogador 1')
  236.  
  237.  
  238.     """
  239.    Metodo responsavel por exibir a caixa de dialogo no final das partidas  
  240.    """
  241.     def DialogoJogo(self, mensagem):
  242.         # exibe a caixa de dialogo e recebe a opcao escolhida pelos jogadores (True ou False)
  243.         resp = messagebox.askretrycancel(title='Temos um vencedor!', message=mensagem)
  244.  
  245.         # se o jogador escolher "Repetir", reinicia o jogo. Se escolher cancelar, fecha o jogo
  246.         if resp == True:
  247.             self.ReiniciarGame()
  248.         else:
  249.             self.window.quit()
  250.  
  251.     """
  252.    Metodo que reinicia a partida, zerando as variaveis para uma nova rodasa  
  253.    """
  254.     def ReiniciarGame(self):
  255.         self.rodadaJogador = 1 # volta a rodada ao jogador 1
  256.         self.listaGames = list(range(1, 10)) # recria a lista de possibilidades
  257.         self.ganhou = False
  258.         self.varInfo.set('Rodada do Jogador 1')
  259.  
  260.         # Limpa o tabuleiro com as marcações "x" e "o"
  261.         self.charGame1.set('')
  262.         self.charGame2.set('')
  263.         self.charGame3.set('')
  264.         self.charGame4.set('')
  265.         self.charGame5.set('')
  266.         self.charGame6.set('')
  267.         self.charGame7.set('')
  268.         self.charGame8.set('')
  269.         self.charGame9.set('')
  270.  
  271. # FIM DA CLASSE TIPTAPTOE
  272.  
  273. # Instancia a classe e inicia o jogo! LET'S PLAY!
  274. TipTapToe()
Advertisement
Add Comment
Please, Sign In to add comment