#πŸ”’ Any way to optimise this code?

28 messages Β· Page 1 of 1 (latest)

hot ledge
#

Hello, my knowledge on python is quite basic and beginner, I have created a game of tic tac toe in ~40 minutes,
I was wondering if theres any way to optimise this? I dislike the fact i have elif statement on elif statement over and over again.

Text was too long so I will send it in multiple pieces

wraith treeBOT
#

@hot ledge

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

hot ledge
#
import time
import os

def clear(): #clear terminal function

    if os.name == "nt": #os.name checks what OS user is on, "nt" = windows
        os.system("cls") #"cls" is used to clear the terminal on windows
    else:
        os.system("clear") #"clear" is used to clear the terminal on anything else
#
def board():
    print(" |", a1, "|", a2, "|", a3, "|" "\n", "|", b1, "|", b2, "|", b3, "|" "\n", "|", c1, "|", c2, "|", c3, "|" "\n")
#
def player_one_move():

    while True:
        global a1, a2, a3, b1, b2, b3, c1, c2, c3

        move = input("Player 1, Please enter a move: ")

        if move.lower() == "a1" and a1 == "#":
            a1 = "X"
            break
        elif move.lower() == "a2" and a2 == "#":
            a2 = "X"
            break
        elif move.lower() == "a3" and a3 == "#":
            a3 = "X"
            break
        elif move.lower() == "b1" and b1 == "#":
            b1 = "X"
            break        
        elif move.lower() == "b2" and b2 == "#":
            b2 = "X"
            break
        elif move.lower() == "b3" and b3 == "#":
            b3 = "X"
            break
        elif move.lower() == "c1" and c1 == "#":
            c1 = "X"
            break
        elif move.lower() == "a2" and c2 == "#":
            c2 = "X"
            break
        elif move.lower() == "c3" and c3 == "#":
            c3 = "X"
            break
        else:
            print("Invalid Move")
            time.sleep(0.75)
            clear()
            board()
#
def player_two_move():

    while True:
        global a1, a2, a3, b1, b2, b3, c1, c2, c3

        move = input("Player 2, Please enter a move: ")

        if move.lower() == "a1" and a1 == "#":
            a1 = "O"
            break
        elif move.lower() == "a2" and a2 == "#":
            a2 = "O"
            break
        elif move.lower() == "a3" and a3 == "#":
            a3 = "O"
            break
        elif move.lower() == "b1" and b1 == "#":
            b1 = "O"
            break        
        elif move.lower() == "b2" and b2 == "#":
            b2 = "O"
            break
        elif move.lower() == "b3" and b3 == "#":
            b3 = "O"
            break
        elif move.lower() == "c1" and c1 == "#":
            c1 = "O"
            break
        elif move.lower() == "a2" and c2 == "#":
            c2 = "O"
            break
        elif move.lower() == "c3" and c3 == "#":
            c3 = "O"
            break
        else:
            print("Invalid Move")
            time.sleep(0.75)
            clear()
            board()          
#
def win_check():
    global game

    #Checks if player 1 won
    if a1 == a2 == a3 == "X":
        game = False
        print("GAME OVER \nPLAYER 1 WINS")
        time.sleep(3)
    elif b1 == b2 == b3 == "X":
        game = False
        print("GAME OVER \nPLAYER 1 WINS")
        time.sleep(3)
    elif c1 == c2 == c3 == "X":
        game = False
        print("GAME OVER \nPLAYER 1 WINS")
        time.sleep(3)
    elif a1 == b1 == c1 == "X":
        game = False
        print("GAME OVER \nPLAYER 1 WINS")
        time.sleep(3)
    elif a2 == b2 == c2 == "X":
        game = False
        print("GAME OVER \nPLAYER 1 WINS")
        time.sleep(3)
    elif a3 == b3 == c3 == "X":
        game = False
        print("GAME OVER \nPLAYER 1 WINS")
        time.sleep(3)
    elif a1 == b2 == c3 == "X":
        game = False
        print("GAME OVER \nPLAYER 1 WINS")
        time.sleep(3)
    elif a3 == b2 == c1 == "X":
        game = False
        print("GAME OVER \nPLAYER 1 WINS")

    #Checks if player 2 won
    elif a1 == a2 == a3 == "O":
        game = False
        print("GAME OVER \nPLAYER 2 WINS")
        time.sleep(3)
    elif b1 == b2 == b3 == "O":
        game = False
        print("GAME OVER \nPLAYER 2 WINS")
        time.sleep(3)
    elif c1 == c2 == c3 == "O":
        game = False
        print("GAME OVER \nPLAYER 2 WINS")
        time.sleep(3)
    elif a1 == b1 == c1 == "O":
        game = False
        print("GAME OVER \nPLAYER 2 WINS")
        time.sleep(3)
    elif a2 == b2 == c2 == "O":
        game = False
        print("GAME OVER \nPLAYER 2 WINS")
        time.sleep(3)
    elif a3 == b3 == c3 == "O":
        game = False
        print("GAME OVER \nPLAYER 2 WINS")
        time.sleep(3)
    elif a1 == b2 == c3 == "O":
        game = False
        print("GAME OVER \nPLAYER 2 WINS")
        time.sleep(3)
    elif a3 == b2 == c1 == "O":
        game = False
        print("GAME OVER \nPLAYER 2 WINS")
        time.sleep(3)
#
def play():
    while True:
        clear()
        board() 
        win_check()
        if game == False:
            break
        player_one_move()
        clear()
        board() 
        win_check()
        if game == False:
            break
        player_two_move()
#
#defining variables
game = True
a1 = "#"
a2 = "#"
a3 = "#"
b1 = "#"
b2 = "#" 
b3 = "#"
c1 = "#"
c2 = "#"
c3 = "#"

play()
#

Any help is highly appreciated.

quasi wasp
#

!paste instead please

wraith treeBOT
#
Pasting large amounts of code

If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.

hot ledge
#

omg, thank you so much

clear frost
#

First of all, don't use global. It's a big ick.

#

!global is hard to debug if something screws up

wraith treeBOT
#
Globals

When adding functions or classes to a program, it can be tempting to reference inaccessible variables by declaring them as global. Doing this can result in code that is harder to read, debug and test. Instead of using globals, pass variables or objects as parameters and receive return values.

Instead of writing

def update_score():
    global score, roll
    score = score + roll
update_score()

do this instead

def update_score(score, roll):
    return score + roll
score = update_score(score, roll)

For in-depth explanations on why global variables are bad news in a variety of situations, see this Stack Overflow answer.

clear frost
#

Secondly, if you have learnt dictionary, use it in this case. So you have a lot less if else statements.

quasi wasp
#

if you have learnt lists you could store the moves in a 3x3 list which you could iterate through intstead of having to check each one manually

clear frost
#

For GameDev, they use a lot of classes. So you could probably switch the dictionary for classes and make class methods for your tic tac toe game.

quasi wasp
#

what I did when I made a tic tac toe game was to assign player X = 1 and player O = -1 and then check the sum of rows, columns, and diagonals to see if they are 3 or -3 to check for a winner

#

yeah that used OOP

hot ledge
#

thanks guys, much appreciated :)

quasi wasp
#
self.board = [
            [0, 0, 0],
            [0, 0, 0],
            [0, 0, 0],
        ]``` and then whichever position X / O picks I add or subtract 1 to that square
#

if you are confused about the self everywhere that's the class attributes instead of global vars

wraith treeBOT
#
Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.