Python TIC TAC TOE Tutorial | Beginner Friendly Tutorial
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
📝 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.
🎨 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.
🏆 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.
🔄 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.
🤖 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
💡juego de tic-tac-toe
💡código
💡Python
💡consola
💡AI básico
💡variables globales
💡bucle de juego
💡funciones
💡entrada del jugador
💡condición de victoria
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
hey everyone so in today's video we're
going to be focusing on a beginner
project that nearly
every single programmer has made at
least once
this project is the classic tic-tac-toe
game
here we're going to make a tic tac toe
game that runs in the actual python
console and even make a very basic ai
bot at the end
this video should reinforce and test a
lot of those beginner skills
that you need to work on before you
start working on more advanced projects
so if you like this code project
showcase i have many more advanced
projects
ready to be shown off okay so let's get
right into the code
so before you start any sort of project
and especially before you start any
projects at larger scales
you want to think about what features do
i need to create to make this functional
so with tic tac toe what do we need to
do
well first we should probably create
some sort of game board so
maybe our first task would be printing
the game board then
after that we want to take some sort of
player input and then actually put that
onto the board
so take player input
then after that we want to check to see
if that player input
resulted in a win or a tie so
check for win or tie then
after that we're going to want to switch
the player
and then we want to check to see if that
player won
on their move so we're gonna check
for win or tie again so with all that
said we can just loop through all this
continuously
and we should have a working tic-tac-toe
game
all right so what are we going to need
to do first
before we start off i kind of want to
set some global variables that are going
to help us a little bit later
so i think our first global variable is
actually going to be our board piece
right and for this board we're going to
be creating a list so
let's create this list called board and
we're going to set it equal
to a three by three square
of dashes
whoops i'm going to put that there then
i'm going to go down
here
and then one more list
all right so here we have our game board
all right and we're going to set
one more global variable and we're going
to set equal to the current player
all right so let's initialize this
variable
with the string x
so we're going to start off every game
with player x
all right we're going to do two more
variables the first one of those is
going to be the winner variable
and we're going to initialize this first
with no value right
because we don't have any value of
winner and then
once we start making that game loop we
can actually tell
the computer that when the winner equals
x
0 or if it's a tie to actually break out
of that loop
and then this loop is going to be
controlled by our last global variable
which is the game
running variable and we're going to set
that equal to true
to start it off all right so now let's
try to make a function to print this
game board and let's
make it in a form that is a little
easier for a
user to read all right so let's go down
here and make our first function
and we're going to call it defining
print board
and this function is going to take in
one argument which is actually the board
all right so making this all we're going
to do
is print each row of the board
all right so let's go in
and do three separate print statements
so
we're gonna do board bracket zero
and then i'm gonna put a little bit of a
space in between and i'm going to do
that little pipe
there just so it resembles the um
tic tac toe board a little bit more all
right we're going to do the same thing
again
and then board bracket 2 all right on
the next line
we're gonna print board
bracket three
plus pipe
plus board bracket two
plus the pipe
plus board bracket
five i'm gonna go back and fix that
because that shouldn't be a
two should be a four alright and then
i'm actually gonna
copy this line down to the next one
just to speed things up a little bit and
we're gonna hit it with
six seven
and eight all right so
well if we actually call this function
let's call
print board and let's pass in board
if we actually run it over here
all right we got this board right here
all right so you guys get the idea we
got the three by three square
but let's take this one step further all
right
how about inside of each after each one
of these print statements
we just add a horizontal row of dashes
just to make it look
a little bit better so we can say print
and then let's just kind of eyeball it
maybe like
eight maybe that'll work we'll kind of
just play around with it and see
how many dashes is the correct amount of
dashes
all right now let's run it again
uh let's add like two more dashes then
perfect i think that's good enough good
enough for me all right so now that we
have that print board function down i
think we're ready to
take the next step and take some sort of
player input
so let's make that function all right
define
player input and that also is going to
take in one
argument and we're going to call it
board just for this like a read
code readability and i think the easiest
way
to take player input for a tic-tac-toe
game that is running the console is to
just
use the inbuilt python function
input all right so what we're going to
do is we're going to ask the user to
select a number
one through nine and each number is
going to correspond with
a section on the game board so let's go
up here
one would be right here two right here
nine down here you guys get the idea
all right so let's create a variable
let's call it inp
and then we're going to set it equal to
the input function and then we're going
to prompt the user to
enter a number one through nine
all right but if you guys know anything
about this
input function the input the native
python input function is it always
returns a string
value all right but if we're going to
want to work with the indexes
in this board we're going to want that
in the form of an integer
but quick fix for that we can just
tap into the int conversion so now we
got a number one through nine from the
user
all right so what we're gonna do is
we need to take this input and we need
to check to see if it is a valid
position on the board
meaning that it is a number one through
nine and it's also
a position that is not that is not
occupied by the other player so what we
can do
is we can say if input
is greater than or equal to one
and input is
less than or equal to nine
and board
bracket inp minus 1
equals a dash then what we can do is set
the board bracket input minus
one equal
to that current player variable that we
have above
so let's take a look at what i just
wrote here these first two
expressions make sure that the input is
a valid number
one through nine then this one right
here
checks to see that the at the bot at the
position
and the board that the player inputted
that there's a dash there meaning that
no player has gone there yet and then
down here
we set that position equal to the
current player
so then what we can also do is say let's
say that
whatever input in there was invalid for
whatever reason we can just tell the
user
oops
player is already in that spot or
whatever message you want to say there
all right so how about we go down here
and we just start that game loop and we
can start seeing all these parts
work together so let's create a while
loop and say while
the game is running we're going to first
print board and then
pass in the board and then we're gonna
have
the player input and we're gonna pass in
the board there as well
so when we run this we can enter number
one through nine let's just put three
and now we got the x there and let's put
five and then we can put six
right but we're gonna keep going on and
on we don't have a switching player we
can't check it
blah blah blah all right so we're in an
endless loop here so i'm just going to
close
out of that all right so now we can move
on for the next section which is
checking for
win or a tie so you guys know
tic-tac-toe you know that there's the
three ways to win you can win
horizontally
you can win up and down or you can win
diagonally all right so we're going to
need to check
each one of those conditions okay so
let's check the horizontal first so
we're going to create a function called
check horizontal all right
and we're going to put in the board here
and we're also going to tap into one of
the global variables we made earlier
which is that winner variable
right because we're gonna after all
we're checking to see if there's a
winner
so we're gonna put in global winner
this global keyword basically says that
we're gonna
if we make changes to the winner
variable within the scope of this
function
the winner variable changes within the
scope of the entire file
now if you guys don't understand that
then here's a concept
so when every single variable you make
in python has a certain scope to it
right
if you create a variable if you define a
variable within a function
that variable is valid for everything
within that function
and then if you make a variable that is
valid for everything in the file like we
did up here
we call those global variables right now
if we want to
modify a variable like that within a
function we can just use the global
keyword and the computer will know
that hey we want to make changes to the
global variables
all right so now that we've said this we
can check the horizontals
right so we're going to do that with a
few
if statements so we can say if board
bracket
0 equals board bracket 1
which equals board bracket two
and board bracket one
does not equal a dash
right going over what i just did there
we just checked that if
the board at each one of these positions
are equal to each other
and it does not equal this then we know
that whatever the player is there
must be the winner so
we can say we can set that winner
equal to whatever players at these
positions so we're going to say
winner equals board bracket zero you
could say winner equals word bracket one
or
winner equals four bracket two it
doesn't matter because all these values
are equal okay and what we're also going
to do here
is return true
okay this is going to come in handy
later when we're actually
calling all these functions together to
check for different conditions right
and if something returns true then we
can say we can do
if statements with the function so that
we can say
if check horizontal is true then
we can break out the game loop or
something like that right
so now let's do
elif board bracket
three equals four
bracket four equals board bracket
five and board bracket
three does not equal a dash
winner equals
board bracket three and we can return
true again and then for the last one we
can do elif
board bracket six
equals four bracket seven which equals
board
bracket a and board bracket
six does not equal a dash
all right and then we're gonna do the
same thing set winner equal to board
bracket
six now we're going to return true
all right so we got the first one of
these done okay so now we gotta move on
and we gotta check the rows
okay so let's define a new function
again called check
row we're also gonna pass in one
argument to it board
we're gonna tap into that global winner
variable
and then now we're going to do the if
statements again so if
board bracket 0 equals
and then for the rows the next one would
be board
bracket 3 the next one would be board
bracket six they go up by three each
time
and then board brackets zero
is not equal
and we can set the winner equal to any
one of these
and then we can return true again
and then i'm going to copy this right
here so then i'm going to hit it with
the elif
and then place that in and then i'm
going to
change these a little bit so this one
would be
the next position which would be one and
then this would be a
four and then this would be a seven
and this one would just be one and then
we're going to set
the winner equal to the 1 and then
we're going to do elf again we're going
to copy that down
we can do 0 1 2
five then eight and then back down to
two
for here and then we can do
two okay so now that we have the check
row we have to check horizontal this one
will be a little bit shorter because all
we have to do is check the two
horizontals
right
oh not check um check diagonal that's
what i meant to say
let me say check diag set it equal or
passing the board argument sorry and
then tap into that global winner
variable
and then we all we got to do is say if
board
bracket zero um equals board bracket
four which equals board bracket 8.
that's not on board and board
bracket 0 does not equal
dash winner
equals board bracket zero
return true and
elif
board bracket two
equals board bracket four
which equals board bracket six
and four bracket two does not equal a
dash then winner
equals board bracket two
returning true okay
so now that we got all three of these
functions we should be able to check
for any sort of if any player wins
right but now let's check to see if
there's a tie
and this is very very easy to implement
okay
so let's say check tie and pass in board
and then all we have to do is one
conditional statement
okay so now we can say if that
dash is not in the board
then all we have to do is
we can print out that game board again
right and then we can just
tell the user
that it's a tie
and then what we can do is also we can
tap
into that game running variable
and then we can set game
running equal to false
all right so all we got to do is since
this is a list we can check to see
if that list contains this variable this
value and if it doesn't then we know
that all the
positions are taking up and there's not
any winner so there must be a tie
okay so now that we've done this we are
ready
to switch the player okay
so let's come down here and make that
new function
switch player
okay we don't need to pass any arguments
into this because we're not going to be
making amount of any modifications to
the board
and this will be very easy to do so
let's set
let's bring in that current player
global variable and all we got to do is
say
if the current player double equal
assigns
x then we can set the current player
equal to o
so notice what i did here the double
equal sign
for the boolean expression checking to
see if that current player at this
moment
is equal to x and if that's so then
we're
reassigning that value to o with
the single equal sign okay
and then oh we get then in any other
case
else we can
assign the current player equal to x
okay so we're getting very close to
finishing this
okay so now that we have created all
these functions
to check to see if there's a winner
we're going to create one more master
function
just so we don't have to type all these
into the game running variable all right
so let's come down here
let's say define check for win
all right and then we're going to pass
in all these things
right so remember when i said above that
we're going to use these return true
methods
or return true values later so what we
can do is we can say
if check diagonals
or check horizontals or
check row
and then we're going to pass in the
board to all these
and we're also going to pass in the
board up to here
actually we don't need to do that up
there we're going to come down here
and we're going to say print and then
we're going to utilize an
f string here for those who don't know f
strings it's just a faster way to type
in strings instead of having to
do that plus
some other thing right you can just do
an
f string and say okay the winner is
and then put within what in curly
brackets whatever you want to do and we
can
tap in to the winner
okay and then what we can also do
is now that we have this made
we can come down to our game loop and we
can say we can take the player input
and then we can check if check when
and then we can check tie
and then we can actually call that
switch
player method
and then we're going to pass the board
for that
okay so now we actually run this we
enter a number
one okay now the next step is o
next step is x okay now we can go down
and we can say
five six and then eight
and then say okay here it is the winner
is
o all right so now let's create
some sort of ability for the computer
to make some moves so we don't have to
um continue to go against ourselves
okay so let's make a new function and
we're going to come down here
and create a computer okay so let's
define this function
computer and what we're going to
actually do is
pass in the board variable again but
we're going to actually import
a python module that you guys should
become very familiar with as the more i
use python
and that is the random module okay
so this this bot may not be very good at
the game
but at least it's going to be able to
make a move okay
so let's just create a loop for whenever
the
whenever the computer is up to make a
move and we want to create a loop
because if we're using something random
then
it might take a couple random iterations
for it to find a spot on the board
that's not already taken by another
player
okay and let's make the o the bot for us
okay
so let's say while um the player
uh current player
is equal to o
we're going to tap into that random
module and we're going to generate a
random number
zero to eight okay because that those
correspond to different spots on our
board
so let's create a variable called
position okay
and we're going to set it equal to
random.rand
int and then we're going to do it from
0 to 8. and then now we're going to
check to see if that position on the
board is already occupied
but a easy way to do this is we can just
check to see if the board
bracket position
equals a dash let me know that no one
has gone there yet and then we can set
board bracket position
equal to oh okay and after this happens
all we got to do is
just switch the player again all right
so now if we go down here we have switch
player and then we can call the computer
again down here and then
after the computer goes what do we have
to do check for win or tie again
so check for win
and then check for tie
okay so now let's run this and we should
have a pretty
good project so
let's enter a number of one oh there
that the player made a move down there
oh man move down there two oh it might
beat me
there we go the winner is x and
there you have it guys there is our tic
tac toe game
up and running so if you guys enjoyed
this video please
like and subscribe to help get my
channel out there and then also if you
like this type of video let me know down
in the comments if you want to see more
advanced tutorials
i can also make a tic-tac-toe game that
actually has an intelligent ai bot that
you can go against
so if you guys want to see that advanced
tutorial let me know
also if you guys want to see more
advanced projects be sure to stay tuned
also
i'm going to have a link to this github
page in the description so if you guys
want to go and compare this to the code
then compare your code to mine then go
ahead and click it down there
but that's going to be it for me thanks
guys
Ver Más Videos Relacionados
5.0 / 5 (0 votes)