码迷,mamicode.com
首页 > 编程语言 > 详细

Learn Python 015: Tic Tac Toe Game

时间:2017-07-17 18:48:52      阅读:153      评论:0      收藏:0      [点我收藏+]

标签:==   pre   ber   bsp   str   not   nic   div   else   

board = [‘   ‘ for i in range(9)]


def print_board():
    row_1 = ‘|{}|{}|{}|‘.format(board[0], board[1], board[2])
    row_2 = ‘|{}|{}|{}|‘.format(board[3], board[4], board[5])
    row_3 = ‘|{}|{}|{}|‘.format(board[6], board[7], board[8])

    print(‘\n‘)
    print(row_1)
    print(row_2)
    print(row_3)
    print(‘\n‘)


def player_move(icon):
    if icon == ‘ X ‘:
        number = 1
    elif icon == ‘ O ‘:
        number = 2
    print(‘Your turn player {}.‘.format(number))
    choice = int(input(‘Enter your move (1-9): ‘).strip())
    if board[choice - 1] == ‘   ‘:
        board[choice - 1] = icon
    else:
        print(‘\n‘)
        print(‘That space is taken!‘)


def victory(icon):
    if (board[0] == icon and board[1] == icon and board[2] == icon) or        (board[3] == icon and board[4] == icon and board[5] == icon) or        (board[6] == icon and board[7] == icon and board[8] == icon) or        (board[0] == icon and board[3] == icon and board[6] == icon) or        (board[1] == icon and board[4] == icon and board[7] == icon) or        (board[2] == icon and board[5] == icon and board[8] == icon) or        (board[0] == icon and board[4] == icon and board[8] == icon) or        (board[2] == icon and board[4] == icon and board[6] == icon):
        return True
    else:
        return False


def game_is_draw():
    if ‘   ‘ not in board:
        return True
    else:
        return False

while True:
    print_board()
    player_move(‘ X ‘)
    print_board()
    if victory(‘ X ‘):
        print(‘X wins! Nicely done!‘)
        break
    elif game_is_draw():
        print(‘Its a draw!‘)
        break
    player_move(‘ O ‘)
    if victory(‘ O ‘):
        print_board()
        print(‘O wins! Nicely done!‘)
        break
    elif game_is_draw():
        print(‘Its a draw!‘)
        break

 

Learn Python 015: Tic Tac Toe Game

标签:==   pre   ber   bsp   str   not   nic   div   else   

原文地址:http://www.cnblogs.com/mxyzptlk/p/7196618.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!