Как я могу реализовать функцию «check_space_taken» в python

#python #python-3.x #function

#python #python-3.x #функция

Вопрос:

мне нужно реализовать функцию, которая проверяет, занято ли место в моих крестиках-ноликах, которые воспроизводятся в терминале. проблема в том, что я не вижу, как я могу избежать выбранной позиции, чтобы попасть на доску, если пробел занят. я уже создал функцию в своем коде.:

 import random

board = [[' ',' ',' '],
         [' ',' ',' '],
         [' ',' ',' ']]

def checkwin(board):
    for i in range(3):
        if board[i][0] != " " and board[i][0] == board[i][1] == board[i][2]:
            return True  #winning row
        if board[0][i] != " " and board[0][i] == board[1][i] == board[2][i]:
            return True  #winning column
        #winning diagonals
        if board[1][1] != " " and board[0][0] == board[1][1] == board[2][2]:
            return True
        if board[1][1] != " " and board[2][0] == board[1][1] == board[0][2]:
            return True
        else:
            return False

def check_space_taken(board, number):
    if not choose_position(board, number) == ' ':
        return True
    else:
        return False

def choose_position(board, number):
    if number <= 3:
        board[0][number-1] = 'X'
    elif number <= 6:
        board[1][number-4] = 'X'
    elif number <= 9:
        board[2][number-7] = 'X'
    return board, number

def computer_position(board, computer_number):
    computer_number = random.randint(0,9)
    if computer_number <= 3:
        board[0][computer_number-1] = 'O'
    elif computer_number <= 6:
        board[1][computer_number-4] = 'O'
    elif computer_number <= 9:
        board[2][computer_number-7] = 'O'
    return board, computer_number

Game_over = False

while not Game_over:
    player_input = int(input('move to: '))
    player_changed_board = choose_position(board, player_input)
    computer_input = random.randint(0,9)
    computer_changed_board = computer_position(board, computer_input)

    for x in player_changed_board:
        print(x)

    for y in computer_changed_board:
        print('computer move')
        print(y)

    if checkwin(board):
        print('n-----------------------Congrats you won-----------------------n')
        Game_over = True
 

Ответ №1:

Я думаю, это было бы проще, если бы вы использовали координаты x, y, но здесь идет:

 from itertools import chain
from random import choice


def cast(x, y, base):
    """
    Create a y by x matrix from a vector
    """
    if x * y == len(base):
        return [list(base[i*x: x i*x]) for i in range(y)]
    raise ValueError('Dimensions do not agree with base')

def flat(board):
    """
   Create a 1D vector from a matrix 
    """
    return [*chain.from_iterable(board)]

def check_space_taken(board, number):
    """
    check if a space is taken
    """
    return flat(board)[number] == ' '

def empty_space_indices(board):
    """
    find all empty spaces
    """
    flattened = flat(board)
    return [*filter(lambda x: flattened[x]==' ', range(len(flattened)))]

def play(board, number, letter):
    """
   Simplify the code base by using a single function for move-making 
    """
    board = flat(board)
    board[number] = letter
    board = cast(3, 3, board)
    return board

def won(board, letter):
    """
    checkwin seems to have a bug
    """
    for i in range(3):
        if letter == board[i][0] == board[i][1] == board[i][2]:
            return True
        elif letter == board[0][i] == board[1][i] == board[2][i]:
            return True
        elif letter == board[0][0] == board[1][1] == board[2][2]:
            return True
        elif letter == board[2][0] == board[1][1] == board[0][2]:
            return True
    return False

def show(board):
    """
    Neat representation of the board.
    checkout the module tabulate for better options:
        https://github.com/astanin/python-tabulate
    """
    table = 'n'.join("{}|{}|{}".format(*row) for row in board)
    table = table.join('n' * 2)
    print(table)
    return table

def game_over(board):
    """
    check if the board is full or there is a winner
    """
    return len(empty_space_indices(board))==0 or won(board, 'x') or won(board, 'o')
    
def main(board=None):
    """REPL"""
    if board:
        show(board)
    board = board if not isinstance(board, type(None)) else [
        [' ',' ',' '],
        [' ',' ',' '],
        [' ',' ',' ']
    ]
    player_move = None
    while not game_over(board):
        while not player_move in empty_space_indices(board):
            player_move = int(input(f'pick a tile from {empty_space_indices(board)}:nt'))
        board = play(board, player_move, 'x')
        
        if not game_over(board):
            computer_move = choice(empty_space_indices(board))
            board = play(board, computer_move, 'o')
            
        show(board)

main()
 

Предупреждение:
Я думаю, что может быть что-то не так, checkwin потому что следующее не завершило игру:

 x|o|o
 |o|o
x|x|x
 

вы можете использовать следующее для проверки:

 def relist(table):
    """parse the table from show back into a list"""
    t = table.splitlines()
    return [i.split('|') for i in t]
    
t = """x|o|o
 |o|o
x|x|x"""
rt = relist(t)

for r in rt: print(r)
print(checkwin(rt))
print(game_over(rt))
print(won(rt, 'x'))