def test_removeCars(self): car1 = Car("Car1", "EAST", "STRAIGHT") car2 = Car("Car2", "EAST", "RIGHT") car3 = Car("Car3", "EAST", "LEFT") lane = [car1, car2, car3, car3] simulator.removeCars(lane, "LEFT") self.assertEqual(lane, [car1, car2, car3])
def test_countCars(self): car1 = Car("Car1", "EAST", "STRAIGHT") car2 = Car("Car2", "EAST", "RIGHT") car3 = Car("Car3", "EAST", "LEFT") lane = [car1, car2, car3, car3] answer = simulator.countCars(lane, "LEFT") self.assertEqual(answer, 2)
def setUp(self): make = "GM" self.model = "Malibu" year = 2020 self.price = 40000 self.km = 10000 self.avto1 = Car(make, self.model, year) self.avto2 = Car(make, self.model, year, price=self.price)
def test_countAllCars(self): """ Used to test the counnt all cars method """ controller = TrafficLightController("TEST") car1 = Car("Car1", "EAST", "STRAIGHT") car2 = Car("Car2", "EAST", "RIGHT") car3 = Car("Car3", "EAST", "LEFT") lane = [car1, car2, car3, car3] self.assertEqual(simulator.CountAllCars(lane), (1, 3))
def test_removeCars(self): """ Test for removing cars """ car1 = Car("Car1", "EAST", "STRAIGHT") car2 = Car("Car2", "EAST", "RIGHT") car3 = Car("Car3", "EAST", "LEFT") eastLane = [car1, car2, car3, car3] simulator.removeCars(eastLane, "LEFT") self.assertEqual(eastLane, [car1, car2, car3])
def test_lightSignalsLogic(self): """ Tests our logic for our light signals """ car1 = Car("Car1", "EAST", "STRAIGHT") car2 = Car("Car2", "EAST", "RIGHT") car3 = Car("Car3", "EAST", "LEFT") car4 = Car("Car4", "NORTH", "RIGHT") testFunctions.eastLane = [car1, car2, car3] testFunctions.northLane = [car4, car4] self.assertEqual(testFunctions.lightSignals(), ("eo", "er"))
def test_sensorAllGo(self): controller = TrafficLightController("MOCK") tl = controller.getTL() tl.switchOff() tl.greenOn() tl.tgreenOn() car1 = Car("Car1", "EAST", "STRAIGHT") car2 = Car("Car2", "EAST", "RIGHT") car3 = Car("Car3", "EAST", "LEFT") lane = [car1, car2, car3, car3] simulator.sensor(controller, lane) self.assertEqual(lane, [car2, car3, car3])
def test_lightSignalWaitLogicTwo(self): """ Test further logic behind the wait times """ car1 = Car("Car1", "EAST", "STRAIGHT") car2 = Car("Car2", "EAST", "RIGHT") car3 = Car("Car3", "EAST", "LEFT") car4 = Car("Car4", "NORTH", "RIGHT") car5 = Car("Car5", "NORTH", "STRAIGHT") testFunctions.eastLane = [car1, car2, car3] testFunctions.northLane = [car4, car5] testFunctions.northController.wait_other = 7 # test border value self.assertEqual(testFunctions.lightSignals(), ("eo", "er"))
def main(): """Demo test code to show how to use car class.""" my_car = Car("Car", 180) my_car.drive(30) print("fuel =", my_car.fuel) print("odo =", my_car.odometer) print(my_car) print("Car {}, {}".format(my_car.fuel, my_car.odometer)) print("Car {self.fuel}, {self.odometer}".format(self=my_car)) limo = Car("limo", 100) limo.add_fuel(20) print("The {} has {} units of fuel. The odometer reads: {}".format(limo.name, limo.fuel, limo.odometer)) limo.drive(115) print("The {} has {} units of fuel. The odometer reads: {}".format(limo.name, limo.fuel, limo.odometer))
def test_sensorStraightOrange(self): """ Test straight orange lights """ controller = TrafficLightController("MOCK") tl = controller.getTL() tl.switchOff() tl.tredOn() tl.orangeOn() car1 = Car("Car1", "EAST", "STRAIGHT") car2 = Car("Car2", "EAST", "RIGHT") car3 = Car("Car3", "EAST", "LEFT") lane = [car1, car2, car3, car3] simulator.sensor(controller, lane) self.assertEqual(lane, [car2, car3])
def run_tests(): """Run the tests on the functions.""" # assert test with no message - used to see if the function works properly assert repeat_string("Python", 1) == "Python" # the test below should fail repeat_string("hi", 2) assert repeat_string("hi", 2) == "hi hi" test_car = Car() assert test_car.odometer == 0, "Car does not set odometer correctly" test_car = Car(fuel=10) assert test_car.fuel == 10 test_car = Car() assert test_car.fuel == 0
def add_car(self): if input("Is the car a supercar? (y/n): ") == "y": model = input("What model is the car?: ") self.__cars.append(Supercar(model)) # Instantiate Supercar else: model = input("What model is the car?: ") self.__cars.append(Car(model)) # Instantiate Car
def __init__(self, num_of_genes, map_handler, end_spread, mutation_rate, pop_size): """Sets up the object and creates the initial population of Car objects. Args: num_of_genes (int): The number of genes per car. map_handler (MapHandler obj): An object for controlling the map. end_spread (int): The number of genes to remove and replace from the end of the gene list. mutation_rate (float): The chance of the Dna to mutate. pop_size (int): The number of Cars in the population. """ self.population = [] # Array to hold the current population self.mating_pool = [] # List which we will use for our "mating pool" self.generations = 0 # Number of generations self.finished = False # Are we finished evolving? self.map_handler = map_handler self.mutation_rate = mutation_rate self.num_of_genes = num_of_genes self.end_spread = end_spread self.start_point = map_handler.find_line_midpoint( self.map_handler.starting_line) # Creates the population of cars with random genes for id in range(0, pop_size): self.population.append( Car(self.map_handler, self.start_point, self.num_of_genes, self.end_spread, id))
def test_lightSignalWaitLogic(self): """ Tests the logic being wait times in light signals """ car1 = Car("Car1", "EAST", "STRAIGHT") car2 = Car("Car2", "EAST", "RIGHT") car3 = Car("Car3", "EAST", "LEFT") car4 = Car("Car4", "NORTH", "RIGHT") car5 = Car("Car5", "NORTH", "STRAIGHT") testFunctions.eastLane = [car1, car2, car3] testFunctions.northLane = [car4, car5, car4] for i in range(10): # Force wait to be tripped testFunctions.northController.IncrementOtherWait() self.assertEqual(testFunctions.lightSignals(), ("no", "nr"))
def test_carAttr(self): """ Test the attributes are set correctly """ car = Car("Car1", "WEST", "LEFT") self.assertEqual(car.getName(), "Car1") self.assertEqual(car.getEnter(), "WEST") self.assertEqual(car.getDirection(), "LEFT")
def test_lightsBrokenLogic(self): """ Tests lightsAreBroken works as intended """ simulator.lightsAreBroken = True controller = TrafficLightController("TEST") tl = controller.getTL() tl.switchOff() tl.greenOn() tl.tgreenOn() car1 = Car("Car1", "EAST", "STRAIGHT") car2 = Car("Car2", "EAST", "RIGHT") car3 = Car("Car3", "EAST", "LEFT") lane = [car1, car2, car3, car3] simulator.sensor(controller, lane) self.assertEqual(lane, [car1, car2, car3, car3]) # Reset the variable so as not to break anything simulator.lightsAreBroken = False
def __init__(self): pygame.init() self.window = pygame.display.set_mode((500, 800)) pygame.display.set_caption("Racing AI") self.clock = pygame.time.Clock() self.execute = True self.car = Car(250, 650, self.window) self.agent = DQNAgent(inputs=4, n_actions=2) self.episode_durations = [] self.update_agent = pygame.USEREVENT + 1 update_timer = 100 pygame.time.set_timer(self.update_agent, update_timer)
def run(self): while True: self.main_menu() user_input = input() if user_input == "1": i = 0 print( "Please answer the following questions for your top 5 dream cars" ) while len(self.car_list) < 5: i += 1 print(f"Car #{i}") make = self.questions.make() model = self.questions.model() year = self.questions.year() color = self.questions.color() rank = self.questions.rank() self.car_list.append( Car(make=make, model=model, year=year, color=color, rank=rank)) user_input = None while user_input != "6": self.sorting_menu() user_input = input() if user_input == "1": self.sort.sort_by_entry(car_list=self.car_list) elif user_input == "2": self.sort.sort_by_ranking(car_list=self.car_list) elif user_input == "3": self.sort.sort_by_year(car_list=self.car_list) elif user_input == "4": self.sort.sort_by_make(car_list=self.car_list) elif user_input == "5": self.sort.random_sort(car_list=self.car_list) elif user_input == "6": break else: print('try again') elif user_input == "2": break else: print("Not an option, try again") print(self.car_list)
def crossover(self): """Constructs a new generation using the mating pool.""" # Refill the population with children from the mating pool for i in range(len(self.population)): # Pick two parents from the mating pool a = randrange(0, len(self.mating_pool)) b = randrange(0, len(self.mating_pool)) partnerA = self.mating_pool[a] partnerB = self.mating_pool[b] child = partnerA.crossover(partnerB, self.mutation_rate) # Create a new member of the population by overriding the old one self.population[i] = \ Car(self.map_handler, self.start_point, self.num_of_genes, self.end_spread, self.population[i].id, child) self.generations += 1
def generateCars(number): global all_cars all_cars += number roads = ["NORTH","SOUTH","EAST","WEST"] directions = ["LEFT","RIGHT","STRAIGHT"] for i in range(1,number+1): name = "Car" + str(i) enter = random.choice(roads) direction = random.choice(directions) car = Car(name,enter,direction) if enter=="NORTH": northLane.append(car) elif enter=="EAST": eastLane.append(car) elif enter=="WEST": westLane.append(car) elif enter=="SOUTH": southLane.append(car) else: print("ERROR:","direction",direction,"does not exist.")
for row in data: for item in row: print(item, end=" ") print() # functions def draw(color, x, y): pygame.draw.rect(screen, color, ((x * STEP, y * STEP), (STEP, STEP))) # cars audi = Car("Ауди", car_fuel=100) # game loop while True: # keys for i in pygame.event.get(): if i.type == pygame.QUIT: exit() elif i.type == pygame.KEYDOWN: if i.key == pygame.K_UP: audi.move_up(1) elif i.key == pygame.K_RIGHT: audi.move_right(1)
#导入类 from cars import Car my_new_car = Car('audi','a4','2016') print(my_new_car.get_descriptive_name()) my_new_car.odometer_reading = 23 my_new_car.read_odometer() #导入多个类 from cars import ElectricCar,Car my_tesla = ElectricCar('tesla','model s',2016) print(my_tesla.get_descriptive_name()) my_tesla.battery.describe_battery() my_tesla.battery.get_range() #导入一个模块 import cars my_beetle =cars.Car('volkswagen','beetle',2016) print(my_beetle.get_descriptive_name()) my_tesla = cars.Car('tesla','roadster',2016)
from cars import Car bmv = Car('bmw', 90) jugul = Car('jigul', 120) print(jugul.car_ride()) print(bmv.marka) print(getattr(bmv,"speed")) if (hasattr(jugul, "speed")): print('it actually rides') else: print("it is broken") print(Car.__doc__) #получение документации print(Car.__dict__) # # for attr in dir(bmv): # if attr[0] == '_': # print(attr) # for item in bmv.__dict__: # print(item, bmv.__dict__[item])
def run_episodes(self, num_episodes=20): track = Track(50, self.window) bg_cars = [] avg = 0 for i_episode in range(num_episodes): self.createNewCars(bg_cars) self.car = Car(250, 650, self.window) self.execute = True while self.execute: keys = pygame.key.get_pressed() self.window.fill((0, 255, 0)) for event in pygame.event.get(): if event.type == pygame.QUIT or keys[pygame.K_0]: pygame.quit() if not self.car.ok and len(bg_cars) == 0: self.execute = False bg_cars = self.cleanUpCars(bg_cars) while len(bg_cars) < 2 and self.car.ok: randomno = random.randint(1, 50) if randomno == 1: new_car = BackgroundCars( BG_CARS[random.randint(0, 5)], self.window ) will_append = True for cars in bg_cars: if cars.collide(new_car): will_append = False break if will_append: bg_cars.append(new_car) self.RANDOM_CARS_COUNT += 1 track.draw() track.move() for i in random.sample( list(range(self.RANDOM_CARS_COUNT)), self.RANDOM_CARS_COUNT ): bg_cars[i].draw() bg_cars[i].move() if self.car.ok: state = self.get_state(bg_cars) self.car.score += ( self.car.x if self.car.x < 250 else 500 - self.car.x ) // 50 self.car.score += 2 self.car.draw() for cars in bg_cars: if self.car.y + 100 < cars.y: self.car.score += 50 if cars.collide(self.car): self.car.ok = False self.car.score //= 2 if self.car.x < 50 or self.car.x + self.car.width > 450: self.car.score //= 2 self.car.ok = False action = self.agent.select_action(state) if action == 0: self.car.left() elif action == 1: self.car.right() else: pass reward = self.car.score next_state = self.get_state(bg_cars) if self.car.ok else None self.agent.memory.push(state, action, reward, next_state) self.agent.learn() self.display_text() # self.clock.tick(60) pygame.display.update() while bg_cars: for i in range(len(bg_cars)): bg_cars[i].move() bg_cars[i].draw() bg_cars = self.cleanUpCars(bg_cars) if i_episode % 10 == 0: self.agent.target_brain.load_state_dict(self.agent.brain.state_dict()) print("\n\nAverage of last 10 episodes: ", avg / 10, "\n") avg = 0 print("\nScore for episode", i_episode + 1, " ----- ", self.car.score) avg += self.car.score pygame.time.wait(100) pygame.quit()
from customermenu import Customer from cars import Car from carstock import Carstock from motorbikes import Motorbike # import all object customer = Customer(Car(), Carstock(), Motorbike()) main_menu = True while True: if main_menu: print(""" *************VEHİCLE RENTAL SHOP************* C - Rent a car B - Rent a motorbike E - Exit """) main_menu = False choice = input("Your choice: ") if choice == "C" or choice == "c": print(""" *************CAR MENU************* 1 - Display car stock 2 - Request a car for hourly 3 - Request a car for daily
# 04/03/2021 This file is for executing the cars.py classes # Execution # drive() we will not have an access to this function name yet from cars import Car mycar = Car("BMW", "530xi", "black") # Car is the class, yourcar = Car("Lexus", "Lexus IS", "silver") mycar.drive() mycar.set_odometer_reader(50) mycar.get_description() yourcar.do_something() mycar.get_description() print("***************************") yourcar.get_description() yourcar.drive() yourcar.set_odometer_reader(30) yourcar.get_description() ## 04/03/2021 print("___Electric car instances______") class ElecricCar(Car): def __init__(self, brand, model, color): super().__init__(brand, model, color) self.battery_size = 60
# Importing classese # As we add more functionality to our classes, our files can very long, even when using inheritance properly. As such we should move them into their own modules. # Importing a single class from cars import Car # After importing the module cars, we can use the class Car from it as if the class was in this file myNewCar = Car("audi", "a4", 2019) print(myNewCar.getDescriptiveName()) myNewCar.odometerReading = 23 myNewCar.readOdometer()
import random from turtle import Screen from score import Score from cars import Car from player import Player screen = Screen() screen.setup(600,600) screen.tracer(0) player=Player() screen.listen() screen.onkey(player.move_up, "Up") game_on=True cars=Car() score=Score() while game_on: time.sleep(0.1) if player.ycor() >= 280: player.begin() cars.speed_up() score.level_up() for car in cars.all_cars: if car.distance(player)<=20: score.end() game_on=False
from turtle import Screen from player import Player from scoreboard import Scoreboard from cars import Car import time screen = Screen() screen.setup(width=600, height=600) screen.bgcolor("white") screen.tracer(0) player = Player() scoreboard = Scoreboard() loop_count = 0 speed = 0.2 car = Car() all_cars = [car] screen.listen() screen.onkey(player.move_forward, "Up") screen.onkey(player.move_backward, "Down") game_is_on = True while game_is_on: time.sleep(speed) loop_count += 1 screen.update() for item in all_cars: item.move() if item.xcor() - 30 < player.xcor() < item.xcor() + 30 and item.ycor( ) - 20 < player.ycor() < item.ycor() + 20:
from cars import Car, ElectricCar my_dream_car = Car('Audi', 'Q5', 2019) print(my_dream_car.get_descriptive_name()) my_tesla = ElectricCar('tesla', 'model s', 2019) print(my_tesla.get_descriptive_name())