python实现简单井字棋游戏-创新互联
井字棋,英文名叫Tic-Tac-Toe,是一种在3*3格子上进行的连珠游戏,和五子棋类似,由于棋盘一般不画边框,格线排成井字故得名。游戏需要的工具仅为纸和笔,然后由分别代表O和X的两个游戏者轮流在格子里留下标记(一般来说先手者为X),任意三个标记形成一条直线,则为获胜。
专注于为中小企业提供网站设计、做网站服务,电脑端+手机端+微信端的三站合一,更高效的管理,为中小企业秀山土家族苗族免费做网站提供优质的服务。我们立足成都,凝聚了一批互联网行业人才,有力地推动了上1000+企业的稳健成长,帮助中小企业通过网站建设实现规模扩充和转变。游戏的难点在于,如何判断连接成了一条线;横、竖、斜三个方向;
游戏的代码:
#!/usr/bin/env python3 # -*- coding:utf-8 -*- u''' Created on 2019年4月13日 @author: wuluo ''' __author__ = 'wuluo' __version__ = '1.0.0' __company__ = u'重庆交大' __updated__ = '2019-04-13' # 创建井字棋的程序 def initBoard(): global board # 调用全局的board board = [None] * 3 print("井字棋:") for i in range(len(board)): board[i] = ["+ "] * 3 # 打印井字棋的程序 def printBoard(): global board for i in range(len(board)): for j in range(len(board[i])): print(board[i][j], end=" ") print("") # 开始下棋的程序 def startGame(): global board player = 0 while isGameContinue(): if player <= 8: if player % 2 == 0: # 甲方下棋 print("==>黑方下棋") if not playChess("x"): continue else: # 乙方下棋 print("==>白方下棋") if not playChess("○"): continue player += 1 else: print("平局") break def playChess(chess): # 获取位置 x = int(input("==> X=")) - 1 y = int(input("==> Y=")) - 1 if board[x][y] == "+ ": board[x][y] = chess printBoard() return True # 落子成功 else: print("==> 已有棋子 请重新落子\a") printBoard() return False # 落子失败 def isGameContinue(): for i in range(len(board)): for j in range(len(board[i])): if board[i][j] != "+ ": # 横向 if j == 0: if board[i][j] == board[i][j + 1] == board[i][j + 2]: whoWin(i, j) return False # 竖向 if i == 0: if board[i][j] == board[i + 1][j] == board[i + 2][j]: whoWin(i, j) return False # 正斜 if i == 0 and j == 0: if board[i][j] == board[i + 1][j + 1] == board[i + 2][j + 2]: whoWin(i, j) return False # 反斜 if i == 2 and j == 0: if board[i][j] == board[i - 1][j + 1] == board[i - 2][j + 2]: whoWin(i, j) return False return True def whoWin(i, j): if board[i][j] == "x": print("黑方胜!") else: print("白方胜!") for i in range(3): print("win") class main(): board = [] initBoard() printBoard() startGame() if __name__ == "__main__": main()
本文名称:python实现简单井字棋游戏-创新互联
本文链接:http://pwwzsj.com/article/dgocjh.html