DEV Community

Milkman
Milkman

Posted on

Tic-tac-toe with Python

Hi there, this my first ever post. I'm doing this as part of my study to learn computer science. I started learning python 6 months ago, but gonna be honest here, I didn't take it seriously and procrastinated a lot. I just realized a couple months ago that in one year I'll be going to university, so I really should learn a bit about computer science. So I started learning python a bit more seriously now and I'll be sharing about my first program that I created by myself, which is a tic-tac-toe game.

So here's a rundown to my program

So firstly I used a dictionary to assign each of the boxes, with letters going to the left and numbers going downDictionary

I then created an infinite loop using while True where each turns will be played. In that loop I also created a function called GameCondition to see determine the winners of the game. Alt Text (Note: I really don't know if this part of the program can be improved, but this is the best that I could think of.)

This is the part where we will get the inputs from the players Alt Text In this part, we first get the input from the user. Because I made the dictionary with uppercase letters, I also used the upper function to make all the inputs uppercased. After that we determine if the player is X or O by counting the number of turns that have been played. Because we start with X, the one with even numbers will always be X and O will always be y, so I just used a conditional statement to determine if the number of rerun is odd or not. After that we use the GameCondition function to see if there has been a winner or not. If it returns false, the code will print the board again and continue to loop again. If it returns True, the code will print the final result and breaks from the loop, hence stopping the code.

(Note: I did realize that I need a way to determine if that particular dictionary has been taken by another player or has been played, but I haven't figured out how to solve that problem, so I'll probably improve my code down in the future.)

Discussion (0)