Python TIC TAC TOE Tutorial | Beginner Friendly Tutorial

Code Coach
6 Mar 202125:14

Summary

TLDREn este video, se presenta un proyecto básico de juego de tic-tac-toe en Python que incluye la creación de un tablero de juego, la toma de entrada del jugador, la verificación de ganador o empate y la implementación de un bot AI simple. El tutorial es ideal para principiantes en programación y sirve para reforzar habilidades fundamentales antes de abordar proyectos más avanzados.

Takeaways

  • 🎯 El proyecto básico de Tic-tac-toe es un excelente ejercicio para principiantes en programación.
  • 📝 La creación del tablero de juego implica definir una lista de 3x3 con guiones para marcar las casillas.
  • 🔄 La función 'print board' es crucial para visualizar el estado actual del tablero de juego.
  • 🤖 El manejo de la entrada del jugador y la actualización correspondiente en el tablero es una parte fundamental del juego.
  • ✅ La verificación de ganador o empate es esencial para determinar el resultado de la partida.
  • 🔄 La función 'check horizontal' y 'check row' se utilizan para verificar las posibles victorias en líneas horizontales o verticales.
  • 🔄 La función 'check diagonal' verifica si hay una victoria en las líneas diagonales del tablero.
  • 👥 La función 'switch player' permite alternar entre los jugadores X e O después de cada movimiento.
  • 💡 La implementación de un bot AI básico para el juego añade un reto adicional al proyecto.
  • 🔗 Compartir y comentar el código en GitHub permite la colaboración y el mejoramiento continuo del proyecto.
  • 📈 Los tutoriales avanzados en programación pueden incluir la creación de bots AI más sofisticados para juegos como el Tic-tac-toe.

Q & A

  • ¿Qué proyecto se aborda en el video de hoy?

    -El proyecto abordado en el video es el clásico juego de tic-tac-toe, creando una versión que se ejecuta en la consola de Python y incluye un bot de AI básico.

  • ¿Cuál es la primera tarea que se debe realizar al desarrollar este proyecto de tic-tac-toe?

    -La primera tarea es crear un tablero de juego, que en este caso se realiza imprimiendo un tablero de 3x3 con guiones.

  • ¿Cómo se toman las decisiones de los jugadores en el juego?

    -Las decisiones de los jugadores se toman a través de la función de entrada de usuario, donde se les pide que seleccionen un número del 1 al 9, cada número corresponde a una casilla del tablero de juego.

  • ¿Cómo se verifica si hay un ganador en el juego de tic-tac-toe?

    -Se verifica si hay un ganador comprobando las tres posiciones horizontales, verticales y diagonales del tablero. Si todas las casillas en una de estas líneas coinciden y no están vacías, se ha encontrado un ganador.

  • ¿Cómo se implementa un tablero de juego legible por los usuarios?

    -Se implementa un tablero de juego legible imprimiendo cada fila del tablero con guiones adicionales para separar las casillas y hacer que el tablero se asemeje al juego tradicional de tic-tac-toe.

  • ¿Qué función se utiliza para imprimir el tablero de juego?

    -La función utilizada para imprimir el tablero de juego se llama 'print_board', y acepta como argumento el tablero en sí.

  • ¿Cómo se maneja el cambio de turno entre jugadores?

    -El cambio de turno se maneja mediante la función 'switch_player', que simplemente intercambia el valor de la variable 'current_player' entre 'X' y 'O'.

  • ¿Cómo se define y se implementa la función 'check_for_win' para verificar si hay un ganador?

    -La función 'check_for_win' se define llamando a otras funciones como 'check_horizontal', 'check_rows' y 'check_diagonals', y utiliza sus valores de retorno para determinar si hay un ganador. Si alguna de estas funciones devuelve 'True', significa que se ha encontrado un ganador y la función 'check_for_win' también devuelve 'True'.

  • ¿Cómo se verifica si hay un empate en el juego?

    -Se verifica si hay un empate comprobando si no hay guiones ('-') en el tablero. Si no hay guiones, significa que todas las casillas están ocupadas y no hay un ganador, por lo que es un empate.

  • ¿Qué es el módulo de Python que se utiliza para dar movimientos al bot de AI?

    -El módulo de Python utilizado para dar movimientos al bot de AI es el módulo 'random', que permite generar números aleatorios para seleccionar casillas en el tablero.

  • ¿Cómo se llama la función que permite al bot de AI hacer su movimiento?

    -La función que permite al bot de AI hacer su movimiento se llama 'computer_move', y utiliza el módulo 'random' para seleccionar una casilla al azar en el tablero.

  • ¿Cómo se puede mejorar el bot de AI para que no sea tan básico?

    -Para mejorar el bot de AI, se podría implementar un algoritmo más avanzado que tome en cuenta las jugadas anteriores y realice movimientos estratégicos en lugar de moverse solo por azar.

Outlines

00:00

📝 Introducción al Proyecto Tic-Tac-Toe

En este primer párrafo, se presenta el objetivo del video: desarrollar un proyecto básico de un juego de tic-tac-toe en Python. El proyecto tiene como finalidad reforzar y probar habilidades fundamentales de programación antes de abordar proyectos más avanzados. Se menciona la creación de un tablero de juego, la aceptación de entrada del jugador y la implementación de un AI básico. Además, se destaca la importancia de definir características y variables globales para el buen funcionamiento del juego.

05:02

🎨 Diseño y Visualización del Tablero

Este segmento se centra en la creación y visualización del tablero de tic-tac-toe. Se describe la función 'print board' que permite imprimir cada fila del tablero con una representación visual que se asemeja al juego tradicional. Se discute la adición de líneas horizontales de guiones para mejorar la apariencia. También se aborda la función 'define player input', que permite al usuario ingresar un número de 1 a 9 correspondiente a una casilla en el tablero, siempre y cuando la posición esté disponible.

10:02

🏆 Verificando Ganadores y Empates

En este apartado, se detallan las funciones para verificar si hay un ganador o un empate en el juego de tic-tac-toe. Se explica cómo se deben verificar las condiciones para ganar horizontal, vertical y diagonalmente. Se presentan las funciones 'check horizontal', 'check row' y 'check diag' para realizar estas verificaciones, y se utiliza la variable global 'winner' para almacenar el resultado. Además, se introduce la función 'check tie' para determinar si el juego ha terminado en un empate.

15:03

🔄 Cambiando de Jugador y Comportamiento del Juego

Este párrafo cubre la función 'switch player', que permite alternar entre los jugadores X y O después de cada turno. También se describe la función 'check for win', que combina los resultados de las funciones de verificación de ganador para determinar si el juego ha terminado. Finalmente, se menciona la necesidad de una función 'computer' para que el computador haga movimientos aleatorios en el juego, proporcionando un oponente básico para el jugador humano.

20:11

🤖 Implementación de un AI Básico y Finalización del Juego

En el último párrafo, se aborda la implementación de un AI básico que permite al computador jugar contra el usuario. Se utiliza el módulo 'random' de Python para que el computador seleccione un movimiento aleatoriamente. La función 'computer' se encarga de asignar un movimiento al computador y actualiza el tablero en consecuencia. Además, se describe cómo se repite el proceso de verificación de ganadores y empates, y cómo se alterna entre los jugadores hasta que se determine un ganador o se declare un empate.

Mindmap

Keywords

💡proyecto de programación

El término 'proyecto de programación' se refiere a una tarea o conjunto de tareas que un programador o un equipo de programadores trabajan para crear un software o sistema. En el video, el proyecto de programación es un juego de tic-tac-toe, que es un ejemplo clásico para principiantes para practicar y mejorar sus habilidades de codificación.

💡juego de tic-tac-toe

El 'juego de tic-tac-toe' es un juego de estrategia simple para dos jugadores en el que se marcan 'X' o 'O' en una cuadrícula de 3x3. El objetivo es hacer una línea horizontal, vertical o diagonal de propios símbolos antes que el oponente. En el video, el juego se implementa en Python y se incluye la creación de un AI básico para jugar contra el usuario.

💡código

El 'código' es la serie de instrucciones escritas en un lenguaje de programación que un ordenador puede entender y ejecutar. En el video, el código es la base para crear el juego de tic-tac-toe, incluyendo la lógica para manejar la entrada del jugador, la representación de la tabla de juego y el algoritmo para el AI.

💡Python

Python es un lenguaje de programación de alto nivel, conocido por su legibilidad y simplicidad de uso. En el video, Python es el lenguaje de programación utilizado para desarrollar el juego de tic-tac-toe, mostrando cómo se pueden realizar proyectos simples y posiblemente más complejos en este lenguaje.

💡consola

La 'consola' es una interfaz de usuario que permite a los usuarios interactuar con el sistema o un programa a través de comandos escritos. En el contexto del video, la consola se refiere a la ventana de texto en la que se ejecuta el juego de tic-tac-toe creado en Python.

💡AI básico

El término 'AI básico' se refiere a una inteligencia artificial sencilla que puede realizar tareas o juegos simples sin la necesidad de un sistema complejo o avanzado. En el video, el AI básico es un componente del juego de tic-tac-toe que permite al usuario jugar contra la computadora en lugar de un oponente humano.

💡variables globales

Las 'variables globales' son variables que se definen fuera de cualquier función o bloque de código y están disponibles para todo el programa. En el video, las variables globales se utilizan para almacenar información crítica para el juego, como el tablero de juego, el jugador actual y la condición de victoria o empate.

💡bucle de juego

El 'bucle de juego' es una sección de código que se repite continuamente durante el juego, controlando el flujo de la juego y las interacciones del jugador. En el video, el bucle de juego se ejecuta hasta que se determine un ganador o se establezca un empate.

💡funciones

Las 'funciones' son bloques de código reutilizables que se pueden llamar desde diferentes partes de un programa. En el video, se definen varias funciones para manejar tareas específicas del juego, como imprimir el tablero, tomar la entrada del jugador, verificar la condición de victoria o empate y realizar un movimiento del AI.

💡entrada del jugador

La 'entrada del jugador' se refiere a la interacción del usuario con el juego, donde se introducen comandos o acciones que afectan el juego. En el video, la entrada del jugador es crucial para el avance del juego de tic-tac-toe y se obtiene a través de la función 'player input'.

💡condición de victoria

La 'condición de victoria' es la situación en la que un jugador logra ganar el juego siguiendo ciertas reglas. En tic-tac-toe, las condiciones de victoria incluyen tener una línea horizontal, vertical o diagonal de símbolos del jugador. El video muestra cómo programar el juego para reconocer y declarar una victoria cuando se cumple una de estas condiciones.

Highlights

The video focuses on creating a classic tic-tac-toe game in Python, a project most programmers have attempted at least once.

The tic-tac-toe game will run in the Python console and will include a basic AI bot.

The project is designed to reinforce and test beginner programming skills before moving on to more advanced projects.

The first step in creating the game is to design the game board, which is a 3x3 grid of dashes initially.

Global variables are introduced to help with the game's logic, including the board, current player, winner, and game running status.

A function to print the game board is created for better readability and user experience.

Player input is taken using Python's built-in input function, with the user prompted to select a number from one to nine.

The input is validated to ensure it is a valid position on the board and not already occupied.

A game loop is established to continuously cycle through the game's processes.

Functions are created to check for winning conditions horizontally, vertically, and diagonally.

A tie is checked for by ensuring no dash remains on the board, indicating all positions are filled.

The player's turn is switched after each move, alternating between 'X' and 'O'.

A 'check for win' function is created to consolidate the win condition checks and streamline the game logic.

A basic AI bot is introduced that makes random moves on the board.

The AI bot's implementation uses Python's random module to select its moves.

The game continues to check for win or tie conditions after the AI bot's move.

The video encourages viewers to engage by liking, subscribing, and commenting for more advanced tutorials and projects.

A GitHub link is provided for viewers to compare their code with the tutorial's code.

Transcripts

play00:00

hey everyone so in today's video we're

play00:02

going to be focusing on a beginner

play00:04

project that nearly

play00:05

every single programmer has made at

play00:07

least once

play00:08

this project is the classic tic-tac-toe

play00:11

game

play00:12

here we're going to make a tic tac toe

play00:14

game that runs in the actual python

play00:16

console and even make a very basic ai

play00:18

bot at the end

play00:20

this video should reinforce and test a

play00:22

lot of those beginner skills

play00:23

that you need to work on before you

play00:25

start working on more advanced projects

play00:28

so if you like this code project

play00:29

showcase i have many more advanced

play00:31

projects

play00:32

ready to be shown off okay so let's get

play00:35

right into the code

play00:36

so before you start any sort of project

play00:39

and especially before you start any

play00:40

projects at larger scales

play00:42

you want to think about what features do

play00:44

i need to create to make this functional

play00:46

so with tic tac toe what do we need to

play00:49

do

play00:50

well first we should probably create

play00:51

some sort of game board so

play00:53

maybe our first task would be printing

play00:58

the game board then

play01:01

after that we want to take some sort of

play01:03

player input and then actually put that

play01:05

onto the board

play01:06

so take player input

play01:10

then after that we want to check to see

play01:12

if that player input

play01:14

resulted in a win or a tie so

play01:17

check for win or tie then

play01:20

after that we're going to want to switch

play01:22

the player

play01:26

and then we want to check to see if that

play01:28

player won

play01:29

on their move so we're gonna check

play01:32

for win or tie again so with all that

play01:35

said we can just loop through all this

play01:37

continuously

play01:38

and we should have a working tic-tac-toe

play01:41

game

play01:42

all right so what are we going to need

play01:45

to do first

play01:46

before we start off i kind of want to

play01:48

set some global variables that are going

play01:50

to help us a little bit later

play01:52

so i think our first global variable is

play01:54

actually going to be our board piece

play01:56

right and for this board we're going to

play01:57

be creating a list so

play01:59

let's create this list called board and

play02:02

we're going to set it equal

play02:03

to a three by three square

play02:06

of dashes

play02:10

whoops i'm going to put that there then

play02:13

i'm going to go down

play02:14

here

play02:21

and then one more list

play02:29

all right so here we have our game board

play02:32

all right and we're going to set

play02:33

one more global variable and we're going

play02:35

to set equal to the current player

play02:37

all right so let's initialize this

play02:40

variable

play02:40

with the string x

play02:44

so we're going to start off every game

play02:46

with player x

play02:47

all right we're going to do two more

play02:49

variables the first one of those is

play02:51

going to be the winner variable

play02:52

and we're going to initialize this first

play02:54

with no value right

play02:55

because we don't have any value of

play02:57

winner and then

play02:59

once we start making that game loop we

play03:01

can actually tell

play03:02

the computer that when the winner equals

play03:05

x

play03:05

0 or if it's a tie to actually break out

play03:08

of that loop

play03:09

and then this loop is going to be

play03:10

controlled by our last global variable

play03:12

which is the game

play03:14

running variable and we're going to set

play03:16

that equal to true

play03:17

to start it off all right so now let's

play03:20

try to make a function to print this

play03:21

game board and let's

play03:23

make it in a form that is a little

play03:26

easier for a

play03:27

user to read all right so let's go down

play03:29

here and make our first function

play03:31

and we're going to call it defining

play03:32

print board

play03:34

and this function is going to take in

play03:37

one argument which is actually the board

play03:38

all right so making this all we're going

play03:42

to do

play03:42

is print each row of the board

play03:46

all right so let's go in

play03:49

and do three separate print statements

play03:51

so

play03:52

we're gonna do board bracket zero

play03:56

and then i'm gonna put a little bit of a

play03:57

space in between and i'm going to do

play03:59

that little pipe

play04:00

there just so it resembles the um

play04:04

tic tac toe board a little bit more all

play04:06

right we're going to do the same thing

play04:08

again

play04:10

and then board bracket 2 all right on

play04:13

the next line

play04:15

we're gonna print board

play04:18

bracket three

play04:21

plus pipe

play04:26

plus board bracket two

play04:29

plus the pipe

play04:33

plus board bracket

play04:36

five i'm gonna go back and fix that

play04:38

because that shouldn't be a

play04:39

two should be a four alright and then

play04:42

i'm actually gonna

play04:44

copy this line down to the next one

play04:47

just to speed things up a little bit and

play04:49

we're gonna hit it with

play04:51

six seven

play04:55

and eight all right so

play04:59

well if we actually call this function

play05:01

let's call

play05:02

print board and let's pass in board

play05:06

if we actually run it over here

play05:12

all right we got this board right here

play05:14

all right so you guys get the idea we

play05:16

got the three by three square

play05:17

but let's take this one step further all

play05:20

right

play05:20

how about inside of each after each one

play05:23

of these print statements

play05:24

we just add a horizontal row of dashes

play05:27

just to make it look

play05:28

a little bit better so we can say print

play05:31

and then let's just kind of eyeball it

play05:33

maybe like

play05:35

eight maybe that'll work we'll kind of

play05:38

just play around with it and see

play05:40

how many dashes is the correct amount of

play05:42

dashes

play05:44

all right now let's run it again

play05:48

uh let's add like two more dashes then

play05:56

perfect i think that's good enough good

play05:58

enough for me all right so now that we

play06:00

have that print board function down i

play06:01

think we're ready to

play06:03

take the next step and take some sort of

play06:05

player input

play06:07

so let's make that function all right

play06:09

define

play06:10

player input and that also is going to

play06:14

take in one

play06:14

argument and we're going to call it

play06:16

board just for this like a read

play06:17

code readability and i think the easiest

play06:20

way

play06:21

to take player input for a tic-tac-toe

play06:23

game that is running the console is to

play06:24

just

play06:24

use the inbuilt python function

play06:28

input all right so what we're going to

play06:30

do is we're going to ask the user to

play06:31

select a number

play06:32

one through nine and each number is

play06:34

going to correspond with

play06:36

a section on the game board so let's go

play06:39

up here

play06:40

one would be right here two right here

play06:42

nine down here you guys get the idea

play06:45

all right so let's create a variable

play06:47

let's call it inp

play06:48

and then we're going to set it equal to

play06:50

the input function and then we're going

play06:51

to prompt the user to

play06:53

enter a number one through nine

play06:57

all right but if you guys know anything

play06:59

about this

play07:00

input function the input the native

play07:03

python input function is it always

play07:05

returns a string

play07:07

value all right but if we're going to

play07:09

want to work with the indexes

play07:10

in this board we're going to want that

play07:12

in the form of an integer

play07:14

but quick fix for that we can just

play07:17

tap into the int conversion so now we

play07:21

got a number one through nine from the

play07:22

user

play07:23

all right so what we're gonna do is

play07:27

we need to take this input and we need

play07:29

to check to see if it is a valid

play07:31

position on the board

play07:32

meaning that it is a number one through

play07:34

nine and it's also

play07:36

a position that is not that is not

play07:39

occupied by the other player so what we

play07:42

can do

play07:43

is we can say if input

play07:47

is greater than or equal to one

play07:52

and input is

play07:55

less than or equal to nine

play07:58

and board

play08:01

bracket inp minus 1

play08:05

equals a dash then what we can do is set

play08:09

the board bracket input minus

play08:12

one equal

play08:15

to that current player variable that we

play08:17

have above

play08:18

so let's take a look at what i just

play08:20

wrote here these first two

play08:23

expressions make sure that the input is

play08:25

a valid number

play08:26

one through nine then this one right

play08:29

here

play08:30

checks to see that the at the bot at the

play08:33

position

play08:34

and the board that the player inputted

play08:36

that there's a dash there meaning that

play08:38

no player has gone there yet and then

play08:40

down here

play08:41

we set that position equal to the

play08:42

current player

play08:44

so then what we can also do is say let's

play08:47

say that

play08:48

whatever input in there was invalid for

play08:50

whatever reason we can just tell the

play08:52

user

play08:54

oops

play08:59

player is already in that spot or

play09:03

whatever message you want to say there

play09:07

all right so how about we go down here

play09:10

and we just start that game loop and we

play09:12

can start seeing all these parts

play09:13

work together so let's create a while

play09:15

loop and say while

play09:17

the game is running we're going to first

play09:20

print board and then

play09:23

pass in the board and then we're gonna

play09:26

have

play09:27

the player input and we're gonna pass in

play09:30

the board there as well

play09:31

so when we run this we can enter number

play09:35

one through nine let's just put three

play09:37

and now we got the x there and let's put

play09:40

five and then we can put six

play09:43

right but we're gonna keep going on and

play09:45

on we don't have a switching player we

play09:47

can't check it

play09:48

blah blah blah all right so we're in an

play09:49

endless loop here so i'm just going to

play09:51

close

play09:51

out of that all right so now we can move

play09:55

on for the next section which is

play09:56

checking for

play09:57

win or a tie so you guys know

play09:59

tic-tac-toe you know that there's the

play10:00

three ways to win you can win

play10:02

horizontally

play10:03

you can win up and down or you can win

play10:05

diagonally all right so we're going to

play10:06

need to check

play10:07

each one of those conditions okay so

play10:11

let's check the horizontal first so

play10:14

we're going to create a function called

play10:16

check horizontal all right

play10:19

and we're going to put in the board here

play10:24

and we're also going to tap into one of

play10:25

the global variables we made earlier

play10:28

which is that winner variable

play10:31

right because we're gonna after all

play10:33

we're checking to see if there's a

play10:34

winner

play10:35

so we're gonna put in global winner

play10:38

this global keyword basically says that

play10:40

we're gonna

play10:41

if we make changes to the winner

play10:44

variable within the scope of this

play10:45

function

play10:46

the winner variable changes within the

play10:48

scope of the entire file

play10:50

now if you guys don't understand that

play10:52

then here's a concept

play10:53

so when every single variable you make

play10:55

in python has a certain scope to it

play10:58

right

play10:58

if you create a variable if you define a

play11:00

variable within a function

play11:02

that variable is valid for everything

play11:05

within that function

play11:06

and then if you make a variable that is

play11:09

valid for everything in the file like we

play11:10

did up here

play11:11

we call those global variables right now

play11:14

if we want to

play11:15

modify a variable like that within a

play11:17

function we can just use the global

play11:19

keyword and the computer will know

play11:20

that hey we want to make changes to the

play11:22

global variables

play11:24

all right so now that we've said this we

play11:27

can check the horizontals

play11:28

right so we're going to do that with a

play11:31

few

play11:32

if statements so we can say if board

play11:35

bracket

play11:36

0 equals board bracket 1

play11:39

which equals board bracket two

play11:44

and board bracket one

play11:48

does not equal a dash

play11:51

right going over what i just did there

play11:53

we just checked that if

play11:54

the board at each one of these positions

play11:57

are equal to each other

play11:58

and it does not equal this then we know

play12:00

that whatever the player is there

play12:02

must be the winner so

play12:05

we can say we can set that winner

play12:08

equal to whatever players at these

play12:11

positions so we're going to say

play12:13

winner equals board bracket zero you

play12:15

could say winner equals word bracket one

play12:17

or

play12:17

winner equals four bracket two it

play12:19

doesn't matter because all these values

play12:20

are equal okay and what we're also going

play12:23

to do here

play12:24

is return true

play12:28

okay this is going to come in handy

play12:30

later when we're actually

play12:32

calling all these functions together to

play12:34

check for different conditions right

play12:35

and if something returns true then we

play12:37

can say we can do

play12:38

if statements with the function so that

play12:41

we can say

play12:42

if check horizontal is true then

play12:45

we can break out the game loop or

play12:47

something like that right

play12:48

so now let's do

play12:52

elif board bracket

play12:55

three equals four

play12:58

bracket four equals board bracket

play13:02

five and board bracket

play13:06

three does not equal a dash

play13:10

winner equals

play13:13

board bracket three and we can return

play13:17

true again and then for the last one we

play13:20

can do elif

play13:21

board bracket six

play13:26

equals four bracket seven which equals

play13:29

board

play13:30

bracket a and board bracket

play13:34

six does not equal a dash

play13:38

all right and then we're gonna do the

play13:39

same thing set winner equal to board

play13:42

bracket

play13:42

six now we're going to return true

play13:45

all right so we got the first one of

play13:47

these done okay so now we gotta move on

play13:49

and we gotta check the rows

play13:52

okay so let's define a new function

play13:54

again called check

play13:55

row we're also gonna pass in one

play13:57

argument to it board

play13:58

we're gonna tap into that global winner

play14:02

variable

play14:02

and then now we're going to do the if

play14:03

statements again so if

play14:05

board bracket 0 equals

play14:09

and then for the rows the next one would

play14:11

be board

play14:12

bracket 3 the next one would be board

play14:15

bracket six they go up by three each

play14:17

time

play14:18

and then board brackets zero

play14:22

is not equal

play14:26

and we can set the winner equal to any

play14:28

one of these

play14:30

and then we can return true again

play14:33

and then i'm going to copy this right

play14:36

here so then i'm going to hit it with

play14:39

the elif

play14:40

and then place that in and then i'm

play14:43

going to

play14:44

change these a little bit so this one

play14:46

would be

play14:47

the next position which would be one and

play14:49

then this would be a

play14:50

four and then this would be a seven

play14:54

and this one would just be one and then

play14:57

we're going to set

play14:58

the winner equal to the 1 and then

play15:02

we're going to do elf again we're going

play15:04

to copy that down

play15:06

we can do 0 1 2

play15:11

five then eight and then back down to

play15:15

two

play15:15

for here and then we can do

play15:18

two okay so now that we have the check

play15:21

row we have to check horizontal this one

play15:23

will be a little bit shorter because all

play15:25

we have to do is check the two

play15:26

horizontals

play15:27

right

play15:31

oh not check um check diagonal that's

play15:33

what i meant to say

play15:35

let me say check diag set it equal or

play15:38

passing the board argument sorry and

play15:41

then tap into that global winner

play15:42

variable

play15:43

and then we all we got to do is say if

play15:46

board

play15:46

bracket zero um equals board bracket

play15:51

four which equals board bracket 8.

play15:59

that's not on board and board

play16:03

bracket 0 does not equal

play16:07

dash winner

play16:10

equals board bracket zero

play16:14

return true and

play16:17

elif

play16:20

board bracket two

play16:23

equals board bracket four

play16:28

which equals board bracket six

play16:32

and four bracket two does not equal a

play16:36

dash then winner

play16:40

equals board bracket two

play16:44

returning true okay

play16:47

so now that we got all three of these

play16:49

functions we should be able to check

play16:52

for any sort of if any player wins

play16:55

right but now let's check to see if

play16:58

there's a tie

play16:59

and this is very very easy to implement

play17:02

okay

play17:03

so let's say check tie and pass in board

play17:07

and then all we have to do is one

play17:09

conditional statement

play17:10

okay so now we can say if that

play17:14

dash is not in the board

play17:19

then all we have to do is

play17:23

we can print out that game board again

play17:26

right and then we can just

play17:30

tell the user

play17:34

that it's a tie

play17:39

and then what we can do is also we can

play17:42

tap

play17:42

into that game running variable

play17:46

and then we can set game

play17:50

running equal to false

play17:53

all right so all we got to do is since

play17:55

this is a list we can check to see

play17:57

if that list contains this variable this

play18:00

value and if it doesn't then we know

play18:01

that all the

play18:02

positions are taking up and there's not

play18:04

any winner so there must be a tie

play18:07

okay so now that we've done this we are

play18:10

ready

play18:10

to switch the player okay

play18:14

so let's come down here and make that

play18:17

new function

play18:18

switch player

play18:22

okay we don't need to pass any arguments

play18:23

into this because we're not going to be

play18:24

making amount of any modifications to

play18:26

the board

play18:27

and this will be very easy to do so

play18:30

let's set

play18:31

let's bring in that current player

play18:34

global variable and all we got to do is

play18:36

say

play18:37

if the current player double equal

play18:40

assigns

play18:41

x then we can set the current player

play18:45

equal to o

play18:48

so notice what i did here the double

play18:51

equal sign

play18:52

for the boolean expression checking to

play18:54

see if that current player at this

play18:56

moment

play18:56

is equal to x and if that's so then

play18:59

we're

play18:59

reassigning that value to o with

play19:02

the single equal sign okay

play19:05

and then oh we get then in any other

play19:08

case

play19:09

else we can

play19:12

assign the current player equal to x

play19:15

okay so we're getting very close to

play19:19

finishing this

play19:20

okay so now that we have created all

play19:22

these functions

play19:23

to check to see if there's a winner

play19:25

we're going to create one more master

play19:27

function

play19:27

just so we don't have to type all these

play19:28

into the game running variable all right

play19:30

so let's come down here

play19:32

let's say define check for win

play19:36

all right and then we're going to pass

play19:38

in all these things

play19:40

right so remember when i said above that

play19:42

we're going to use these return true

play19:44

methods

play19:45

or return true values later so what we

play19:47

can do is we can say

play19:48

if check diagonals

play19:52

or check horizontals or

play19:56

check row

play20:00

and then we're going to pass in the

play20:02

board to all these

play20:11

and we're also going to pass in the

play20:13

board up to here

play20:17

actually we don't need to do that up

play20:18

there we're going to come down here

play20:20

and we're going to say print and then

play20:23

we're going to utilize an

play20:24

f string here for those who don't know f

play20:26

strings it's just a faster way to type

play20:28

in strings instead of having to

play20:29

do that plus

play20:33

some other thing right you can just do

play20:36

an

play20:36

f string and say okay the winner is

play20:40

and then put within what in curly

play20:41

brackets whatever you want to do and we

play20:42

can

play20:43

tap in to the winner

play20:47

okay and then what we can also do

play20:50

is now that we have this made

play20:53

we can come down to our game loop and we

play20:56

can say we can take the player input

play20:58

and then we can check if check when

play21:03

and then we can check tie

play21:08

and then we can actually call that

play21:11

switch

play21:11

player method

play21:17

and then we're going to pass the board

play21:19

for that

play21:21

okay so now we actually run this we

play21:24

enter a number

play21:25

one okay now the next step is o

play21:28

next step is x okay now we can go down

play21:31

and we can say

play21:32

five six and then eight

play21:35

and then say okay here it is the winner

play21:38

is

play21:38

o all right so now let's create

play21:41

some sort of ability for the computer

play21:46

to make some moves so we don't have to

play21:48

um continue to go against ourselves

play21:51

okay so let's make a new function and

play21:54

we're going to come down here

play21:55

and create a computer okay so let's

play21:57

define this function

play21:59

computer and what we're going to

play22:00

actually do is

play22:03

pass in the board variable again but

play22:05

we're going to actually import

play22:07

a python module that you guys should

play22:09

become very familiar with as the more i

play22:11

use python

play22:12

and that is the random module okay

play22:15

so this this bot may not be very good at

play22:18

the game

play22:19

but at least it's going to be able to

play22:20

make a move okay

play22:22

so let's just create a loop for whenever

play22:25

the

play22:25

whenever the computer is up to make a

play22:27

move and we want to create a loop

play22:29

because if we're using something random

play22:31

then

play22:32

it might take a couple random iterations

play22:35

for it to find a spot on the board

play22:36

that's not already taken by another

play22:37

player

play22:38

okay and let's make the o the bot for us

play22:41

okay

play22:42

so let's say while um the player

play22:46

uh current player

play22:50

is equal to o

play22:53

we're going to tap into that random

play22:54

module and we're going to generate a

play22:56

random number

play22:57

zero to eight okay because that those

play23:00

correspond to different spots on our

play23:01

board

play23:02

so let's create a variable called

play23:03

position okay

play23:08

and we're going to set it equal to

play23:10

random.rand

play23:11

int and then we're going to do it from

play23:15

0 to 8. and then now we're going to

play23:18

check to see if that position on the

play23:19

board is already occupied

play23:21

but a easy way to do this is we can just

play23:23

check to see if the board

play23:25

bracket position

play23:29

equals a dash let me know that no one

play23:31

has gone there yet and then we can set

play23:34

board bracket position

play23:38

equal to oh okay and after this happens

play23:42

all we got to do is

play23:43

just switch the player again all right

play23:46

so now if we go down here we have switch

play23:50

player and then we can call the computer

play23:53

again down here and then

play23:56

after the computer goes what do we have

play23:58

to do check for win or tie again

play24:00

so check for win

play24:06

and then check for tie

play24:14

okay so now let's run this and we should

play24:16

have a pretty

play24:18

good project so

play24:21

let's enter a number of one oh there

play24:23

that the player made a move down there

play24:25

oh man move down there two oh it might

play24:27

beat me

play24:29

there we go the winner is x and

play24:32

there you have it guys there is our tic

play24:34

tac toe game

play24:35

up and running so if you guys enjoyed

play24:37

this video please

play24:39

like and subscribe to help get my

play24:40

channel out there and then also if you

play24:43

like this type of video let me know down

play24:44

in the comments if you want to see more

play24:46

advanced tutorials

play24:47

i can also make a tic-tac-toe game that

play24:49

actually has an intelligent ai bot that

play24:51

you can go against

play24:52

so if you guys want to see that advanced

play24:54

tutorial let me know

play24:56

also if you guys want to see more

play24:57

advanced projects be sure to stay tuned

play24:59

also

play25:00

i'm going to have a link to this github

play25:02

page in the description so if you guys

play25:04

want to go and compare this to the code

play25:06

then compare your code to mine then go

play25:09

ahead and click it down there

play25:10

but that's going to be it for me thanks

play25:12

guys

Rate This

5.0 / 5 (0 votes)

Etiquetas Relacionadas
PythonProgramaciónJuegoTic-tac-toeAIBásicoTutorialCódigoConsola