Question

from tkinter import *
from random import randrange

### def
def sqlines(x=0, y=0):
    n = 0
    while n < 5:      
        can.create_rectangle(x, y, x+sq, y+sq, fill = "purple")  
        x = x + sq * 2 
        n = n + 1

def chess():
    y = 0
    while y < 10:
        if y % 2 == 0:
            x = 0
        else:
            x = 1
        sqlines(x*sq, y*sq)
        y = y + 1

def delcircles():
    can.delete(ALL)
    chess()

def circle(x, y, r, color):
    can.create_oval(x-r, y-r, x+r, y+r, fill=color)

def add_circle():
    x = sq/2 + randrange(10) * sq
    y = sq/2 + randrange(10)  * sq
    circle(x, y, 20/3, "red")


### main       
sq = 20       
win = Tk()
win.title("Chess")    
can = Canvas(win, bg = "white", height = sq*10, width  = sq*10)
can.pack(side = TOP, padx = 5, pady = 5)

but1 = Button(win, text="Chess", command = chess)
but1.pack(side = LEFT, padx = 3, pady = 3)

but2 = Button(win, text="Circles", command = add_circle)
but2.pack(side = RIGHT, padx = 3, pady = 3)

but3 = Button(win, text ="Delete", command = delcircles)
but3.pack(side = RIGHT, padx = 3, pady = 3)

win.mainloop()

I had to write a script which contains a chess board, this is okay, but then the task was to create circles randomly on the board. I found this code, but I don't understand how does it work. So could you please explain? I really don't understand.

def add_circle():
        x = sq/2 + randrange(10) * sq
        y = sq/2 + randrange(10)  * sq
        circle(x, y, 20/3, "red")
Was it helpful?

Solution

randrange picks a number from 0 to the input number(10), so x would equal

sq/2 + randum number between 0 and 10 * sq

and y would equal

sq/2 + random number between 0 and 10 * sq

Was that your question?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top