VisuAlg Web

Jogo da velha em Python: matriz e posições

Nesta versão Python, o exemplo aplica matriz 3x3, validação de entrada e alternância de turnos em laços.

Nesta versão Python, o exemplo aplica matriz 3x3, validação de entrada e alternância de turnos em laços.

Exemplo de códigoPython

import os

m = [["-"] * 3 for _ in range(3)]

def show_board():
    os.system("cls" if os.name == "nt" else "clear")
    print(" Tic-Tac-Toe (Engine)")
    print("")
    for l in range(3):
        for c in range(3):
            print(f"[{m[l][c]:1}]", end=" ")
        print("")

# Making manual moves on the board:
m[1][1] = "X"
m[0][2] = "O"

show_board()
Exemplo de códigoPython

import os

m = [["-"] * 3 for _ in range(3)]

def show_board():
    os.system("cls" if os.name == "nt" else "clear")
    print(" Tic-Tac-Toe (Collision Bonus)")
    print("")
    for l in range(3):
        for c in range(3):
            print(f"[{m[l][c]:1}]", end=" ")
        print("")

for turn in range(1, 9 + 1):
    current_symbol = "X" if turn % 2 == 1 else "O"

    show_board()
    print("")
    print("Player turn: ", current_symbol)

    print("Which row do you want to play? ", end="")
    played_row = int(input())
    print("Which column do you want to play? ", end="")
    played_col = int(input())

    if played_row < 1 or played_row > 3 or played_col < 1 or played_col > 3:
        print("Invalid position! Lose the turn.")
    else:
        l = played_row - 1
        c = played_col - 1
        if m[l][c] == "-":
            m[l][c] = current_symbol
        else:
            print("Cell already occupied! Lose the turn.")

show_board()
print("End of game!")