def testCarStart(self): #tests initilization of cars and checks variables print("Starting start test") car1 = car.car() car2 = car.car(position=20) car1.setNextCar(car2) Test.assertEqual(self, 0, car1.getSpeed(), "speed of car 1 does not equal 0") Test.assertEqual(self, 0, car1.getPosition(), "Position of car 1 does not equal 0") Test.assertEqual(self, 0, car1.getAccel(), "Acceleration of car 1 does not equal 0") Test.assertEqual(self, 100, car1.getMaxSpeed(), "Max Speed of car 1 does not equal 100") Test.assertEqual(self, 20, car1.getDistanceForward(car2), "Distance between cars is not 20") Test.assertEqual(self, 20, car2.getDistanceBehind(car1), "Distance from car 2 to car 1 is not 20")
def testKeepDistance(self): print("Starting distancing test") car1 = car.car(mode="automatic") car2 = car.car(mode="override",position=20,speed=20) car1.setNextCar(car2) car1.setSpeedAim(40) count = 0 while (count < 50): print(count) print("Car 1 position: " + str(car1.position) + " speed: " + str(car1.getSpeed())) print("Car 2 position: " + str(car2.position) + " speed: " + str(car2.getSpeed())) car1.act() car2.act() count = count + 1
def setUp(self): self.car_make = "Toyota" self.car_model = "Camry" self.car_year = "1999" self.car_owner = "Car Owner" self.car_mileage = 140000 unittest.TestCase.setUp(self) self.car = car(self.car_make, self.car_model, self.car_year, self.car_mileage, self.car_owner)
def main(): c = [car.car('Ford', 'F-150', '2010', '1599.99'), car.car('Jeep', 'Wrangler', '2001', '7500.99'), car.car('Honda', 'Accord', '2016', '31299.00'), car.car('Chevrolet', 'Corvette', '1969', '89950.79')] for i in c: print(i) for i in c: year = i.get_year() if 2006 >= year: cost = i.get_price() new_cost = (cost * .9) i.set_price(new_cost) c[1].set_year(2002) print(c[1])
def __init__(self, fname=None, lname=None, age=None, gender=None, address=None, city=None, zipcode=None): self.fname = fname self.lname = lname self.age = age self.gender = gender self.address = address self.city = city self.zipcode = zipcode self.name = self.fname + ' ' + self.lname self.car = None self.car = car("", "", "", None , None)
def train_and_show_navigation(): close('all') # create instances of a car and a track monaco = track.track() ferrari = car.car() n_trials = 2000 n_time_steps = 1000 # maximum time steps for each trial ferrari.reset() figure(0) xlim(-0.1,1.1) ylim(-0.1,1.1) monaco.plot_track() ferrari.plot_navigation() for j in arange(n_trials): # before every trial, reset the track and the car. # the track setup returns the initial position and velocity. (position_0, velocity_0) = monaco.setup() ferrari.reset() # choose a first action action = ferrari.choose_action(position_0, velocity_0, 0) # iterate over time for i in arange(n_time_steps) : # the track receives which action was taken and # returns the new position and velocity, and the reward value. (position, velocity, R) = monaco.move(action) # the car chooses a new action based on the new states and reward, and updates its parameters action = ferrari.choose_action(position, velocity, R) # check if the race is over if monaco.finished is True: break if j%100 == 0: # plots the race result every 100 trials monaco.plot_world() if j%10 == 0: print 'Trial:', j if j == 0 or j == 50 or j==100 or j==250 or j==500 or j==750 or j==999 or j==1250 or j==1500 or j==1750 or j==1999: figure(j+1) xlim(-0.1,1.1) ylim(-0.1,1.1) monaco.plot_track() ferrari.plot_navigation() return ferrari #returns a trained car
def testCarSpeed(self): #should check speed print("Starting speed test") car1 = car.car(mode="override") car1.setSpeed(20) Test.assertEqual(self, 0, car1.getPosition(), "Car 1 was not where assumed") Test.assertEqual(self, 20, car1.getSpeed(), "Car 1 is not driving with assumed speed") car1.act() Test.assertEqual(self, 20, car1.getPosition(), "Car 1 was still not where assumed") car1.setSpeed(30) car1.act() Test.assertEqual(self, 50, car1.getPosition(), "Car 1 was not where assumed")
def addInventory(self): s = raw_input("Enter Seriel no(example - MERC1234-2014):") f = raw_input("Enter Fuel type (example - DIESEL/PETROL):") y = raw_input("Enter model year (example - 2014):") c = raw_input("Enter Color (example - RED ):") m = raw_input("Enter manufaturer (example - ge):") md = raw_input("Enter model (example - sparks):") olnw = raw_input("Enter f its old or new (example - new/old):") mycar = car.car(s, f, y, c, m, md, olnw) rec = [mycar, 'a'] self.invcache[s]=rec print "Car with seriel no {0} sucessfully added to invertory".format(s)
def testCarAccel(self): print("Starting acceleration test") car1 = car.car(mode="automatic") Test.assertEqual(self, 0, car1.getPosition(), "car 1 was not at 0") car1.setSpeedAim(50) car1.act() Test.assertEqual(self, 2, car1.getPosition(), "Car 1 was not at 2") Test.assertEqual(self, 2, car1.getSpeed(), "Car did not have a speed of 2") car1.act() Test.assertEqual(self, 6, car1.getPosition(), "Car was not at 6") Test.assertEqual(self, 4, car1.getSpeed(), "Car did was not at speed 4") count = 0 while (count < 25): car1.act() count = count + 1 Test.assertEqual(self, 750, car1.getPosition(), "car was not at expected position") Test.assertEqual(self, 50, car1.getSpeed(), "car has either crossed or not reached speed limit") car1.act() Test.assertEqual(self, 800, car1.getPosition(), "car has not moved after achieving max speed")
import time parking_list = [] car_list = [] parking_slot_1 = parking_slot(pos_x=[200, 400], pos_y=[200, 400], number=1) parking_slot_2 = parking_slot(pos_x=[400, 600], pos_y=[400, 600], number=2) parking_slot_3 = parking_slot(pos_x=[600, 800], pos_y=[600, 800], number=3) parking_list.append(parking_slot_1) parking_list.append(parking_slot_2) parking_list.append(parking_slot_3) # car_1 = car(number=1, pos_x=[250, 350], pos_y=[250, 350]) car_1 = car(number=1, pos_x=[0, 0], pos_y=[0, 0]) car_2 = car(number=2, pos_x=[0, 0], pos_y=[0, 0]) car_3 = car(number=3, pos_x=[0, 0], pos_y=[0, 0]) car_4 = car(number=4, pos_x=[0, 0], pos_y=[0, 0]) car_5 = car(number=5, pos_x=[0, 0], pos_y=[0, 0]) car_list.append(car_1) car_list.append(car_2) car_list.append(car_3) car_list.append(car_4) car_list.append(car_5) # for car in car_list: # car_center = car.get_car_center() # print(car.number, car_center)
from car import car c = car('bmw','white','sports car') c.status() c.start() c.status() c.speedup() c.stop() c.status()
def main(): #esto es que creamos una clase llamada car from car import car #para poder usarla funcion timepara el sleep import time #tamaño de la pantalla screenwidth = 800 screenheight = 600 #colores green = (0, 205, 0) black = (20, 20, 20) grey = (135, 135, 135) grey2 = (145, 145, 145) white = (255, 255, 255) red = (255, 0, 0) #velocidad inical del playerCar speed = 1 score = 0 #definimos tupla, son constantes de dos coordenadas size = (screenwidth, screenheight) #creamos la agrupación de los sprites screen = pygame.display.set_mode(size) pygame.display.set_caption("Cars racing") #te da todas las fuentes fonts = pygame.font.get_fonts() #print(fonts) fonts = pygame.font.SysFont('Arial', 30) font_score = pygame.font.SysFont('Arial', 20) #music pygame.mixer.music.load('audio/soundtrack.mp3') pygame.mixer.music.play(-1) #Jugadores = color, anchura, altura, speed playerCar = car('images/alonso.png', red, 170, 150, 70) #obtenemos la coordenada x del rectangulo playerCar.rect.x = 150 - playerCar.image.get_width() / 2 playerCar.rect.y = screenheight - 100 all_sprites_list = pygame.sprite.Group() car1 = car('images/español.png', black, 170, 150, 70) car1.rect.x = 250 - playerCar.image.get_width() / 2 car1.rect.y = screenheight - 100 car2 = car('images/amarillo.png', red, 170, 150, random.randint(50, 100)) car2.rect.x = 350 - playerCar.image.get_width() / 2 car2.rect.y = screenheight - 600 car3 = car('images/japo.png', red, 170, 150, random.randint(50, 100)) car3.rect.x = 150 - playerCar.image.get_width() / 2 car3.rect.y = screenheight - 1020 car4 = car('images/andorra.png', red, 170, 150, random.randint(50, 100)) car4.rect.x = 450 - playerCar.image.get_width() / 2 car4.rect.y = screenheight - 900 car5 = car('images/schumacher.png', red, 170, 150, random.randint(50, 100)) car5.rect.x = 550 - playerCar.image.get_width() / 2 car5.rect.y = screenheight - 600 #cargamos el coche roto breakcar = car('images/cocheestrellado.png', red, 170, 150, random.randint(50, 100)) breakcar.rect.x = 600 breakcar.rect.y = -600 #creamos lista con todos los sprites all_sprites_list.add(playerCar) all_sprites_list.add(car1) all_sprites_list.add(car2) all_sprites_list.add(car3) all_sprites_list.add(car4) all_sprites_list.add(car5) all_sprites_list.add(breakcar) #declaramos la variable game over y finished gameover = False finished = False #agrupamineot de coahes que llegan all_coming_cars = pygame.sprite.Group() all_coming_cars.add(car1, car2, car3, car4, car5) #definir reloj clock = pygame.time.Clock() while not finished: while not gameover: for event in pygame.event.get(): if event.type == pygame.QUIT: finished = True #velocidad de juego con las flechas keys = pygame.key.get_pressed() if keys[pygame.K_LEFT]: if playerCar.rect.x > 60: playerCar.moveLeft(5) if keys[pygame.K_RIGHT]: if playerCar.rect.x < 500: playerCar.moveRight(5) if keys[pygame.K_UP]: if playerCar.rect.y > 0: #speed +=0.05 playerCar.moveUp(5) if keys[pygame.K_DOWN]: if playerCar.rect.y < 500: #speed -=0.05 playerCar.moveDown(5) #movimiento de coche #logica del juego for car in all_coming_cars: car.moveForward(speed) if car.rect.y > screenheight: car.changeSpeed(random.randint(50, 100)) car.rect.y = -200 # car.repaint(random.choice(lista_colores)) #lista de colisiones car_collision_list = pygame.sprite.spritecollide( playerCar, all_coming_cars, False, pygame.sprite.collide_mask) for car in car_collision_list: #breakcar = pygame.image.load('images/cocheestrellado.png') '''breakcar.rect.x=playerCar.rect.x breakcar.rect.y=playerCar.rect.y #textos text=fonts.render("GAME OVER / FIN DEL JUEGO", True, red) screen.blit(text, (250, 250)) pygame.display.flip()''' #audio explosion #añadimos el sonido para el choque con algun coche effect = pygame.mixer.Sound('audio/crash.wav') effect.play(1) breakcar.rect.x = playerCar.rect.x breakcar.rect.y = playerCar.rect.y time.sleep(3) all_sprites_list.update() gameover = True screen.fill(grey2) #dibujar carretera pygame.draw.rect(screen, black, [100, 0, 500, screenheight]) #punto inicial, punto final y grosor pygame.draw.line(screen, white, [200, 0], [200, screenheight], 5) pygame.draw.line(screen, white, [300, 0], [300, screenheight], 5) pygame.draw.line(screen, white, [400, 0], [400, screenheight], 5) pygame.draw.line(screen, white, [500, 0], [500, screenheight], 5) #dibujar sprites all_sprites_list.draw(screen) text = fonts.render("Cars racing", True, black) screen.blit(text, (screenwidth - text.get_width() - 10, 30)) text_score = font_score.render("Score: " + str(score), True, black) screen.blit(text_score, (screenwidth - text_score.get_width() - 10, 60)) score += 1 pygame.display.flip() clock.tick(60) #textos #text=fonts.render("GAME OVER / FIN DEL JUEGO", True, red) text = fonts.render("Pulsa Y para reintentar o N para cerrar", True, red) screen.blit(text, (250, 250)) pygame.display.flip() #print("Parece que tu no eres Fernando Alonso, eres demasiado malo.") for event in pygame.event.get(): if event.type == pygame.QUIT: finished = True keys = pygame.key.get_pressed() if keys[pygame.K_y]: main() elif keys[pygame.K_n]: finished = True pygame.quit()
def train_car(save_learning_curve=False): close('all') # create instances of a car and a track monaco = track.track() ferrari = car.car() n_trials = 1000 n_time_steps = 1000 # maximum time steps for each trial if save_learning_curve: learn_curve_file = open(params.LEARNING_CURVE_FILE, 'a') ''' net = nn.NeuralNetwork(params.POS_NEURONS, params.POS_RANGE, params.VEL_NEURONS, params.STATIC_VEL_RANGE, params.NB_OUTPUTS, params.ETA, params.GAMMA, params.LAMBDA) my_net.compute_network_output() ''' for j in arange(n_trials): # before every trial, reset the track and the car. # the track setup returns the initial position and velocity. (position_0, velocity_0) = monaco.setup() ferrari.reset() # choose a first action action = ferrari.choose_action(position_0, velocity_0, 0) # iterate over time for i in arange(n_time_steps): # the track receives which action was taken and # returns the new position and velocity, and the reward value. (position, velocity, R) = monaco.move(action) # the car chooses a new action based on the new states and reward, # and updates its parameters action = ferrari.choose_action(position, velocity, R) # check if the race is over if monaco.finished is True: break else: print "Did not finish the track" print "Total reward:", monaco.total_reward if save_learning_curve: print >> learn_curve_file, \ j, monaco.time, monaco.total_reward, monaco.finished if j % 100 == 0 and not save_learning_curve: # plots the race result every 100 trials monaco.plot_world() if j % 10 == 0: print print 'TRIAL:', j # uncomment only when plotting navigation maps #if (j+1)%100 == 0: # plot_navigation_map(ferrari, j+1) if save_learning_curve: learn_curve_file.close() return ferrari #returns a trained car
from car import car from collection import collectionCar from main import functionsdealer car1 = car('test1', 'wood', '100', '120', '1991', '1991') car2 = car('test2', 'ev', '100', '130', '1991', '1991') car3 = car('test3', 'wood', '100', '140', '1991', '1991') coll = collectionCar() coll.addCar(car1) coll.addCar(car2) coll.addCar(car3) m = functionsdealer() total = m.saleyear('1991', coll.get_list()) total1 = m.benefityear('1991', coll.get_list()) total2 = m.soldmake('wood', coll.get_list()) total3 = m.purchase('wood', coll.get_list()) m.displaybenefitsale(total1) m.displaysale(total) m.displaysoldmakesale(total2) m.displaysoldpurchase(total3)
from car import car, Electriccar my_car = car() print my_car.engineSize #print my_car.make #make is private instance and will not print, it gives error print my_car.getmake() #to be able to print make, add another function called def getmake print my_car.getcolour() print my_car.getmileage() my_car.engineSize = "2.4l" #there is no need for setengineSize as it is public and could be updated with this code print my_car.engineSize my_car.setmake("BMW") print my_car.getmake() my_car.setcolour("Black") print my_car.getcolour() my_car.setmileage(5000) print my_car.getmileage() my_car.move(10) print my_car.getmileage() my_car.paint("black") print my_car.getcolour() #my_car.engineSize = "3.6l" #updating engineSize needs no set function as it is public, otherwise there will be a need for setengineSize function
import time from car import car import RPi.GPIO as GPIO Mycar = car() while True: cmdlist = ['f', 'r', 'c'] keyin = input("Input Command:") cmd = keyin[0] if cmd not in cmdlist: print("Invalid Command. Process Killed.\n") GPIO.cleanup() quit() if cmd == "f": Mycar.setSpeed(50, 50) time.sleep(0.4) for i in range(0, 6): Mycar.setSpeed(100, 0) time.sleep(0.4) Mycar.setSpeed(0, 0) time.sleep(0.2) Mycar.setSpeed(50, 50) time.sleep(0.2) Mycar.setSpeed(50, 50) elif cmd == "r": Mycar.setSpeed(50, 50) time.sleep(0.5) for i in range(0, 3): Mycar.setSpeed(0, 100) time.sleep(0.4) Mycar.setSpeed(0, 0)
def train_car(): close('all') # create instances of a car and a track monaco = track.track() ferrari = car.car() n_trials = 1000 n_time_steps = 500 # maximum time steps for each trial # create figure figure(200) f_time = subplot(111) xlim(0,n_trials/10) ylim(0,1000) figure(400) f_el = subplot(111) total_time = 10 time_array = [] for j in arange(1, n_trials+1): # before every trial, reset the track and the car. # the track setup returns the initial position and velocity. (position_0, velocity_0) = monaco.setup() ferrari.reset() # total time of time per 10 trial # choose a first action action = ferrari.choose_action(position_0, velocity_0, 0) # iterate over time for i in arange(n_time_steps) : # the track receives which action was taken and # returns the new position and velocity, and the reward value. (position, velocity, R) = monaco.move(action) # the car chooses a new action based on the new states and reward, and updates its parameters action = ferrari.choose_action(position, velocity, R) # check if the race is over if monaco.finished is True: total_time += i break if i == 999: total_time += 1000 if j%100 == 0: # plots the race result every 100 trials monaco.plot_world() if j%10 == 0: # plot average of essays to reach goal time_array.append(total_time / 10) # plot total_time = 0 print 'Trial:', j f_el.imshow(ferrari.c_m_eligibility) f_time.plot(time_array) return ferrari #returns a trained car
def main(): # init pygame pygame.init() black = 0, 0, 0 red = 255, 0, 0 size = width, height = int(1366 * 0.95), int(768 * 0.95) screen = pygame.display.set_mode(size, pygame.DOUBLEBUF) font = pygame.font.Font("arcade.ttf", 12) map__ = map_(screen, lambda x: x**3, lines=200) cars = [ car(vec(width / 3, height / 2), vec(0, 0), "car.png") for i in range(amount_cars) ] def update_forces(dt, tick): # manually moving the car/adding force via engine + fuel if cars[cur_car].forward: cars[cur_car].move(50.0) if cars[cur_car].backward: cars[cur_car].move(-50.0) if cars[cur_car].right: cars[cur_car].rotate(-5) if cars[cur_car].left: cars[cur_car].rotate(5) if cars[cur_car].boosting: cars[cur_car].move(100) for car in cars: car.update(dt, tick) # semi implicit euler integration def draw(): offset_x, offset_y = int(width / 2 - cars[cur_car].rect.center[0]), int( height / 2 - cars[cur_car].rect.center[1]) screen.fill(black) # clear screen # render map #map__.render(offset_x, offset_y) # render cars for i, car in enumerate(cars): if i != cur_car: screen.blit( car.transformed_sprite, (int(car.rect.center[0] - car.rect.width / 2 + offset_x), int(car.rect.center[1] - car.rect.height / 2 + offset_y))) # current car is supposed to be centered cars[cur_car].render_rays(screen) screen.blit( cars[cur_car].transformed_sprite, (int(width / 2 - cars[cur_car].rect.size[0] / 2), int(height / 2 - cars[cur_car].rect.size[1] / 2))) # draw sprites # render GUI and HUD hud = font.render( "force: %s acceleration: %s velocity: %s position: %s" % (cars[cur_car].force, cars[cur_car].acceleration, cars[cur_car].velocity, cars[cur_car].pos), True, red) screen.blit(hud, (10, 10)) # swap buffers pygame.display.flip() def poll(): global cur_car global amount_cars events = pygame.event.get() for event in events: if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: sys.exit() if event.key == pygame.K_LEFT or event.key == pygame.K_a: cars[cur_car].left = True if event.key == pygame.K_RIGHT or event.key == pygame.K_d: cars[cur_car].right = True if event.key == pygame.K_UP or event.key == pygame.K_w: cars[cur_car].forward = True if event.key == pygame.K_DOWN or event.key == pygame.K_s: cars[cur_car].backward = True if event.key == pygame.K_SPACE: cars[cur_car].boosting = True if event.key == pygame.K_RSHIFT: cars[cur_car].left = False cars[cur_car].right = False cars[cur_car].backward = False cars[cur_car].forward = False cur_car = (cur_car + 1) % amount_cars if event.type == pygame.KEYUP: if event.key == pygame.K_LEFT or event.key == pygame.K_a: cars[cur_car].left = False if event.key == pygame.K_RIGHT or event.key == pygame.K_d: cars[cur_car].right = False if event.key == pygame.K_UP or event.key == pygame.K_w: cars[cur_car].forward = False if event.key == pygame.K_DOWN or event.key == pygame.K_s: cars[cur_car].backward = False if event.key == pygame.K_SPACE: cars[cur_car].boosting = False clock = pygame.time.Clock() dt = 0 tick = 0 while 1: poll() draw() update_forces(dt / 1000, tick) tick += 1 dt = clock.tick(60) # in milliseconds
def average_trainings_last_trials(eps, decrease): close('all') # create instances of a car and a track monaco = track.track() ferrari = car.car(eps, decrease) n_trials = 1000 n_time_steps = 1000 # maximum time steps for each trial n_indep_cars = 5. times = zeros(n_trials) avg_times = zeros(n_trials) for k in arange(n_indep_cars): monaco = track.track() ferrari = car.car(eps, decrease) for j in arange(n_trials): # before every trial, reset the track and the car. # the track setup returns the initial position and velocity. (position_0, velocity_0) = monaco.setup() ferrari.reset() # choose a first action action = ferrari.choose_action(position_0, velocity_0, 0) # iterate over time for i in arange(n_time_steps): # the track receives which action was taken and # returns the new position and velocity, and the reward value. (position, velocity, R) = monaco.move(action) # the car chooses a new action based on the new states and reward, and updates its parameters action = ferrari.choose_action(position, velocity, R) # check if the race is over if monaco.finished is True: break if j%10 == 0: print 'Eps:',eps,'Car:',k, 'Trial:', j times[j] = monaco.time avg_times = avg_times + times/n_indep_cars avgtime_lasttrials = sum(avg_times[-10:])/10; figure(1) plot(avg_times) ylabel('Latency') xlabel('Trial') out_str = str(n_indep_cars)+'_latency'+str(eps)+'_avgtime_lasttrials'+str(avgtime_lasttrials)+'.png' if decrease: out_str = str(n_indep_cars)+'_latency'+str(eps)+'_decreasing_avgtime_lasttrials'+str(avgtime_lasttrials)+'.png' savefig(out_str) return avg_times '''
pygame.display.set_caption("Cars racing") #te da todas las fuentes #fonts = pygame.font.get_fonts() #print(fonts) fonts = pygame.font.SysFont('Arial', 30) font_score = pygame.font.SysFont('Arial', 20) #music #pygame.mixer.music.load('audio/soundtrack.mp3') #pygame.mixer.music.play (-1) #Jugadores = color, anchura, altura, speed playerCar = car("images/murder.png", red, 60, 80, 70) #obtenemos la coordenada x del rectangulo playerCar.rect.x = 150 - playerCar.image.get_width() / 2 playerCar.rect.y = screenheight - 100 all_sprites_list = pygame.sprite.Group() car1 = car("images/police.png", black, 60, 80, 70) car1.rect.x = 250 - playerCar.image.get_width() / 2 car1.rect.y = screenheight - 100 car2 = car("images/police.png", white, 60, 80, random.randint(50, 100)) car2.rect.x = 350 - playerCar.image.get_width() / 2 car2.rect.y = screenheight - 600 car3 = car("images/police.png", green, 60, 80, random.randint(50, 100))
def train_car(save_learning_curve = False): close('all') # create instances of a car and a track monaco = track.track() ferrari = car.car() n_trials = 1000 n_time_steps = 1000 # maximum time steps for each trial if save_learning_curve: learn_curve_file = open(params.LEARNING_CURVE_FILE, 'a') ''' net = nn.NeuralNetwork(params.POS_NEURONS, params.POS_RANGE, params.VEL_NEURONS, params.STATIC_VEL_RANGE, params.NB_OUTPUTS, params.ETA, params.GAMMA, params.LAMBDA) my_net.compute_network_output() ''' for j in arange(n_trials): # before every trial, reset the track and the car. # the track setup returns the initial position and velocity. (position_0, velocity_0) = monaco.setup() ferrari.reset() # choose a first action action = ferrari.choose_action(position_0, velocity_0, 0) # iterate over time for i in arange(n_time_steps) : # the track receives which action was taken and # returns the new position and velocity, and the reward value. (position, velocity, R) = monaco.move(action) # the car chooses a new action based on the new states and reward, # and updates its parameters action = ferrari.choose_action(position, velocity, R) # check if the race is over if monaco.finished is True: break else: print "Did not finish the track" print "Total reward:", monaco.total_reward if save_learning_curve: print >> learn_curve_file, \ j, monaco.time, monaco.total_reward, monaco.finished if j%100 == 0 and not save_learning_curve: # plots the race result every 100 trials monaco.plot_world() if j%10 == 0: print print 'TRIAL:', j # uncomment only when plotting navigation maps #if (j+1)%100 == 0: # plot_navigation_map(ferrari, j+1) if save_learning_curve: learn_curve_file.close() return ferrari #returns a trained car
#filename = "c_no_hurry.in" filename = "b_should_be_easy.in" file = open(filename, "r") R, C, F, N, B, T = [int(x) for x in file.readline().split(" ")] # matrix = np.zeros([R,C]) # Crea oggetti car cars_to_assign = [] for i in range(F): macchina = car(i, None, 0, 0, 100) cars_to_assign.append(macchina) # Crea oggetti ride indexRide = 0 rides = [ ] # lo costruisco in modo che sia ordinato, cosi' la scelta iniziale delle ride e' facile for line in file: a, b, x, y, s, f = [int(x) for x in line.split(" ")] raid = ride(indexRide, a, b, x, y, s, f) costo = cars_to_assign[0].greedy_cost( raid, 0, T, B ) # al tempo 0, visto che le macchine partono dalla stessa posizione, il costo e' lo stesso per tutte le macchine
if world.window.lane_pos_y[0] + world.window.y <= cursor_pos[ 1] <= world.window.lane_pos_y[1] + world.window.y: new_y = (world.window.lane_pos_y[0] + world.window.y + world.window.lane_pos_y[1] + world.window.y) / 2 if world.window.lane_pos_y[1] + world.window.y <= cursor_pos[ 1] <= world.window.lane_pos_y[2] + world.window.y: new_y = (world.window.lane_pos_y[1] + world.window.y + world.window.lane_pos_y[2] + world.window.y) / 2 if world.window.lane_pos_y[2] + world.window.y <= cursor_pos[ 1] <= world.window.bot_shoulder_pos_y + world.window.y: new_y = (world.window.lane_pos_y[2] + world.window.y + world.window.bot_shoulder_pos_y + world.window.y) / 2 new_obst = car(cursor_pos[0], new_y, "obstacle", game) game.obst_list.add(new_obst) game.all_sprites.add(new_obst) bluecarlist.append(cursor_pos) # world.updateWinPos(game) world.window.redrawGameWindow(game, world.WorldSize_px) if keys[pygame.K_q]: pygame.quit() game.run = False pygame.quit() print("Saving data")
def main(index_designated=2): car_ = car() car_.straight() time.sleep(1) car_.forward() time.sleep(1) camera_ = camera() # index_desigated = 2 #0 = b, 1 = g, 2 = r kernel = np.ones((4, 4), np.float32) / 16 counter = 0 while True: ret, frame = camera_.usb_camera.read() shape = frame.shape weight, height = shape[0] // 10, shape[1] // 10 resize_frame = cv2.resize(frame, (height, weight), interpolation=cv2.INTER_CUBIC) resize_frame = cv2.filter2D(resize_frame, -1, kernel) gray_frame = cv2.cvtColor(resize_frame, cv2.COLOR_BGR2GRAY) Z = resize_frame.reshape((-1, 3)) Z = np.float32(Z) criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0) K = 12 ret, label, center = cv2.kmeans(Z, K, None, criteria, 10, cv2.KMEANS_RANDOM_CENTERS) center = np.uint8(center) res = center[label.flatten()] k_img = res.reshape((resize_frame.shape)) hsv_frame = rgbtohsl(k_img) # try hsl #cv2.imshow('k_img', hsv_frame) Z = hsv_frame.reshape((-1, 3)) Z = np.float32(Z) K = 2 ret, label, center = cv2.kmeans(Z, K, None, criteria, 10, cv2.KMEANS_RANDOM_CENTERS) center = np.uint8(center) res = center[label.flatten()] k_hsv = res.reshape((hsv_frame.shape)) #cv2.imshow("k_hsv", k_hsv) h_list = [] s_list = [] l_list = [] for x in range(0, weight): for y in range(0, height): tmp_h = k_hsv[x, y, 0] tmp_s = k_hsv[x, y, 1] tmp_l = k_hsv[x, y, 2] if (tmp_h not in h_list): h_list.append(tmp_h) s_list.append(tmp_s) l_list.append(tmp_l) else: if (tmp_s not in s_list): h_list.append(tmp_h) s_list.append(tmp_s) l_list.append(tmp_l) else: if (tmp_l not in l_list): h_list.append(tmp_h) s_list.append(tmp_s) l_list.append(tmp_l) result_frame = np.zeros((resize_frame.shape)) count_1 = 0 count_2 = 0 for x in range(0, weight): for y in range(0, height): if (k_hsv[x, y, 0] == h_list[0] and k_hsv[x, y, 1] == s_list[0]\ and k_hsv[x, y, 2] == l_list[0]): count_1 += 1 else: count_2 += 1 x_list = [] y_list = [] if (count_1 > count_2): for x in range(0, weight): for y in range(0, height): if (k_hsv[x, y, 0] == h_list[1] and k_hsv[x, y, 1] == s_list[1]\ and k_hsv[x, y, 2] == l_list[1]): tmp_color = (resize_frame[x, y, 0], resize_frame[x, y, 1], \ resize_frame[x, y, 2]) max_color = max(tmp_color) max_index = tmp_color.index(max_color) # blue if (max_index == index_desigated): if (max_index == 0): result_frame[x, y, 1] = result_frame[x, y, 2] = 255 result_frame[x, y, 0] = 255 x_list.append(x) y_list.append(y) elif (max_index == 1): result_frame[x, y, 0] = result_frame[x, y, 2] = 255 result_frame[x, y, 1] = 255 x_list.append(x) y_list.append(y) else: result_frame[x, y, 0] = result_frame[x, y, 1] = 255 result_frame[x, y, 2] = 255 x_list.append(x) y_list.append(y) else: result_frame[x, y, 0] = result_frame[ x, y, 1] = result_frame[x, y, 2] = 0 else: for x in range(0, weight): for y in range(0, height): if (k_hsv[x, y, 0] == h_list[0] and k_hsv[x, y, 1] == s_list[0]\ and k_hsv[x, y, 2] == l_list[0]): tmp_color = (resize_frame[x, y, 0], resize_frame[x, y, 1], \ resize_frame[x, y, 2]) max_color = max(tmp_color) max_index = tmp_color.index(max_color) if (max_index == index_desigated): if (max_index == 0): result_frame[x, y, 1] = result_frame[x, y, 2] = 255 result_frame[x, y, 0] = 255 x_list.append(x) y_list.append(y) elif (max_index == 1): result_frame[x, y, 0] = result_frame[x, y, 2] = 255 result_frame[x, y, 1] = 255 x_list.append(x) y_list.append(y) else: result_frame[x, y, 0] = result_frame[x, y, 1] = 255 result_frame[x, y, 2] = 255 x_list.append(x) y_list.append(y) else: result_frame[x, y, 0] = result_frame[ x, y, 1] = result_frame[x, y, 2] = 0 avg_x = sum(x_list) / len(x_list) avg_y = sum(y_list) / len(y_list) mean_weight = int(weight / 2) #|v mean_height = int(height / 2) #-> if abs(avg_x - mean_weight) < 5: if abs(avg_y - mean_height) < 5: car_.forward() time.sleep(0.1) else: car_.set_throttle(0.1) if (avg_y - mean_height > 0): car_.turn_right() time.sleep(0.1) else: car_.turn_left() time.sleep(0.1) elif abs(avg_x - mean_weight) > 5: car_.set_throttle(0.1) if abs(avg_y - mean_height < 5): if (avg_x - mean_weight > 0): car_.set_throttle(-0.1) time.sleep(0.1) else: if (avg_y - mean_height > 0): if (avg_x - mean_weight > 0): car_.set_throttle(-0.1) car_.turn_right() time.sleep(0.1) else: car_.set_throttle(0.1) car_.turn_left() time.sleep(0.1) else: car_.stop() time.sleep(0.1) #cv2.imshow('result', result_frame) savename = "./test_img/" + str(counter) + ".png" cv2.imwrite(savename, result_frame) counter += 1 if (cv2.waitKey(1) == 'q'): break camera_.usb_camera.release() cv2.destroyAllWindows()
from car import car if __name__ == "__main__": print("Hola mundo") car = car() car.license = "AMS234" car.driver = "Andres Herrera" print(vars(car)) car2 = car() car2.license = "AAS234" car2.driver = "Andrea Herrera" print(vars(car2))
rand_number = random.random() if rand_number < 0.1: return True else: return False def pick_which_car(list_of_cars): random_index = random.randint(0, len(list_of_cars) - 1) return list_of_cars[random_index] time_now = 0 # initialize the cars in the simulation, store in a list l_cars_before_entering_road = [car.car(str(x)) for x in range(10) ] ## all the cars in the simulation l_cars_after_leaving_road = [] #priority queue for the road road_A = [ ] #it's an empty list for now, we'll modify this by using the heapq methods seconds_to_simulate = 60 ## loop through the time (in seconds), and update the priority queue at each time, time_to_stop_simulation = time_now + seconds_to_simulate while time_now < time_to_stop_simulation: # for each item in the priority queue (road_X), decrease the key (representing the seconds) by one for queue_tuple in road_A: queue_tuple[1].total_travel_time += 1 if queue_tuple[1].time_to_intersection == 0:
#(1080, 1920, 3) def find_line(self): self.gray = cv2.cvtColor(np.float32(self.img), cv2.COLOR_BGR2GRAY) #kernel_size = 5 #self.blur_gray = cv2.GaussianBlur(self.gray, (kernel_size, kernel_size), 0) self.edges = cv2.Canny(self.gray, 50, 150, apertureSize=3) minLineLength = 100 maxLineGap = 10 lines = cv2.HoughLinesP(edges, 1, np.pi/180, 100, \ minLineLength, maxLineGap) for x1, y1, x2, y2 in lines[0]: cv2.line(self.img, (x1, y1), (x2, y2), (0, 255, 0), 2) cv2.imwrite("line.png", self.img) if __name__ == "__main__": car = car() #angle = 50 #dc = car.angle_to_duty_cycle(angle) #car.pwm.ChangeDutyCycle(dc) #testing on no car img = cv2.imread("testing_img.png") procs = image_processing() #procs = image_processing(resize_im) print("shape: ", procs.img.size) procs.find_line()
from car import car bmw = car("KA028907", 5) bmw.start() bmw.change_gear() bmw.stop()
from car import car from truck import truck obj= car("ac","steering_wheel","seat_belt","audio_play") print(obj.deploy_airbags()) obj1 = truck(100,60,6,40,1500,10,"blue") print(obj1.load()) print(obj1.unload()) print(obj1.no_of_wheels) print(obj1.speed) print(obj1.weight) print(obj1.mileage) print(obj1.color)
from car import car, electriccar my_beetle = car('volkswagen', 'beetle', 2016) print(my_beetle.car_info()) my_tesla = electriccar('tesla', 'roadster', 2016) print(my_tesla.car_info())
stream.seek(0) nsent = send_stuff(sock, stream.read()) if nsent == -1: print("client closed connection, stopping") stop_ev.set() stream.seek(0) stream.truncate() time.sleep(.0001) #send_stuff(client_socket, struct.pack('<L', 0)) except socket.error: print("connection broken, client no longer recieving") print(datetime.datetime.now().strftime(time_format)) stop_ev.stop(None) carlos = car() #initialize car object tc = termCondition() js_source = SocketReader(commands_in_sock) #joystick input from socket server_thread = threading.Thread(target=server_process, args=[tc, stream_out_sock, stream]) controller = ControllerObject(js_source) #controller handler controller.start_thread() try: camera = picamera.PiCamera() camera.resolution = (128, 96) camera.framerate = 20 server_thread.start() time.sleep(2) camera.start_recording(stream, format='rgb')
import time import RPi.GPIO as GPIO import numpy as np from adafruit_motorkit import MotorKit from car import car car_ = car() car_.stop()
from car import car car1 = car("KA028907", 5) car2 = car("KA028907", 4) car3 = car("KA028907", 5) car4 = car("KA028907", 6) car1.start() car2.stop()
def average_trainings_softmax(): close('all') # create instances of a car and a track monaco = track.track() ferrari = car.car() n_trials = 1000 n_time_steps = 1000 # maximum time steps for each trial n_indep_cars = 3. times = zeros(n_trials) rewards = zeros(n_trials) avg_times = zeros(n_trials) avg_rewards = zeros(n_trials) for k in arange(n_indep_cars): monaco = track.track() ferrari = car.car() for j in arange(n_trials): # before every trial, reset the track and the car. # the track setup returns the initial position and velocity. (position_0, velocity_0) = monaco.setup() ferrari.reset() # choose a first action action = ferrari.choose_action_softmax(position_0, velocity_0, 0) # iterate over time for i in arange(n_time_steps) : # the track receives which action was taken and # returns the new position and velocity, and the reward value. (position, velocity, R) = monaco.move(action) # the car chooses a new action based on the new states and reward, and updates its parameters action = ferrari.choose_action_softmax(position, velocity, R) # check if the race is over if monaco.finished is True: break if j%100 == 0: # plots the race result every 100 trials monaco.plot_world() if j%10 == 0: print k, 'Trial:', j times[j] = monaco.time rewards[j] = monaco.total_reward avg_times = avg_times + times/n_indep_cars avg_rewards = avg_rewards + rewards/n_indep_cars figure(1) plot(avg_times) ylabel('Latency') xlabel('Trial') show() figure(2) plot(avg_rewards) ylabel('Total reward') xlabel('Trial') show()
def importWorld(fn_array, fn_route): global solarCar solarCar = car.car() solarCar.loadArray(fn_array) return
from car import car c = car('benz','red','suv') c.status() c.start() c.status() c.speedup() c.stop() c.status()
def newTires(self, vehicle, tires): if vehicle.price < 250000: self.amount = tires * 250 else: self.amount = tires * 1000 print( f'Your total cost is {self.amount} remeber to come back after a 100,000 miles!' ) # This method checls the total cost of the work def Totalcost(self, vehicle): print(f'Your cost for the total work is {self.amount}') tesla = car('Tesla', 'Model x', 80000, 2018, 'white', 220, True) richmond = mechanicgarage('Bob', 1500, 0) # richmond.newTires(tesla,3) # richmond.changeColor(tesla, 2000) # richmond.Totalcost(tesla) # McLaren = supercar('McLaren', 'F1', 1000000, 1961, "red", 231, 627,4000, False) # italymechanic = mechanicgarage('Dan', 40000, 0) # italymechanic.newTires(McLaren, 2)
def train_car(maserati): close('all') print_log = False dynamicEpsilon = False doOptimalActionAnalysis = False; useOptimalCar = False n_trials = 1000 if dynamicEpsilon or doOptimalActionAnalysis: numCars = 10 else: numCars = 10 epsilons = array([0.1]) #0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9 if dynamicEpsilon: epsilons = array([-1, -5, -9]) # parameters for epsilon function ####################################################################################################################################### numEpsilons = epsilons.size n_time_steps = 1000 # maximum time steps for each trial timeLog = NaN * zeros((numCars,numEpsilons,n_trials)) rewardLog = NaN * zeros((numCars,numEpsilons,n_trials)) optimalActionsInterval = 20 # number of trials between each rendition of optimal actions optimalActionsResolution = 100; # density of evaluation coordinates optimalActions = NaN * zeros((ceil(n_trials / optimalActionsInterval),optimalActionsResolution,optimalActionsResolution)) # create instances of a car and a track monaco = track.track() for c in arange(numCars): print "Starting sim of car ", c, "of", numCars for e in arange(numEpsilons): print "Epsilon ", e, "of", numEpsilons if maserati == None: if useOptimalCar: print "Using optimal car" ferrari = optimal_car.optimal_car() else: print "Using standard car" ferrari = car.car() else: print "Using loaded car" ferrari = maserati monaco.ferrari = ferrari #ferrari.set_epsilon(0.1) for j in arange(n_trials): # before every trial, reset the track and the car. # the track setup returns the initial position and velocity. (position_0, velocity_0) = monaco.setup() ferrari.reset() if not useOptimalCar: if dynamicEpsilon: ferrari.set_epsilon( exp(epsilons[e] * double(j)/n_trials) )# t = 0 else: ferrari.set_epsilon( epsilons[e] ) # choose a firsttion action = ferrari.choose_action(position_0, velocity_0, 0, print_results = print_log) # iterate over time for i in arange(n_time_steps) : #if dynamicEpsilon: # ferrari.set_epsilon( exp(epsilons[e] * ((double(i)/n_time_steps))) ) #else: # ferrari.set_epsilon( epsilons[e] ) # the track receives which action was taken and # returns the new position and velocity, and the reward value. (position, velocity, R) = monaco.move(action) # the car chooses a new action based on the new states and reward, and updates its parameters action = ferrari.choose_action(position, velocity, R, print_results = print_log) # monaco.plot_world() # check if the race is over if monaco.finished is True: break # if j == 30 and i >= 0: # print_log = True if monaco.finished: timeLog[c][e][j] = i else: timeLog[c][e][j] = NaN rewardLog[c][e][j] = monaco.total_reward if j%10 == 0: monaco.plot_world() if (doOptimalActionAnalysis and (j%optimalActionsInterval == optimalActionsInterval - 1)): coords = linspace(0+1/(2*optimalActionsResolution),1-1/(2*optimalActionsResolution),optimalActionsResolution) for ix in arange(optimalActionsResolution): for iy in arange(optimalActionsResolution): px = coords[ix] py = coords[iy] (optAction, Q) = ferrari.actionMaxQ(ferrari.posCellsActivity((px, py)), ferrari.velCellsActivity((0,0))) optimalActions[floor(j/optimalActionsInterval)][ix][iy] = optAction print 'Trial:', j #print 'Q policy stats: epsilon = ', ferrari.epsilon , 'epsilon ~=', (ferrari.pc_rand/(ferrari.pc_Qmax+ferrari.pc_rand)), 'e', e, ' epsilons[e]', epsilons[e] if (numEpsilons + numCars > 2): print "Car", c, ", epislon ",e ," times and rewards:" print timeLog[c][e] print rewardLog[c][e] if doOptimalActionAnalysis: np.savetxt("optimalActions.log",optimalActions.flatten()) if (numEpsilons + numCars > 2): np.savetxt("timeLogs.log",timeLog.flatten()) np.savetxt("rewardLogs.log",rewardLog.flatten()) print ferrari.best_actions[0] print ferrari.best_actions[1] print ferrari.best_actions[2] return ferrari #returns a trained car
from pylab import * import track import car monaco = car.car() p = [0.5,0.5] v = [0.3,0.8] pos = monaco.posCellsActivity(p) vel = monaco.velCellsActivity(v) figure(200) clf() im1 = imshow(vel) draw()
import person import car import cycle myPerson = person.person("elendil") myDoctor = person.Doctor("Elendil") myLawyer = person.Lawyer("Elendil") print(myPerson.name) print(myDoctor.name) print(myLawyer.name) myCar = car.car() myCar.exclaim() myYogoCar = car.Yugo() myYogoCar.exclaim() myYogoCar.push() myEmailPerson = person.EmailPerson("elendil", "*****@*****.**") print(myEmailPerson.name) print(myEmailPerson.email) car.car.exclaim(myCar) myDuck = person.Duck("Elendil Zheng") print(myDuck.name) myDuck.name = "Zheng Elendil" print(myDuck.name) myCycle = cycle.cycle(10) print(myCycle.diameter) myCycle.diameter = 10 print(myCycle.diameter) print(myCycle.radius) #Hack to visit private variable print(myCycle._cycle__radius)
# while player.pos[0] not in roads[1]: # player.pos[0]+=tileSize startPos = getIntersectionNear(roads,(0,0),7) endPos = getIntersectionNear(roads,(100,100)) playerStart = getRoadNear(roads,(0,0),0) print(playerStart,endPos) player = car([playerStart[0]*tileSize,playerStart[1]*tileSize]) player.pos[0]+=tileSize/2 player.pos[1]+=tileSize/2 print(player.pos) newTiles(city,startPos,tileDimX,tileDimY) print(playerStart,endPos) npcs = [] total = 1500 for n in range(total): start, end = None,None
import pygame from car import car pygame.init() dimensions = {'w': 1500, 'h': 800} canvas = pygame.display.set_mode((dimensions['w'], dimensions['h'])) tron = car() def main(): tron.update() tron.draw(canvas) running = True while running: pygame.time.delay(20) canvas.fill((0, 0, 0)) for event in pygame.event.get(): if event.type == pygame.QUIT: running = False pygame.quit() keys = pygame.key.get_pressed() if keys[pygame.K_UP]: tron.change_direction('up') if keys[pygame.K_DOWN]: tron.change_direction('down') if keys[pygame.K_LEFT]: tron.change_direction('left')
import race import car import optimal_car import numpy as np doTraining = True doLoad = False doSave = False fileName = 'autosave_weights' maserati = car.car() if doLoad: #maserati.weights = np.loadtxt(fileName) #maserati = race.train_car(maserati) #maserati.best_actions.append([1, 1, 2, 2, 1, 2, 0, 6, 6, 3, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 5]) # solsmed, Time: 21 #maserati.best_actions.append([1, 1, 2, 2, 2, 2, 1, 1, 1, 1, 3, 3, 3, 3, 5, 5, 3, 5, 5, 5, 5, 5, 5]) # perfectly positioned crash, Time: 22 #maserati.best_actions.append([1, 1, 2, 2, 2, 0, 0, 0, 0, 0, 0, 2, 5, 4, 4, 4, 5, 4, 4, 4, 4, 5, 5, 4]) # triangle crash, Time: 23 #maserati.best_actions.append([1, 1, 3, 1, 6, 1, 3, 6, 3, 6, 3, 6, 1, 1, 3, 6, 6, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5]) # learned, crash free, Time: 27 maserati.best_actions.append([1, 2, 2, 2, 7, 2, 7, 2, 2, 2, 7, 7, 3, 3, 3, 4, 4, 4, 5, 5, 5, 4, 5, 5]) # epsilon 0.01 ? if doTraining: if doLoad: maserati = race.train_car(maserati) else: maserati = race.train_car(None) print 'Training finished.' if doSave:
import car as car_i car_info_1 = car_i.car("subaru", "outback", color="blue", tow_package=True) print(car_info_1)