hi guys i have a small problem. the cars in my program collide against each other. it works when i don't have any class car. but now there's some confusion with the speed of the car. ive worked for hours on this but no solution found.

i hope u guys can do it for me thanks.

import Tkinter as tk
import time
import sys
import datetime as dt
from Tkinter import *
import random

root=tk.Tk()
root.title("Traffic Simulation")
canvas = tk.Canvas(root, width=1000, height=400, bg="#FFFFFF")
canvas.pack()

class Car(object):
  def __init__(self, a,b,c,d, outline='blue', fill='blue'):
    self.rect = canvas.create_rectangle(a,b,c,d, outline=outline, fill=fill)
    self.rear_bumper = 150
    self.front_bumper = -10
    self.xspeed = 2
    self.yspeed = 0
   

  def set_speed(self, xspeed, yspeed):
    self.speed = xspeed, yspeed


   
  def move(self):
    canvas.move(self.rect, self.speed[0], self.speed[1])
   
    vehicle=canvas.coords(self.rect)
    canvas.update()
   
car1 = Car(-30, 155, -10, 170, outline='blue', fill='blue')
car2 = Car(-30, 155, -10, 170, outline='blue', fill = 'blue')


times1 = ['2000']
timer1 = random.choice(times1)
times2 = ['4000']
timer2 = random.choice(times2)


car1.bumper = 150, -10
car2.bumper = 150, -10

car1.set_speed(2,0)
car2.set_speed(4,0)

# move car
while True:
    car1.move()
    canvas.after(timer1, car2.move)
   
    time.sleep(0.025)

    car1.rear_bumper += car1.xspeed
    car2.front_bumper += car2.xspeed

    diff_between_cars = car1.rear_bumper - car2.front_bumper

    print car1.rear_bumper

    if 50 <= diff_between_cars < 60:
        car2.set_speed = 2,0  #decelerate
    elif diff_between_cars < 50:
        car2.set_speed = 1,0  #match speed of front car

    canvas.update()


root.mainloop()

Recommended Answers

All 2 Replies

Can you explain what is wrong with the speed of the car? It seems fine to me.

Me too!
The cars are moving fine and displays speed.
Is it syntax or logical error?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.