1

Как реализовать смену цвета при коллизии/столкновении в tkinter?

from tkinter import *
import time
import random

WIDTH = 1024
HEIGHT = 720

tk = Tk()
cv = Canvas(tk, width=WIDTH, height=HEIGHT)
tk.title('Tkinter ballz')
cv.pack()

class Ball:
    def __init__(self, size, color):
        self.shape = cv.create_oval(10, 10, size, size, fill=color)
        self.xspeed = random.randint(-10, 11)
        if self.xspeed == 0:
            self.xspeed = random.randint(-10, 11)
        self.yspeed = random.randint(-10, 11)
        if self.yspeed == 0:
            self.yspeed = random.randint(-10, 11)

    def move(self):
        cv.move(self.shape, self.xspeed, self.yspeed)
        pos = cv.coords(self.shape)
        if pos[3] >= HEIGHT or pos[1] <= 0:
            self.yspeed = -self.yspeed

        if pos[2] >= WIDTH or pos[0] <= 0:
            self.xspeed = -self.xspeed

colors = ['red', 'gold', 'orange', 'magenta', 'green', 'pink', 'cyan', 'black', 'grey', 'blue']
balls = []
for i in range(21):
    balls.append(Ball(50, random.choice(colors)))





while True:
    for ball in balls:
        ball.move()
    tk.update()
    time.sleep(0.01)

Хочу реализовать это в функции move,чтобы при столкновении со стенкой цвет круга заменялся на случайный.

1 ответ 1

1

Свойства фигуры на canvas можно менять при помощи метода .itemconfig(). В вашем случае внутри метода класса нужно будет вызывать cv.itemconfig(self.shape, fill=newcolor). Можно добавить отдельный метод для изменения цвета и прописать в методе move, чтобы при столкновении со "стенками" кроме направления менялся еще и цвет:

class Ball:
    def __init__(self, size, color):
        ...

    def move(self):
        cv.move(self.shape, self.xspeed, self.yspeed)
        pos = cv.coords(self.shape)
        if pos[3] >= HEIGHT or pos[1] <= 0:
            self.yspeed = -self.yspeed
            self.set_color(random.choice(colors))

        if pos[2] >= WIDTH or pos[0] <= 0:
            self.xspeed = -self.xspeed
            self.set_color(random.choice(colors))

    def set_color(self, color):
        cv.itemconfig(self.shape, fill=color)

Дополнительно про itemconfig

0

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.