Assigning specific IDs to turtles created in a for loop

32 views Asked by At

I have created a checkers game in Python turtle and am trying to assign a specific ID to each turtle created in the for loop. Is there a way I can assign a specific ID to each of these turtles? The code is below.

I am trying to find a way to register the collision detection so I can remove the turtle from the checkerboard after one of the pieces has been jumped.

I created the checkerboard using a turtle and fillcolor and created a way for the user to select which of the pieces to move around on the board (not the best strategy) but at least it works (kinda). I am now trying to figure out a way to hide or remove the pieces jumped by another.

import tkinter as tk
import turtle as trtl

window = trtl.Screen()

checkers = trtl.Turtle()
score1 = trtl.Turtle()
score2 = trtl.Turtle()
s1 = 0
s2 = 0
font = ("Arial",18)
score1.penup()
score2.penup()
score1.goto(-300,300)
score2.goto(-300,-300)
score1.write("Score: " + str(s1),font = font)
score2.write("Score: " + str(s2),font = font)

pieces1 = []
pieces2 = []
color1 = "black"
color2 = "red"
x = -200
y = 250
size = 50

def setup(x,y,c1,c2):
    global size
    checkers.speed(20)
    checkers.penup()
    checkers.goto(x,y)
    checkers.pendown()
    for i in range(8):
        checkers.begin_fill()
        checkers.fillcolor(c1)
        for sq in range(4):
            checkers.forward(size)
            checkers.right(90)
        if i % 2 != 0:
            checkers.fillcolor(c2)
        checkers.end_fill()
        checkers.forward(size)

for i in range(8):
    if i % 2 == 0:
        setup(x,y,color1,color2)
        y -= size
    else:
        setup(x,y,color2,color1)
        y -= size

checkers.hideturtle()

x = -175
y = 225

for i in range(4):
    p1 = trtl.Turtle()
    p1.shape("circle")
    p1.turtlesize(2)
    p1.color("white")
    p1.penup()
    p1.goto(x,y)
    pieces1.append(p1)
    x += 100
  
x = -125
y = -125

for i in range(4):
    p2 = trtl.Turtle()
    p2.shape("circle")
    p2.turtlesize(2)
    p2.color("gray")
    p2.penup()
    p2.goto(x,y)
    pieces2.append(p2)
    x += 100

move_x = 0
move_y = 0

def get_coords(x,y):
    global move_x,move_y
    move_x = x
    move_y = y
    return move_x, move_y

def move_piece(x,y):
    global move_x, move_y
    for i in range(len(pieces1)):
        if abs(pieces1[i].xcor() - x) <= 5 and abs(pieces1[i].ycor() - y) <= 5:
            pieces1[i].goto(move_x,move_y)
        if abs(pieces2[i].xcor() - x) <= 5 and abs(pieces2[i].ycor() - y) <= 5:
            pieces2[i].goto(move_x,move_y)
        
        #if abs(pieces1[i].xcor() - x) <= 5 and abs(pieces2[i].xcor() - y) <= 5:        


print (window.onclick(get_coords))
for i in range(len(pieces1)):
    pieces1[i].onclick(move_piece)
    pieces2[i].onclick(move_piece)
window.mainloop()
0

There are 0 answers