最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

python - Testing all possible winning condition for tic tac via input testing - Stack Overflow

programmeradmin8浏览0评论

only function definitions were given to me like and i had to strictly follow the instruction

def draw_board(board):
    pass
def welcome(board):
    pass
like these.....

so this is what i have wrote

noughtsandcrosses.py

import random
import os.path
import json
random.seed()


def draw_board(board):

    '''
    function:draw_board
    parameter:board
    prints board
    return:None
    '''

    for i in board:
        print(f"{'-'*11}".center(50))
        print(f"| {' | '.join(i)} |".center(50))
    print(f"{'-'*11}".center(50))


def welcome(board):

    '''
    function:welcome
    parameter:board
    prints welcome message
    return:None
    '''

    print('Welcome to the "Unbeatable Noughts and Crosses" game.')
    print("The board layout is show below:")
    draw_board(board)
    print("When prompted, enter the number corresponding to the square you want.")


def initialise_board(board):

    '''
    function:initialise_board
    parameter:board
    sets board to empty
    returns board
    '''

    for i in range(len(board)):
        for j in range(len(board)):
            board [i][j] = " "
    return board

def get_player_move(board):

    '''
    function:get_player_move
    parameters:board
    gets player move
    returns:row and col
    '''

    while True:
        try:
            print("                    1 2 3")
            print("                    4 5 6")
            print("Choose your square: 7 8 9 :", end="")
            user_input = int(input())
            if user_input < 1 or user_input > 9:
                raise Exception("enter between 1 to 9")
                continue
            row  = (user_input -1 )//3
            col = (user_input-1)%3
            if board[row][col] == ' ':
                return row,col
            else:
                print("Cell already occupied")
        except Exception as e:
            print(e)
# this is best
def choose_computer_move(board):
    '''
    #     function:choose_computer_move
    #     parameter:board
    #     gets computer move

    #             LOGIC:
    #                 first priority:  BLOCK OR CHECK FOR WIN

    #                     BLOCK:
    #                         1st entry (user): checks for ALL possible moves from the single position
    #                         2nd entry (user): finds the single possible next move that can possibly let the user win
    #                         last entry (computer)takes the row and column of the possible next move
    #                         and places its next move there
    #                     CHECK FOR WIN:
    #                         if after the possible two moves from computer , if consecutive two cells are filled by computer
    #                         then it finds the index of the winning cell and places the next move there

    #                 second priority: OCCUPY EMPTY CENTER OR CORNERS TO BLOCK TWO MOVE COMBINATIONS
    #                     Important: second priority blocks TWO MOVE COMBINATION , i have listed all the corner combinations
    #                     so it checks the possible combination move and places there

    #     returns row,col
    #     '''
    winning_conditions = [
        [(0, 0), (0, 1), (0, 2)],
        [(1, 0), (1, 1), (1, 2)],
        [(2, 0), (2, 1), (2, 2)],
        [(0, 0), (1, 0), (2, 0)],
        [(0, 1), (1, 1), (2, 1)],
        [(0, 2), (1, 2), (2, 2)],
        [(0, 0), (1, 1), (2, 2)],
        [(0, 2), (1, 1), (2, 0)]
    ]

    for condition in winning_conditions:
        cells = [board[row][col] for row, col in condition]
        if cells.count('O') == 2 and cells.count(' ') == 1:
            empty_index = cells.index(' ')
            return condition[empty_index]

    for condition in winning_conditions:
        cells = [board[row][col] for row, col in condition]
        if cells.count('X') == 2 and cells.count(' ') == 1:
            empty_index = cells.index(' ')
            return condition[empty_index]

    corners = [(0,0), (0,2), (2,0), (2,2)]
    edges = [(0,1), (1,0), (1,2), (2,1)]

    if (board[0][0] == 'X' and board[2][2] == 'X') or (board[0][2] == 'X' and board[2][0] == 'X'):
        for edge in edges:
            if board[edge[0]][edge[1]] == ' ':
                return edge

    if board[1][1] == ' ':
        return (1, 1)
    if board[0][0] == 'X' and board[2][2] == ' ':
        return (2, 2)
    if board[2][0] == 'X' and board[0][2] == ' ':
        return (0, 2)
    if board[0][2] == 'X' and board[2][0] == ' ':
        return (2, 0)
    if board[2][2] == 'X' and board[0][0] == ' ':
        return (0, 0)

    for corner in corners:
        if board[corner[0]][corner[1]] == ' ':
            return corner

    for edge in edges:
        if board[edge[0]][edge[1]] == ' ':
            return edge

    return None
def check_for_win(board, mark):

    '''
    function:check_for_win
    parameters:board,mark
        if all the three consecutive cells are filled it returns True
        else False
    returns:True or False
    '''
    winning_conditions = [
        [(0, 0), (0, 1), (0, 2)],
        [(1, 0), (1, 1), (1, 2)],
        [(2, 0), (2, 1), (2, 2)],
        [(0, 0), (1, 0), (2, 0)],
        [(0, 1), (1, 1), (2, 1)],
        [(0, 2), (1, 2), (2, 2)],
        [(0, 0), (1, 1), (2, 2)],
        [(0, 2), (1, 1), (2, 0)]
    ]

    for condition in winning_conditions:
        condition_met = True
        for (row, col) in condition:
            if board[row][col] != mark:
                condition_met = False
                break
        if condition_met:
            return True

    return False

def check_for_draw(board):

    '''
    function:check_for_draw
    parameter:board
    returns:True if all cells are filled otherwise False
    '''
    for i in range(len(board)):
        for j in range(len(board)):
            if board[i][j] == ' ':
                return False
    return True

def play_game(board):
    initialise_board(board)
    draw_board(board)
    cur_player='X'
    while True:
        if cur_player == "X":
            row,col = get_player_move(board)
            board[row][col] = "X"
        else:
            try:
                row,col = choose_computer_move(board)
                board[row][col] = "O"
            except Exception as e:
                print(e)
                return
        draw_board(board)

        if check_for_win(board,cur_player):
            if cur_player == "X":
                print("Player X Won")
                return 1
            else:
                print("Computer Won")
                return -1
        if check_for_draw(board):
            print("Draw No one Won ")
            return 0
        if cur_player == "X":
            cur_player = "O"
        else:
            cur_player = "X"

def menu():

    '''
    function:menu
    paramenter:None
    returns choice
    '''
    print("Enter one of the following options:\n\t1 - play game\n\t2 - save your score in the leaderboard\n\t3 - Load and display the loaderboard\n\tq - End program")
    choice = input("\n1,2,3 or q? ")
    return choice

def load_scores():
    '''
    function:load_scores
    parameter:none
    reuturns json data from leaderboar.txt file
    '''
    if os.path.exists('leaderboard.txt'):
        with open('leaderboard.txt', 'r') as file:
            leaders = json.load(file)
    else:
        leaders = {}
    return leaders

def save_score(score):

    '''
    function:save_score
    parameter:score
    takes in user name and saves it in leaderboar.txt file
    returns:None
    '''
    name = input("Enter your name: ")
    leaders = load_scores()
    leaders[name] = score
    with open('leaderboard.txt', 'w') as file:
        json.dump(leaders, file)
    return


def display_leaderboard(leaders):

    '''
    function:display_leaderboard
    parameter:leaders
    prints the leaderboard
    '''
    sorted_leaders = sorted(leaders.values(),reverse=True)
    print("\nNAME: SCORE")
    for score in sorted_leaders:
        for name in leaders.keys():
            if leaders[name] == score:
                print(f"{name}: {score}")
                break
    # print(leaders)

playgame.py The instruction was that i shall not change any code of play_game.py

#You will have to import your other module in this module
from noughtsandcrosses import *

    
def main():
    board = [ ['1','2','3'],\
              ['4','5','6'],\
              ['7','8','9']]

    welcome(board)
    total_score = 0
    while True:
        choice = menu()
        if choice == '1':
            score = play_game(board)
            total_score += score
            print('Your current score is:',total_score)
        if choice == '2':
            save_score(total_score)
        if choice == '3':
            leader_board = load_scores()
            display_leaderboard(leader_board)
        if choice == 'q':
            print('Thank you for playing the "Unbeatable Noughts and Crosses" game.')
            print('Good bye')
            return


    
# Program execution begins here
if __name__ == '__main__':
    main()

TO execute i do

python3 play_game.py

i have tested some combinations and this code is working great like human [1,9] the computer is correctly blocking via [2,5]

So this was my college assignment , the instruction was that i had to only write function logics in noughtsandcrosses.py the playgame.py is as it as and is not changed Only function declaration were give in noughtsandcrosses.py so i wrote the above code , all the input logs and error logs were given at the instruction

I am not allowed to make new functions and i have to make sure computer only wins or draws and human cant win.

How can i test this code I wanna test all the possible combinations of winning so that i can be safe that computer only wins , Please help me I only check all the winning inputs by human that can potentially win ,

发布评论

评论列表(0)

  1. 暂无评论