笔者在最近的python学习中,写了一段五子棋的简单的显示代码(未能进行胜负的判断),但是胜负判断应该实现起来并不难,以前用C语言写过一个完整的五子棋,相信对于很多人来说并不难。
python语言比较精简,相对于C语言和C++来说较为容易上手,下面是我的代码,若有不好的地方欢迎大家批评指正。
import os
def print_board(board):
print(board[1] + '|' + board[2] + '|' + board[3])
print('-+-+-')
print(board[4] + '|' + board[5] + '|' + board[6])
print('-+-+-')
print(board[7] + '|' + board[8] + '|' + board[9])
def main():
init_board = {1: ' ', 2: ' ', 3: ' ', 4: ' ', 5: ' ', 6: ' ', 7: ' ', 8: ' ', 9: ' ' }
begin = True
notchoose = True
pieces = '甲方'
count = 0
while begin:
curr_board = init_board.copy()
begin = False
turn = 'x'
count = 0
print_board(curr_board)
num = int(input('轮到%s走棋,请输入数字' % pieces))
os.system('cls')
print_board(curr_board)
while count < 9:
if turn == 'x':
pieces = '乙方'
else:
pieces = '甲方'
while (notchoose):
move = int(input('轮到%s走棋,请输入位置' % pieces))
if (curr_board[move] != ' '):
notchoose = True
else:
notchoose = False
count += 1
if turn == 'x':
curr_board[move] = 'o'
turn = 'o'
else:
curr_board[move] = 'x'
turn = 'x'
notchoose = True
os.system('cls')
print_board(curr_board)
if __name__ == '__main__':
main()
整体实现比较简单,用了一个字典来储存棋盘的信息,然后拷贝一个字典来储存棋盘的变化,python值传递的方式目前还未深入了解,因此这篇文章采用了最基本的语法来实现五子棋的基本功能。