用python实现五子棋实例

本文实例为大家分享了用python实现五子棋的具体代码,供大家参考,具体内容如下

# 制作一个棋盘"""++++++++++++++++++++++++++++++++++++++++"""def createBoard():board = []for i in range(15):board.append(["+"] * 15)return boarddef printBoard():#print(" ", end="")for i in range(1, 16):number = str(i).rjust(3)print(number, end="")print()#打印列号之后换行for i in range(15):number = str(i + 1).ljust(3)#注意这个函数,是将行号每个都变成左对齐,占3位,以实现棋盘对齐功能print(number, end="")#打印行号for j in range(15):print(board[i][j], end="")print()def isGameOver():count = 0# 先判断连续for x in range(15):for y in range(15):if board[x][y] != "+":count += 1# 向右if y < 11:flag = True #表示默认游戏结束for c in range(y + 1, y + 5):if board[x][y] != board[x][c]:flag = Falsebreakif flag:if board[x][y] == "●":print(">>>黑方胜!")else :print(">>>白方胜!")return True; # 表示游戏结束# 向下if x < 11:if board[x][y] == board[x+1][y] == board[x+2][y] == board[x+3][y] == board[x+4][y]:if board[x][y] == "●":print(">>>黑方胜!")else :print(">>>白方胜!")return True# 向右下if x < 11 and y < 11:if board[x][y] == board[x+1][y+1] == board[x+2][y+2] == board[x+3][y+3] == board[x+4][y+4]:if board[x][y] == "●":print(">>>黑方胜!")else :print(">>>白方胜!")return True# 向右上if x > 3 and y < 11:if board[x][y] == board[x-1][y+1] == board[x-2][y+2] == board[x-3][y+3] == board[x-4][y+4]:if board[x][y] == "●":print(">>>黑方胜!")else :print(">>>白方胜!")return True# 再判断和棋if count == 15 ** 2:print(">>>和棋!")return Truereturn False#如果以上连棋都没出现就游戏继续def chess(c):x, y = eval(input("请输入坐标:"))x -= 1y -= 1if board[x][y] == "+":board[x][y] = creturn Trueelse:print(">>>此处已有棋子,请重新下棋!")return False# 程序的开始board = createBoard(); printBoard()player = 0while not isGameOver():#游戏继续的操作if player % 2 == 0:print(">>>请黑方下棋,", end="")if not chess("●"):continueelse:print(">>>请白方下棋,", end="")if not chess("○"):continueprintBoard()player += 1print(">>>游戏结束!")

用python实现五子棋实例
文章图片

五子棋胜局判断的根据所在如上图。
【用python实现五子棋实例】以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

    推荐阅读