初步接触python后,尝试着写一写小游戏

井字棋游戏

首先创建一个棋盘:

theBoard = {'top-l':' ','top-m':' ','top-r':' ',
          'mid-l':' ','mid-m':' ','mid-r':' ',
          'bot-l':' ','bot-m':' ','bot-r':' '}

定义一下输出棋盘以及判断胜负的函数:

def print_board(board):
    print('\n' + board['top-l'] + '|' + board['top-m'] + '|' + board['top-r'])
    print('-+-+-')
    print(board['mid-l'] + '|' + board['mid-m'] + '|' + board['mid-r'])
    print('-+-+-')
    print(board['bot-l'] + '|' + board['bot-m'] + '|' + board['bot-r'] + '\n')
def isWin(board,X,O):
    if (board['top-l'] == X and board['top-m'] == X and board['top-r'] == X) or (board['mid-l'] == X and board['mid-m'] == X and board['mid-r'] == X) or (board['bot-l'] == X and board['bot-m'] == X and board['bot-r'] == X) or \
        (board['top-l'] == X and board['mid-l'] == X and board['bot-l'] == X) or (board['top-m'] == X and board['mid-m'] == X and board['bot-m'] == X) or (board['top-r'] == X and board['mid-r'] == X and board['bot-r'] == X) or \
        (board['top-l'] == X and board['mid-m'] == X and board['bot-r'] == X) or (board['top-r'] == X and board['mid-m'] == X and board['bot-l'] == X):
        return 'X wins!'
    elif (board['top-l'] == O and board['top-m'] == O and board['top-r'] == O) or (board['mid-l'] == O and board['mid-m'] == O and board['mid-r'] == O) or (board['bot-l'] == O and board['bot-m'] == O and board['bot-r'] == O) or \
        (board['top-l'] == O and board['mid-l'] == O and board['bot-l'] == O) or (board['top-m'] == O and board['mid-m'] == O and board['bot-m'] == O) or (board['top-r'] == O and board['mid-r'] == O and board['bot-r'] == O) or \
        (board['top-l'] == O and board['mid-m'] == O and board['bot-r'] == O) or (board['top-r'] == O and board['mid-m'] == O and board['bot-l'] == O):
        return 'O wins!'
    else:
        return 

建立循环:

turn = 'X'
for i in range(9):
    print_board(theBoard)
    print('position:')
    position = input()
    theBoard[position] = turn
    print(isWin(theBoard,'X','O',))
    if isWin(theBoard,'X','O') == 'X wins!' or isWin(theBoard,'X','O') == 'O wins!' :
        print_board(theBoard)
        break
    if turn == 'X':
        turn = 'O'
    else:
        turn = 'X'

运行结果:

Last modification:July 12th, 2020 at 01:14 am