Anybody else learning Python right now? I have coded in Perl for 30 years, but I think it’s time to learn Python, so I started taking the “Automate the Boring Stuff with Python” course on Udemy. One of the examples given was a tic-tac-toe game, and since I just watched WarGames yesterday I decided I would write a tic-tac-toe game. I have never written a game in my life, either.
Interestingly I got to the “Put X in the center square” part of WarGames at exactly the same time as my course got to putting X in the center square, and I took a pic of it. I didn’t plan it that way, it just worked out that way.
Considering I’ve never written Python before, I think this is pretty good.
Also, I know of only one issue with the program: I don’t trap a bad move, so if you enter garbage for the move, it crashes. As far as I can tell, it properly detects a win or a stalemate, though, which is cool.
Constructive feedback welcome. Comments of “Convert it to OOP” not welcome.
Edited to add: I have updated it to catch an invalid move.
Sounds like you and I started using Perl around the same time. It’s so versatile, and I love its regular expression capabilities.
Python and I never got along, so I avoid it. I am in the minority.
You should take a look at Julia (the language), which might appeal to you. It uses a just in time compiler that makes it nearly as fast as C, and it has syntax similar to Python, but it uses braces instead of indents (Perl like, and important to me). Search Julia vs Python for some interesting reading, and good luck!
Thanks, I’ll check that out. I am learning Python because I need it for work. So far I’m finding some cool things, but also several annoyances. I don’t understand OOP (despite years of trying to get it), so a lot of this is gibberish to me.
Similar, I’m trying to learn JavaScript so I can create something for work (on the side). I was looking at python as well, but I’d read that a lot of people who do full stack development ( web front and js.node back ) stick with JavaScript. Cool app tho
I am still responsible for maintaining some procedural programming from the 1990s. It is written in the Clipper / Dbase language. I remember when I started programming then, how quickly we shifted to OOP because it helped us to translate real world objects into code. That is one thing we loved and was happy to move away from procedural code.
Do you still find it easy to use procedural programming?
I too hope to learn python, although time is tight. I am getting a little taste of it by using Qtile, which is done in python.
@unixdude I like your tic-tac-toe It’s perfect
Try this one by (Gemini flash 2.0) I fixed some errors.
import os
def clear_screen():
"""Clears the terminal screen."""
os.system('cls' if os.name == 'nt' else 'clear')
def draw_board(board):
"""Draws the Tic-Tac-Toe board."""
clear_screen()
print("---------")
for i in range(3):
print(f"| {board[i][0]} | {board[i][1]} | {board[i][2]} |")
print("---------")
def check_win(board, player):
"""Checks if a player has won."""
# Check rows
for row in board:
if all(cell == player for cell in row):
return True
# Check columns
for col in range(3):
if all(board[row][col] == player for row in range(3)):
return True
# Check diagonals
if all(board[i][i] == player for i in range(3)):
return True
if all(board[i][2 - i] == player for i in range(3)):
return True
return False
def check_draw(board):
"""Checks if the game is a draw."""
return all(cell != " " for row in board for cell in row)
def get_move(board, player):
"""Gets the player's move."""
while True:
try:
move = int(input(f"Player {player}, enter your move (1-9): ")) - 1
row, col = divmod(move, 3)
if 0 <= row < 3 and 0 <= col < 3 and board[row][col] == " ":
return row, col
else:
print("Invalid move. Try again.")
except (ValueError, IndexError):
print("Invalid input. Enter a number between 1 and 9.")
def tic_tac_toe():
"""Plays a game of Tic-Tac-Toe."""
board = [[" " for _ in range(3)] for _ in range(3)]
players = ["X", "O"]
current_player = 0
while True:
draw_board(board)
row, col = get_move(board, players[current_player])
board[row][col] = players[current_player]
if check_win(board, players[current_player]):
draw_board(board)
print(f"Player {players[current_player]} wins!")
break
elif check_draw(board):
draw_board(board)
print("It's a draw!")
break
current_player = 1 - current_player # Switch players
if __name__ == "__main__":
tic_tac_toe()