Esempio n. 1
0
def main():
	my_car = car(0)
	for i in range(10):
		my_car.computeVoid()
	my_car.getMilles()
	other_car = car(42)
	other_car.getMilles()
	for i in range(4):
		my_car.computeVoid()
Esempio n. 2
0
def car_load(simulation_id):
    car_data_a = []
    car_data_b = []
    arr = os.listdir('./' + simulation_id)
    for i in range(len(arr)):
        if car_fileend in arr[i]:
            filename = simulation_id + '/' + arr[i]
            continue
    try:
        f = open(filename, 'r')
        f = f.readlines()
        car_data_a.clear()
        car_data_b.clear()

        for i in range(len(f)):
            g = f[i].split()
            s = []
            for j in range(1, 8):
                s.append(float(g[j]))
            if g[0] == 'A':
                s.append(0)
            else:
                s.append(1)
            t = car(s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7])
            if s[7] == 0:
                car_data_a.append(t)
            else:
                car_data_b.append(t)
        return [car_data_a, car_data_b]
    except:
        print('Open file fail!!')
Esempio n. 3
0
 def spawn_car(self):
     auto = car()
     auto.setup(self.cube_list, self.car_list)
     auto.time_service(self.hour, self.timer_minute, self.timer_second)
     self.car_list.append(auto)
     self.total_car += 1
     self.total_car_min += 1
Esempio n. 4
0
def simulate(carfile, track, inst):
    instructions = np.loadtxt(open(inst, "rb"), delimiter=",", skiprows=1)
    track = np.loadtxt(open(track, "rb"), delimiter=",", skiprows=1)
    carsim = car(carfile)
    
    distance = 0
    while carsim.evolve(track[distance], instructions[distance]):
        print(distance, carsim.cur_v)
        distance += 1

    print("GOT TO: " + str(distance))
Esempio n. 5
0
    def __init__(self, mode=1):

        # random seed
        random.seed()

        # mode init
        self.mode = mode
        self.record = False
        self.recordsign = RECORDSIGNINTERVAL

        # game screen initialization
        pygame.init()
        if self.mode != 100:
            self.screen = pygame.display.set_mode((1024, 768), DOUBLEBUF)

        # game clock initialization
        self.clock = pygame.time.Clock()
        self.opponent_counter = 0
        pygame.time.set_timer(RECORDSIGN, TIMEDELTA * 25)

        # object queue initialization
        self.objects = []
        self.collideds = []
        main_car = car(fname=IMAGE_PATH + 'car.png', sc=0.1)
        self.objects.append(main_car)

        # background and text interface init
        self.background = background(fname=IMAGE_PATH + 'bg.png',
                                     frname=IMAGE_PATH + 'road.png')
        self.status = font(FONT, FONTSIZE, (20, 200))
        self.instruction = font(FONT, FONTSIZE, (20, 40))
        self.instruction.update("GAME INSTRUCTION")
        self.instruction.update("--------------------------")
        self.instruction.update("SPACE: CHANGE GMAE MODE")
        self.instruction.update("ARROW KEY: MOVE")
        self.instruction.update("NUMBER: CHANGE LANE NUMBER")
        self.instruction.update("A-H: CHANGE LANE")
        self.instruction.update("R: RECORD")

        # event message
        self.events = []
        self.action = None
Esempio n. 6
0
    def setup(self):
        self.background_music_list = ["../Sound/traffic.wav"]
        self.current_background_song = 0
        self.play_background_song()

        y = 1050
        for j in map:
            x = 30
            for i in j:
                self.cube_list.append(cube(x - 30, y - 30, x, y, i))
                x = x + 60
            y = y - 60

        self.car_list = arcade.SpriteList()

        auto = car()
        auto.setup(self.cube_list, self.car_list)
        auto.time_service(self.hour, self.timer_minute, self.timer_second)
        self.car_list.append(auto)
        self.total_car += 1
        self.total_car_min += 1

        self.timer_start = datetime.datetime.now().replace(microsecond=0)
Esempio n. 7
0
    def update(self):

        # update message handling
        self.status.clear()
        yacc = 0
        xacc = 0
        lane = 0
        lanenum = 0
        self.recordsign -= 1
        self.opponent_counter += 1
        if self.opponent_counter % OPPONENT_CLOCK == 0:
            opponent_counter = 0
            self.events.append(OPPONENTCARSPAWN)
        for key in self.events:
            if key == OPPONENTCARSPAWN:
                l = random.randint(1, self.background.lanenum - 2)
                pos = self.background.spawnpoint[l]
                op_car = car(fname=IMAGE_PATH + 'opponent_car.png',
                             posx=pos[0],
                             posy=pos[1],
                             spdy=random.uniform(4, 12),
                             sc=0.1,
                             isdrag=False,
                             lane=l)
                self.objects.append(op_car)
            if key == RECORDSIGN:
                self.recordsign = RECORDSIGNINTERVAL
            #if key==pygame.K_DOWN: yacc = 1
            #if key==pygame.K_UP: yacc = -1
            if key == pygame.K_RIGHT: xacc = 1
            if key == pygame.K_LEFT: xacc = -1
            if key == pygame.K_1: lanenum = 1
            if key == pygame.K_2: lanenum = 2
            if key == pygame.K_3: lanenum = 3
            if key == pygame.K_4: lanenum = 4
            if key == pygame.K_5: lanenum = 5
            if key == pygame.K_a: lane = 1
            if key == pygame.K_s: lane = 2
            if key == pygame.K_d: lane = 3
            if key == pygame.K_f: lane = 4
            if key == pygame.K_g: lane = 5
            if key == pygame.K_h: lane = 6
            if key == pygame.K_j: lane = 7

        # update timer & action
        if OPPONENTCARSPAWN in self.events:
            self.events.remove(OPPONENTCARSPAWN)
        if RECORDSIGN in self.events: self.events.remove(RECORDSIGN)
        if (self.mode == 100 or 3) and self.action in self.events:
            self.events.remove(self.action)

        # update main character status: state 1
        if self.mode == 1:
            self.objects[0].accelerate([xacc, yacc])

        # update main character status: state 2
        # TODO: if lane!=0 and lane<=self.background.lanenum and (not self.objects[0].istargeting):
        if lane != 0 and lane <= self.background.lanenum:
            pos = np.array(self.background.spawnpoint[lane - 1])
            pos[1] = self.objects[0].position[1]
            self.objects[0].settarget(pos)
            # TODO: self.onLane=lane-1

        # update main background status: state 2
        if lanenum != 0:
            self.background.updatespawnpoint(lanenum)

        # update other objects status
        while self.collideds:
            self.collideds[-1].load(IMAGE_PATH + 'opponent_car.png')
            self.collideds.pop()
        removeid = []
        main = self.objects[0]
        for i, obj in enumerate(self.objects):
            obj.update()
            x, y = obj.position
            rect = obj.surface.get_rect()
            if i == 0:
                if x < self.background.minbound[0]:
                    x = self.background.minbound[0]
                if y < self.background.minbound[1]:
                    y = self.background.minbound[1]
                if x > self.background.maxbound[0]:
                    x = self.background.maxbound[0]
                if y > self.background.maxbound[1]:
                    y = self.background.maxbound[1]
                obj.position = np.array([x, y])
            if i != 0:
                if y > self.background.maxbound[1] + 20: removeid.append(i)
                if main.rect.colliderect(obj.rect): self.collideds.append(obj)

        # update background and font interface
        pos = main.position
        spd = main.speed
        # TODO: onLane = self.onLane
        dist = float('inf')
        for i, sp in enumerate(self.background.spawnpoint):
            if abs(sp[0] - main.position[0]) < dist:
                dist = abs(sp[0] - main.position[0])
                onLane = i
        dist = np.array([float('inf')] * 5)
        for obj in self.objects[1:]:
            l = obj.lane
            if abs(dist[l]) > abs(main.position[1] - obj.position[1]):
                dist[l] = main.position[1] - obj.position[1]
        qdist = (dist - 50) / 100 + 0.5
        qdist[np.where(dist >= 350)] = 4
        qdist[np.where(dist < -449)] = -5
        qdist = qdist.astype('int')

        self.status.update("game mode: %d" % self.mode)
        self.status.update("position: %d,%d" % (pos[0], pos[1]))
        self.status.update("speed: %d,%d" % (spd[0], spd[1]))
        self.status.update("lane: %d" % onLane)
        for i in range(0, 5):
            self.status.update("nearest distance: %.3f" % dist[i])
        for i in range(0, 5):
            self.status.update("quantized distance: %d" % qdist[i])
        self.background.update()

        # remove redundant objects
        for id in removeid:
            obj = self.objects[id]
            self.objects.pop(id)
            del obj

        # collision cars
        for collider in self.collideds:
            collider.load(IMAGE_PATH + 'hit_car.png')

        # feature parser
        feature = None
        legal_action = np.array([0, 1, 2, 3, 4])
        state = np.zeros([5, 11]).astype('int')
        state[onLane, 0] = 1
        for i in range(0, 5):
            state[i, qdist[i] + 6] = 1
        if self.record:
            feature = [0] * 15
            feature[onLane] = 1
            feature[qdist[onLane] + 10] = 1

        return feature, state, legal_action
Esempio n. 8
0
        default=1.0,
        help='length of the car from steering column to the back')
    parser.add_argument('-rf',
                        '--reference_velocity',
                        default=1,
                        help='reference velocity of the car')
    parser.add_argument('-hr',
                        '--horizons',
                        default=20,
                        help='number of time stamps')

    #We will further add arguments for cv as well

    args = parser.parse_args()

    rc_car = car()
    mpc = MPC(float(args.max_speed), float(args.min_speed),
              float(args.discrete_time), float(args.length_car),
              float(args.reference_velocity), args.horizons)
    rc_cv = ComputerVision()
    # rc_pwm = pwm()

    try:

        # time1=time.time()
        coeffs, T = rc_cv.run('circle1.jpg')

        cte = coeffs[2]

        epsi = atan(-coeffs[1])
        print("slope initially", epsi)
Esempio n. 9
0
#클래스외부에서 변수내용 변경가능


#자동차 클래스 만들어보기
class car:
    color = ""
    speed = 0

    def upspeed(self, value):
        self.speed += value

    def downspeed(self, value):
        self.speed -= value


mycar1 = car()
mycar2 = car()
mycar3 = car()

mycar1.color = "빨강"
mycar2.color = "파랑"
mycar3.color = "노랑"

mycar1.upspeed(30)
mycar2.upspeed(60)
print("자동차 1의 색상은 %s이며, 현재 속도는 %dkm입니다." % (mycar1.color, mycar1.speed))
print("자동차 2의 색상은 %s이며, 현재 속도는 %dkm입니다." % (mycar2.color, mycar2.speed))
print("자동차 3의 색상은 %s이며, 현재 속도는 %dkm입니다." % (mycar3.color, mycar3.speed))

#모듈화 하여 호출하고, 속도가 150 이상일 경우 속도 고정하기
import code12 as car_code
Esempio n. 10
0
    def update(self, dt):
        for c in self.loc:
            #
            # GAME THEORY STUFF DONE HERE, CHANGE ACCELERATIONS
            # Coalition Game Start.
            if len(self.loc) != 0:
                cars = []
                [carInC, carNotInC] = [MergeAndSplit(1, 100, self.loc, 15)[0], MergeAndSplit(1, 100, self.loc, 15)[1]]
                for cinc in carInC:
                    if before_intersection(cinc):
                        cinc.on_tick(1)
                    else:
                        cinc.on_tick(0)
                for cnotinc in carNotInC:
                    if before_intersection(cnotinc):
                        cnotinc.on_tick(-1)
                    else:
                        cnotinc.on_tick(0)
                if len(carInC) != 0:
                    cars.extend(carInC[i] for i in range(len(carInC)))
                if len(carNotInC) != 0:
                    cars.extend(carNotInC[i] for i in range(len(carNotInC)))
                if len(cars) != 0:
                    self.loc = deepcopy(cars)
                # Coalition Game End.

            # Update car's acceleration each tick
            #c.on_tick(0)

        # Randomly generate a new car - TODO: MAKE SURE CARS DONT SPAWN
        # ON TOP OF EACH OTHER
        if(randint(0,self.SPAWN_RATE) == 0):
            lane = randint(0, 11)
            if lane == 0:
                self.loc.append(car(deepcopy(self.lane_0), 'blue'))
            if lane == 1:
                self.loc.append(car(deepcopy(self.lane_1), 'yellow'))
            if lane == 2:
                self.loc.append(car(deepcopy(self.lane_2), 'green'))
            if lane == 3:
                self.loc.append(car(deepcopy(self.lane_3), 'pink'))
            if lane == 4:
                self.loc.append(car(deepcopy(self.lane_4), 'blue'))
            if lane == 5:
                self.loc.append(car(deepcopy(self.lane_5), 'yellow'))
            if lane == 6:
                self.loc.append(car(deepcopy(self.lane_6), 'green'))
            if lane == 7:
                self.loc.append(car(deepcopy(self.lane_7), 'pink'))
            if lane == 8:
                self.loc.append(car(deepcopy(self.lane_8), 'blue'))
            if lane == 9:
                self.loc.append(car(deepcopy(self.lane_9), 'yellow'))
            if lane == 10:
                self.loc.append(car(deepcopy(self.lane_10), 'green'))
            if lane == 11:
                self.loc.append(car(deepcopy(self.lane_11), 'pink'))

            # Make sure addition didn't cause a collision
            for c1 in self.loc:
                if c1.time == 0:
                    for c2 in self.loc:
                        if check_collision(c1,c2) and c1.time != c2.time:
                            self.loc.remove(c1)
                            break
        # Delete out of bound cars and check for collisions
        new_loc = []
        for c1 in self.loc:
            for c2 in self.loc:
                if c1.position != c2.position and check_collision(c1,c2):
                    if after_intersection(c1) and after_intersection(c1):
                        c1.color = 'red'
                        c2.color = 'red'
            if not check_out_of_bounds(c1):
                new_loc.append(c1)
        self.loc = new_loc
Esempio n. 11
0
    lens = []
    for p in paths:
        lens.append(len(p))
    maxlen = max(lens)
    for i in range(len(paths)):
        paths[i].extend([paths[i][-1]]*(maxlen-lens[i]))
    return paths

if __name__ == '__main__':
    number_of_cars = 4
    init_states = [0, 15, 3, 12]
    init_directions = [1, 1, 1, 1]
    goals = [15,0,12,3]
    cars = []
    for i in range(number_of_cars):
        car_ins = car(init_states[i], init_directions[i], i+1)
        cars.append(car_ins)
    route = []
    exchange = True
    for i in range(number_of_cars):
        if exchange:
            route.append(cars[i].find_path(cars[i].state, goals[i]))
        else:
            route.append(cars[i].find_path(cars[i].state, goals[i],
                        [acar.state for acar in cars if acar != cars[i]]))
        if len(route[i]) < 2:
            pass
        else:
            cars[i].update_direction(route[i][0], route[i][1])
      #  s.write(actions[i])
    target_achieved = False
Esempio n. 12
0
import car
if __name__ == '__main__':
    ca = car("aa", 2, [2, 2], 0)
    print(ca)
Esempio n. 13
0
def eval_genomes(ge, config):
    width = 1920
    height = 900
    fps = 60

    playerSprite = pygame.image.load(os.path.join(localpath, "car.png"))
    map = pygame.image.load(os.path.join(localpath, "map.png"))
    mapRect = map.get_rect()

    pygame.init()
    display = pygame.display.set_mode((width, height))
    pygame.display.set_caption('racecar')

    #initialize and track each genome
    nets = []
    genomes = []
    playerList = pygame.sprite.Group()

    for id, genome in ge:
        genome.fitness = 0

        nets.append(neat.nn.FeedForwardNetwork.create(genome, config))
        genomes.append(genome)
        playerList.add(car([200, 300], 0))

    #60 fps
    clock = pygame.time.Clock()
    deltaT = clock.tick(fps)

    #intialize player (human)
    #   player = car([200, 300], 0)
    #   playerList.add(player)

    quit = False
    drawRays = False

    while not quit:
        deltaT = clock.tick(fps)

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                quit = True
            if event.type == pygame.KEYUP and event.key == pygame.K_r:
                drawRays = not drawRays

        #human controls
#        keysPressed = pygame.key.get_pressed()
#        input = [-(int(keysPressed[pygame.K_w]) - int(keysPressed[pygame.K_s])), (int(keysPressed[pygame.K_a]) - int(keysPressed[pygame.K_d]))]

#update genomes
        for x, player in enumerate(playerList):
            inputs = nets[x].activate(player.rayDistances(map))
            roundedInputs = [round(a) for a in inputs]
            player.updateMovement(roundedInputs, deltaT)

            status = player.checkStatus(map)
            if (status[0] == 'finish'):
                print('finished a lap, time: ', status[1])
                genomes[x].fitness += 50 + int(100 / status[1])

            if (status[0] == 'checkpoint'):
                print('checkpoint achieved')
                genomes[x].fitness += 5

            if (status[0] == 'crash'):
                print('crashed')
                player.changeStatus(False)

            if (player.playerSpeed > 0.5):
                genomes[x].fitness += 0.001

        survivingPlayerList = pygame.sprite.Group()
        #        survivingGenomes = []
        #        survivingNets = []
        #
        for x, player in enumerate(playerList):
            if player.status == True:
                survivingPlayerList.add(player)


#                survivingGenomes.append(genomes[x])
#                survivingNets.append(nets[x])
#
        playerList = survivingPlayerList
        #        genomes = survivingGenomes
        #        nets = survivingNets

        #check current generation population
        if len(playerList) < 1:
            quit = True
            break

        #render goes bottom first, top last
        display.blit(map, mapRect)
        playerList.draw(display)
        if drawRays:
            for player in playerList:
                for ray in player.drawRay(display, map):
                    pygame.draw.line(display, ray[1], ray[2], ray[3], ray[4])

        pygame.display.update()

    pygame.quit()
Esempio n. 14
0
    def on_key_press(self, key, modifiers):
        if key == arcade.key.F:
            self.set_fullscreen(not self.fullscreen)

            width, height = self.get_size()
            self.set_viewport(0, width, 0, height)

        if key == arcade.key.C:
            if (self.change == 1):
                for auto in self.car_list:
                    if (auto.fov.sprite.alpha != 0):
                        auto.fov.sprite.alpha = 0
                        auto.fov.stop_sprite.alpha = 0
                self.change = 0
            else:
                for auto in self.car_list:
                    if (auto.fov.sprite.alpha == 0):
                        auto.fov.sprite.alpha = 255
                        auto.fov.stop_sprite.alpha = 255
                self.change = 1

        if key == arcade.key.KEY_1:
            auto = car()
            auto.setup(self.cube_list, self.car_list)
            auto.time_service(self.hour, self.timer_minute, self.timer_second)
            self.car_list.append(auto)
            self.total_car += 1
            self.total_car_min += 1

        if key == arcade.key.P:
            auto = car()
            auto.ignore = True
            auto.speed = 500
            auto.setup(self.cube_list, self.car_list)
            auto.time_service(self.hour, self.timer_minute, self.timer_second)
            self.car_list.append(auto)
            self.total_car += 1
            self.total_car_min += 1

        if key == arcade.key.UP:
            if (self.hour < 23):
                self.hour = self.hour + 1
                self.timer_start = datetime.datetime.now().replace(
                    microsecond=0)
                self.timer_second = 0
                self.timer_minute = 0
                self.timer_string_min = "00"
                self.timer_string_sec = "00"
                self.incidenti_min = 0
                self.total_car_min = 0

        if key == arcade.key.DOWN:
            if (self.hour > 0):
                self.hour = self.hour - 1
                self.timer_start = datetime.datetime.now().replace(
                    microsecond=0)
                self.timer_second = 0
                self.timer_minute = 0
                self.timer_string_min = "00"
                self.timer_string_sec = "00"
                self.incidenti_min = 0
                self.total_car_min = 0
Esempio n. 15
0
from car import *

# Instantiating an object

arr = [12,25,27,28]
car1 = car('toyota','red','sedan',25, 15, arr)
car2 = car('lexus','blue','SUV',17, 15, arr)
print(car1.get_range())
print(car2.get_range())
print(car1.mileage)
car1.set_mileage(15)
print(car1.mileage)
print(car1.get_avg_mileage())
print('Hello World')
Esempio n. 16
0
                    if down != 0:
                        print("------------stall {} seconds.--------------".
                              format(down))
                        total += down
                        down = 0
                    show(rep, per_res, fit_car)
                    fit_car.base += rep[0].dest.dist_to_D() / speed
                    for r in rep:
                        #print(type(self.graph.get_task(r.number)))
                        self.graph.remove(self.graph.get_task(r.number))
                    #self.graph.show()
                else:
                    down_cars_base(cars, 1)
                    down += 1
                    #print("down {}".format(down))
                    continue
            else:
                return
        print("totally stall : {} seconds".format(total))


tasks = []
with open('tasks1.txt', 'r') as f:
    Lines = f.readlines()
    for line in Lines:
        tasks.append(map_dataline_to_task(line))
cars = [car(1), car(2)]
inst = instance(tasks=tasks, cars=cars)
#inst.graph.show()
inst.run()
Esempio n. 17
0
    def update(self, dt):
        # Randomly generate a new car - TODO: MAKE SURE CARS DONT SPAWN
        # ON TOP OF EACH OTHER
        if (randint(0, self.SPAWN_RATE) == 0):
            lane = randint(0, 11)
            if lane == 0:
                self.loc.append(car(deepcopy(self.lane_0), 'blue'))
            if lane == 1:
                self.loc.append(car(deepcopy(self.lane_1), 'yellow'))
            if lane == 2:
                self.loc.append(car(deepcopy(self.lane_2), 'green'))
            if lane == 3:
                self.loc.append(car(deepcopy(self.lane_3), 'pink'))
            if lane == 4:
                self.loc.append(car(deepcopy(self.lane_4), 'blue'))
            if lane == 5:
                self.loc.append(car(deepcopy(self.lane_5), 'yellow'))
            if lane == 6:
                self.loc.append(car(deepcopy(self.lane_6), 'green'))
            if lane == 7:
                self.loc.append(car(deepcopy(self.lane_7), 'pink'))
            if lane == 8:
                self.loc.append(car(deepcopy(self.lane_8), 'blue'))
            if lane == 9:
                self.loc.append(car(deepcopy(self.lane_9), 'yellow'))
            if lane == 10:
                self.loc.append(car(deepcopy(self.lane_10), 'green'))
            if lane == 11:
                self.loc.append(car(deepcopy(self.lane_11), 'pink'))

        if len(self.loc) != 0:
            cars = []
            [carInC, carNotInC] = [
                MergeAndSplit(0, 1000, self.loc, 5)[0],
                MergeAndSplit(0, 1000, self.loc, 5)[1]
            ]
            for cinc in carInC:
                cinc.on_tick(1)
            for cnotinc in carNotInC:
                cnotinc.on_tick(-1)
            if len(carInC) != 0:
                cars.extend(carInC[i] for i in range(len(carInC)))
            if len(carNotInC) != 0:
                cars.extend(carNotInC[i] for i in range(len(carNotInC)))
            if len(cars) != 0:
                self.loc = deepcopy(cars)

        # a list of cars who are inside the intersection
        #################   This is a Strategic Game   #################

        if self.SWITCH == True:

            crashCars = []
            cars_in_intersection = []
            for eachCar in self.loc:
                if after_intersection(eachCar) == False and before_intersection(
                        eachCar) == False:  # the car inside the intersection
                    cars_in_intersection.append(eachCar)
            cars_positions = [
                next_position(eachCar) for eachCar in cars_in_intersection
            ]
            #print('cars-positions = ', cars_positions)

            if len(cars_in_intersection) >= 2:
                for i in range(len(cars_positions)):
                    crashCars.append(
                        tellCollapse(cars_positions[i],
                                     cars_positions[i + 1:]).copy())
            for group in crashCars:
                if len(group) != 0:
                    velocity_assign = strategicGame(crashCars)
                    velocity_cars_index = []
                    velocity_cars = []
                    velocity_cars_index.append(
                        cars_positions.index(group[i])
                        for i in range(len(group)))
                    velocity_cars.append(cars_in_intersection[i])
                    for i in range(len(velocity_cars)):
                        velocity_cars[i].on_tick(velocity_assign[i])

        # strategicGame(crashCars)
        self.SWITCH = not self.SWITCH
        #################   This is a Strategic Game   #################

        new_loc = []
        for c in self.loc:
            if not check_out_of_bounds(c):
                new_loc.append(deepcopy(c))
        self.loc = new_loc