Learn Python 015: Tic Tac Toe Game

本文介绍了一个使用Python实现的简易版井字游戏代码。该程序通过定义游戏板、玩家输入、胜利条件判断及平局判断等核心功能,实现了两个玩家之间的交互式游戏过程。文章适合初学者学习简单的游戏开发及Python编程。
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

 

转载于:https://www.cnblogs.com/mxyzptlk/p/7196618.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值