Tic-tac-toe, the English name is Tic-Tac-Toe, is a kind of renju game played on a 3*3 grid. It is similar to Gobang. Because the board generally does not have a border, the grid lines are arranged in tic-tac-toe so it is named. The only tools needed for the game are paper and pen, and then two players representing O and X take turns to leave marks in the grid (generally, the first player is X), any three marks forming a straight line, it is a win .
The difficulty of the game is how to judge that the connection is a line; horizontal, vertical and oblique directions;
Game code:
#! /usr/bin/env python3
# - *- coding:utf-8-*-
u'''
Created on April 13, 2019
@ author: wuluo
'''
__ author__ ='wuluo'
__ version__ ='1.0.0'
__ company__ = u'Chongqing Jiaotong University'
__ updated__ ='2019-04-13'
# Program for creating tic-tac-toe
def initBoard():
global board #Call the global board
board =[None]*3print("Tic-Tac-Toe:")for i inrange(len(board)):
board[i]=["+ "]*3
# Program for printing tic-tac-toe
def printBoard():
global board
for i inrange(len(board)):for j inrange(len(board[i])):print(board[i][j], end=" ")print("")
# The program to start playing chess
def startGame():
global board
player =0whileisGameContinue():if player <=8:if player %2==0:
# Party A plays chess
print("==Black plays chess")if not playChess("x"):continueelse:
# Party B plays chess
print("==White plays chess")if not playChess("○"):continue
player +=1else:print("draw")break
def playChess(chess):
# Get location
x =int(input("== X="))-1
y =int(input("== Y="))-1if board[x][y]=="+ ":
board[x][y]= chess
printBoard()return True #Successful
else:print("==There are already pieces, please re-set\a")printBoard()return False #Failed
def isGameContinue():for i inrange(len(board)):for j inrange(len(board[i])):if board[i][j]!="+ ":
# Horizontal
if j ==0:if board[i][j]== board[i][j +1]== board[i][j +2]:whoWin(i, j)return False
# Vertical
if i ==0:if board[i][j]== board[i +1][j]== board[i +2][j]:whoWin(i, j)return False
# Forward oblique
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
# Backslash
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("Black wins!")else:print("White wins!")for i inrange(3):print("win")classmain():
board =[]initBoard()printBoard()startGame()if __name__ =="__main__":main()
Game results:
Another result is a tie:
The above is the whole content of this article, I hope it will be helpful to everyone's study.
Recommended Posts