Esempio n. 1
0
    def __init__(self, carX, carY, window, goal, best=False):
        self.car = Car(carX, carY)
        self.window = window
        self.dead = self.car.dead
        self.finished = self.car.finished
        self.fitness = 0

        self.brain = Brain(5000)
        self.goal = goal
        self.bestCar = best
Esempio n. 2
0
class TestCar(unittest.TestCase):
    def setUp(self):
        self.engine = Engine()
        self.gearbox = Gearbox("manual", 5)
        self.car = Car("Ford", "Escort", self.engine, self.gearbox)

    def test_car_can_start(self):
        self.assertEqual("Vrrrmmm!", self.car.start())

    def test_car_can_change_gear(self):
        self.car.change_gear(2)
        self.assertEqual(2, self.car.gearbox.current_gear)
Esempio n. 3
0
class TestCar(unittest.TestCase):
    def setUp(self):
        self.car = Car(license_plate='111112')

    def tearDown(self):
        pass

    def test_calculate_price_first_time(self):
        price = self.car.calculate_price(False)
        self.assertEqual(price, 5.00)

    def test_calculate_price_second_time(self):
        price = self.car.calculate_price(True)
        self.assertEqual(price, 2.50)
Esempio n. 4
0
    def __init__(self, carX, carY, window, best=False, scale: float = 1.48):
        self.car = Car(carX, carY, scale)
        self.scale = scale
        self.window = window
        self.dead = self.car.dead
        self.fitness = 0
        self.step = 0
        self.maxStep = 500
        self.reset = False
        self.reset2 = False

        self.nn = NeuralNetwork()
        self.bestCar = best

        self.index = 0
class TestCar(unittest.TestCase):

    def setUp(self):
        self.car = Car()

    def test_car_can_start_engine(self):
        self.assertEqual("Vrrmmm", self.car.start_engine())
    def __init__(self) -> None:
        self._action_spec = array_spec.BoundedArraySpec(shape=(),
                                                        dtype=np.int32,
                                                        minimum=0,
                                                        maximum=3,
                                                        name="action")
        self._observation_spec = array_spec.BoundedArraySpec(
            shape=(8, ), dtype=np.float32, minimum=0, name="observation")

        self.circuit = circuit.fromJSON("circuits/BONK_CIRCUIT.json")
        self.agent = Car(self.circuit.startingPoint.x,
                         self.circuit.startingPoint.y)
        self._episode_ended = False
        self.discount = 0.9925
        self.stepCountingCounter = 0

        self.viewer = None
Esempio n. 7
0
class Agent:
    def __init__(self, carX, carY, window, goal, best=False):
        self.car = Car(carX, carY)
        self.window = window
        self.dead = self.car.dead
        self.finished = self.car.finished
        self.fitness = 0

        self.brain = Brain(5000)
        self.goal = goal
        self.bestCar = best

    def draw(self, batch, foreground, background, vertices, show):
        car = self.car.draw(batch, foreground, self.bestCar)
        if show:
            eyes = self.car.eyes(batch, background)
            hitbox = self.car.hitbox(batch, background)
            intersectEyes = self.car.intersectEyes(batch, vertices, background)
            return car, eyes, hitbox, intersectEyes
        return car

    def generateHitbox(self):
        hitbox = self.car.generateHitbox()
        return hitbox

    def move(self, dt):
        if (self.brain.step < len(self.brain.instructions)):
            instruction = self.brain.instructions[self.brain.step]
            self.brain.step += 1

            self.car.updateGA(dt, instruction)
        else:
            self.dead = True

    def update(self, dt):
        if not self.dead and not self.finished:
            self.move(dt)

            pos = self.car.position
            if (pos.x < 2 or pos.y < 2 or pos.x > self.window.x - 2
                    or pos.y > self.window.y - 2):
                self.dead = True
            elif (abs(self.goal - pos) < 10):
                self.finished = True
        else:
            self.car.dead = self.dead
            self.car.finished = self.finished

    def calcFitness(self):
        if self.finished:
            self.fitness = 1 / 16 + 10000 / (self.brain.step**2)
        else:
            self.fitness = 1 / (abs(self.goal - self.car.position)**2)

    def clone(self, carX, carY, best=False):
        baby = Agent(carX, carY, window=self.window, goal=self.goal, best=best)
        baby.brain = self.brain.clone()
        return baby
Esempio n. 8
0
    def __parse_file_data(self, data):
        """ Parse the meat of the file and return automobiles """
        automobiles = []

        for line in data:
            line_list = line.split(' ')

            type = line_list[0]
            license_plate = line_list[1]

            if type == "Truck":
                bed_down = True if line_list[2] == 'bed_down' else False
                is_muddy = True if line_list[3].strip() == 'muddy' else False
                automobile = Truck(license_plate=license_plate.strip(),
                                   bed_down=bed_down,
                                   is_muddy=is_muddy)
            elif type == "Car":
                automobile = Car(license_plate=license_plate.strip())
            else:
                automobile = None

            automobiles.append(automobile)

        return automobiles
Esempio n. 9
0
class Agent:
    def __init__(self, carX, carY, window, best=False, scale: float = 1.48):
        self.car = Car(carX, carY, scale)
        self.scale = scale
        self.window = window
        self.dead = self.car.dead
        self.fitness = 0
        self.step = 0
        self.maxStep = 500
        self.reset = False
        self.reset2 = False

        self.nn = NeuralNetwork()
        self.bestCar = best

        self.index = 0

    def draw(self, batch, foreground, background, vertices, show):
        car = self.car.draw(batch, foreground, self.bestCar)
        # intersectEyes = self.car.intersectEyes(batch, vertices, background)
        # if show or not self.dead:
        # eyes = self.car.eyes(batch, background)
        # hitbox = self.car.hitbox(batch, background)
        # return car, intersectEyes, eyes, hitbox
        # return car, intersectEyes, eyes
        # return car, intersectEyes
        return car

    def generateHitbox(self):
        hitbox = self.car.generateHitbox()
        return hitbox

    def move(self, dt, vertices):
        if self.step < self.maxStep:
            inputnn = []
            self.car.mathIntersect(vertices)
            inputnn = self.car.observe()
            if len(inputnn) > 7:
                instruction = self.nn.feedforward(inputnn)
            else:
                instruction = 3
                print(f"Input: {inputnn}")
            self.step += 1

            self.car.updateWithInstruction(dt, instruction)
        else:
            self.dead = True

    def update(self, dt, vertices):
        if not self.dead:
            if self.car.currentCheckpoint > 1 and self.reset == False:
                self.maxStep += 1000
                self.reset = True
            if self.car.currentCheckpoint > 2 and self.reset2 == False:
                self.maxStep += 1000
                self.reset2 = True
            self.move(dt, vertices)

            pos = self.car.position
            if (pos.x < 2 or pos.y < 2 or pos.x > self.window.x - 2
                    or pos.y > self.window.y - 2):
                self.dead = True
        else:
            self.car.dead = self.dead

    def calcFitness(self, skeletonLines, checkpoints, blindSpot, blindIndex):
        if self.car.currentCheckpoint > 0 or self.car.currentLap > 0:
            if self.car.currentCheckpoint >= checkpoints:
                self.car.currentLap += 1
                self.car.currentCheckpoint = 0
            minimum = 100000
            minLine = None
            for line in skeletonLines:
                distance = d if (d := line.distance(
                    self.car.position)) != None else 99999
                if distance < minimum:
                    minimum = distance
                    minLine = line
            if minimum > 80:
                minDistance = 100000
                minSpot = None
                for spot in blindSpot:
                    distance = abs(self.car.position - spot)
                    if distance < minDistance:
                        minDistance = distance
                        minSpot = spot
                indexSpot = blindSpot.index(minSpot)
                index = blindIndex[indexSpot]
                minLine = skeletonLines[index]
            else:
                index = skeletonLines.index(minLine)

            linesToIndex = skeletonLines[:index]
            distanceToIndex = 0
            for line in linesToIndex:
                startPointLine, endPointLine = line.getEndPoints()
                distanceToIndex += abs(endPointLine - startPointLine)

            lineToOutside = linline.fromVector(minLine.n,
                                               self.car.position)  #BC
            intersection = lineToOutside.intersect(minLine)  #B
            startPoint, _ = minLine.getEndPoints()  #A
            if startPoint.x == None:
                distanceLine = 0
            elif startPoint.y == None:
                distanceLine = 0
            elif intersection == None:
                distanceLine = 0
            else:
                distanceLine = intersection - startPoint  #AB

            if index > 10 and self.car.currentCheckpoint < 3:
                self.fitness = 0
            else:
                self.fitness = ((self.car.currentLap * 100) +
                                (abs(distanceLine) * 100) +
                                distanceToIndex * 100)**2 / self.step
            self.index = index
        else:
Esempio n. 10
0
 def setUp(self):
     self.car = Car(license_plate='111112')
Esempio n. 11
0
File: a2.py Progetto: liproqq/bta_py
from classes.car import Car
import pickle
from pathlib import Path

data_folder = Path("python_basics/tag09/")

file_to_open = data_folder / "cars.pkl"

f = open(file_to_open, "wb")

new_car1 = Car()
new_car2 = Car("Toyota", "silver")

pickle.dump(new_car1, f)
pickle.dump(new_car2, f)

f.close()
Esempio n. 12
0
#        circuit_checkpoints[i].append(Vector2D(point[0],point[1]))

dir_path = os.path.dirname(os.path.realpath(__file__))
path = dir_path + '/' + 'circuits/SIGMA_FALLS_GA.json'

batch = pyglet.graphics.Batch()
topper = pyglet.graphics.OrderedGroup(3)
foreground = pyglet.graphics.OrderedGroup(2)
background = pyglet.graphics.OrderedGroup(1)
circuitLayer = pyglet.graphics.OrderedGroup(0)

running = True

circ = circuit.fromJSON(path, window=[1920,1080], method="fromFullPoints")

car = Car(circ.startingPoint.x,circ.startingPoint.y)
car.position = circ.startingPoint

backGround = pyglet.sprite.Sprite(circ.background, x=0,y=0, batch=batch, group=circuitLayer)
foreGround = pyglet.sprite.Sprite(circ.backgroundTopper, x=0,y=0, batch=batch, group=topper)

key = pyglet.window.key
key_handler = key.KeyStateHandler()
speed = 1.0

@window.event
def on_close():
    running = False

@window.event
def on_draw():
class circuitEnv(py_environment.PyEnvironment):
    def __init__(self) -> None:
        self._action_spec = array_spec.BoundedArraySpec(shape=(),
                                                        dtype=np.int32,
                                                        minimum=0,
                                                        maximum=3,
                                                        name="action")
        self._observation_spec = array_spec.BoundedArraySpec(
            shape=(8, ), dtype=np.float32, minimum=0, name="observation")

        self.circuit = circuit.fromJSON("circuits/BONK_CIRCUIT.json")
        self.agent = Car(self.circuit.startingPoint.x,
                         self.circuit.startingPoint.y)
        self._episode_ended = False
        self.discount = 0.9925
        self.stepCountingCounter = 0

        self.viewer = None

    def action_spec(self):
        return self._action_spec

    def observation_spec(self):
        return self._observation_spec

    def _reset(self):
        self.agent.reset()
        self.circuit.reset()

        self.agent.updateWithInstruction(dt, None)
        self.agent.mathIntersect(self.circuit.vertices)

        self.stepCountingCounter = 0
        self._episode_ended = False
        return ts.restart(self._observe())

    def _step(self, action):
        if self._episode_ended:
            print('episode ended')
            return self.reset()

        #run physics
        self.agent.updateWithInstruction(dt, action)
        hitbox = self.agent.generateHitbox()
        self.agent.mathIntersect(self.circuit.vertices)

        self.stepCountingCounter += 1
        if self.circuit.collidedWithCar(hitbox):
            self._episode_ended = True
            return ts.termination(self._observe(), reward=-500.0)
        elif self.circuit.carCollidedWithCheckpoint(self.agent):
            reward = 300 * self.discount**self.stepCountingCounter
            return ts.transition(self._observe(), reward=reward)
        else:
            return ts.transition(self._observe(), reward=0)

    def _observe(self):
        return np.array(self.agent.observe(), dtype=np.float32)

    ### DRAWING STUFF ###
    def render(self, mode="human"):
        if self.viewer is None:
            self.viewer = Viewer(1920, 1080, self.agent, self.circuit)
        self.viewer.render()
 def setUp(self):
     self.car = Car()
Esempio n. 15
0
from classes.street import Street
from classes.car import Car
from classes.street import read_from_database, reset_visited
from classes.street import read_junc_coords
from visualization.read_coords import get_info
from choose_next_street import choose_random

input_file = "input_data.txt"
general_info = get_info(input_file)
NUM_CARS = general_info["cars_num"]

TIME_LEFT = [general_info["timespan"]] * NUM_CARS
LEN_VIEWED = 0
START = general_info["start_point"]
FLEET = [Car(START, i) for i in range(NUM_CARS)]

curr = START
time_left = TIME_LEFT[0]
car = FLEET[0]

while time_left > 0:
    street_list = read_from_database(curr)
    next_street = choose_random(street_list, time_left)

    if next_street:
        next_point = next_street.junctions[1]

        print("-- Move car{} from {} to {}".format(car, curr, next_point))
        curr = next_point
        time_left -= next_street.time
        next_street.set_is_visited()
Esempio n. 16
0
 def setUp(self):
     self.engine = Engine()
     self.gearbox = Gearbox("manual", 5)
     self.car = Car("Ford", "Escort", self.engine, self.gearbox)