井字棋,英文名叫Tic-Tac-Toe,是一种在3*3格子上进行的连珠游戏,和五子棋类似,由于棋盘一般不画边框,格线排成井字故得名。游戏需要的工具仅为纸和笔,然后由分别代表O和X的两个游戏者轮流在格子里留下标记(一般来说先手者为X),任意三个标记形成一条直线,则为获胜。
游戏的难点在于,如何判断连接成了一条线;横、竖、斜三个方向;
游戏的代码:
#!/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入门之井字棋小游戏python实现简单井字棋小游戏python实现井字棋小游戏Python实现的井字棋(Tic Tac Toe)游戏示例python实现井字棋游戏Python实现井字棋小游戏