Пример #1
0
class main:

	def __init__ (self):
		self.app = Tk()
		self.app.title('Tic Tac Toe')
		#self.app.resizable(width=False, height=False)
		#width and hight of window
		w = 900
		h = 1100
		#width and hight of screen
		ws = self.app.winfo_screenwidth()
		hs = self.app.winfo_screenheight()
		#calculate position
		x = ws/2 - w/2
		y = hs/2 - h/2
		#place window -> pramaters(visina, dolzina, pozicija x, pozicija y)
		self.app.geometry("%dx%d+%d+%d" % (w,h, x, y))

		#======================================
		self.frame = Frame() #main frame
		self.frame.pack(fill = 'both', expand = True)
		self.label = Label(self.frame, text	= 'Tic Tac Toe', height = 4, bg = 'white', fg = 'blue')
		self.label.pack(fill='both', expand = True)
		#self.label2 = Label(self.frame, text	= 'here', height = 2, bg = 'white', fg = 'blue') odkomentiri samo za develop-------------
		#self.label2.pack(fill='both', expand = True)
		self.canvas = Canvas(self.frame, width = 900, height = 900)
		self.canvas.pack(fill = 'both', expand = True)
		self.framepod = Frame(self.frame)#sub frame
		self.framepod.pack(fill = 'both', expand = True)
		self.Single = Button(self.framepod, text = 'Start single player', height = 4, command = self.startsingle, bg = 'white', fg = 'blue')
		self.Single.pack(fill='both', expand = True, side=RIGHT)
		self.Multi = Button(self.framepod, text = 'Start double player', height = 4, command = self.double, bg = 'white', fg = 'blue')
		self.Multi.pack(fill='both', expand = True, side=RIGHT)
		self.board = AI()
		self.draw()

	def double(self): 
		#cleans the all simbols from canvas
		self.canvas.delete(ALL)
		self.label['text'] = ('Tic Tac Toe Game')
		self.canvas.bind("<ButtonPress-1>", self.place)
		self.draw() #---------------------------------------
		self.table=[[-1,-1,-1],[-1,-1,-1],[-1,-1,-1]]
		self.c=0 #counter
		self.e=False #flag for end game

	def draw(self): #draws the outline lines
		self.canvas.create_rectangle(0,0,900,900, outline='black')
		self.canvas.create_rectangle(300,900,600,0, outline='black')
		self.canvas.create_rectangle(0,300,900,600, outline='black')

	def place(self, event):
		for i in range(0,900,300):
			for j in range(0,900,300):
				if event.x in range(i,i+300) and event.y in range(j, j+300):
					if self.canvas.find_enclosed(i,j,i+300, j+300) == ():
						if self.c % 2 == 0:
							#calculate points to draw circle
							x=(2*i+300)/2
							y=(2*j+300)/2
							x2=int(i/300)
							y2=int(j/300)
							self.canvas.create_oval(x+75,y+75,x-75,y-75, width = 4, outline="blue")
							self.table[y2][x2] = 4
							self.c+=1
						else:
							#calculate points to draw cross
							x=(2*i+300)/2
							y=(2*j+300)/2
							x2=int(i/300)
							y2=int(j/300)
							self.canvas.create_line(x+60,y+60,x-60,y-60, width = 4, fill="red")
							self.canvas.create_line(x-60,y+60,x+60,y-60, width = 4, fill="red")
							self.table[y2][x2] = 1
							self.c+=1
		self.check() 


	def startsingle(self):
		self.canvas.delete(ALL)
		self.label['text'] = ('Tic Tac Toe Game')
		self.canvas.bind("<ButtonPress-1>", self.placeone)
		self.draw()
		self.board = AI()

	def placeone(self, event):
		player = 'X'
		for i in range(0,900,300):
			for j in range(0,900,300):
				if event.x in range(i,i+300) and event.y in range(j, j+300):
					if self.canvas.find_enclosed(i,j,i+300, j+300) == ():
						x=(2*i+300)/2
						y=(2*j+300)/2
						x2=int(i/300)
						y2=int(j/300)
						self.canvas.create_line(x+60,y+60,x-60,y-60, width = 4, fill="red")
						self.canvas.create_line(x-60,y+60,x+60,y-60, width = 4, fill="red")

						
						player_move = x2 + 3*y2 #spremeni
						self.board.make_move(player_move, player)
						
		if self.board.complete():
			self.label['text'] = (self.board.winner())
			self.canvas.unbind("ButtonPress-1")
			self.board = AI()
		elif self.board.winner() != None:
			self.label['text'] = (self.board.winner())
			self.canvas.unbind("ButtonPress-1")
			self.board = AI()
		else:
			player = self.board.get_enemy(player)
			computer_move = self.board.determine(self.board, player)
			self.board.make_move(computer_move, player)

			ti = computer_move % 3
			tj = computer_move / 3

			x=(600*ti+300)/2
			y=(600*tj+300)/2
			#self.label2['text'] = str(computer_move) + '  ti ' + str(ti) + ' tj ' + str(tj) + ' y ' + str(y) + ' x ' +str(x)
			self.canvas.create_oval(x+75,y+75,x-75,y-75, width = 4, outline="blue")
			
			if self.board.winner() != None:
				self.label['text'] = (self.board.winner())
				self.canvas.unbind("ButtonPress-1")
				self.board = AI()

 

	def check(self):
		#checks for win
		#horitontal
		for i in range(3):
			if sum(self.table[i])==3:
				self.label['text'] = ('X wins')
				self.end()
			if sum(self.table[i])==12:
				self.label['text'] = ('O wins')
				self.end()
		#vertical
		self.vs=[[row[i] for row in self.table] for i in range(3)]
		for i in range(3):
			if sum(self.vs[i])==3:
				self.label['text'] = ('X wins')
				self.end()
			if sum(self.vs[i])==12:
				self.label['text'] = ('O wins')
				self.end()
		#diagonals
		self.dig1=0
		self.dig2=0
		for i in range(3):
			self.dig1+=self.table[i][i]
		for i in range(3):
			self.dig2+=self.table[2-i][i]

		if self.dig1==3:
			self.label['text'] = ('X wins')
			self.end()
		if self.dig1==12:
			self.label['text'] = ('O wins')
			self.end()
		if self.dig2==3:
			self.label['text'] = ('X wins')
			self.end()
		if self.dig2==12:
			self.label['text'] = ('O wins')
			self.end()

		#draw
		if self.e==False:
			a=0
			for i in range(3):
				a+=sum(self.table[i])
			if a == 24: #5 *4 + 4 * 1 --> 5 circles and 4 crosses
				self.label['text'] = ('Draw')
				self.end()

	def end(self):
		self.canvas.unbind("<ButtonPress-1>")
		self.e=True

	def mainloop(self):
		self.app.mainloop()
Пример #2
0
class main:
   
    def __init__(self,master):
        self.frame = Frame(master)
        self.frame.pack(fill="both", expand=True)
        self.canvas = Canvas(self.frame, width=300, height=300)
        self.canvas.pack(fill="both", expand=True)
        self.label=Label(self.frame, text='Tic Tac Toe Game', height=6, bg='black', fg='blue')
        self.label.pack(fill="both", expand=True)
        self.frameb=Frame(self.frame)
        self.frameb.pack(fill="both", expand=True)
        self.Start1=Button(self.frameb, text='Click here to start\ndouble player', height=4, command=self.start1,bg='white', fg='purple')
        self.Start1.pack(fill="both", expand=True, side=RIGHT)
        self.Start2=Button(self.frameb, text='Click here to start\nsingle player', height=4, command=self.start2,bg='purple', fg='white')
        self.Start2.pack(fill="both", expand=True, side=LEFT)     
        self._board()

    def start1(self):
        self.canvas.delete(ALL)
        self.label['text']=('Tic Tac Toe Game')
        self.canvas.bind("<ButtonPress-1>", self.sgplayer)  
        self._board()
        self.TTT=[[0,0,0],[0,0,0],[0,0,0]]
        self.i=0
        self.j=False

    def start2(self):
        self.canvas.delete(ALL)
        self.label['text']=('Tic Tac Toe Game')
        self.canvas.bind("<ButtonPress-1>", self.dgplayer)  
        self._board()
        self.TTT=[[0,0,0],[0,0,0],[0,0,0]]
        self.i=0
        self.j=False
        self.trigger=False

    def end(self):
        self.canvas.unbind("<ButtonPress-1>")
        self.j=True
        
    
    def _board(self):
        self.canvas.create_rectangle(0,0,300,300, outline="black")
        self.canvas.create_rectangle(100,300,200,0, outline="black")
        self.canvas.create_rectangle(0,100,300,200, outline="black")
        
    def sgplayer(self,event):
        for k in range(0,300,100):
            for j in range(0,300,100):
                if event.x in range(k,k+100) and event.y in range(j,j+100):
                    if self.canvas.find_enclosed(k,j,k+100,j+100)==():
                        if self.i%2==0:
                            X=(2*k+100)/2
                            Y=(2*j+100)/2
                            X1=int(k/100)
                            Y1=int(j/100)
                            self.canvas.create_oval( X+25, Y+25, X-25, Y-25, width=4, outline="black")
                            self.TTT[Y1][X1]+=1
                            self.i+=1
                        else:                         
                            X=(2*k+100)/2
                            Y=(2*j+100)/2
                            X1=int(k/100)
                            Y1=int(j/100)
                            self.canvas. create_line( X+20, Y+20, X-20, Y-20, width=4, fill="black")
                            self.canvas. create_line( X-20, Y+20, X+20, Y-20, width=4, fill="black")
                            self.TTT[Y1][X1]+=9
                            self.i+=1
        self.check()

    def dgplayer(self,event):
        for k in range(0,300,100):
            for j in range(0,300,100):
                if self.i%2==0:
                    if event.x in range(k,k+100) and event.y in range(j,j+100):
                        if self.canvas.find_enclosed(k,j,k+100,j+100)==():
                            X=(2*k+100)/2
                            Y=(2*j+100)/2
                            X1=int(k/100)
                            Y1=int(j/100)
                            self.canvas.create_oval( X+25, Y+25, X-25, Y-25, width=4, outline="black")
                            self.TTT[Y1][X1]+=1
                            self.i+=1
                            self.check()
                            self.trigger=False                           
                else:
                    print(self.i)
                    self.check()
                    print("checked")
                    self.AIcheck()
                    print("AIchecked")
                    self.trigger=False
                    
                    

                        
                        
    def check(self):
        #horizontal check
        for i in range(0,3):
            if sum(self.TTT[i])==27:
                self.label['text']=('2nd player wins!')
                self.end()
            if sum(self.TTT[i])==3:
                self.label['text']=('1st player wins!')
                self.end()
        #vertical check
        #the matrix below transposes self.TTT so that it could use the sum fucntion again
        self.ttt=[[row[i] for row in self.TTT] for i in range(3)]
        for i in range(0,3):            
            if sum(self.ttt[i])==27:
                self.label['text']=('2nd player wins!')
                self.end()
            if sum(self.ttt[i])==3:
                self.label['text']=('1st player wins!')
                self.end()
        #check for diagonal wins
        if self.TTT[1][1]==9:
            if self.TTT[0][0]==self.TTT[1][1] and self.TTT[2][2]==self.TTT[1][1] :
                self.label['text']=('2nd player wins!')
                self.end()
            if self.TTT[0][2]==self.TTT[1][1] and self.TTT[2][0]==self.TTT[1][1] :
                self.label['text']=('2nd player wins!')
                self.end()
        if self.TTT[1][1]==1:
            if self.TTT[0][0]==self.TTT[1][1] and self.TTT[2][2]==self.TTT[1][1] :
                self.label['text']=('1st player wins!')
                self.end()
            if self.TTT[0][2]==self.TTT[1][1] and self.TTT[2][0]==self.TTT[1][1] :
                self.label['text']=('1st player wins!')
                self.end()
        #check for draws
        if self.j==False:
            a=0
            for i in range(0,3):
                a+= sum(self.TTT[i])
            if a==41:
                self.label['text']=("It's a pass!")
                self.end()

                
    def AIcheck(self):
        #This is built on the self.check function
        self.ttt=[[row[i] for row in self.TTT] for i in range(3)]
        #DEFENSE
        #this is the horizontal checklist    
        for h in range(0,3): 
            k=0
            j=0            
            if sum(self.TTT[h])==2:
                while k <3:
                    if k==h:
                        while j <3:
                            if self.trigger==False:
                                if self.TTT[k][j]==0:
                                    self.cross(j,k)
                                    break
                            j+=1
                    k+=1
        #this is the vertical checklist
        for h in range(0,3):
            k=0
            j=0
            if sum(self.ttt[h])==2:                        
                while k <3:
                    if k==h:
                        while j <3:
                            if self.trigger==False:
                                if self.ttt[k][j]==0:
                                    self.cross(k,j)
                                    break
                            j+=1
                    k+=1                    
        #this is the diagonal checklist
        if self.TTT[1][1]==1:
            if self.TTT[0][0]==1:
                if self.trigger==False:
                    if self.TTT[2][2]==0:
                        self.cross(2,2)
            if self.TTT[0][2]==1:
                if self.trigger==False:
                    if self.TTT[2][0]==0:
                        self.cross(0,2)
            if self.TTT[2][0]==1:
                if self.trigger==False:
                    if self.TTT[0][2]==0:
                        self.cross(2,0)
            if self.TTT[2][2]==1:
                if self.trigger==False:
                    if self.TTT[0][0]==0:
                        self.cross(0,0)
                        
        if self.TTT[1][1]==0:
            if self.trigger==False:
                self.cross(1,1)
                self.trigger=True
        else:
            if self.trigger==False:
                self.randmove()

    def cross(self, k, j):
        # k is the x coords
        # j is the y coords
        X=(200*k+100)/2
        Y=(200*j+100)/2
        X1=int(k)
        Y1=int(j)
        self.canvas. create_line( X+20, Y+20, X-20, Y-20, width=4, fill="black")
        self.canvas. create_line( X-20, Y+20, X+20, Y-20, width=4, fill="black")
        self.TTT[Y1][X1]+=9
        self.check()
        self.i+=1
        self.trigger=True

                

    def randmove(self):
        while True:
            k=(randint(0,2))
            j=(randint(0,2))
            if self.TTT[j][k]==0:
                X=(200*k+100)/2
                Y=(200*j+100)/2
                self.canvas. create_line( X+20, Y+20, X-20, Y-20, width=4, fill="black")
                self.canvas. create_line( X-20, Y+20, X+20, Y-20, width=4, fill="black")
                self.TTT[j][k]+=9
                self.check()
                self.i+=1
                self.trigger=True
                break
            else:
                k=(randint(0,2))*100
                j=(randint(0,2))*100
Пример #3
0
class main:
   
    def __init__(self,master):
        self.frame = Frame(master)
        self.frame.pack(fill="both", expand=True)
        self.canvas = Canvas(self.frame, width=300, height=300)
        self.canvas.pack(fill="both", expand=True)
        self.label=Label(self.frame, text="Master Yunrui's Gomoku Game", height=6, bg='black', fg='pink')
        self.label.pack(fill="both", expand=True)
        self.frameb=Frame(self.frame)
        self.frameb.pack(fill="both", expand=True)
        self.Start1=Button(self.frameb, text='Click here to start\n may the plump be with you...', height=4, command=self.start1,bg='white', fg='purple')
        self.Start1.pack(fill="both", expand=True, side=RIGHT)
        self._board()

    def start1(self):
        self.canvas.delete(ALL)
        self.canvas.bind("<ButtonPress-1>", self.multiplayer)  
        self._board()
        self.board=Board() 
        self.player1 = Player(1)
        self.player2 = Player(2)
        self.turn = 1
        self.j=False
        self.Start1['text']=("Click To Restart")


    def end(self):
        self.canvas.unbind("<ButtonPress-1>")
        self.j=True
        
    
    def _board(self):
        for i in xrange(0,300,20):
            self.canvas.create_line(i,0,i,300)

        for j in xrange(0,300,20):
            self.canvas.create_line(0,j,300,j)
    
    def distance(self,x1,y1,x2,y2):
        return math.sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1))


        
    def multiplayer(self,event):

        x = event.x
        y = event.y
        for j in range(0,300,20):
            for i in range(0,300,20):
                if (self.distance(x,y,i,j)<5):
                    if self.turn==1:
                        print("click",i,j)
                        self.canvas.create_oval( i+5, j+5, i-5, j-5, width=2, outline="black")
                        self.player1.move(self.board,i/20,j/20)
                        self.turn=2
                        if self.player1.win(self.board,i/20,j/20):
                            self.label['text']=('Play 1 Wins')

                            print("Player 1 wins")
                            self.end()
                    else:
                        print("click",i,j)
                        self.canvas.create_oval( i+5, j+5, i-5, j-5, width=2, outline="pink")
                        self.player2.move(self.board,i/20,j/20)
                        self.turn=1
                        if self.player2.win(self.board,i/20,j/20):
                            self.label['text']=('Play 2 Wins')
                            print("Player 2 wins")
                            self.end()
        
        print(x,y,self.canvas.find_closest(x,y)[0])

    def check(self):
        #horizontal check
        for i in range(0,3):
            if sum(self.TTT[i])==27:
                self.label['text']=('2nd player wins!')
                self.end()
            if sum(self.TTT[i])==3:
                self.label['text']=('1st player wins!')
                self.end()
        #vertical check
        #the matrix below transposes self.TTT so that it could use the sum fucntion again
        self.ttt=[[row[i] for row in self.TTT] for i in range(3)]
        for i in range(0,3):            
            if sum(self.ttt[i])==27:
                self.label['text']=('2nd player wins!')
                self.end()
            if sum(self.ttt[i])==3:
                self.label['text']=('1st player wins!')
                self.end()
        #check for diagonal wins
        if self.TTT[1][1]==9:
            if self.TTT[0][0]==self.TTT[1][1] and self.TTT[2][2]==self.TTT[1][1] :
                self.label['text']=('2nd player wins!')
                self.end()
            if self.TTT[0][2]==self.TTT[1][1] and self.TTT[2][0]==self.TTT[1][1] :
                self.label['text']=('2nd player wins!')
                self.end()
        if self.TTT[1][1]==1:
            if self.TTT[0][0]==self.TTT[1][1] and self.TTT[2][2]==self.TTT[1][1] :
                self.label['text']=('1st player wins!')
                self.end()
            if self.TTT[0][2]==self.TTT[1][1] and self.TTT[2][0]==self.TTT[1][1] :
                self.label['text']=('1st player wins!')
                self.end()
        #check for draws
        if self.j==False:
            a=0
            for i in range(0,3):
                a+= sum(self.TTT[i])
            if a==41:
                self.label['text']=("It's a pass!")
                self.end()

                
    def AIcheck(self):
        #This is built on the self.check function
        self.ttt=[[row[i] for row in self.TTT] for i in range(3)]
        #DEFENSE
        #this is the horizontal checklist    
        for h in range(0,3): 
            k=0
            j=0            
            if sum(self.TTT[h])==2:
                while k <3:
                    if k==h:
                        while j <3:
                            if self.trigger==False:
                                if self.TTT[k][j]==0:
                                    self.cross(j,k)
                                    break
                            j+=1
                    k+=1
        #this is the vertical checklist
        for h in range(0,3):
            k=0
            j=0
            if sum(self.ttt[h])==2:                        
                while k <3:
                    if k==h:
                        while j <3:
                            if self.trigger==False:
                                if self.ttt[k][j]==0:
                                    self.cross(k,j)
                                    break
                            j+=1
                    k+=1                    
        #this is the diagonal checklist
        if self.TTT[1][1]==1:
            if self.TTT[0][0]==1:
                if self.trigger==False:
                    if self.TTT[2][2]==0:
                        self.cross(2,2)
            if self.TTT[0][2]==1:
                if self.trigger==False:
                    if self.TTT[2][0]==0:
                        self.cross(0,2)
            if self.TTT[2][0]==1:
                if self.trigger==False:
                    if self.TTT[0][2]==0:
                        self.cross(2,0)
            if self.TTT[2][2]==1:
                if self.trigger==False:
                    if self.TTT[0][0]==0:
                        self.cross(0,0)
                        
        if self.TTT[1][1]==0:
            if self.trigger==False:
                self.cross(1,1)
                self.trigger=True
        else:
            if self.trigger==False:
                self.randmove()

    def cross(self, k, j):
        # k is the x coords
        # j is the y coords
        X=(200*k+100)/2
        Y=(200*j+100)/2
        X1=int(k)
        Y1=int(j)
        self.canvas. create_line( X+20, Y+20, X-20, Y-20, width=4, fill="black")
        self.canvas. create_line( X-20, Y+20, X+20, Y-20, width=4, fill="black")
        self.TTT[Y1][X1]+=9
        self.check()
        self.i+=1
        self.trigger=True
         

    def randmove(self):
        while True:
            k=(randint(0,2))
            j=(randint(0,2))
            if self.TTT[j][k]==0:
                X=(200*k+100)/2
                Y=(200*j+100)/2
                self.canvas. create_line( X+20, Y+20, X-20, Y-20, width=4, fill="black")
                self.canvas. create_line( X-20, Y+20, X+20, Y-20, width=4, fill="black")
                self.TTT[j][k]+=9
                self.check()
                self.i+=1
                self.trigger=True
                break
            else:
                k=(randint(0,2))*100
                j=(randint(0,2))*100
Пример #4
0
class SurfaceManipulator(Frame):
    r"""
    A translation surface editor in tk.
    """

    # STATIC METHODS AND OBJECTS

    current = None
    # boolean variable to remember if the hook was run!
    _clear_hook_was_run = 0

    @staticmethod
    def launch(geometry="800x700+10+10"):
        r"""Prefered way to gain access to a SurfaceManipulator window."""
        if SurfaceManipulator.current is None:
            SurfaceManipulator._clear_hook()
            root = Tk()
            root.geometry(geometry)
            SurfaceManipulator.current = SurfaceManipulator(root)
        return SurfaceManipulator.current

    @staticmethod
    def _window_destroyed(surface_manipulator):
        if SurfaceManipulator.current is surface_manipulator:
            SurfaceManipulator.current = None

    @staticmethod
    def _clear_hook():
        if not SurfaceManipulator._clear_hook_was_run:
            # Hack due to Nathan Dunfield (http://trac.sagemath.org/ticket/15152)
            import IPython.lib.inputhook as ih
            ih.clear_inputhook()
            SurfaceManipulator._clear_hook_was_run = 1

    # NORMAL METHODS

    def __init__(self, parent, surface=None, surfaces=[]):
        r"""
        INPUT:
        - ``surfaces`` -- a list of surfaces that the editor may modify
        - ``surface`` -- surface selected by default
        - ``parent`` -- parent Tk window
        """
        Frame.__init__(self, parent)
        self._parent = parent
        self.pack(fill="both", expand=1)

        # Run something when closing
        self._parent.wm_protocol("WM_DELETE_WINDOW", self.exit)

        # Surface currently being manipulated
        self._surface = None
        # List of surfaces in editor
        self._surfaces = []
        # More variables to initialize
        self._currentActor = None
        # Initialization of GUI
        self._init_menu()
        self._init_gui()
        # Setup surface list
        for s in surfaces:
            self.add_surface(s)
        # Setup initial surface
        if surface is not None:
            self.add_surface(surface)
        self.set_surface(surface)

    def __repr__(self):
        return "Surface manipulator"

    def add_mega_wollmilchsau(self):
        from geometry.mega_wollmilchsau import MegaWollmilchsau
        s = MegaWollmilchsau()
        sm, sb = s.get_bundle()
        self.set_surface(sb)

    def add_octagon(self):
        from geometry.similarity_surface_generators import TranslationSurfaceGenerators
        ss = TranslationSurfaceGenerators.regular_octagon()
        ss.edit()

    def _init_menu(self):

        self._menubar = Menu(self._parent)
        menubar = self._menubar
        self._parent.config(menu=menubar)

        #new_menu = Menu(menubar, tearoff=0)
        #new_menu.add_command(label="Billiard Table", command=self.on_new_similarity_surface)

        file_menu = Menu(menubar, tearoff=0)
        #file_menu.add_cascade(label="New", menu=new_menu)
        file_menu.add_command(label="Octagon", command=self.add_octagon)
        file_menu.add_command(label="MegaWollmilchsau",
                              command=self.add_mega_wollmilchsau)
        file_menu.add_separator()
        file_menu.add_command(label="About", command=self.on_about)
        file_menu.add_command(label="Export PostScript",
                              command=self.on_export)
        file_menu.add_command(label="Exit",
                              command=self.exit,
                              accelerator="Alt+F4")
        menubar.add_cascade(label="File", underline=0, menu=file_menu)

        self._surface_menu = Menu(menubar, tearoff=0)
        self._selected_surface = IntVar()
        self._selected_surface.set(-1)
        menubar.add_cascade(label="Surface",
                            underline=0,
                            menu=self._surface_menu)
        self._surface_menu.add_radiobutton(label="None",
                                           command=self.menu_select_surface,
                                           variable=self._selected_surface,
                                           value=-1)

    def _init_gui(self):
        self._parent.title("FlatSurf Editor")

        self._canvas = Canvas(self, bg="#444", width=300, height=200)
        self._canvas.pack(fill="both", expand=1)

        self.bottom_text = Label(self, text="Welcome to FlatSurf.", anchor="w")
        self.bottom_text.pack(fill="x", expand=0)

        self.set_actor(None)

    def add_surface(self, newsurface):
        r"""
        Add a surface to the display list for the window.
        Returns the index of the new surface in the surface list.
        """
        if (newsurface == None):
            return -1
        i = 0
        for s in self._surfaces:
            if (s == newsurface):
                return i
            i = i + 1
        self._surfaces.append(newsurface)
        newsurface.zoom_fit_nice_boundary()
        self._reset_surface_menu()
        return len(self._surfaces) - 1

    def exit(self):
        SurfaceManipulator._window_destroyed(self)
        self._parent.destroy()

    def find_bundle(self, surface):
        for surface_bundle in self._surfaces:
            if surface is surface_bundle.get_surface():
                return surface_bundle
        return None

    def get_bundle(self):
        return self._surface

    def get_bundles(self):
        return self._surfaces

    def get_canvas(self):
        return self._canvas

    def get_center(self):
        r"""
        Return the center of the canvas as a pair of integers.
        """
        return (self.get_width() / 2, self.get_height() / 2)

    def get_height(self):
        r"""
        Return the height of the canvas (an integer).
        """
        return self.get_canvas().winfo_height()

    def get_parent(self):
        return self._parent

    def get_surface_bundle(self):
        r"""
        Get the current surface bundle, or None if there is none.
        """
        return self._surface

    def get_width(self):
        r"""
        Return the width of the canvas (an integer).
        """
        return self.get_canvas().winfo_width()

    def menu_select_surface(self):
        r"""
        Called when a surface is selected from a menu.
        """
        i = self._selected_surface.get()
        if i == -1:
            self.set_surface(None)
        else:
            self.set_surface(self._surfaces[i])

    def on_about(self):
        self.set_text("Written by Vincent Delecroix and Pat Hooper.")

    def on_delete_junk(self):
        self._canvas.delete("junk")

    def on_export(self):
        r"""
        Export image as postscript file.
        """
        myFormats = [('PostScript', '*.ps')]
        fileName = tkFileDialog.asksaveasfilename(parent=self,
                                                  filetypes=myFormats,
                                                  title="Save image as...")
        if len(fileName) > 0:
            self._canvas.update()
            self._canvas.postscript(file=fileName)
            self.set_text("Wrote image to " + fileName)

#    def on_new_similarity_surface(self):
#        s = CreateSimilaritySurfaceBundle(len(self._surfaces),self)
#        if s is not None:
#            i = self.set_surface(s)
#            self.set_text("Created new surface `"+self._surfaces[i].get_name()+"'.")

    def _on_no_surface(self):
        self._canvas.delete("all")

    def _on_zoom(self):
        self.set_actor(ZoomActor(self))

    def _on_zoom_box(self):
        self.set_actor(ZoomBoxActor(self))

    def _on_redraw_all(self):
        if self._surface is not None:
            self._surface.redraw_all()

    def _on_recenter(self):
        self.set_actor(RecenterActor(self))

    def _reset_menus(self):
        r"""
        Reset all menus except the file and surface menu
        """
        # The following loop removes all but the first two menus (File and Surface).
        num = len(self._menubar.children)
        for i in range(num, 2, -1):
            self._menubar.delete(i)
        if self._surface != None:
            self._surface.make_menus(self._menubar)

    def _reset_surface_menu(self):
        r"""
        Reset the surface menu.
        """
        ### This is a hack to get the number of items in the menu:
        num = self._surface_menu.index(100) + 1
        # First we remove everything but the first entry ("None")
        for i in range(num - 1, 0, -1):
            #print("removing a child2: "+str(i)+" of "+str(num))
            self._surface_menu.delete(i)
        # Add an entry for every surface in the list.
        for i in range(len(self._surfaces)):
            surface = self._surfaces[i]
            self._surface_menu.add_radiobutton(
                label=surface.get_name(),
                command=self.menu_select_surface,
                variable=self._selected_surface,
                value=i)

    def set_text(self, text):
        self.bottom_text["text"] = text

    def set_actor(self, actor):
        r"""
        Set the current mode of user interaction.
        """
        if (actor != self._currentActor):
            if self._currentActor != None:
                self._currentActor.on_deactivate()
            if (actor == None):
                self.set_text("Nothing going on.")
                # Event bindings
                self._canvas.unbind('<Button-1>')
                self._canvas.unbind('<Button-2>')
                self._canvas.unbind('<Button-3>')
                self._canvas.unbind('<Double-Button-1>')
                self._canvas.unbind('<Shift-Button-1>')
                self._canvas.unbind('<Motion>')
                self.unbind('<FocusIn>')
                self.unbind('<FocusOut>')
                #self._canvas.unbind('<ButtonPress-1>')
                self._canvas.unbind('<ButtonRelease-1>')
                self._canvas.unbind('<B1-Motion>')
                self._parent.unbind('<Key>')
                self._parent.unbind('<KeyRelease>')
            else:
                # Event bindings
                self._canvas.bind('<Button-1>', actor.single_left_click)
                self._canvas.bind('<Double-Button-1>', actor.double_left_click)
                self._canvas.bind('<Triple-Button-1>', actor.double_left_click)
                self._canvas.bind('<Button-2>', actor.single_middle_click)
                self._canvas.bind('<Double-Button-2>',
                                  actor.double_middle_click)
                self._canvas.bind('<Triple-Button-2>',
                                  actor.double_middle_click)
                self._canvas.bind('<Button-3>', actor.single_right_click)
                self._canvas.bind('<Double-Button-3>',
                                  actor.double_right_click)
                self._canvas.bind('<Triple-Button-3>',
                                  actor.double_right_click)
                self._canvas.bind('<Shift-Button-1>', actor.shift_click)
                self._canvas.bind('<Motion>', actor.mouse_moved)
                #self._canvas.bind('<ButtonPress-1>', actor.left_mouse_pressed)
                self._canvas.bind('<ButtonRelease-1>',
                                  actor.left_mouse_released)
                self._canvas.bind('<B1-Motion>', actor.left_dragged)
                self.bind('<FocusIn>', actor.focus_in)
                self.bind('<FocusOut>', actor.focus_out)
                self._parent.bind('<Key>', actor.key_press)
                self._parent.bind('<KeyRelease>', actor.key_release)
                self._currentActor = actor
                self._currentActor.on_activate()

    def set_surface(self, surface_bundle):
        r"""
        Set the current surface to the one given by surface_bundle
        """
        i = self.add_surface(surface_bundle)
        if surface_bundle != self._surface:
            self._canvas.delete("all")
            self._surface = surface_bundle
            self._surface_menu.invoke(i + 1)
            if i >= 0:
                self.set_text("Switched to `" + self._surface.get_name() +
                              "'.")
                self._parent.title(self._surface.get_name())
                self._reset_menus()
                # stop the actor (was a bug).
                self.set_actor(None)
                if isinstance(self._surface, EditorRenderer):
                    self._surface.initial_render()
            else:
                self.set_text("No surface selected.")
                self._parent.title("FlatSurf Editor")
                self._reset_menus()
                self.set_actor(None)
        return i

    def surface_renamed(self):
        if self._surface is not None:
            self._parent.title(self._surface.get_name())
            self._reset_surface_menu()
Пример #5
0
class SurfaceManipulator(Frame):
    r"""
    A translation surface editor in tk.
    """
  
    # STATIC METHODS AND OBJECTS

    current = None
    # boolean variable to remember if the hook was run!
    _clear_hook_was_run = 0

    @staticmethod
    def launch(geometry = "800x700+10+10"):
        r"""Prefered way to gain access to a SurfaceManipulator window."""
        if SurfaceManipulator.current is None:
            SurfaceManipulator._clear_hook()
            root = Tk()
            root.geometry(geometry)
            SurfaceManipulator.current=SurfaceManipulator(root)
        return SurfaceManipulator.current
    
    @staticmethod
    def _window_destroyed(surface_manipulator):
        if SurfaceManipulator.current is surface_manipulator:
            SurfaceManipulator.current = None

    @staticmethod
    def _clear_hook():
        if not SurfaceManipulator._clear_hook_was_run:
            # Hack due to Nathan Dunfield (http://trac.sagemath.org/ticket/15152)
            import IPython.lib.inputhook as ih
            ih.clear_inputhook()
            SurfaceManipulator._clear_hook_was_run = 1

    # NORMAL METHODS


    def __init__(self, parent, surface=None, surfaces=[]):
        r"""
        INPUT:
        - ``surfaces`` -- a list of surfaces that the editor may modify
        - ``surface`` -- surface selected by default
        - ``parent`` -- parent Tk window
        """
        Frame.__init__(self, parent)   
        self._parent = parent
        self.pack(fill="both", expand=1)

        # Run something when closing
        self._parent.wm_protocol ("WM_DELETE_WINDOW", self.exit)

        # Surface currently being manipulated
        self._surface=None
        # List of surfaces in editor
        self._surfaces=[]
        # More variables to initialize
        self._currentActor=None
        # Initialization of GUI
        self._init_menu()
        self._init_gui()
        # Setup surface list
        for s in surfaces:
            self.add_surface(s)
        # Setup initial surface
        if surface is not None:
            self.add_surface(surface)
        self.set_surface(surface)

    def __repr__(self):
        return "Surface manipulator"

    def add_mega_wollmilchsau(self):
        from geometry.mega_wollmilchsau import MegaWollmilchsau
        s = MegaWollmilchsau()
        sm,sb = s.get_bundle()
        self.set_surface(sb)

    def add_octagon(self):
        from geometry.similarity_surface_generators import TranslationSurfaceGenerators
        ss=TranslationSurfaceGenerators.regular_octagon()
        ss.edit()

    def _init_menu(self):
        
        self._menubar = Menu(self._parent)
        menubar=self._menubar
        self._parent.config(menu=menubar)
        
        #new_menu = Menu(menubar, tearoff=0)
        #new_menu.add_command(label="Billiard Table", command=self.on_new_similarity_surface)
        
        file_menu = Menu(menubar, tearoff=0)
        #file_menu.add_cascade(label="New", menu=new_menu)
        file_menu.add_command(label="Octagon", command=self.add_octagon)
        file_menu.add_command(label="MegaWollmilchsau", command=self.add_mega_wollmilchsau)
        file_menu.add_separator()
        file_menu.add_command(label="About", command=self.on_about)
        file_menu.add_command(label="Export PostScript", command=self.on_export)
        file_menu.add_command(label="Exit", command=self.exit, accelerator="Alt+F4")
        menubar.add_cascade(label="File", underline=0, menu=file_menu)

        self._surface_menu = Menu(menubar, tearoff=0)
        self._selected_surface = IntVar()
        self._selected_surface.set(-1)
        menubar.add_cascade(label="Surface", underline=0, menu=self._surface_menu)
        self._surface_menu.add_radiobutton(label="None", 
            command=self.menu_select_surface, variable=self._selected_surface, 
            value=-1)

    def _init_gui(self):
        self._parent.title("FlatSurf Editor")

        self._canvas = Canvas(self, bg="#444", width=300, height=200)
        self._canvas.pack(fill="both", expand=1)
        
        self.bottom_text = Label(self, text="Welcome to FlatSurf.",
            anchor="w")
        self.bottom_text.pack(fill="x", expand=0)

        self.set_actor(None)

    def add_surface(self,newsurface):
        r"""
        Add a surface to the display list for the window.
        Returns the index of the new surface in the surface list.
        """
        if (newsurface==None):
            return -1
        i=0
        for s in self._surfaces:
            if (s==newsurface):
                return i
            i=i+1
        self._surfaces.append(newsurface)
        newsurface.zoom_fit_nice_boundary()
        self._reset_surface_menu()
        return len(self._surfaces)-1

    def exit(self):
        SurfaceManipulator._window_destroyed(self)
        self._parent.destroy()

    def find_bundle(self, surface):
        for surface_bundle in self._surfaces:
            if surface is surface_bundle.get_surface():
                return surface_bundle
        return None

    def get_bundle(self):
        return self._surface

    def get_bundles(self):
        return self._surfaces

    def get_canvas(self):
        return self._canvas

    def get_center(self):
        r"""
        Return the center of the canvas as a pair of integers.
        """
        return ( self.get_width()/2, self.get_height()/2 )

    def get_height(self):
        r"""
        Return the height of the canvas (an integer).
        """
        return self.get_canvas().winfo_height()

    def get_parent(self):
        return self._parent

    def get_surface_bundle(self):
        r"""
        Get the current surface bundle, or None if there is none.
        """
        return self._surface

    def get_width(self):
        r"""
        Return the width of the canvas (an integer).
        """
        return self.get_canvas().winfo_width()

    def menu_select_surface(self):
        r"""
        Called when a surface is selected from a menu.
        """
        i = self._selected_surface.get()
        if i == -1:
            self.set_surface(None)
        else:
            self.set_surface(self._surfaces[i])

    def on_about(self):
        self.set_text("Written by Vincent Delecroix and Pat Hooper.")

    def on_delete_junk(self):
        self._canvas.delete("junk")

    def on_export(self):
        r"""
        Export image as postscript file.
        """
        myFormats = [('PostScript','*.ps')]
        fileName = tkFileDialog.asksaveasfilename(parent=self,
            filetypes=myFormats , title="Save image as...")
        if len(fileName ) > 0:
            self._canvas.update() 
            self._canvas.postscript(file = fileName) 
            self.set_text("Wrote image to "+fileName)

#    def on_new_similarity_surface(self):  
#        s = CreateSimilaritySurfaceBundle(len(self._surfaces),self)
#        if s is not None:
#            i = self.set_surface(s)
#            self.set_text("Created new surface `"+self._surfaces[i].get_name()+"'.")

    def _on_no_surface(self):
        self._canvas.delete("all")

    def _on_zoom(self):
        self.set_actor(ZoomActor(self))

    def _on_zoom_box(self):
        self.set_actor(ZoomBoxActor(self))

    def _on_redraw_all(self):
        if self._surface is not None:
            self._surface.redraw_all()

    def _on_recenter(self):
        self.set_actor(RecenterActor(self))

    def _reset_menus(self):
        r"""
        Reset all menus except the file and surface menu
        """
        # The following loop removes all but the first two menus (File and Surface).
        num = len(self._menubar.children)
        for i in range(num,2,-1):
            self._menubar.delete(i)
        if self._surface!= None:
            self._surface.make_menus(self._menubar)

    def _reset_surface_menu(self):
        r"""
        Reset the surface menu.
        """
        ### This is a hack to get the number of items in the menu: 
        num = self._surface_menu.index(100)+1
        # First we remove everything but the first entry ("None")
        for i in range(num-1,0,-1):
            #print("removing a child2: "+str(i)+" of "+str(num))
            self._surface_menu.delete(i)
        # Add an entry for every surface in the list.
        for i in range( len(self._surfaces) ):
            surface = self._surfaces[i]
            self._surface_menu.add_radiobutton(label=surface.get_name(),
                command=self.menu_select_surface, variable=self._selected_surface,
                value=i)

    def set_text(self, text):
        self.bottom_text["text"]=text

    def set_actor(self, actor):
        r"""
        Set the current mode of user interaction.
        """
        if (actor != self._currentActor):
            if self._currentActor != None:
                self._currentActor.on_deactivate()
            if (actor==None):
                self.set_text("Nothing going on.")
                # Event bindings
                self._canvas.unbind('<Button-1>')
                self._canvas.unbind('<Button-2>')
                self._canvas.unbind('<Button-3>')
                self._canvas.unbind('<Double-Button-1>')
                self._canvas.unbind('<Shift-Button-1>')
                self._canvas.unbind('<Motion>')
                self.unbind('<FocusIn>')
                self.unbind('<FocusOut>')
                #self._canvas.unbind('<ButtonPress-1>')
                self._canvas.unbind('<ButtonRelease-1>')
                self._canvas.unbind('<B1-Motion>')
                self._parent.unbind('<Key>')
                self._parent.unbind('<KeyRelease>')
            else:
                # Event bindings
                self._canvas.bind('<Button-1>', actor.single_left_click)
                self._canvas.bind('<Double-Button-1>', actor.double_left_click)
                self._canvas.bind('<Triple-Button-1>', actor.double_left_click)
                self._canvas.bind('<Button-2>', actor.single_middle_click)
                self._canvas.bind('<Double-Button-2>', actor.double_middle_click)
                self._canvas.bind('<Triple-Button-2>', actor.double_middle_click)
                self._canvas.bind('<Button-3>', actor.single_right_click)
                self._canvas.bind('<Double-Button-3>', actor.double_right_click)
                self._canvas.bind('<Triple-Button-3>', actor.double_right_click)
                self._canvas.bind('<Shift-Button-1>', actor.shift_click)
                self._canvas.bind('<Motion>', actor.mouse_moved)
                #self._canvas.bind('<ButtonPress-1>', actor.left_mouse_pressed)
                self._canvas.bind('<ButtonRelease-1>', actor.left_mouse_released)
                self._canvas.bind('<B1-Motion>',actor.left_dragged)
                self.bind('<FocusIn>', actor.focus_in)
                self.bind('<FocusOut>', actor.focus_out)
                self._parent.bind('<Key>', actor.key_press)
                self._parent.bind('<KeyRelease>', actor.key_release)
                self._currentActor=actor
                self._currentActor.on_activate()

    def set_surface(self,surface_bundle):
        r"""
        Set the current surface to the one given by surface_bundle
        """
        i = self.add_surface(surface_bundle)
        if surface_bundle != self._surface:
            self._canvas.delete("all")
            self._surface=surface_bundle
            self._surface_menu.invoke(i+1)
            if i >= 0:
                self.set_text("Switched to `"+self._surface.get_name()+"'.")
                self._parent.title(self._surface.get_name())
                self._reset_menus()
                # stop the actor (was a bug).
                self.set_actor(None)
                if isinstance(self._surface, EditorRenderer):
                    self._surface.initial_render()
            else:
                self.set_text("No surface selected.")
                self._parent.title("FlatSurf Editor")
                self._reset_menus()
                self.set_actor(None)
        return i

    def surface_renamed(self):
        if self._surface is not None:
            self._parent.title(self._surface.get_name())
            self._reset_surface_menu()
class TTT:
    '''
        main class for interface and game handling
    '''
    def __init__(self, master):
        self.frame = Frame(master)
        self.frame.pack(fill="both", expand=True)
        self.label = Label(self.frame, text='Tic Tac Toe Game', height=2, font="Arial 14", bg='black', fg='blue')
        self.label.pack(fill="both", expand=True)
        self.canvas = Canvas(self.frame, width=300, height=300)
        self.canvas.pack(fill="both", expand=True)
        self.status = Label(self.frame, text='Start Game', height=2, font="Arial 14", bg='white', fg='black')
        self.status.pack(fill="both", expand=True)
        self.reset = Button(self.frame, text="Reset Game", command=self.reset)
        self.reset.pack(fill="both", expand=True)
        self.__board()
        self.canvas.bind("<ButtonPress-1>", self.handler)
        self.board = [0 for x in range(0, 9)]
        self.winner = None
        self.lastmoves = []

    def get_free_cells(self):
        moves = []
        for i,v in enumerate(self.board):
            if v == 0:
                moves.append(i)
        return moves

    def mark(self,pos, marker):
        self.board[pos] = marker
        self.lastmoves.append(pos)

    def revert_last_move(self):
        self.board[self.lastmoves.pop()] = 0
        self.winner = None

    def is_gameover(self):
        win_positions = [(0,1,2), (3,4,5), (6,7,8), (0,3,6),(1,4,7),(2,5,8), (0,4,8), (2,4,6)]
        for i,j,k in win_positions:
            if self.board[i] == self.board[j] and self.board[j] == self.board[k] and self.board[i] != 0:
                self.winner = self.board[i]
                return True
        if 0 not in self.board:
            self.winner = 0
            return True
        return False

    def get_score(self):
        if self.is_gameover():
            if self.winner == 2:
                return 1 # Won
            elif self.winner == 1:
                return -1
        return 0
        
    def get_cell_value(self,pos):
        return self.board[pos]

    def __board(self):
        self.canvas.create_rectangle(0, 0, 300, 300, outline="black")
        self.canvas.create_rectangle(100, 300, 200, 0, outline="black")
        self.canvas.create_rectangle(0, 100, 300, 200, outline="black")

    def reset(self):
        self.canvas.delete(ALL)
        self.__board()
        self.changeStatus('Start Game')
        self.canvas.bind("<ButtonPress-1>", self.handler)
        self.board = [0 for x in range(0, 9)]
        self.winner = None
        self.lastmoves = []

    def changeStatus(self, status):
        self.status['text'] = status

    def markFinal(self, pos, marker):
        x = pos%3
        y = int(pos/3)
        # print pos, marker
        if marker == 2:
            X = 100 * (x + 1)
            Y = 100 * (y + 1)
            self.canvas.create_oval(X - 25, Y - 25, X - 75, Y - 75, width=4, outline="green")
            self.changeStatus("X's Move !")
        else:
            X = 100 * x
            Y = 100 * y
            self.canvas.create_line(X + 25, Y + 25, X + 75, Y + 75, width=4, fill="red")
            self.canvas.create_line(X + 25, Y + 75, X + 75, Y + 25, width=4, fill="red")
            self.changeStatus("O's Move !")
        
        self.board[pos] = marker

    def handler(self, event):
        '''
        handle mouse click event on the board
        '''
        x = int(event.x / 100)
        y = int(event.y / 100)
        if self.board[y*3+x] == 0:
            self.markFinal(y*3+x, 2)
            if self.is_gameover():
                self.canvas.unbind("<ButtonPress-1>")
                if self.winner == 2:
                    self.changeStatus("O Won the Game !")
                elif self.winner == 1:
                    self.changeStatus("X Won the Game !")
                else:
                    self.changeStatus("Game Draw !")
                return

            pos, score = min_max_move(self, 1)
            self.markFinal(pos, 1);

            if self.is_gameover():
                self.canvas.unbind("<ButtonPress-1>")
                if self.winner == 2:
                    self.changeStatus("O Won the Game !")
                elif self.winner == 1:
                    self.changeStatus("X Won the Game !")
                else:
                    self.changeStatus("Game Draw !") 
Пример #7
0
class main:
    def __init__(self, master):
        self.frame = Frame(master)
        self.frame.pack(fill="both", expand=True)
        self.canvas = Canvas(self.frame, width=600, height=600)
        self.canvas.pack(fill="both", expand=True)
        self.label = Label(self.frame,
                           text='Tic Tac Toe',
                           height=2,
                           bg='white',
                           fg='black')
        self.label.pack(fill="both", expand=True)
        self.frameb = Frame(self.frame)
        self.frameb.pack(fill="both", expand=True)
        self.Start2 = Button(self.frameb,
                             text='Two players',
                             height=4,
                             command=self.start2,
                             bg='yellow',
                             fg='black')
        self.Start2.pack(fill="both", expand=True, side=RIGHT)
        self.Start1 = Button(self.frameb,
                             text='One player',
                             height=4,
                             command=self.start1,
                             bg='yellow',
                             fg='black')
        self.Start1.pack(fill="both", expand=True, side=LEFT)
        self.whichPlayer = 1
        self.computerPlays = False

    def start2(self):
        self.computerPlays = False
        self.canvas.delete(ALL)
        #initialize board
        self.board = [[0] * 3 for i in range(3)]
        self.canvas.bind("<ButtonPress-1>", self.move)
        #draw board
        self.drawGrid()
        self.rows = [0, 0, 0]
        self.cols = [0, 0, 0]
        self.diag1 = 0
        self.diag2 = 0
        self.label['text'] = 'Tic Tac Toe'
        self.turns = 1

    def start1(self):
        self.whichPlayer = 1
        print('you (circle) vs computer (cross)')
        self.computerPlays = True
        self.canvas.delete(ALL)
        #initialize board
        self.board = [[0] * 3 for i in range(3)]
        #draw board
        self.drawGrid()
        self.rows = [0, 0, 0]
        self.cols = [0, 0, 0]
        self.diag1 = 0
        self.diag2 = 0
        self.label['text'] = 'Tic Tac Toe'
        self.canvas.bind("<ButtonPress-1>", self.move)
        self.turns = 1

    def computerMove(self):
        posx = randint(0, 2)
        posy = randint(0, 2)
        if (self.turns > 8):
            self.label['text'] = 'Draw!'
            self.endGame()
        #attack
        moved = False
        for i in range(3):
            if (self.rows[i] == -2):
                for j in range(3):
                    if (self.board[i][j] == 0):
                        self.drawCross(j, i)
                        self.board[i][j] = -1
                        self.rows[i] -= 1
                        self.cols[j] -= 1
                        if (i == j):
                            self.diag1 -= 1
                        if (i + j == 2):
                            self.diag2 -= 1
                        moved = True
        if (moved == False):
            for i in range(3):
                if (self.cols[i] == -2):
                    for j in range(3):
                        if (self.board[j][i] == 0):
                            self.drawCross(i, j)
                            self.board[j][i] = -1
                            self.rows[j] -= 1
                            self.cols[i] -= 1
                            if (i == j):
                                self.diag1 -= 1
                            if (i + j == 2):
                                self.diag2 -= 1
                            moved = True
        if (moved == False):
            if (self.diag1 == -2):
                for i in range(3):
                    if (self.board[i][i] == 0):
                        self.drawCross(i, i)
                        self.board[i][i] = -1
                        self.rows[i] -= 1
                        self.cols[i] -= 1
                        if (i == j):
                            self.diag1 -= 1
                        if (i + j == 2):
                            self.diag2 -= 1
                        moved = True
        if (moved == False):
            if (self.diag2 == -2):
                for i in range(3):
                    if (self.board[i][2 - i] == 0):
                        self.drawCross(2 - i, i)
                        self.board[i][2 - i] = -1
                        self.rows[i] -= 1
                        self.cols[2 - i] -= 1
                        if (i == j):
                            self.diag1 -= 1
                        if (i + j == 2):
                            self.diag2 -= 1
                        moved = True
        #defense
        moved = False
        for i in range(3):
            if (self.rows[i] == 2):
                for j in range(3):
                    if (self.board[i][j] == 0):
                        self.drawCross(j, i)
                        self.board[i][j] = -1
                        self.rows[i] -= 1
                        self.cols[j] -= 1
                        if (i == j):
                            self.diag1 -= 1
                        if (i + j == 2):
                            self.diag2 -= 1
                        moved = True
        if (moved == False):
            for i in range(3):
                if (self.cols[i] == 2):
                    for j in range(3):
                        if (self.board[j][i] == 0):
                            self.drawCross(i, j)
                            self.board[j][i] = -1
                            self.rows[j] -= 1
                            self.cols[i] -= 1
                            if (i == j):
                                self.diag1 -= 1
                            if (i + j == 2):
                                self.diag2 -= 1
                            moved = True
        if (moved == False):
            if (self.diag1 == 2):
                for i in range(3):
                    if (self.board[i][i] == 0):
                        self.drawCross(i, i)
                        self.board[i][i] = -1
                        self.rows[i] -= 1
                        self.cols[i] -= 1
                        self.diag1 -= 1
                        moved = True
        if (moved == False):
            if (self.diag2 == 2):
                for i in range(3):
                    if (self.board[i][2 - i] == 0):
                        self.drawCross(2 - i, i)
                        self.board[i][2 - i] = -1
                        self.rows[i] -= 1
                        self.cols[2 - i] -= 1
                        self.diag2 -= 1
                        moved = True

        if (moved == False):
            while (self.board[posx][posy] != 0):  #random choice
                posx = randint(0, 2)
                posy = randint(0, 2)
            if (self.board[posx][posy] == 0):
                self.board[posx][posy] = -1
                self.rows[posx] -= 1
                self.cols[posy] -= 1
                if (posx == posy):
                    self.diag1 -= 1
                if (posx + posy == 2):
                    self.diag2 -= 1
                self.drawCross(posy, posx)
                moved = True
        for i in range(3):
            if (self.rows[i] == -3 or self.cols[i] == -3 or self.diag1 == -3
                    or self.diag2 == -3):
                self.label['text'] = ('Computer wins!')
                self.endGame()
        self.whichPlayer = 1
        self.turns += 1

    def drawCross(self, row, col):
        lon = 100
        offset = 50
        self.canvas.create_line(row * 200 + offset,
                                col * 200 + offset,
                                row * 200 + offset + lon,
                                col * 200 + offset + lon,
                                width=4,
                                fill="red")
        self.canvas.create_line(row * 200 + offset + lon,
                                col * 200 + offset,
                                row * 200 + offset,
                                col * 200 + offset + lon,
                                width=4,
                                fill="red")

    def drawGrid(self):
        self.canvas.create_rectangle(0, 0, 600, 600, outline="black")
        self.canvas.create_rectangle(200, 600, 400, 0, outline="black")
        self.canvas.create_rectangle(0, 200, 600, 400, outline="black")

    def move(self, event):

        X = event.x / 200
        Y = event.y / 200
        cell = [X, Y]
        if (self.board[cell[1]][cell[0]] == 0):
            if (self.whichPlayer == 1):
                self.board[cell[1]][cell[0]] += 1
                self.rows[cell[1]] += 1
                self.cols[cell[0]] += 1
                if (cell[1] == cell[0]):
                    self.diag1 += 1
                if (cell[1] + cell[0] == 2):
                    self.diag2 += 1
                self.whichPlayer = 2
                self.canvas.create_oval(X * 200 + 150,
                                        Y * 200 + 150,
                                        X * 200 + 50,
                                        Y * 200 + 50,
                                        width=4,
                                        outline="blue")
                if (self.computerPlays == True and self.turns < 9):
                    self.computerMove()
            else:
                self.board[cell[1]][cell[0]] -= 1
                self.rows[cell[1]] -= 1
                self.cols[cell[0]] -= 1
                if (cell[1] == cell[0]):
                    self.diag1 -= 1
                if (cell[1] + cell[0] == 2):
                    self.diag2 -= 1
                self.whichPlayer = 1
                self.drawCross(X, Y)

        for i in range(3):
            if (self.rows[i] == 3 or self.cols[i] == 3 or self.diag1 == 3
                    or self.diag2 == 3):
                self.label['text'] = ('1st player wins!')
                self.endGame()
        for i in range(3):
            if (self.rows[i] == -3 or self.cols[i] == -3 or self.diag1 == -3
                    or self.diag2 == -3):
                self.label['text'] = ('2nd player wins!')
                self.endGame()
        if (self.turns >= 9):
            self.label['text'] = 'Draw!'
            self.endGame()
        self.turns += 1
        print(self.turns)

    def endGame(self):
        print('END GAME')
        self.canvas.unbind("<ButtonPress-1>")
Пример #8
0
class main:
    def __init__(self):
        self.app = Tk()
        self.app.title('Tic Tac Toe')
        #self.app.resizable(width=False, height=False)
        #width and hight of window
        w = 900
        h = 1100
        #width and hight of screen
        ws = self.app.winfo_screenwidth()
        hs = self.app.winfo_screenheight()
        #calculate position
        x = ws / 2 - w / 2
        y = hs / 2 - h / 2
        #place window -> pramaters(visina, dolzina, pozicija x, pozicija y)
        self.app.geometry("%dx%d+%d+%d" % (w, h, x, y))

        #======================================
        self.frame = Frame()  #main frame
        self.frame.pack(fill='both', expand=True)
        self.label = Label(self.frame,
                           text='Tic Tac Toe',
                           height=4,
                           bg='white',
                           fg='blue')
        self.label.pack(fill='both', expand=True)
        #self.label2 = Label(self.frame, text	= 'here', height = 2, bg = 'white', fg = 'blue') odkomentiri samo za develop-------------
        #self.label2.pack(fill='both', expand = True)
        self.canvas = Canvas(self.frame, width=900, height=900)
        self.canvas.pack(fill='both', expand=True)
        self.framepod = Frame(self.frame)  #sub frame
        self.framepod.pack(fill='both', expand=True)
        self.Single = Button(self.framepod,
                             text='Start single player',
                             height=4,
                             command=self.startsingle,
                             bg='white',
                             fg='blue')
        self.Single.pack(fill='both', expand=True, side=RIGHT)
        self.Multi = Button(self.framepod,
                            text='Start double player',
                            height=4,
                            command=self.double,
                            bg='white',
                            fg='blue')
        self.Multi.pack(fill='both', expand=True, side=RIGHT)
        self.board = AI()
        self.draw()

    def double(self):
        #cleans the all simbols from canvas
        self.canvas.delete(ALL)
        self.label['text'] = ('Tic Tac Toe Game')
        self.canvas.bind("<ButtonPress-1>", self.place)
        self.draw()  #---------------------------------------
        self.table = [[-1, -1, -1], [-1, -1, -1], [-1, -1, -1]]
        self.c = 0  #counter
        self.e = False  #flag for end game

    def draw(self):  #draws the outline lines
        self.canvas.create_rectangle(0, 0, 900, 900, outline='black')
        self.canvas.create_rectangle(300, 900, 600, 0, outline='black')
        self.canvas.create_rectangle(0, 300, 900, 600, outline='black')

    def place(self, event):
        for i in range(0, 900, 300):
            for j in range(0, 900, 300):
                if event.x in range(i, i + 300) and event.y in range(
                        j, j + 300):
                    if self.canvas.find_enclosed(i, j, i + 300, j + 300) == ():
                        if self.c % 2 == 0:
                            #calculate points to draw circle
                            x = (2 * i + 300) / 2
                            y = (2 * j + 300) / 2
                            x2 = int(i / 300)
                            y2 = int(j / 300)
                            self.canvas.create_oval(x + 75,
                                                    y + 75,
                                                    x - 75,
                                                    y - 75,
                                                    width=4,
                                                    outline="blue")
                            self.table[y2][x2] = 4
                            self.c += 1
                        else:
                            #calculate points to draw cross
                            x = (2 * i + 300) / 2
                            y = (2 * j + 300) / 2
                            x2 = int(i / 300)
                            y2 = int(j / 300)
                            self.canvas.create_line(x + 60,
                                                    y + 60,
                                                    x - 60,
                                                    y - 60,
                                                    width=4,
                                                    fill="red")
                            self.canvas.create_line(x - 60,
                                                    y + 60,
                                                    x + 60,
                                                    y - 60,
                                                    width=4,
                                                    fill="red")
                            self.table[y2][x2] = 1
                            self.c += 1
        self.check()

    def startsingle(self):
        self.canvas.delete(ALL)
        self.label['text'] = ('Tic Tac Toe Game')
        self.canvas.bind("<ButtonPress-1>", self.placeone)
        self.draw()
        self.board = AI()

    def placeone(self, event):
        player = 'X'
        for i in range(0, 900, 300):
            for j in range(0, 900, 300):
                if event.x in range(i, i + 300) and event.y in range(
                        j, j + 300):
                    if self.canvas.find_enclosed(i, j, i + 300, j + 300) == ():
                        x = (2 * i + 300) / 2
                        y = (2 * j + 300) / 2
                        x2 = int(i / 300)
                        y2 = int(j / 300)
                        self.canvas.create_line(x + 60,
                                                y + 60,
                                                x - 60,
                                                y - 60,
                                                width=4,
                                                fill="red")
                        self.canvas.create_line(x - 60,
                                                y + 60,
                                                x + 60,
                                                y - 60,
                                                width=4,
                                                fill="red")

                        player_move = x2 + 3 * y2  #spremeni
                        self.board.make_move(player_move, player)

        if self.board.complete():
            self.label['text'] = (self.board.winner())
            self.canvas.unbind("ButtonPress-1")
            self.board = AI()
        elif self.board.winner() != None:
            self.label['text'] = (self.board.winner())
            self.canvas.unbind("ButtonPress-1")
            self.board = AI()
        else:
            player = self.board.get_enemy(player)
            computer_move = self.board.determine(self.board, player)
            self.board.make_move(computer_move, player)

            ti = computer_move % 3
            tj = computer_move / 3

            x = (600 * ti + 300) / 2
            y = (600 * tj + 300) / 2
            #self.label2['text'] = str(computer_move) + '  ti ' + str(ti) + ' tj ' + str(tj) + ' y ' + str(y) + ' x ' +str(x)
            self.canvas.create_oval(x + 75,
                                    y + 75,
                                    x - 75,
                                    y - 75,
                                    width=4,
                                    outline="blue")

            if self.board.winner() != None:
                self.label['text'] = (self.board.winner())
                self.canvas.unbind("ButtonPress-1")
                self.board = AI()

    def check(self):
        #checks for win
        #horitontal
        for i in range(3):
            if sum(self.table[i]) == 3:
                self.label['text'] = ('X wins')
                self.end()
            if sum(self.table[i]) == 12:
                self.label['text'] = ('O wins')
                self.end()
        #vertical
        self.vs = [[row[i] for row in self.table] for i in range(3)]
        for i in range(3):
            if sum(self.vs[i]) == 3:
                self.label['text'] = ('X wins')
                self.end()
            if sum(self.vs[i]) == 12:
                self.label['text'] = ('O wins')
                self.end()
        #diagonals
        self.dig1 = 0
        self.dig2 = 0
        for i in range(3):
            self.dig1 += self.table[i][i]
        for i in range(3):
            self.dig2 += self.table[2 - i][i]

        if self.dig1 == 3:
            self.label['text'] = ('X wins')
            self.end()
        if self.dig1 == 12:
            self.label['text'] = ('O wins')
            self.end()
        if self.dig2 == 3:
            self.label['text'] = ('X wins')
            self.end()
        if self.dig2 == 12:
            self.label['text'] = ('O wins')
            self.end()

        #draw
        if self.e == False:
            a = 0
            for i in range(3):
                a += sum(self.table[i])
            if a == 24:  #5 *4 + 4 * 1 --> 5 circles and 4 crosses
                self.label['text'] = ('Draw')
                self.end()

    def end(self):
        self.canvas.unbind("<ButtonPress-1>")
        self.e = True

    def mainloop(self):
        self.app.mainloop()
Пример #9
0
class main:
    def __init__(self, master):
        self.frame = Frame(master)
        self.frame.pack(fill="both", expand=True)
        self.canvas = Canvas(self.frame, width=300, height=300)
        self.canvas.pack(fill="both", expand=True)
        self.label = Label(self.frame,
                           text='Tic Tac Toe Game',
                           height=6,
                           bg='black',
                           fg='blue')
        self.label.pack(fill="both", expand=True)
        self.frameb = Frame(self.frame)
        self.frameb.pack(fill="both", expand=True)
        self.Start1 = Button(self.frameb,
                             text='Click here to start\ndouble player',
                             height=4,
                             command=self.start1,
                             bg='white',
                             fg='purple')
        self.Start1.pack(fill="both", expand=True, side=RIGHT)
        self.Start2 = Button(self.frameb,
                             text='Click here to start\nsingle player',
                             height=4,
                             command=self.start2,
                             bg='purple',
                             fg='white')
        self.Start2.pack(fill="both", expand=True, side=LEFT)
        self._board()

    def start1(self):
        self.canvas.delete(ALL)
        self.label['text'] = ('Tic Tac Toe Game')
        self.canvas.bind("<ButtonPress-1>", self.sgplayer)
        self._board()
        self.TTT = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
        self.i = 0
        self.j = False

    def start2(self):
        self.canvas.delete(ALL)
        self.label['text'] = ('Tic Tac Toe Game')
        self.canvas.bind("<ButtonPress-1>", self.dgplayer)
        self._board()
        self.TTT = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
        self.i = 0
        self.j = False
        self.trigger = False

    def end(self):
        self.canvas.unbind("<ButtonPress-1>")
        self.j = True

    def _board(self):
        self.canvas.create_rectangle(0, 0, 300, 300, outline="black")
        self.canvas.create_rectangle(100, 300, 200, 0, outline="black")
        self.canvas.create_rectangle(0, 100, 300, 200, outline="black")

    def sgplayer(self, event):
        for k in range(0, 300, 100):
            for j in range(0, 300, 100):
                if event.x in range(k, k + 100) and event.y in range(
                        j, j + 100):
                    if self.canvas.find_enclosed(k, j, k + 100, j + 100) == ():
                        if self.i % 2 == 0:
                            X = (2 * k + 100) / 2
                            Y = (2 * j + 100) / 2
                            X1 = int(k / 100)
                            Y1 = int(j / 100)
                            self.canvas.create_oval(X + 25,
                                                    Y + 25,
                                                    X - 25,
                                                    Y - 25,
                                                    width=4,
                                                    outline="black")
                            self.TTT[Y1][X1] += 1
                            self.i += 1
                        else:
                            X = (2 * k + 100) / 2
                            Y = (2 * j + 100) / 2
                            X1 = int(k / 100)
                            Y1 = int(j / 100)
                            self.canvas.create_line(X + 20,
                                                    Y + 20,
                                                    X - 20,
                                                    Y - 20,
                                                    width=4,
                                                    fill="black")
                            self.canvas.create_line(X - 20,
                                                    Y + 20,
                                                    X + 20,
                                                    Y - 20,
                                                    width=4,
                                                    fill="black")
                            self.TTT[Y1][X1] += 9
                            self.i += 1
        self.check()

    def dgplayer(self, event):
        for k in range(0, 300, 100):
            for j in range(0, 300, 100):
                if self.i % 2 == 0:
                    if event.x in range(k, k + 100) and event.y in range(
                            j, j + 100):
                        if self.canvas.find_enclosed(k, j, k + 100,
                                                     j + 100) == ():
                            X = (2 * k + 100) / 2
                            Y = (2 * j + 100) / 2
                            X1 = int(k / 100)
                            Y1 = int(j / 100)
                            self.canvas.create_oval(X + 25,
                                                    Y + 25,
                                                    X - 25,
                                                    Y - 25,
                                                    width=4,
                                                    outline="black")
                            self.TTT[Y1][X1] += 1
                            self.i += 1
                            self.check()
                            self.trigger = False
                else:
                    print(self.i)
                    self.check()
                    print("checked")
                    self.AIcheck()
                    print("AIchecked")
                    self.trigger = False

    def check(self):
        #horizontal check
        for i in range(0, 3):
            if sum(self.TTT[i]) == 27:
                self.label['text'] = ('2nd player wins!')
                self.end()
            if sum(self.TTT[i]) == 3:
                self.label['text'] = ('1st player wins!')
                self.end()
        #vertical check
        #the matrix below transposes self.TTT so that it could use the sum fucntion again
        self.ttt = [[row[i] for row in self.TTT] for i in range(3)]
        for i in range(0, 3):
            if sum(self.ttt[i]) == 27:
                self.label['text'] = ('2nd player wins!')
                self.end()
            if sum(self.ttt[i]) == 3:
                self.label['text'] = ('1st player wins!')
                self.end()
        #check for diagonal wins
        if self.TTT[1][1] == 9:
            if self.TTT[0][0] == self.TTT[1][1] and self.TTT[2][2] == self.TTT[
                    1][1]:
                self.label['text'] = ('2nd player wins!')
                self.end()
            if self.TTT[0][2] == self.TTT[1][1] and self.TTT[2][0] == self.TTT[
                    1][1]:
                self.label['text'] = ('2nd player wins!')
                self.end()
        if self.TTT[1][1] == 1:
            if self.TTT[0][0] == self.TTT[1][1] and self.TTT[2][2] == self.TTT[
                    1][1]:
                self.label['text'] = ('1st player wins!')
                self.end()
            if self.TTT[0][2] == self.TTT[1][1] and self.TTT[2][0] == self.TTT[
                    1][1]:
                self.label['text'] = ('1st player wins!')
                self.end()
        #check for draws
        if self.j == False:
            a = 0
            for i in range(0, 3):
                a += sum(self.TTT[i])
            if a == 41:
                self.label['text'] = ("It's a pass!")
                self.end()

    def AIcheck(self):
        #This is built on the self.check function
        self.ttt = [[row[i] for row in self.TTT] for i in range(3)]
        #DEFENSE
        #this is the horizontal checklist
        for h in range(0, 3):
            k = 0
            j = 0
            if sum(self.TTT[h]) == 2:
                while k < 3:
                    if k == h:
                        while j < 3:
                            if self.trigger == False:
                                if self.TTT[k][j] == 0:
                                    self.cross(j, k)
                                    break
                            j += 1
                    k += 1
        #this is the vertical checklist
        for h in range(0, 3):
            k = 0
            j = 0
            if sum(self.ttt[h]) == 2:
                while k < 3:
                    if k == h:
                        while j < 3:
                            if self.trigger == False:
                                if self.ttt[k][j] == 0:
                                    self.cross(k, j)
                                    break
                            j += 1
                    k += 1
        #this is the diagonal checklist
        if self.TTT[1][1] == 1:
            if self.TTT[0][0] == 1:
                if self.trigger == False:
                    if self.TTT[2][2] == 0:
                        self.cross(2, 2)
            if self.TTT[0][2] == 1:
                if self.trigger == False:
                    if self.TTT[2][0] == 0:
                        self.cross(0, 2)
            if self.TTT[2][0] == 1:
                if self.trigger == False:
                    if self.TTT[0][2] == 0:
                        self.cross(2, 0)
            if self.TTT[2][2] == 1:
                if self.trigger == False:
                    if self.TTT[0][0] == 0:
                        self.cross(0, 0)

        if self.TTT[1][1] == 0:
            if self.trigger == False:
                self.cross(1, 1)
                self.trigger = True
        else:
            if self.trigger == False:
                self.randmove()

    def cross(self, k, j):
        # k is the x coords
        # j is the y coords
        X = (200 * k + 100) / 2
        Y = (200 * j + 100) / 2
        X1 = int(k)
        Y1 = int(j)
        self.canvas.create_line(X + 20,
                                Y + 20,
                                X - 20,
                                Y - 20,
                                width=4,
                                fill="black")
        self.canvas.create_line(X - 20,
                                Y + 20,
                                X + 20,
                                Y - 20,
                                width=4,
                                fill="black")
        self.TTT[Y1][X1] += 9
        self.check()
        self.i += 1
        self.trigger = True

    def randmove(self):
        while True:
            k = (randint(0, 2))
            j = (randint(0, 2))
            if self.TTT[j][k] == 0:
                X = (200 * k + 100) / 2
                Y = (200 * j + 100) / 2
                self.canvas.create_line(X + 20,
                                        Y + 20,
                                        X - 20,
                                        Y - 20,
                                        width=4,
                                        fill="black")
                self.canvas.create_line(X - 20,
                                        Y + 20,
                                        X + 20,
                                        Y - 20,
                                        width=4,
                                        fill="black")
                self.TTT[j][k] += 9
                self.check()
                self.i += 1
                self.trigger = True
                break
            else:
                k = (randint(0, 2)) * 100
                j = (randint(0, 2)) * 100
Пример #10
0
class main:
    def __init__(self, master):
        self.frame = Frame(master)
        self.frame.pack(fill="both", expand=True)
        self.canvas = Canvas(self.frame, width=600, height=600)
        self.canvas.pack(fill="both", expand=True)
        self.label = Label(self.frame, text="Tic Tac Toe", height=2, bg="white", fg="black")
        self.label.pack(fill="both", expand=True)
        self.frameb = Frame(self.frame)
        self.frameb.pack(fill="both", expand=True)
        self.Start2 = Button(self.frameb, text="Two players", height=4, command=self.start2, bg="yellow", fg="black")
        self.Start2.pack(fill="both", expand=True, side=RIGHT)
        self.Start1 = Button(self.frameb, text="One player", height=4, command=self.start1, bg="yellow", fg="black")
        self.Start1.pack(fill="both", expand=True, side=LEFT)
        self.whichPlayer = 1
        self.computerPlays = False

    def start2(self):
        self.computerPlays = False
        self.canvas.delete(ALL)
        # initialize board
        self.board = [[0] * 3 for i in range(3)]
        self.canvas.bind("<ButtonPress-1>", self.move)
        # draw board
        self.drawGrid()
        self.rows = [0, 0, 0]
        self.cols = [0, 0, 0]
        self.diag1 = 0
        self.diag2 = 0
        self.label["text"] = "Tic Tac Toe"
        self.turns = 1

    def start1(self):
        self.whichPlayer = 1
        print("you (circle) vs computer (cross)")
        self.computerPlays = True
        self.canvas.delete(ALL)
        # initialize board
        self.board = [[0] * 3 for i in range(3)]
        # draw board
        self.drawGrid()
        self.rows = [0, 0, 0]
        self.cols = [0, 0, 0]
        self.diag1 = 0
        self.diag2 = 0
        self.label["text"] = "Tic Tac Toe"
        self.canvas.bind("<ButtonPress-1>", self.move)
        self.turns = 1

    def computerMove(self):
        posx = randint(0, 2)
        posy = randint(0, 2)
        if self.turns > 8:
            self.label["text"] = "Draw!"
            self.endGame()
        # attack
        moved = False
        for i in range(3):
            if self.rows[i] == -2:
                for j in range(3):
                    if self.board[i][j] == 0:
                        self.drawCross(j, i)
                        self.board[i][j] = -1
                        self.rows[i] -= 1
                        self.cols[j] -= 1
                        if i == j:
                            self.diag1 -= 1
                        if i + j == 2:
                            self.diag2 -= 1
                        moved = True
        if moved == False:
            for i in range(3):
                if self.cols[i] == -2:
                    for j in range(3):
                        if self.board[j][i] == 0:
                            self.drawCross(i, j)
                            self.board[j][i] = -1
                            self.rows[j] -= 1
                            self.cols[i] -= 1
                            if i == j:
                                self.diag1 -= 1
                            if i + j == 2:
                                self.diag2 -= 1
                            moved = True
        if moved == False:
            if self.diag1 == -2:
                for i in range(3):
                    if self.board[i][i] == 0:
                        self.drawCross(i, i)
                        self.board[i][i] = -1
                        self.rows[i] -= 1
                        self.cols[i] -= 1
                        if i == j:
                            self.diag1 -= 1
                        if i + j == 2:
                            self.diag2 -= 1
                        moved = True
        if moved == False:
            if self.diag2 == -2:
                for i in range(3):
                    if self.board[i][2 - i] == 0:
                        self.drawCross(2 - i, i)
                        self.board[i][2 - i] = -1
                        self.rows[i] -= 1
                        self.cols[2 - i] -= 1
                        if i == j:
                            self.diag1 -= 1
                        if i + j == 2:
                            self.diag2 -= 1
                        moved = True
        # defense
        moved = False
        for i in range(3):
            if self.rows[i] == 2:
                for j in range(3):
                    if self.board[i][j] == 0:
                        self.drawCross(j, i)
                        self.board[i][j] = -1
                        self.rows[i] -= 1
                        self.cols[j] -= 1
                        if i == j:
                            self.diag1 -= 1
                        if i + j == 2:
                            self.diag2 -= 1
                        moved = True
        if moved == False:
            for i in range(3):
                if self.cols[i] == 2:
                    for j in range(3):
                        if self.board[j][i] == 0:
                            self.drawCross(i, j)
                            self.board[j][i] = -1
                            self.rows[j] -= 1
                            self.cols[i] -= 1
                            if i == j:
                                self.diag1 -= 1
                            if i + j == 2:
                                self.diag2 -= 1
                            moved = True
        if moved == False:
            if self.diag1 == 2:
                for i in range(3):
                    if self.board[i][i] == 0:
                        self.drawCross(i, i)
                        self.board[i][i] = -1
                        self.rows[i] -= 1
                        self.cols[i] -= 1
                        self.diag1 -= 1
                        moved = True
        if moved == False:
            if self.diag2 == 2:
                for i in range(3):
                    if self.board[i][2 - i] == 0:
                        self.drawCross(2 - i, i)
                        self.board[i][2 - i] = -1
                        self.rows[i] -= 1
                        self.cols[2 - i] -= 1
                        self.diag2 -= 1
                        moved = True

        if moved == False:
            while self.board[posx][posy] != 0:  # random choice
                posx = randint(0, 2)
                posy = randint(0, 2)
            if self.board[posx][posy] == 0:
                self.board[posx][posy] = -1
                self.rows[posx] -= 1
                self.cols[posy] -= 1
                if posx == posy:
                    self.diag1 -= 1
                if posx + posy == 2:
                    self.diag2 -= 1
                self.drawCross(posy, posx)
                moved = True
        for i in range(3):
            if self.rows[i] == -3 or self.cols[i] == -3 or self.diag1 == -3 or self.diag2 == -3:
                self.label["text"] = "Computer wins!"
                self.endGame()
        self.whichPlayer = 1
        self.turns += 1

    def drawCross(self, row, col):
        lon = 100
        offset = 50
        self.canvas.create_line(
            row * 200 + offset,
            col * 200 + offset,
            row * 200 + offset + lon,
            col * 200 + offset + lon,
            width=4,
            fill="red",
        )
        self.canvas.create_line(
            row * 200 + offset + lon,
            col * 200 + offset,
            row * 200 + offset,
            col * 200 + offset + lon,
            width=4,
            fill="red",
        )

    def drawGrid(self):
        self.canvas.create_rectangle(0, 0, 600, 600, outline="black")
        self.canvas.create_rectangle(200, 600, 400, 0, outline="black")
        self.canvas.create_rectangle(0, 200, 600, 400, outline="black")

    def move(self, event):

        X = event.x / 200
        Y = event.y / 200
        cell = [X, Y]
        if self.board[cell[1]][cell[0]] == 0:
            if self.whichPlayer == 1:
                self.board[cell[1]][cell[0]] += 1
                self.rows[cell[1]] += 1
                self.cols[cell[0]] += 1
                if cell[1] == cell[0]:
                    self.diag1 += 1
                if cell[1] + cell[0] == 2:
                    self.diag2 += 1
                self.whichPlayer = 2
                self.canvas.create_oval(
                    X * 200 + 150, Y * 200 + 150, X * 200 + 50, Y * 200 + 50, width=4, outline="blue"
                )
                if self.computerPlays == True and self.turns < 9:
                    self.computerMove()
            else:
                self.board[cell[1]][cell[0]] -= 1
                self.rows[cell[1]] -= 1
                self.cols[cell[0]] -= 1
                if cell[1] == cell[0]:
                    self.diag1 -= 1
                if cell[1] + cell[0] == 2:
                    self.diag2 -= 1
                self.whichPlayer = 1
                self.drawCross(X, Y)

        for i in range(3):
            if self.rows[i] == 3 or self.cols[i] == 3 or self.diag1 == 3 or self.diag2 == 3:
                self.label["text"] = "1st player wins!"
                self.endGame()
        for i in range(3):
            if self.rows[i] == -3 or self.cols[i] == -3 or self.diag1 == -3 or self.diag2 == -3:
                self.label["text"] = "2nd player wins!"
                self.endGame()
        if self.turns >= 9:
            self.label["text"] = "Draw!"
            self.endGame()
        self.turns += 1
        print(self.turns)

    def endGame(self):
        print("END GAME")
        self.canvas.unbind("<ButtonPress-1>")
Пример #11
0
class TTT:
    '''
        main class for interface and game handling
    '''
    def __init__(self, master):
        self.frame = Frame(master)
        self.frame.pack(fill="both", expand=True)
        self.label = Label(self.frame,
                           text='Tic Tac Toe Game',
                           height=2,
                           font="Arial 14",
                           bg='black',
                           fg='blue')
        self.label.pack(fill="both", expand=True)
        self.canvas = Canvas(self.frame, width=300, height=300)
        self.canvas.pack(fill="both", expand=True)
        self.status = Label(self.frame,
                            text='Start Game',
                            height=2,
                            font="Arial 14",
                            bg='white',
                            fg='black')
        self.status.pack(fill="both", expand=True)
        self.reset = Button(self.frame, text="Reset Game", command=self.reset)
        self.reset.pack(fill="both", expand=True)
        self.__board()
        self.canvas.bind("<ButtonPress-1>", self.handler)
        self.board = [0 for x in range(0, 9)]
        self.winner = None
        self.lastmoves = []

    def get_free_cells(self):
        moves = []
        for i, v in enumerate(self.board):
            if v == 0:
                moves.append(i)
        return moves

    def mark(self, pos, marker):
        self.board[pos] = marker
        self.lastmoves.append(pos)

    def revert_last_move(self):
        self.board[self.lastmoves.pop()] = 0
        self.winner = None

    def is_gameover(self):
        win_positions = [(0, 1, 2), (3, 4, 5), (6, 7, 8), (0, 3, 6), (1, 4, 7),
                         (2, 5, 8), (0, 4, 8), (2, 4, 6)]
        for i, j, k in win_positions:
            if self.board[i] == self.board[j] and self.board[j] == self.board[
                    k] and self.board[i] != 0:
                self.winner = self.board[i]
                return True
        if 0 not in self.board:
            self.winner = 0
            return True
        return False

    def get_score(self):
        if self.is_gameover():
            if self.winner == 2:
                return 1  # Won
            elif self.winner == 1:
                return -1
        return 0

    def get_cell_value(self, pos):
        return self.board[pos]

    def __board(self):
        self.canvas.create_rectangle(0, 0, 300, 300, outline="black")
        self.canvas.create_rectangle(100, 300, 200, 0, outline="black")
        self.canvas.create_rectangle(0, 100, 300, 200, outline="black")

    def reset(self):
        self.canvas.delete(ALL)
        self.__board()
        self.changeStatus('Start Game')
        self.canvas.bind("<ButtonPress-1>", self.handler)
        self.board = [0 for x in range(0, 9)]
        self.winner = None
        self.lastmoves = []

    def changeStatus(self, status):
        self.status['text'] = status

    def markFinal(self, pos, marker):
        x = pos % 3
        y = int(pos / 3)
        # print pos, marker
        if marker == 2:
            X = 100 * (x + 1)
            Y = 100 * (y + 1)
            self.canvas.create_oval(X - 25,
                                    Y - 25,
                                    X - 75,
                                    Y - 75,
                                    width=4,
                                    outline="green")
            self.changeStatus("X's Move !")
        else:
            X = 100 * x
            Y = 100 * y
            self.canvas.create_line(X + 25,
                                    Y + 25,
                                    X + 75,
                                    Y + 75,
                                    width=4,
                                    fill="red")
            self.canvas.create_line(X + 25,
                                    Y + 75,
                                    X + 75,
                                    Y + 25,
                                    width=4,
                                    fill="red")
            self.changeStatus("O's Move !")

        self.board[pos] = marker

    def handler(self, event):
        '''
        handle mouse click event on the board
        '''
        x = int(event.x / 100)
        y = int(event.y / 100)
        if self.board[y * 3 + x] == 0:
            self.markFinal(y * 3 + x, 2)
            if self.is_gameover():
                self.canvas.unbind("<ButtonPress-1>")
                if self.winner == 2:
                    self.changeStatus("O Won the Game !")
                elif self.winner == 1:
                    self.changeStatus("X Won the Game !")
                else:
                    self.changeStatus("Game Draw !")
                return

            pos, score = min_max_move(self, 1)
            self.markFinal(pos, 1)

            if self.is_gameover():
                self.canvas.unbind("<ButtonPress-1>")
                if self.winner == 2:
                    self.changeStatus("O Won the Game !")
                elif self.winner == 1:
                    self.changeStatus("X Won the Game !")
                else:
                    self.changeStatus("Game Draw !")