Tic Tac Toe - Python

Python, R, e altri linguaggi usati nella BI, per creare visualizzazioni, implementare tecniche di Machine Learning etc.
Rispondi
Avatar utente

Andrea90
Messaggi: 2192 | Topic creati
Iscritto il: dom 28 giu 2020, 19:41
Luogo: Bologna
Ringraziato: 666 volte
Contatta:

Tic Tac Toe - Python

Messaggio da Andrea90 »

Buonasera a tutti gli amici del forum :wave:

Visto che ho cominciato da poco a studiare il linguaggio Python, mi è venuta in mente l'idea di provare a creare un piccolo programmino che esegua il famoso giochino del Tic Tac Toe, utilizzando le nozioni apprese finora.

Piccolo screen della partita demo:

Immagine

Pertanto vi lascio in calce il codice utilizzato così se qualcuno fosse interessato a prenderne visione o a provarlo sul suo pc, lo può fare senza problemi, magari lasciando anche un feedback su eventuali modifiche o migliorie da apporre.

La speranza è anche quella di alimentare, con il tempo, la sezione dedicata agli altri linguaggi utili per l'analisi dati e la BI in generale, non solo quelle di PowerQuery e Power Bi (che per carità ci fa sempre piacere ricevere quesiti dagli utenti :lol: ).

Io nel frattempo continuerò ad approfondire queste tematiche, così che un domani possa fare del mio meglio per fornire un aiuto a tutti coloro che ne faranno richiesta.

Buon proseguimento con lo studio della Bi a tutti quanti :clap: ;)

A presto,

Andrea

Codice: Seleziona tutto

d = {1:1,2:5,3:9}
b = {"11":" ","12":" ","13":" ","21":" ","22":" ","23":" ","31":" ","32":" ","33":" "}
p = {"Player1":"Player2","Player2":"Player1"}

row1 = " " + b["11"] + " | " + b["12"] + " | " + b["13"] +" "
del1 = "-----------"
row2 = " " + b["21"] + " | " + b["22"] + " | " + b["23"] +" "
del2 = "-----------"
row3 = " " + b["31"] + " | " + b["32"] + " | " + b["33"] +" "
    
def board():
    # Show up the board
    row1 = " " + b["11"] + " | " + b["12"] + " | " + b["13"] +" "
    del1 = "-----------"
    row2 = " " + b["21"] + " | " + b["22"] + " | " + b["23"] +" "
    del2 = "-----------"
    row3 = " " + b["31"] + " | " + b["32"] + " | " + b["33"] +" "
    print(row1)
    print(del1)
    print(row2)
    print(del2)
    print(row3)

def clean_board(b):
    # Clean up the board
    for i in range(1,4):
        for j in range(1,4):
            cnt = str(i) + str(j)
            b[cnt] = " "
    return b

def sel_sign():
    # Let the players choose their signs
    sign1 = input("First player, please select your sign --> ")
    if len(sign1) != 1:
        print("Just one character")
        sign1 = input("First player, please select your sign --> ")
    sign2 = input("Second player want to use the character --> ").upper()
    if len(sign2) != 1 or sign2.upper() == sign1.upper():
        print("Just one character, and it must be different from that of the Player1")
        sign2 = input("Second player, please select your sign --> ")
    return sign1.upper(), sign2.upper()

def cur_ply(ply):
    # Identify the current player
    if ply == "":
        ply = "Player1"
    else:
        ply = p[ply]
    return ply

def cur_sign(sign1, sign2, cur_ply):
    # Identify the current player's sign
    if cur_ply == "Player1":
        cur_sign = sign1
    else:
        cur_sign = sign2
    return cur_sign

def player_choice_row():    
    # Let the player chooses the row where he wants to put his sign
    val_err = 1
    sel_row = 0
    while val_err != 0 or sel_row not in [1,2,3]:
        try:
            sel_row = int(input("Please select the n° row where you want to add your sign (1-3)-->"))
            val_err = 0
        except ValueError:
            val_err = 1
    return sel_row

def player_choice_col():
    # Let the player chooses the column where he wants to put his sign
    val_err = 1
    sel_col = 0
    while val_err != 0 or sel_col not in [1,2,3]:
        try:
            sel_col = int(input("Please select the n° col where you want to add your sign (1-3)-->"))
            val_err = 0
        except ValueError:
            val_err = 1
    return sel_col

def chk_choice(sel_row, sel_col):
    # Check if the row-col number is a valid choice
    valid = False
    chk = str(sel_row) + str(sel_col)
    if b[chk] == " ":
        valid = True
    return valid

def design_b(sel_row, sel_col, sign_to_use):
    # Insert the sign on the board
    chk = str(sel_row) + str(sel_col)
    b[chk] = sign_to_use

def chk_winner():
    # Check if the player has won
    winner = False
    if (b["11"] == b["12"] == b["13"]) and b["11"] != " ":
        winner = True
    elif (b["21"] == b["22"] == b["23"]) and b["21"] != " ":
        winner = True
    elif (b["31"] == b["32"] == b["33"]) and b["31"] != " ":
        winner = True
    elif (b["11"] == b["21"] == b["31"]) and b["11"] != " ":
        winner = True
    elif (b["12"] == b["22"] == b["32"]) and b["12"] != " ":
        winner = True
    elif (b["13"] == b["23"] == b["33"]) and b["13"] != " ":
        winner = True
    elif (b["11"] == b["22"] == b["33"]) and b["11"] != " ":
        winner = True
    elif (b["13"] == b["22"] == b["31"]) and b["13"] != " ":
        winner = True 
    return winner

def again():
    # Ask to continue
    vrb = ""
    while vrb.upper() not in ["Y","N"]:
        vrb = input("Do you want to keep playing (Y/N) ? ")
    if vrb.upper() == "Y":
        return True
    else:
        return False

def play():
    # main code
    ply = ""
    to_continue = True
    valid_choice = False
    winner = False
    cnt = 1
    # Define the two signs to use
    sign1, sign2 = sel_sign()
    # Define the current player
    player = cur_ply(ply)
    while to_continue != False and winner != True and cnt != 10:
        # Define the current sign based on the current player
        sign_to_use = cur_sign(sign1,sign2,player)
        while valid_choice != True:
            # Ask what is the row num
            nrow = player_choice_row()
            # Ask what is the col num
            ncol = player_choice_col()
            # Check if it is correct
            valid_choice = chk_choice(nrow, ncol)
        # Fill the selected space
        design_b(nrow, ncol, sign_to_use)
        # Show the board
        board()
        # Clear valid choice
        valid_choice = False
        # Check if there is a winner
        winner = chk_winner()
        if winner == True:
            pass
        else:
            # Counter
            cnt = cnt + 1
            if cnt == 10:
                pass
            else:
                # Ask if they want to continue
                to_continue = again()
                # Define the next player
                player = cur_ply(player)
    return player, winner, cnt

def result():
    # this is the commmand to use in order to play the tic tac toe game
    clean_board(b)

    board()
    
    player, winner, cnt = play()
    if winner == True:
        print(f"Congratulations {player}, you are the winner")
    elif winner == False and cnt == 10:
        print("This is a tie")
    else:
        print(f"{player} quit the game")
        
result()


Se hai gradito l'aiuto che hai ricevuto considera di contribuire alle spese per il mantenimento del forum facendo una libera DONAZIONE --> Link

Ricordarsi di segnare come "RISOLTE" le discussioni per le quali si è ricevuto un feedback positivo. Per vedere come fare --> Link
Rispondi