示例#1
0
def main_sorting():
    car_list = [
        Car('BMW', 'M3'),
        Car('Tesla', '3', 100)
    ]

    print(car_list)

    car_list.sort(key=lambda car: car.speed, reverse=True)

    import operator
    print(sorted(car_list, key=operator.attrgetter('speed', 'brand')))
    print(car_list)

    return
示例#2
0
def main(ai_control: bool, car_pos: tuple, parking_pos: tuple) -> float:
    """
    Given intitial car and parking positions, this function
    runs the game environment.
    """
    pygame.init()
    screen = pygame.display.set_mode((const.WINDOW_WIDTH, const.WINDOW_HEIGHT),
                                     pygame.SCALED)
    pygame.display.set_caption('Parking AI')
    clock = pygame.time.Clock()
    all_sprites = pygame.sprite.Group()
    crashed, closed, parked = False, False, False
    # Create car instance and add to list of sprites
    car = Car(car_pos, ai_control)
    all_sprites.add(car)
    # Create parking instance and check distance from car
    parking = Parking(parking_pos)
    car.update_parking_distance(parking)

    scores = []
    pixels = []
    initial_loop = True
    while not (crashed or closed or parked):
        if not ai_control:
            clock.tick(const.FPS)
        events = pygame.event.get()
        if not initial_loop:
            pixels.append(pygame.surfarray.array2d(screen))
            closed = car.control(events, pixels[-1])
        all_sprites.update()
        if not initial_loop:
            # Check car status and calculate score
            crashed = car.check_boundary_crash(screen)
            parked = parking.car_is_parked(car)
            score = get_reward(car, parking, crashed, parked)
            scores.append(score)
        else:
            initial_loop = False
        # Update graphics
        screen.fill(const.GREY)
        # print_states(screen, car)
        parking.draw(screen)
        all_sprites.draw(screen)
        pygame.display.flip()

    pygame.quit()
    return scores, pixels
示例#3
0
def track_cars(boxes, scores, cars, width, height, fps):

    ###CHECK FOR EXISTING CARS###
    x = 0
    saved = False  #Keep track of if a box is new
    for box in boxes[0]:
        if scores[0][x] >= 0.5:  #Only if confidence score above threshold
            upper_x = box[1] * width
            upper_y = box[0] * height
            lower_x = box[3] * width
            lower_y = box[2] * height

            for car in cars:
                if car.distance(upper_x, upper_y, lower_x,
                                lower_y) <= car.delta_pos:
                    car.update(upper_x, upper_y, lower_x, lower_y, fps)
                    saved = True  #Don't double up on detections

            if not saved:
                cars.append(Car(upper_x, upper_y, lower_x,
                                lower_y))  #Uppercase Car is a class

        x = x + 1  #Index for scores
        saved = False
示例#4
0
from classes import Point, Car, Curve, TrackPiece, Track, is_out, closest_point, distances
from functions import rotate
from physics import Time, ASPHALT_DRAG, SAND_DRAG
from rl_agent import RL_Driver
import hyperparameters as hp
import gui_manager as gui
from track_construction import track_points1, curvatures1

T = Time(dt=0.042, dilation=1)

voiture1 = Car(0,
               0,
               heading=0,
               length=20,
               width=10,
               name="kloz",
               T=T,
               color='pink',
               controls=('Up', 'Left', 'Down', 'Right'))
voiture1.trace(None)

voiture2 = Car(0,
               0,
               heading=0,
               length=20,
               width=10,
               name="bob",
               T=T,
               controls=('z', 'q', 's', 'd'),
               thrust=50)
示例#5
0
#     AUTHOR                   : EExuke
#     FILE NAME                : my_car.py
#     FILE DESCRIPTION         : Python file
#     FIRST CREATION DATE      : 2020/02/12
# --------------------------------------------------------------------------
#     Version                  : 1.0
#     Last Change              : 2020/02/12
## ************************************************************************** ##

#-----------------------------------------------------------
#                  MAIN PROCESS
#-----------------------------------------------------------
# 导入car.py中的Car类
from classes import Car, ElecCar

my_new_car = Car('audi', 'a6', 2020)
my_new_car.get_descriptive_name()

my_new_car.odometer_reading = 23
my_new_car.read_odometer()

my_tesla = ElecCar('tesla', 'model 3', 2020)
my_tesla.get_descriptive_name()
my_tesla.battery.describe_battery()
my_tesla.battery.get_range()

#-----------------------------------------------------------
# 导入整个模块,与函数相同
# import classes
# 用时:classes.Car()
示例#6
0
    if bg_y2 > bg.get_height():
        bg_y2 = bg.get_height() * -1

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            quit()

        if event.type == speed_up:
            fps += 1
            mcqueen.score_ += 1
            start_range -= 15
            stop_range -= 30

        if event.type == run_new_car:
            cars.append(Car(120, 220, car_speed))

        if event.type == special_car:
            police = Police(120, 200, car_speed)
            ambulance = Ambulance(150, 318, car_speed)
            fire_truck = FireTruck(150, 450, car_speed)
            special_cars = [police, ambulance, fire_truck]
            index = randrange(0, len(special_cars))
            cars.append(special_cars[index])
            special_cars[index].siren()
            time_counter = 0

        if event.type == hole_on_track:
            holes.append(Hole())

    # ____CARS____
示例#7
0
from classes import Car

# from classes import Person
#
# person1 = Person('John')
# person1.print_info()
#
# person2 = Person('Katy')
# # print(person2._Person__age)
# # print(person2.get_age())
# # person2.set_age(22)
# print(person2.age)
# person2.age = 36
# person2.print_info()

mustang = Car('Mustang')
mustang.hp = 3
mustang.car_info()

porsche = Car('Porsche')
porsche.hp = 200
porsche.year = 1950
porsche.color = 'Grey'
porsche.car_info()
示例#8
0
# import classes, platform # platform is a built in module
from classes import Car  # import just one thing from a module
import platform

newCar = Car("Chevy", "Silverado", "Silver")
print(newCar.model)

# classes.car1.printCar()
x = platform.system()
print(x)
#print(dir(classes)) # dir is a built-in function
示例#9
0
from classes import Car

jaguar = Car('Peta', 'White', '35', '1.5')
jaguar.starts()
jaguar.breaks()
jaguar.set_colour('BLUE')
jaguar.get_colour()
示例#10
0
# classes aggregation

from classes import Car, Product

cart = Car()

p1 = Product('t-shirt', 50)
p2 = Product('cup', 10)
p3 = Product('book', 20)

cart.insert_product(p1)
cart.insert_product(p2)
cart.insert_product(p3)

cart.product_list()

print(cart.total_sum())
示例#11
0
# This code contains simple examples about importing classes in Python.
# Importing a single class
from classes import Car

# Importing Multiple Classes in a Module
from classes import Car, ElectricCar

my_beetle = Car('volkswagen', 'beetle', 2016)
print(my_beetle.get_descriptive_name())

my_tesla = ElectricCar('tesla', 'roadster', 2016)
print(my_tesla.get_descriptive_name())

# Importing All Classes from a Module
# from classes import *

# Import a Module into a Module
示例#12
0
def manual_loop(screen: pygame.Surface, circuit: typing.List[Border]):
    """
    Boucle principale pour le mode manuel du programme

    Parameters
    ----------
    screen:
        La fenêtre du programme
    circuit:
        La liste des bordures représentant le circuit
    """
    screen_width = SETTINGS.screen_size[0]
    clock = pygame.time.Clock()
    small_font = pygame.font.SysFont('Arial', ceil(18 * SETTINGS.scale_avg))
    title_font = pygame.font.SysFont('Arial', ceil(30 * SETTINGS.scale_avg))
    dt = 1
    color = pygame.Color(SETTINGS.car_color)
    init_pos, init_angle = calc_starting_pos(circuit["point1"],
                                             circuit["point2"])
    car = Car(circuit["bordures"],
              color=color,
              starting_pos=init_pos,
              abs_rotation=init_angle)
    running = True
    start_time = time.time()

    on_pause = False

    while running:
        temp = check_events()
        if temp == 2:
            break
        if temp == 3:
            on_pause = not on_pause

        screen.fill(SETTINGS.colors["background"])
        draw.circuit(screen, circuit["bordures"])
        draw.car(screen, [car])
        delta = dt * FPS / 1000

        if not on_pause:
            pressed = pygame.key.get_pressed()
            if pressed[SETTINGS.left_key]:
                car.abs_rotation -= SETTINGS.car_maniability * delta
            if pressed[SETTINGS.right_key]:
                car.abs_rotation += SETTINGS.car_maniability * delta
            car.apply_vector(car.direction_vector())

            if min(car.position) < 0:
                car.set_position(max(car.position[0], 0),
                                 max(car.position[1], 0))
            if max(car.position) > screen_width:
                car.set_position(min(car.position[0], screen_width),
                                 min(car.position[1], screen_width))
            if not car.detection(screen, SETTINGS.display_rays):
                running = False
                print("Votre voiture a touché un mur - fin de la partie")

        draw.general_stats(screen, small_font, clock, None, None, start_time)
        if on_pause:
            draw.pause_screen(screen, title_font)
            start_time += dt / 1000
        pygame.display.flip()
        dt = clock.tick(FPS)

    for _ in range(30):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                return
        time.sleep(0.05)
示例#13
0
def AI_loop(screen: pygame.Surface, circuit: dict) -> Network:
    """
    Boucle principale pour le mode automatique du programme

    Le but ici est d'entraîner des IA pour qu'elles soient le plus performant possible sur le
    circuit, donc en trouver au moins une qui arrive à la fin du circuit sans toucher aucune
    bordure.

    Parameters
    ----------
    screen:
        La fenêtre du programme
    circuit:
        Un dictionnaire contenant la liste des bordures représentant le circuit, ainsi que les deux
        points définissant la ligne de départ

    Returns
    -------
    Network:
        Le meilleur réseau de la dernière génération complétée
    """
    print("Astuce : Appuyez sur la touche R si une voiture tourne en rond\n")
    clock = pygame.time.Clock()
    small_font = pygame.font.SysFont('Arial', ceil(18 * SETTINGS.scale_avg))
    title_font = pygame.font.SysFont('Arial', ceil(30 * SETTINGS.scale_avg))
    dt = 1
    init_pos, init_angle = calc_starting_pos(circuit["point1"],
                                             circuit["point2"])
    cars = [
        Car(circuit["bordures"],
            color=SETTINGS.colors["cars"],
            starting_pos=init_pos,
            abs_rotation=init_angle) for _ in range(SETTINGS.cars_number)
    ]
    networks = [Network(c) for c in cars]
    networks[0].from_json(BackupManager().load()["network"])
    networks[0].car.color = "#00FF00"
    running = True

    increment = 0
    last_sorted_networks = None
    on_pause = False

    while running:
        increment += 1
        endgen = False
        cleanup_done = False
        start_time = time.time()
        while not endgen:

            temp = check_events()
            if temp == 1:
                endgen = True
            if temp == 2:
                return last_sorted_networks[
                    0] if last_sorted_networks is not None else None
            if temp == 3:
                on_pause = not on_pause

            screen.fill(SETTINGS.colors["background"])
            draw.circuit(screen, circuit["bordures"])
            draw.car(screen, (net.car for net in networks))

            delta = dt * FPS / 1000
            if not on_pause:
                # Gestion du mouvement de la voiture
                for net in networks:
                    if not net.dead:
                        net.update()
                        net.car.abs_rotation += SETTINGS.car_maniability * delta * net.direction

                        net.car.apply_vector(net.car.direction_vector() *
                                             net.engine * 2 *
                                             SETTINGS.scale_avg)
                        if not net.car.detection(screen,
                                                 SETTINGS.display_rays):
                            net.dead = True
                            net.car.death_time = time.time()

                survived = sum(1 for n in networks if not n.dead)
                if survived == 0:
                    endgen = True
                elif time.time() - start_time > 10 and not cleanup_done:
                    for net in networks:
                        if (not net.dead) and net.car.position[0] < 150:
                            net.dead = True
                            net.car.death_time = time.time()

            draw.general_stats(screen, small_font, clock, increment, survived,
                               start_time)
            draw.car_specs(screen, small_font, networks[0])
            draw.car_network(screen, small_font, networks[0])
            if on_pause:
                draw.pause_screen(screen, title_font)
                elapsed = dt / 1000
                start_time += elapsed
                for net in networks:
                    if not net.dead:
                        net.car.start_time += elapsed
            pygame.display.flip()
            dt = clock.tick(FPS)

        arrival = circuit["bordures"][-1]  # ligne d'arrivée
        # calcul des scores
        for net in networks:
            net.score = net.car.get_score()
            if net.car.distance_to_segment(arrival) <= 8:
                net.score += 300  # points bonus si la voiture a atteint la ligne d'arrivée
        average = round(sum([net.score for net in networks]) / len(networks))
        print(f"Génération N°{increment} terminée - score moyen : {average}")
        last_sorted_networks = copy.deepcopy(networks)

        # Darwin
        networks = darwin(networks)

        # Reset des réseaux/voitures
        for net in networks:
            net.dead = 0
            # net.car.position = [80, 130]
            net.car.color = SETTINGS.colors["cars"]
            net.car.reset()
        networks[0].car.color = SETTINGS.colors["main_car"]