# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3
#     name: python3
# ---

# + [markdown] id="view-in-github" colab_type="text"
# <a href="https://colab.research.google.com/github/WuilsonEstacio/Variados-programas-en-python/blob/main/juego_tic_tac_toe.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>

# + id="W4Dtm8dGw_5E" colab={"base_uri": "https://localhost:8080/", "height": 374} outputId="e51c4931-693c-43f2-8e34-0544ccb895f5"
# juego tic tac toe
from matplotlib.pyplot import *
from matplotlib.widgets import *
from math import *
from random import *
from numpy import *
from tkinter import *
from tkinter import messagebox
from tkinter import simpledialog

turno=0
njugador1=""
njugador2=""
listabotones=[]
t=[] # X o N
#turnojugador=StringVar()

for i in range(0,9):
  t.append('N')

boton0=Button(width=9,height=3) #command=cambiar(0)
listaBotones.append(boton0)
boton0.place(x=50, y=50)


# + id="IT8ccUYEoHFD" colab={"base_uri": "https://localhost:8080/"} outputId="af337f00-f5b4-4e4c-a81f-f9db40b01c6e"
from math import *
from random import *
from numpy import *
import itertools

board = ['1', '2', '3', '4', '5', '6', '7', '8', '9']
print(board)

currentToken = 'X'
winningToken = " "
slotsFilled = 0

while not (currentToken == 'X' or slotsFilled == 'O'):
        print('Do you want to be X or O?')
        currentToken = input().upper()

print ("Tic-Tac-Toe por Wilson")
print ("Une tres líneas vertical, horizontal o diagonal y has un Match")
print ("Cual quieres escojer X o O")
print("elige", input())

while winningToken == " and slotsFilled " < 9:
  print("\n")
  print("%s|%s|%s" % (board[0], board[1], board[2]))
  print("-+-+-")
  print("%s|%s|%s" % (board[3], board[4], board[5]))
  print("-+-+-")
  print("%s|%s|%s" % (board[6], board[7], board[8]))
  
  pos = -1
  while (pos == -1):
    pos = int(input("\n%s's turn. Where to? : " % currentToken))
    if pos < 1 or pos > 9:
      pos = -1
      print ("Invalid choice! 1-9 only.")
      
    pos = pos - 1

    if board[pos] == 'X' or board[pos] == 'O':
      pos = -1
      print("That spot has already been taken by %s! Try again" % board[pos])

  board[pos] = currentToken
  slotsFilled = slotsFilled + 1

  row1 = board[0] == currentToken and board[1] ==  currentToken and board[2] == currentToken
  row2 = board[3] == currentToken and board[4] ==  currentToken and board[5] == currentToken
  row3 = board[6] == currentToken and board[7] ==  currentToken and board[8] == currentToken

  col1 = board[0] == currentToken and board[3] ==  currentToken and board[6] == currentToken
  col2 = board[1] == currentToken and board[4] ==  currentToken and board[7] == currentToken
  col3 = board[2] == currentToken and board[5] ==  currentToken and board[8] == currentToken

  diag1 = board[0] == currentToken and board[4] == currentToken and board[8] == currentToken
  diag2 = board[2] == currentToken and board[4] == currentToken and board[6] == currentToken

  row = row1 or row2 or row3
  col = col1 or col2 or col3
  diag = diag1 or diag2

  if (row or col or diag):
    print("\n")
    print("%s|%s|%s" % (board[0], board[1], board[2]))
    print("-+-+-")
    print("%s|%s|%s" % (board[3], board[4], board[5]))
    print("-+-+-")
    print("%s|%s|%s" % (board[6], board[7], board[8]))

    print("Congratulations %s! You won!!" % currentToken)
    winningToken = currentToken
  if currentToken == 'X':
    currentToken = 'O'
  else:
    currentToken = 'X'
  
  if slotsFilled == 9 and winningToken == " ":
    print("No one won :( Better luck next time, players!")

# + id="b-YcRsysZNJy" colab={"base_uri": "https://localhost:8080/"} outputId="50670476-56e8-4275-c10c-42e968d4bd80"
import random

def imprimir(matriz):
    for i in range(4):
        print (' '*22),
        for j in range(4):
            print (matriz[i][j]),
        print ('\n')

def ganador(jugador):
    gana = None
    if gato[1][1]==gato[2][2]==gato[3][3]!='.':
        gana = 'Ganador'
    elif gato[1][3]==gato[2][2]==gato[3][1]!='.':
        gana = 'Ganador'
    for i in range(1,4):
        if gato[i][1]==gato[i][2]==gato[i][3]!='.':
            gana = 'Ganador'
        elif gato[1][i]==gato[2][i]==gato[3][i]!='.':
            gana = 'Ganador'
    if gana == 'Ganador':
        print ('<' + '='*48 + '>')
        print ('> Ha ganado {} <'.format(jugador)).center(50,'=')
        print ('<' + '='*48 + '>\n\n')
        return 'WINNER'

def entradaJugador(jugador,z):
    while True:
        x=None
        y=None
        entrada_jugador = str(input('En que posicion desea marcar?\n'+
                                    '(Ingrese la letra seguido del numero)\n'))
        for caracter in entrada_jugador:
            if caracter in 'abc':
                x = 'abc'.index(caracter) + 1
                letra = caracter.upper()
            elif caracter in '123':
                y=int(caracter)
        if gato[y][x]=='.':
            gato[y][x]=z
            print ('%s ha marcado en %s%d'%(jugador.capitalize(), letra, y))
            imprimir(gato)
            break

def jugada(x,y,z,jugador):
    if gato [y][x]=='.':
        gato[y][x]=z
        if x==1:
            letra='A'
        elif x==2:
            letra='B'
        elif x==3:
            letra='C'
        print ('%s ha marcado en %s%d'%(jugador.capitalize(), letra, y))
        imprimir(gato)

while True:
    gato = [[' ','A','B','C'],['1','.','.','.'],['2','.','.','.'],['3','.','.','.']]
    print (('> bienvenido al juego del gato <'.title()).center(50,'=') + '\n')
    opcion = str(input('Ingrese la opcion de juego:'+
                       '\n 1.- Player vs CPU'+
                       '\n 2.- Player vs Player'+
                       '\n 3.- Salir de la partida\n'))
    imprimir(gato)
    if opcion == '1':
        quien_parte = random.randrange(1)
        if quien_parte==1:
            juega = 'el jugador'
        else:
            juega = 'el contrincante'
        print ('Estas jugando contra la maquina, comienza %s'%(juega))
        while True:
            if juega=='el contrincante':
                x = random.randrange(1,4)
                y = random.randrange(1,4)
                jugada(x,y,'O',juega)
                if ganador(juega) == 'WINNER':
                    break
                juega='el jugador'
            elif juega=='el jugador':
                entradaJugador(juega,'X')
                if ganador(juega) == 'WINNER':
                    break
                juega='el contrincante'
    elif opcion == '2':
        juega = 'el jugador 1'
        while True:
            print ('Turno para %s'%(juega))
            if juega=='el jugador 1':
                entradaJugador(juega,'X')
                if ganador(juega) == 'WINNER':
                    break
                juega='el jugador 2'
            elif juega=='el jugador 2':
                entradaJugador(juega,'O')
                if ganador(juega) == 'WINNER':
                    break
                juega='el jugador 1'
    elif opcion == '3':
        print ('Gracias por jugar! nos vemos en otra partida!')
        break
    else:
        print ('ERROR! Inserte una opcion valida')

# + id="b6M_qudNaTYb"
 self.board = Board(print_function)
 self.menu = Menu(read_function, print_function)
 self.print_function = print_function
        

def start(self):
  while True:
    option = self.menu.ask_menu_option()
    if option == self.EXIT_OPTION:
      break
    else:
      self.board.create_numeric_cells()
      self.print_game_instructions()
      self.board.clean_marks()
      self.ask_cells()
      self.start_new_game()

def start_new_game(self):
  self.board.create_numeric_cells()
  self.print_game_instructions()
  self.board.clean_marks()
  self.ask_cells()

def print_game_instructions(self):
  self.print_function('Select the number of the cell that you want to mark\n')
#@@ -84,7 +87,7 @@ def is_won_in_column(self, col):
def is_won_in_rows(self):        
  return self.is_won_in_row(1) or self.is_won_in_row(2) or self.is_won_in_row(3)

def is_won_in_colums(self):
  def is_won_in_columns(self):
    return self.is_won_in_column(1) or self.is_won_in_column(2) or self.is_won_in_column(3)

def is_won_in_diagonal(self, start_index, step):
  #@@ -96,5 +99,5 @@ def is_won_in_diagonals(self):
      or self.is_won_in_diagonal(self.UPPER_RIGHT_CELL, self.FROM_RIGHT_TO_LEFT_DIAGONAL_STEP)

def is_won(self):
  return self.is_won_in_colums() or self.is_won_in_rows() or self.is_won_in_diagonals()
  return self.is_won_in_columns() or self.is_won_in_rows() or self.is_won_in_diagonals()


# + id="WzGuDK0nalfG"
# Tic-Tac-Toe Program using 
# random number in Python 
  
# importing all necessary libraries 
import numpy as np 
import random 
from time import sleep 
  
# Creates an empty board 
def create_board(): 
    return(np.array([[0, 0, 0], 
                     [0, 0, 0], 
                     [0, 0, 0]])) 
  
# Check for empty places on board 
def possibilities(board): 
    l = [] 
      
    for i in range(len(board)): 
        for j in range(len(board)): 
              
            if board[i][j] == 0: 
                l.append((i, j)) 
    return(l) 
  
# Select a random place for the player 
def random_place(board, player): 
    selection = possibilities(board) 
    current_loc = random.choice(selection) 
    board[current_loc] = player 
    return(board) 
  
# Checks whether the player has three  
# of their marks in a horizontal row 
def row_win(board, player): 
    for x in range(len(board)): 
        win = True
          
        for y in range(len(board)): 
            if board[x, y] != player: 
                win = False
                continue
                  
        if win == True: 
            return(win) 
    return(win) 
  
# Checks whether the player has three 
# of their marks in a vertical row 
def col_win(board, player): 
    for x in range(len(board)): 
        win = True
          
        for y in range(len(board)): 
            if board[y][x] != player: 
                win = False
                continue
                  
        if win == True: 
            return(win) 
    return(win) 
  
# Checks whether the player has three 
# of their marks in a diagonal row 
def diag_win(board, player): 
    win = True
    y = 0
    for x in range(len(board)): 
        if board[x, x] != player: 
            win = False
    win = True
    if win: 
        for x in range(len(board)): 
            y = len(board) - 1 - x 
            if board[x, y] != player: 
                win = False
    return win 
  
# Evaluates whether there is 
# a winner or a tie  
def evaluate(board): 
    winner = 0
      
    for player in [1, 2]: 
        if (row_win(board, player) or
            col_win(board,player) or 
            diag_win(board,player)): 
                 
            winner = player 
              
    if np.all(board != 0) and winner == 0: 
        winner = -1
    return winner 
  
# Main function to start the game 
def play_game(): 
    board, winner, counter = create_board(), 0, 1
    print(board) 
    sleep(2) 
      
    while winner == 0: 
        for player in [1, 2]: 
            board = random_place(board, player) 
            print("Board after " + str(counter) + " move") 
            print(board) 
            sleep(2) 
            counter += 1
            winner = evaluate(board) 
            if winner != 0: 
                break
    return(winner) 
  
# Driver Code 
print("Winner is: " + str(play_game())) 

# + id="LuLZPnDRVOm3"
import tkinter as tk
from tkinter import messagebox

ventana =tk.TK()
ventana.title("ventana primera")
ventana.geometry('388x300')
ventana.configure(background='dark turqouise')
ventana.mainloop()

# + id="DCTWUzq2cqBS"
# importing the required libraries 
import pygame as pg 
import sys 
import time 
from pygame.locals import *
   
# declaring the global variables 
  
# for storing the 'x' or 'o'  
# value as character 
XO = 'x'
  
# storing the winner's value at 
# any instant of code 
winner = None
  
# to check if the game is a draw 
draw = None
  
# to set width of the game window 
width = 400
  
# to set height of the game window 
height = 400
  
# to set background color of the  
# game window 
white = (255, 255, 255) 
  
# color of the straightlines on that  
# white game board, dividing board  
# into 9 parts 
line_color = (0, 0, 0) 
   
# setting up a 3 * 3 board in canvas 
board = [[None]*3, [None]*3, [None]*3] 
  
  
# initializing the pygame window 
pg.init() 
  
# setting fps manually 
fps = 30
  
# this is used to track time 
CLOCK = pg.time.Clock() 
  
# this method is used to build the 
# infrastructure of the display 
screen = pg.display.set_mode((width, height + 100), 0, 32) 
  
# setting up a nametag for the  
# game window 
pg.display.set_caption("My Tic Tac Toe") 
   
# loading the images as python object 
initiating_window = pg.image.load("modified_cover.png") 
x_img = pg.image.load("X_modified.png") 
y_img = pg.image.load("o_modified.png") 
   
# resizing images 
initiating_window = pg.transform.scale(initiating_window, (width, height + 100)) 
x_img = pg.transform.scale(x_img, (80, 80)) 
o_img = pg.transform.scale(y_img, (80, 80)) 
   
def game_initiating_window(): 
      
    # displaying over the screen 
    screen.blit(initiating_window, (0, 0)) 
      
    # updating the display 
    pg.display.update() 
    time.sleep(3)                     
    screen.fill(white) 
   
    # drawing vertical lines 
    pg.draw.line(screen, line_color, (width / 3, 0), (width / 3, height), 7) 
    pg.draw.line(screen, line_color, (width / 3 * 2, 0), (width / 3 * 2, height), 7) 
   
    # drawing horizontal lines 
    pg.draw.line(screen, line_color, (0, height / 3), (width, height / 3), 7) 
    pg.draw.line(screen, line_color, (0, height / 3 * 2), (width, height / 3 * 2), 7) 
    draw_status() 
   
def draw_status(): 
      
    # getting the global variable draw 
    # into action 
    global draw 
      
    if winner is None: 
        message = XO.upper() + "'s Turn"
    else: 
        message = winner.upper() + " won !"
    if draw: 
        message = "Game Draw !"
   
    # setting a font object 
    font = pg.font.Font(None, 30) 
      
    # setting the font properties like  
    # color and width of the text 
    text = font.render(message, 1, (255, 255, 255)) 
   
    # copy the rendered message onto the board 
    # creating a small block at the bottom of the main display 
    screen.fill ((0, 0, 0), (0, 400, 500, 100)) 
    text_rect = text.get_rect(center =(width / 2, 500-50)) 
    screen.blit(text, text_rect) 
    pg.display.update() 
      
def check_win(): 
    global board, winner, draw 
   
    # checking for winning rows 
    for row in range(0, 3): 
        if((board[row][0] == board[row][1] == board[row][2]) and (board [row][0] is not None)): 
            winner = board[row][0] 
            pg.draw.line(screen, (250, 0, 0), 
                         (0, (row + 1)*height / 3 -height / 6), 
                         (width, (row + 1)*height / 3 - height / 6 ), 
                         4) 
            break
   
    # checking for winning columns 
    for col in range(0, 3): 
        if((board[0][col] == board[1][col] == board[2][col]) and (board[0][col] is not None)): 
            winner = board[0][col] 
            pg.draw.line (screen, (250, 0, 0), ((col + 1)* width / 3 - width / 6, 0), \  
                          ((col + 1)* width / 3 - width / 6, height), 4)
            break
   
    # check for diagonal winners 
    if (board[0][0] == board[1][1] == board[2][2]) and (board[0][0] is not None): 
          
        # game won diagonally left to right 
        winner = board[0][0] 
        pg.draw.line (screen, (250, 70, 70), (50, 50), (350, 350), 4) 
          
    if (board[0][2] == board[1][1] == board[2][0]) and (board[0][2] is not None): 
          
        # game won diagonally right to left 
        winner = board[0][2] 
        pg.draw.line (screen, (250, 70, 70), (350, 50), (50, 350), 4) 
   
    if(all([all(row) for row in board]) and winner is None ): 
        draw = True
    draw_status() 
      
def drawXO(row, col): 
    global board, XO 
      
    # for the first row, the image 
    # should be pasted at a x coordinate 
    # of 30 from the left margin 
    if row == 1: 
        posx = 30
          
    # for the second row, the image  
    # should be pasted at a x coordinate  
    # of 30 from the game line      
    if row == 2: 
  
        # margin or width / 3 + 30 from  
        # the left margin of the window 
        posx = width / 3 + 30
          
    if row == 3: 
        posx = width / 3 * 2 + 30
   
    if col == 1: 
        posy = 30
          
    if col == 2: 
        posy = height / 3 + 30
      
    if col == 3: 
        posy = height / 3 * 2 + 30
          
    # setting up the required board  
    # value to display 
    board[row-1][col-1] = XO 
      
    if(XO == 'x'): 
          
        # pasting x_img over the screen  
        # at a coordinate position of 
        # (pos_y, posx) defined in the 
        # above code 
        screen.blit(x_img, (posy, posx)) 
        XO = 'o'
      
    else: 
        screen.blit(o_img, (posy, posx)) 
        XO = 'x'
    pg.display.update() 
   
def user_click(): 
    # get coordinates of mouse click 
    x, y = pg.mouse.get_pos() 
   
    # get column of mouse click (1-3) 
    if(x<width / 3): 
        col = 1
      
    elif (x<width / 3 * 2): 
        col = 2
      
    elif(x<width): 
        col = 3
      
    else: 
        col = None
   
    # get row of mouse click (1-3) 
    if(y<height / 3): 
        row = 1
      
    elif (y<height / 3 * 2): 
        row = 2
      
    elif(y<height): 
        row = 3
      
    else: 
        row = None
        
    # after getting the row and col,  
    # we need to draw the images at 
    # the desired positions 
    if(row and col and board[row-1][col-1] is None): 
        global XO 
        drawXO(row, col) 
        check_win() 
          
def reset_game(): 
    global board, winner, XO, draw 
    time.sleep(3) 
    XO = 'x'
    draw = False
    game_initiating_window() 
    winner = None
    board = [[None]*3, [None]*3, [None]*3] 
   
game_initiating_window() 
   
while(True): 
    for event in pg.event.get(): 
        if event.type == QUIT: 
            pg.quit() 
            sys.exit() 
        elif event.type is MOUSEBUTTONDOWN: 
            user_click() 
            if(winner or draw): 
                reset_game() 
    pg.display.update() 
    CLOCK.tick(fps)

# + id="xiKgrNuYeYa9"
pip install cTurtle

# + id="VpXFmC4aeR5K"
import cTurtle
import random
import sys
import DISPLAY

def DrawTicTacToeBoard(t):
    #Vertical Lines of board
    t.pensize(3)
    t.up()
    t.goto(.5,-.5)
    t.down()
    t.goto(.5,2.5)
    t.up()
    t.goto(1.5,-.5)
    t.down()
    t.goto(1.5,2.5)
    #Horizontal Lines of board
    t.up()
    t.goto(-.5,.5)
    t.down()
    t.goto(2.5,.5)
    t.up()
    t.goto(-.5,1.5)
    t.down()
    t.goto(2.5,1.5)

def flipPlayer(currentPlayer):
    if currentPlayer==0:
        currentPlayer=1
    else:
        currentPlayer=0
    return currentPlayer

def drawWhiteBox(t,x,y):
    t.up()
    t.goto(x-.25,y+.25)
    t.down()
    t.color("white")
    t.begin_fill()
    for i in range(4):
        t.forward(.8)
        t.right(90)
    t.end_fill()
    t.color("black")

def drawMarker(t,currentPlayer,markerList,move,boardLoL):
    by=int(move[0:1])
    bx=int(move[2:])
    y=by+(.22)
    x=bx-(.15)
    drawWhiteBox(t,x,y)
    t.up()
    t.goto(x,y)
    boardLoL[by][bx]=markerList[currentPlayer]
    t.write(markerList[currentPlayer],move=False,align="left",font=("Arial",48,"normal"))

def getValidMove(validMoveList,markerList,currentPlayer,boardLoL):
    move = ""
    while move not in validMoveList:
        move = input("Enter location to place your marker " + markerList[currentPlayer] + ", or EXIT to end game => ")
        if move=="EXIT":
            sys.exit()
        if move in validMoveList:
            by=int(move[0])
            bx=int(move[2:])
            if boardLoL[by][bx]=="":
                return move
            else:
                print("Location already occupied")
                move=""

def gameWon(b):
    for row in range(3):
        if b[row][0]==b[row][1] and b[row][1]==b[row][2] and b[row][0]!="":
            print("Way to go",b[row][0])
            return b[row][0]
    for column in range(3):
        if b[0][column]==b[1][column] and b[1][column]==b[2][column] and b[0][column]!="":
            print("Way to go",b[column][0])
            return b[0][column]
    for diag in range(2):
        if b[0][0]==b[1][1] and b[1][1]==b[2][2] and b[0][0]!="":
            print("Way to go",b[0][0])
            return b[0][0]
        if b[2][0]==b[1][1] and b[1][1]==b[0][2] and b[2][0]!="":
            print("Way to go",b[2][0])
            return[2][0]



    return ""

def boardIsFull(boardLoL):
    return False




def main():
    boardLoL=[["","",""],["","",""],["","",""]]
    markerList=["O","X"]
    validMoveList=["0,0","0,1","0,2","1,0","1,1","1,2","2,0","2,1","2,2"]
    joe=cTurtle.Turtle()
    joe.setWorldCoordinates(-2,3,4,-1)
    joe.ht()
    currentPlayer=random.randint(0,1)
    DrawTicTacToeBoard(joe)
    move = ""
    while boardIsFull(boardLoL)==False and gameWon(boardLoL)=="" and move !="EXIT":
        move = getValidMove(validMoveList,markerList,currentPlayer,boardLoL)
        drawMarker(joe,currentPlayer,markerList,move,boardLoL)
        currentPlayer=flipPlayer(currentPlayer)
    gameWon(boardLoL)
    boardIsFull(boardLoL)

main()

StarcoderdataJupyterScriptsDedupFiltered