kadoshmt_br

Tip Tap Toe (Jogo da Velha)

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