提交 522b5e0c 编写于 作者: MengZian's avatar MengZian

Add new file: master/2020/11/1/Tic-tac-toe - Player versus Player.py

上级 89c5df1c
from sys import exit,exc_info,excepthook,version,stdout
from builtins import tuple,list,str,TypeError,ModuleNotFoundError,print,int,OverflowError,IndexError,input
class Bright:
def PermList(L,/,*,CheckType=True):
if CheckType and L.__class__ is not tuple and L.__class__ is not list and L.__class__ is not str:
raise TypeError("argument must be tuple, list or string")
X=[]
R=[]
T=[]
N=0
for I in L:
X+=[N]
N+=1
T+=[I]
R+=[T]
Y=[N-a for a in X]
Z=tuple(a-1 for a in Y)
while True:
for I in Z:
J=I+1
Y[I]-=1
if Y[I]==0:
X[I:N]=X[J:N]+X[I:J]
Y[I]=N-I
else:
K=N-Y[I]
X[I],X[K]=X[K],X[I]
R+=[[T[a] for a in X]]
break
else:
return R
from time import localtime,sleep
try:
from turtle import setup,title,screensize,isvisible,ht,speed,isdown,pu,pd,goto,setx,sety,write,circle,Terminator
except ModuleNotFoundError as E0:
excepthook(ModuleNotFoundError,E0,exc_info()[2])
print("[Errno 4] Are you using an embeddable ZIP file version of Python 3?")
exit(4)
except:
EI=exc_info()
excepthook(EI[0],EI[1],EI[2])
print("[Errno 5] Something is wrong with 'turtle' module. Reinstalling or repairing your Python 3 is suggested.")
exit(5)
Grid=(1,2,3,4,5,6,7,8,9)
Hint=("-"*8,"During the gameplay,",'type "credits" to show information about this program,','type "rules" to show how to play this game.',"-"*8)
GridStr=tuple(a.__str__() for a in Grid)
Horizontal1=Bright.PermList(Grid[0:3])
Horizontal2=Bright.PermList(Grid[3:6])
Horizontal3=Bright.PermList(Grid[6:9])
Vertical1=Bright.PermList(Grid[0:7:3])
Vertical2=Bright.PermList(Grid[1:8:3])
Vertical3=Bright.PermList(Grid[2:9:3])
Diagonal1=Bright.PermList(Grid[0:9:4])
Diagonal2=Bright.PermList(Grid[2:7:2])
Win=Horizontal1+Horizontal2+Horizontal3+Vertical1+Vertical2+Vertical3+Diagonal1+Diagonal2
Title="Tic-tac-toe (Player versus Player)"
class Data:
Player1Grid=[]
Player2Grid=[]
Log=[">"*8]
Player1Circle=False
Player1First=False
class Draw:
def Board():
setup(600,600,-1,-1)
title(Title)
screensize(300,300)
if isvisible():
ht()
speed(0)
return None
def Grids():
for I in (100,200):
if isdown():
pu()
goto(I,0)
pd()
sety(300)
pu()
goto(0,I)
pd()
setx(300)
pu()
return None
def Numbers():
T=(1,2,3)
for I in T:
for J in T:
goto(I*100-50,340-J*100)
write((I+J*3-3).__str__(),False,"center",("Arial",20,"normal"))
return None
def Circle(P,/):
if P.__class__ is not int:
raise TypeError
if isdown():
pu()
speed(0)
if P==Grid[0]:
goto(50,210)
elif P==Grid[1]:
goto(150,210)
elif P==Grid[2]:
goto(250,210)
elif P==Grid[3]:
goto(50,110)
elif P==Grid[4]:
goto(150,110)
elif P==Grid[5]:
goto(250,110)
elif P==Grid[6]:
goto(50,10)
elif P==Grid[7]:
goto(150,10)
elif P==Grid[8]:
goto(250,10)
else:
raise OverflowError
pd()
speed(3)
circle(40,360)
speed(0)
pu()
return None
def Cross(P,/):
if P.__class__ is not int:
raise TypeError
if isdown():
pu()
speed(0)
if P==Grid[0]:
X,Y=90,290
elif P==Grid[1]:
X,Y=190,290
elif P==Grid[2]:
X,Y=290,290
elif P==Grid[3]:
X,Y=90,190
elif P==Grid[4]:
X,Y=190,190
elif P==Grid[5]:
X,Y=290,190
elif P==Grid[6]:
X,Y=90,90
elif P==Grid[7]:
X,Y=190,90
elif P==Grid[8]:
X,Y=290,90
else:
raise OverflowError
goto(X,Y)
pd()
speed(3)
goto(X-80,Y-80)
pu()
sety(Y)
pd()
goto(X,Y-80)
speed(0)
pu()
return None
def WinLine(L,/):
if L.__class__ is not list:
raise TypeError
if isdown():
pu()
speed(0)
def SlowDraw(X,Y,/):
goto(X,Y)
pd()
speed(3)
return None
if L in Horizontal1:
SlowDraw(10,250)
setx(290)
elif L in Horizontal2:
SlowDraw(10,150)
setx(290)
elif L in Horizontal3:
SlowDraw(10,50)
setx(290)
elif L in Vertical1:
SlowDraw(50,290)
sety(10)
elif L in Vertical2:
SlowDraw(150,290)
sety(10)
elif L in Vertical3:
SlowDraw(250,290)
sety(10)
elif L in Diagonal1:
SlowDraw(10,290)
goto(290,10)
elif L in Diagonal2:
SlowDraw(290,290)
goto(10,10)
else:
raise IndexError
speed(0)
pu()
return None
def Initialize():
stdout.write("Python "+version+"\n\n"+Title+"\n\nPreparing board ... ")
Draw.Board()
stdout.write("grids ... ")
Draw.Grids()
stdout.write("and numbers ... ")
Draw.Numbers()
print("done!\nInitialization complete!\n")
return None
class Query:
Information=("="*8,"Programmer: Meng Zian","Tested on Python 3.9.0 (tags/v3.9.0:9cf6752, Oct 5 2020, 15:34:40) [MSC v.1927 64 bit (AMD64)]","Date: November 1st, 2020\n","Current Python: "+version,"="*8)
HowToPlay=("+"*8,"Rules: two players play this tic-tac-toe game.","In a 3x3 grid, Player 1 draws a pattern into an empty grid and Player 2 draws another pattern in turns.","First player who draws 3 continuous patterns in a horizontal, vertical or diagonal line wins the game.","But with no continuous 3 patterns eventually, the game comes to a draw.","+"*8)
Key=("credits","rules")
def Show():
for I in Hint:
print(I)
return None
def PlayerLog():
Query.Show()
for I in Data.Log:
print(I)
print("<"*8)
return None
def Credits():
for I in Query.Information:
print(I)
return None
def Rules():
for I in Query.HowToPlay:
print(I)
return None
def Begin():
while True:
Data.Player1Circle=input('Player 1 - would you like to be circle or cross? Type "0" if you want to be cross: ')!="0"
print("Player 1 chooses to be circle!") if Data.Player1Circle else print("Player 1 chooses to be cross!")
if input('''Player 2 - do you agree with Player 1's decision? Type "0" if you want to REJECT: ''')=="0":
print("Player 2 rejects Player 1's decision!")
else:
break
while True:
Data.Player1First=input('Player 1 - would you like to go first? Type "0" if you DO NOT want to go first: ')!="0"
print("Player 1 wants to go first!") if Data.Player1First else print("Player 1 wants to let Player 2 go first!")
if input('''Player 2 - do you agree with Player 1's decision? Type "0" if you want to REJECT: ''')=="0":
print("Player 2 rejects Player 1's decision!")
else:
break
print("Player 1 is circle, and Player 2 is cross.") if Data.Player1Circle else print("Player 1 is cross, and Player 2 is circle.")
print("Now it's Player 1's turn!") if Data.Player1First else print("Now it's Player 2's turn!")
Query.Show()
return None
class Action:
def Player1():
while True:
AnswerStr=input("Player 1 - please draw into a grid: ")
if AnswerStr in GridStr:
Answer=int(AnswerStr)
if Answer in Grid:
if Answer in Data.Player1Grid:
Query.PlayerLog()
print("Player 1 - you have drawn into that grid!")
elif Answer in Data.Player2Grid:
Query.PlayerLog()
print("Player 1 - your opponent has drawn into that grid!")
else:
CurrentTime=localtime()
Draw.Circle(Answer) if Data.Player1Circle else Draw.Cross(Answer)
Data.Player1Grid+=[Answer]
Data.Log+=['{1:02d}/{2:02d}/{0} {3:02d}:{4:02d}:{5:02d} - Player 1 drew {6} to grid {7}'.format(CurrentTime[0],CurrentTime[1],CurrentTime[2],CurrentTime[3],CurrentTime[4],CurrentTime[5],"circle" if Data.Player1Circle else "cross",Answer)]
return None
else:
Query.PlayerLog()
print("Player 1 - unknown out of range error, sorry but please try again.")
elif AnswerStr==Query.Key[0]:
Query.Credits()
elif AnswerStr==Query.Key[1]:
Query.Rules()
else:
Query.PlayerLog()
print("Player 1 - please input a valid integer in range!")
def Player2():
while True:
AnswerStr=input("Player 2 - please draw into a grid: ")
if AnswerStr in GridStr:
Answer=int(AnswerStr)
if Answer in Grid:
if Answer in Data.Player2Grid:
Query.PlayerLog()
print("Player 2 - you have drawn into that grid!")
elif Answer in Data.Player1Grid:
Query.PlayerLog()
print("Player 2 - your opponent has drawn into that grid!")
else:
CurrentTime=localtime()
Draw.Cross(Answer) if Data.Player1Circle else Draw.Circle(Answer)
Data.Player2Grid+=[Answer]
Data.Log+=['{1:02d}/{2:02d}/{0} {3:02d}:{4:02d}:{5:02d} - Player 2 drew {6} to grid {7}'.format(CurrentTime[0],CurrentTime[1],CurrentTime[2],CurrentTime[3],CurrentTime[4],CurrentTime[5],"cross" if Data.Player1Circle else "circle",Answer)]
return None
else:
Query.PlayerLog()
print("Player 2 - unknown out of range error, sorry but please try again.")
elif AnswerStr==Query.Key[0]:
Query.Credits()
elif AnswerStr==Query.Key[1]:
Query.Rules()
else:
Query.PlayerLog()
print("Player 2 - please input a valid integer in range!")
class Judge:
Claim=("","Player 1 wins!","Player 2 wins!","Draw!")
def Winner():
Pl1Gl=Data.Player1Grid.__len__()
Pl2Gl=Data.Player2Grid.__len__()
if Data.Player1First:
if Pl1Gl>2:
if Pl1Gl==3:
if Data.Player1Grid in Win:
Draw.WinLine(Data.Player1Grid)
return Judge.Claim[1]
if Pl2Gl==3:
if Data.Player2Grid in Win:
Draw.WinLine(Data.Player2Grid)
return Judge.Claim[2]
elif Pl1Gl==4:
for I in (Data.Player1Grid[0:3],Data.Player1Grid[1:4],Data.Player1Grid[0:2]+Data.Player1Grid[3:4],Data.Player1Grid[2:4]+Data.Player1Grid[0:1]):
if I in Win:
Draw.WinLine(I)
return Judge.Claim[1]
if Pl2Gl==4:
for I in (Data.Player2Grid[0:3],Data.Player2Grid[1:4],Data.Player2Grid[0:2]+Data.Player2Grid[3:4],Data.Player2Grid[2:4]+Data.Player2Grid[0:1]):
if I in Win:
Draw.WinLine(I)
return Judge.Claim[2]
elif Pl1Gl==5:
for I in (Data.Player1Grid[0:3],Data.Player1Grid[1:4],Data.Player1Grid[2:5],Data.Player1Grid[0:5:2],Data.Player1Grid[0:2]+Data.Player1Grid[3:4],Data.Player1Grid[0:2]+Data.Player1Grid[4:5],Data.Player1Grid[2:4]+Data.Player1Grid[0:1],Data.Player1Grid[3:5]+Data.Player1Grid[0:1],Data.Player1Grid[1:3]+Data.Player1Grid[4:5],Data.Player1Grid[3:5]+Data.Player1Grid[1:2]):
if I in Win:
Draw.WinLine(I)
return Judge.Claim[1]
return Judge.Claim[3]
else:
if Pl2Gl>2:
if Pl2Gl==3:
if Data.Player2Grid in Win:
Draw.WinLine(Data.Player2Grid)
return Judge.Claim[2]
if Pl1Gl==3:
if Data.Player1Grid in Win:
Draw.WinLine(Data.Player1Grid)
return Judge.Claim[1]
elif Pl2Gl==4:
for I in (Data.Player2Grid[0:3],Data.Player2Grid[1:4],Data.Player2Grid[0:2]+Data.Player2Grid[3:4],Data.Player2Grid[2:4]+Data.Player2Grid[0:1]):
if I in Win:
Draw.WinLine(I)
return Judge.Claim[2]
if Pl1Gl==4:
for I in (Data.Player1Grid[0:3],Data.Player1Grid[1:4],Data.Player1Grid[0:2]+Data.Player1Grid[3:4],Data.Player1Grid[2:4]+Data.Player1Grid[0:1]):
if I in Win:
Draw.WinLine(I)
return Judge.Claim[1]
elif Pl2Gl==5:
for I in (Data.Player2Grid[0:3],Data.Player2Grid[1:4],Data.Player2Grid[2:5],Data.Player2Grid[0:5:2],Data.Player2Grid[0:2]+Data.Player2Grid[3:4],Data.Player2Grid[0:2]+Data.Player2Grid[4:5],Data.Player2Grid[2:4]+Data.Player2Grid[0:1],Data.Player2Grid[3:5]+Data.Player2Grid[0:1],Data.Player2Grid[1:3]+Data.Player2Grid[4:5],Data.Player2Grid[3:5]+Data.Player2Grid[1:2]):
if I in Win:
Draw.WinLine(I)
return Judge.Claim[2]
return Judge.Claim[3]
return Judge.Claim[0]
def Turn():
Player1sTurn=Data.Player1First
while True:
Continue=Judge.Winner()
if Continue:
return Continue
else:
Action.Player1() if Player1sTurn else Action.Player2()
Player1sTurn=not Player1sTurn
Query.PlayerLog()
def Run():
Initialize()
Query.Begin()
print("Result: "+Judge.Turn()+"\nGood game! Bye!")
sleep(5)
return None
try:
Run()
except:
EI=exc_info()
print()
excepthook(EI[0],EI[1],EI[2])
if Terminator.__subclasscheck__(EI[0]):
print("[Errno 2] You deliberately shut the 'turtle' window!")
exit(2)
else:
print("[Errno 3] Program encountered some other errors, sorry but it is exiting ...")
exit(3)
else:
exit(0)
\ No newline at end of file
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册