Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Tic Tac Toe problem
#1
I have been doing a work on Tic tac toes but I need help with the positioning I have set that when I press a button I draw a circle or an X but the problem is that it can draw where it wants but I need it to make it dead center of the square.

import tkinter
canvas=tkinter.Canvas(width=700, height=700)
canvas.pack()

def board():
    canvas.create_line(50,150,350,150)
    canvas.create_line(150,50,150,350)
    canvas.create_line(250,50,250,350)
    canvas.create_line(50,250,350,250)
    canvas.create_rectangle(50,50,350,350)

    
def kruh(sur):
    x=sur.x
    y=sur.y
    canvas.create_oval(x-30,y-30,x+30,y+30, fill='blue')

canvas.bind('<Button-1>', kruh)

def stvorec(sur):
    x=sur.x
    y=sur.y
    canvas.create_rectangle(x-30,y-30,x+30,y+30,fill='red')

canvas.bind('<Button-3>', stvorec)

Attached Files

Thumbnail(s)
       
Reply
#2
On clicking work out which square the x & y falls within and then draw in the centre of that square.
Reply
#3
The math for that can be pretty confusing. Subtract, then divide, then multiply and lastly add. What all of that does is find the row and column that the mouse is in and then calculate the coordinates of the position needed to be centered in that row and column. Here's one way to implement that:
import tkinter
root = tkinter.Tk()
canvas=tkinter.Canvas(root, width=400, height=400)
canvas.pack()
 
def board():
	canvas.create_line(50,150,350,150)
	canvas.create_line(150,50,150,350)
	canvas.create_line(250,50,250,350)
	canvas.create_line(50,250,350,250)
	canvas.create_rectangle(50,50,350,350)
	 
def get_coordinates (x, y):
	if x > 49 and x < 350 and y > 49 and y < 350 :
		x = ((x - 150) // 100 * 100) + 170 
		y = ((y - 150) // 100 * 100) + 170 
		return x, y
	else :
		return 0, 0

def kruh(sur):
	x, y = get_coordinates (sur.x, sur.y) 
	if x > 0 :
		canvas.create_oval(x,y,x+60,y+60, fill='blue')
canvas.bind('<Button-1>', kruh)
 
def stvorec(sur):
	x, y = get_coordinates (sur.x, sur.y) 
	if x > 0 :
		canvas.create_rectangle(x,y,x+60,y+60,fill='red')
canvas.bind('<Button-3>', stvorec)

board ()
root.mainloop ()
   
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020