Ejemplo n.º 1
0
    def reset(self):
        self.steps = 0
        self.current_reward = 0
        self.total_game += 1

        self.car = Car()
        self.obstacles = []
        self.bunkers = []
        
        l = list(itertools.product(range(self.height), range(self.width)))
        random.shuffle(l)
        i = 0
        n = 0
        while n < self.num_of_obstacles + self.num_of_bunkers:
            r, c = l[i]
            if (r == 0 and c == 0) or (r == self.height - 1 and c == self.width - 1):
                pass
            else:
                if n < self.num_of_obstacles:
                    self.obstacles.append(Obstacle(r, c))
                else:
                    self.bunkers.append(Bunker(r, c))
                n += 1
            i += 1

        return self._get_state()
Ejemplo n.º 2
0
 def test_raise_error_town(self):
     with self.assertRaises(ValueError, msg="Ups should raise error") as context:
         car1 = Car(200.50, "Sedan", "BENTLEY", "47af87f3-3a96-422f-b357-237e4b3684a9", 50000.00)
         car2 = Car(250.40, "Truck", "BMW", "47af87f3-3a96-422f-b357-237e4b3684a9", 20000.00)
         garage = Garage("MISTAKE", 3, [car1, car2], uuid.uuid4())
         self.assertTrue("Incorrect garage town" in context.exception.args)
         self.fail()
Ejemplo n.º 3
0
 def test_garage_town(self):
     car1 = Car(200.50, "Sedan", "BENTLEY", "47af87f3-3a96-422f-b357-237e4b3684a9", 50000.00)
     car2 = Car(250.40, "Truck", "BMW", "47af87f3-3a96-422f-b357-237e4b3684a9", 20000.00)
     garage1 = Garage("Amsterdam", 3, [car1, car2], uuid.uuid4())
     expected = "Amsterdam"
     actual = garage1.town
     self.assertEqual(actual, expected, msg=f"Town should be one of {constants.CARS_TYPES}")
Ejemplo n.º 4
0
 def test_garage_cars(self):
     car1 = Car(200.50, "Sedan", "BENTLEY", "47af87f3-3a96-422f-b357-237e4b3684a9", 50000.00)
     car2 = Car(250.40, "Truck", "BMW", "47af87f3-3a96-422f-b357-237e4b3684a9", 20000.00)
     garage1 = Garage("Amsterdam", 3, [car1, car2], uuid.uuid4())
     expected = [car1, car2]
     actual = garage1.cars
     self.assertEqual(actual, expected)
Ejemplo n.º 5
0
 def test_remove_car(self):
     car1 = Car(200.50, "Sedan", "BENTLEY", "47af87f3-3a96-422f-b357-237e4b3684a9", 50000.00)
     car2 = Car(250.40, "Truck", "BMW", "47af87f3-3a96-422f-b357-237e4b3684a9", 20000.00)
     garage = Garage("Amsterdam", 3, [car1, car2], uuid.uuid4())
     garage.remove_car(car2)
     actual = len(garage.cars)
     expected = 1
     self.assertEqual(actual, expected)
 def test_workflow(self):
     person = Person('Sam', 20, True)
     car = Car('Honda', 'Civic')
     car.wheels = 4
     distance = 90
     result = workflow(unit((person, car, distance)), person_is_of_age,
                       person_is_licensed, car_has_wheels, drive)
     self.assertIsInstance(result, Success)
Ejemplo n.º 7
0
 def test_places(self):
     car1 = Car(200.50, "Sedan", "BENTLEY", "47af87f3-3a96-422f-b357-237e4b3684a9", 50000.00)
     car2 = Car(250.40, "Truck", "BMW", "47af87f3-3a96-422f-b357-237e4b3684a9", 20000.00)
     garage = Garage("Amsterdam", 3, [car1, car2], uuid.uuid4())
     expected = 3
     actual = garage.places
     self.assertEqual(actual, expected)
     self.assertIsInstance(actual, int)
Ejemplo n.º 8
0
 def test_greater_then(self):
     car1 = Car(200.50, "Sedan", "BENTLEY", "47af87f3-3a96-422f-b357-237e4b3684a9", 50000.00)
     car2 = Car(400.60, "Van", "Bugatti", "47af87f3-3a96-422f-b357-237e4b3684a9", 10000.00)
     garage1 = Garage("Amsterdam", 3, [car1], uuid.uuid4())
     garage2 = Garage("Kiev", 3, [car2], uuid.uuid4())
     Tom = Collectioner("Tom", uuid.uuid4(), [garage1])
     Jerom = Collectioner("Jerom", uuid.uuid4(), [garage2])
     actual_Tom = Tom.hit_hat
     actual_Jerom = Jerom.hit_hat
     self.assertGreater(actual_Tom, actual_Jerom)
Ejemplo n.º 9
0
 def test_equal(self):
     car1 = Car(400.50, "Sedan", "BENTLEY", "47af87f3-3a96-422f-b357-237e4b3684a9", 50000.00)
     car2 = Car(400.50, "Van", "Bugatti", "47af87f3-3a96-422f-b357-237e4b3684a9", 10000.00)
     garage1 = Garage("Amsterdam", 3, [car1], uuid.uuid4())
     garage2 = Garage("Kiev", 3, [car2], uuid.uuid4())
     Tom   = Collectioner("Tom", uuid.uuid4(), [garage1])
     Teddy = Collectioner("Teddy", uuid.uuid4(), [garage2])
     actual_Tom = Tom.hit_hat
     actual_Teddy = Teddy.hit_hat
     self.assertEqual(actual_Tom, actual_Teddy)
Ejemplo n.º 10
0
 def test_car_count(self):
     car1 = Car(200.50, "Sedan", "BENTLEY", "47af87f3-3a96-422f-b357-237e4b3684a9", 50000.00)
     car2 = Car(250.40, "Truck", "BMW", "47af87f3-3a96-422f-b357-237e4b3684a9", 20000.00)
     car3 = Car(400.60, "Van", "Bugatti", "47af87f3-3a96-422f-b357-237e4b3684a9", 10000.00)
     car4 = Car(500.90, "Sedan", "Buick", "47af87f3-3a96-422f-b357-237e4b3684a9", 70000.00)
     garage1 = Garage("Amsterdam", 3, [car1, car2], uuid.uuid4())
     garage2 = Garage("Kiev", 3, [car3, car4], uuid.uuid4())
     Tom = Collectioner("Tom", uuid.uuid4(), [garage1, garage2])
     actual = Tom.cars_count
     expected = 4
     self.assertEqual(actual, expected)
Ejemplo n.º 11
0
 def test_add_car_no_free_places(self):
     car1 = Car(200.50, "Sedan", "BENTLEY", "47af87f3-3a96-422f-b357-237e4b3684a9", 50000.00)
     car2 = Car(250.40, "Truck", "BMW", "47af87f3-3a96-422f-b357-237e4b3684a9", 20000.00)
     car3 = Car(400.60, "Van", "Bugatti", "47af87f3-3a96-422f-b357-237e4b3684a9", 10000.00)
     car4 = Car(500.90, "Sedan", "Buick", "47af87f3-3a96-422f-b357-237e4b3684a9", 70000.00)
     garage1 = Garage("Amsterdam", 3, [car1, car2], uuid.uuid4())
     garage2 = Garage("Kiev", 3, [car3], uuid.uuid4())
     Tom = Collectioner("Tom", uuid.uuid4(), [garage1, garage2])
     with self.assertRaises(ValueError, msg="Should raise error") as context:
         Tom.add_car(car4)
     self.assertTrue('There are no free places in the specified garage' in context.exception.args)
Ejemplo n.º 12
0
 def test_str(self):
     car1 = Car(200.50, "Sedan", "BENTLEY", "47af87f3-3a96-422f-b357-237e4b3684a9", 50000.00)
     car2 = Car(250.40, "Truck", "BMW", "47af87f3-3a96-422f-b357-237e4b3684a9", 20000.00)
     garage = Garage("Amsterdam", 3, [car1, car2], uuid.uuid4())
     actual = str(garage)
     expected = "Town = Amsterdam " \
                "Cars:" \
                "[200.5, 'Sedan', 'BENTLEY', '47af87f3-3a96-422f-b357-237e4b3684a9', 50000.0]" \
                "[250.4, 'Truck', 'BMW', '47af87f3-3a96-422f-b357-237e4b3684a9', 20000.0]" \
                "Maximum places in garage = 3" \
                "Garage owner = c5929fab-7c54-4f51-8ffc-23cb389c197c"
     self.assertEqual(actual, expected)
Ejemplo n.º 13
0
 def test_add_first_car(self):
     car1 = Car(200.50, "Sedan", "BENTLEY", "47af87f3-3a96-422f-b357-237e4b3684a9", 50000.00)
     garage = Garage("Amsterdam", 3, [], uuid.uuid4())
     garage.add_car(car1)
     actual = garage.cars
     expected = [car1]
     self.assertEqual(actual, expected)
Ejemplo n.º 14
0
 def test_count_garages(self):
     car1 = Car(200.50, "Sedan", "BENTLEY", "47af87f3-3a96-422f-b357-237e4b3684a9", 50000.00)
     garage1 = Garage("Amsterdam", 3, [car1], uuid.uuid4())
     Tom = Collectioner("Tom", uuid.uuid4(), [garage1])
     Ralf = Collectioner("Tom", uuid.uuid4(), [])
     self.assertEqual(Tom.garages_count, 3)
     self.assertEqual(Ralf.garages_count, 1)
 def test_without_bind(self):
     person = Person('Sam', 20, True)
     car = Car('Honda', 'Civic')
     distance = 90
     pair = (person, car, distance)
     age_check_result = person_is_of_age(pair)
     if isinstance(age_check_result, Success):
         print(age_check_result.msg)
         license_check_result = person_is_licensed(pair)
         if isinstance(license_check_result, Success):
             print(license_check_result.msg)
             wheel_check_result = car_has_wheels(pair)
             if isinstance(wheel_check_result, Success):
                 print(wheel_check_result.msg)
                 drive_result = drive(pair)
                 if isinstance(drive_result, Success):
                     print(drive_result.msg)
                     self.assertIsInstance(drive_result, Success)
                 else:
                     print(drive_result.msg)
                     self.assertIsInstance(drive_result, Success)
             else:
                 print(wheel_check_result.msg)
                 self.assertIsInstance(wheel_check_result, Success)
         else:
             print(license_check_result.msg)
             self.assertIsInstance(license_check_result, Success)
     else:
         print(age_check_result.msg)
         self.assertIsInstance(age_check_result, Success)
Ejemplo n.º 16
0
def shiftplanning(sim):

    while True:
        if tick_to_time(sim.env.now) in drivers:
            print(f"{tick_to_time(sim.env.now)} drives starting to work")
            ob = Car(sim, tick_to_time(sim.env.now), 2, 10)
            sim.car_list.append(ob)  #important

        yield sim.env.timeout(1)
Ejemplo n.º 17
0
 def test_str(self):
     car = Car(200.32, "Sedan", "BENTLEY", "47af87f3-3a96-422f-b357-237e4b3684a9", 50000.00)
     actual = str(car)
     expected = f"Car price = 200.32, " \
         f"car type = Sedan, " \
         f"car number = 47af87f3-3a96-422f-b357-237e4b3684a9, " \
         f"producer = BENTLEY, " \
         f"mileage = 50000.0 km"
     self.assertEqual(actual, expected)
Ejemplo n.º 18
0
 def test_str(self):
     car1 = Car(400.50, "Sedan", "BENTLEY", "47af87f3-3a96-422f-b357-237e4b3684a9", 50000.00)
     garage1 = Garage("Amsterdam", 3, [car1], uuid.uuid4())
     Tom = Collectioner("Tom", uuid.uuid4(), [garage1])
     actual = str(Tom)
     expected = """ Name = Tom 
                 Garages & cars: 
                 ['Amsterdam', 3, 200.5, 'Sedan', 'BENTLEY', '47af87f3-3a96-422f-b357-237e4b3684a9', 50000.0, UUID('4f36a82b-599f-4378-b0e8-5c57d324e15b')] 
                 Garage owner = b7549015-ccaa-4b6d-afa7-0751cf176caa"""
     self.assertEqual(actual, expected)
Ejemplo n.º 19
0
 def test_less_equal_then(self):
     car1 = Car(200.50, "Sedan", "BENTLEY", "47af87f3-3a96-422f-b357-237e4b3684a9", 50000.00)
     car2 = Car(250.40, "Truck", "BMW", "47af87f3-3a96-422f-b357-237e4b3684a9", 20000.00)
     car3 = Car(400.60, "Van", "Bugatti", "47af87f3-3a96-422f-b357-237e4b3684a9", 10000.00)
     car4 = Car(500.90, "Sedan", "Buick", "47af87f3-3a96-422f-b357-237e4b3684a9", 70000.00)
     garage1 = Garage("Amsterdam", 3, [car1, car2], uuid.uuid4())
     garage2 = Garage("Kiev", 3, [car3, car4], uuid.uuid4())
     Tom = Collectioner("Tom", uuid.uuid4(), [garage1])
     Denny = Collectioner("Tom", uuid.uuid4(), [garage1])
     Jerom = Collectioner("Jerom", uuid.uuid4(), [garage2])
     actual_Tom = Tom.hit_hat
     actual_Denny = Denny.hit_hat
     actual_Jerom = Jerom.hit_hat
     expected_Tom = 450.90
     expected_Jerom = 901.50
     self.assertEqual(actual_Tom, expected_Tom)
     self.assertEqual(actual_Jerom, expected_Jerom)
     self.assertLess(actual_Tom, actual_Jerom)
     self.assertLessEqual(actual_Tom, actual_Denny)
 def test_without_workflow(self):
     person = Person('Sam', 20, True)
     car = Car('Honda', 'Civic')
     distance = 90
     result = \
         bind(
             bind(
                 bind(
                     bind(
                         unit((person, car, distance)),
                         person_is_of_age)
                     , person_is_licensed)
                 , car_has_wheels)
             , drive)
     self.assertIsInstance(result, Success)
Ejemplo n.º 21
0
    def inputFileParse(self):
        with open(self.filepath) as fp:
            line = fp.readline()
            words = line.split()
            self.time = int(words[0])
            numIntersection = int(words[1])
            numStreet = int(words[2])
            numCars = int(words[3])
            score = int(words[4])
            cnt = 1
            line = fp.readline()
            cnt = 2
            for x in range(numStreet):
                words = line.split()
                temp = Road(words[2], int(words[3]))
                if words[0] not in self.IntersectionList.keys():
                    self.IntersectionList[words[0]] = Intersection(words[0])
                self.IntersectionList[words[0]].addOutRoad(temp)

                if words[1] not in self.IntersectionList.keys():
                    self.IntersectionList[words[1]] = Intersection(words[1])
                self.IntersectionList[words[1]].addInRoad(temp)

                temp.addFromAndToIntersection(self.IntersectionList[words[0]],
                                              self.IntersectionList[words[1]])
                self.RoadList[words[2]] = temp
                #
                line = fp.readline()
                cnt = cnt + 1

            for x in range(numCars):
                words = line.split()
                num = int(words[0])
                temp2 = []
                for j in range(num):
                    temp2.append(self.RoadList[words[j + 1]])
                Car(temp2)
                line = fp.readline()
Ejemplo n.º 22
0
def main():

    blockZero = []

    blockOne = []

    blockTwo = []

    blockThree = []

    blockFour = []

    blockFive = []

    blockSix = []

    blockSeven = []

    blockEight = []

    blockNine = []

    listZero = []

    listOne = []

    listTwo = []

    listThree = []

    listFour = []

    listFive = []

    listSix = []

    listSeven = []

    listEight = []

    listNine = []

    overflowBuffZero = []

    overflowBuffOne = []

    overflowBuffTwo = []

    overflowBuffThree = []

    overflowBuffFour = []

    overflowBuffFive = []

    overflowBuffSix = []

    overflowBuffSeven = []

    overflowBuffEight = []

    overflowBuffNine = []

    blockLen = 5

    #blockExample = [listExample, OverflowBuffExample]

    listBlocks = [
        blockZero, blockOne, blockTwo, blockThree, blockFour, blockFive,
        blockSix, blockSeven, blockEight, blockNine
    ]

    listLists = [
        listZero, listOne, listTwo, listThree, listFour, listFive, listSix,
        listSeven, listEight, listNine
    ]

    listOverflowBuff = [
        overflowBuffZero, overflowBuffOne, overflowBuffTwo, overflowBuffThree,
        overflowBuffFour, overflowBuffFive, overflowBuffSix, overflowBuffSeven,
        overflowBuffEight, overflowBuffNine
    ]

    for i in range(len(listBlocks)):

        listBlocks[i].append(listLists[i])

        listBlocks[i].append(listOverflowBuff[i])

        for j in range(blockLen):

            listLists[i].append(None)

    #print(listBlocks)

    infile = "directCar.txt"

    outfile = "carparkMod.txt"

    counter = 0

    with open(infile, "r+") as f:

        for row in f:

            counter += 1

    with open(infile, "r+") as f:

        for row in f:

            for i in range(len(listBlocks)):

                for j in range(counter):

                    if j < 5:

                        if row[3] == str(i) and listLists[i][j] is None:

                            listLists[i][j] = row

                            break

                    if row[3] == str(
                            i) and listLists[i][4] is not None and j >= 5:

                        listOverflowBuff[i].append(row)

                        break

    f.close()

    menu()

    choice = (input("Your choice:"))

    print("\n")

    if choice == "1":
        '''Input data '''

        if not os.path.exists(infile):

            carstore = open(infile, "w+")

        else:

            carstore = open(infile, "a")

        carInCarPark = Car.carInput(infile)

        getCarId = str(carInCarPark.getCarID())

        for i in range(len(listBlocks)):

            for j in range(len(listLists[i])):

                if getCarId[-1] == str(i) and listLists[i][j] == None:

                    listLists[i][j] = str(carInCarPark)

                    carstore.write(str(listLists[i][j]))

                    break

                elif getCarId[-1] == str(i) and listLists[i][4] != None:

                    listOverflowBuff[i].append(str(carInCarPark))

                    carstore.write(str(listOverflowBuff[i][-1]))

                    break

        carstore.close()

        print("\n")

        lines = readInList(infile)

        lines.sort()

        reWrite(infile, outfile, lines)

        main()

    elif choice == "2":
        '''Search specific data '''

        result = 0

        carIdSearch = input('Enter the ID : ')

        blockId = int(carIdSearch[3])

        for i in range(len(listLists[blockId])):

            if carIdSearch in listLists[blockId][i]:

                print(listLists[blockId][i])

                result = 1

                break

        for i in range(len(listOverflowBuff[blockId])):

            if carIdSearch in listOverflowBuff[blockId][i]:

                print(listOverflowBuff[blockId][i])

                result = 1

                break

        if result == 0:

            print("No match found.")

        main()

    elif choice == "3":
        '''Read all data'''

        for i in range(len(listBlocks)):

            print("Block #", i, "\n")

            for j in range(blockLen):

                if listLists[i][j] != None:

                    print(listLists[i][j])

            if listOverflowBuff != []:

                for j in range(len(listOverflowBuff[i])):

                    print("Overflow buffer #{}: {}".format(
                        i, listOverflowBuff[i][j]))

            print("=================")

        print("\n")

        lines = readInList(infile)

        lines.sort()

        reWrite(infile, outfile, lines)

        main()

    elif choice == "4":
        ''' Modify data '''

        carIdSearch = input('Enter the ID : ')

        blockId = int(carIdSearch[3])

        modlist = []

        lines = []

        result = 0

        for i in range(len(listLists[blockId])):

            if carIdSearch in listLists[blockId][i]:

                print(listLists[blockId][i])

                oldField = input("Field to modify: ")

                newField = input("New data: ")

                listLists[blockId][i] = listLists[blockId][i].replace(
                    oldField, newField)

                result = 1

                break

        for i in range(len(listOverflowBuff[blockId])):

            if carIdSearch in listOverflowBuff[blockId][i]:

                print(listOverflowBuff[blockId][i])

                oldField = input("Field to modify: ")

                newField = input("New data: ")

                listOverflowBuff[blockId][i] = listOverflowBuff[blockId][
                    i].replace(oldField, newField)

                result = 1

                break

        if result == 0:

            print("No match found.")

        elif result == 1:

            with open(infile, "w+") as f1:

                for i in range(len(listBlocks)):

                    for j in range(blockLen):

                        if listLists[i][j] is not None:

                            f1.write(str(listLists[i][j]))

                    for k in range(len(listOverflowBuff[i])):

                        f1.write(str(listOverflowBuff[i][k]))

            f1.close()

        reWrite(infile, outfile, lines)

        main()

    elif choice == "5":
        ''' Delete data '''

        carIdSearch = input('Enter the ID : ')

        blockId = int(carIdSearch[3])

        modlist = []

        lines = []

        result = 0
        '''Checking if car is in main buffer'''

        for i in range(len(listLists[blockId])):

            if carIdSearch in listLists[blockId][i]:

                print(listLists[blockId][i])

                deleteDesicion = input(
                    "Do you want to delete the record? Y/N: ")

                if deleteDesicion == 'y' or deleteDesicion == 'Y':

                    listLists[blockId][i] = None

                    if listOverflowBuff[i] != []:

                        listLists[blockId][i] = listOverflowBuff[i][0]

                        listOverflowBuff[i].pop(0)

                        break

                    result = 1

                    break

                elif deleteDesicion == 'n' or deleteDesicion == 'N':

                    main()

                else:

                    print("Wrong button pressed. Returning to main menu.")

                    main()
        '''Checking if car is in overflow buffer'''

        for i in range(len(listOverflowBuff[blockId])):

            if carIdSearch in listOverflowBuff[blockId][i]:

                print(listOverflowBuff[blockId][i])

                deleteDesicion = input(
                    "Do you want to delete the record? Y/N: ")

                if deleteDesicion == 'y' or deleteDesicion == 'Y':

                    listOverflowBuff[i].pop(i)

                    result = 1

                    break

                elif deleteDesicion == 'n' or deleteDesicion == 'N':

                    main()

                else:

                    print("Wrong button pressed. Returning to main menu.")

                    main()

        if result == 0:

            print("No match found.")

        elif result == 1:

            with open(infile, "w+") as f1:

                for i in range(len(listBlocks)):

                    for j in range(blockLen):

                        if listLists[i][j] is not None:

                            f1.write(str(listLists[i][j]))

                    for k in range(len(listOverflowBuff[i])):

                        f1.write(str(listOverflowBuff[i][k]))

            f1.close()

        listBlocks = None

        main()

    elif choice == "6":
        ''' Exit '''

        print("Bye!")

        exit()

    elif choice == "0":

        print("Programming God's mode is not implemented yet.")

        main()

    else:

        print("Wrong button pressed.")

        main()
Ejemplo n.º 23
0
screen.blit(bg, (0, 0))
screen.set_alpha(None)



# иконка
img = pygame.image.load('static/img/car.png').convert_alpha()
pygame.display.set_icon(img)

# fps
clock = pygame.time.Clock()
pygame.display.update()

# здесь определяются константы, классы и функции
x = 5
car = Car(200, 750, 'static/img/car.png')
car2 = Car(643, 750, 'static/img/car2.png')
speed = 10
left = False
right = False
up = False
down = False
left2 = False
right2 = False
up2 = False
down2 = False
coins =  pygame.sprite.Group()
blocks = pygame.sprite.Group()
pygame.font.init()
font = pygame.font.SysFont('Comic Sans MS', 30)
f = 0
Ejemplo n.º 24
0
def test_car_error_raised():
    with pytest.raises(ValueError):
        my_car = Car("Ducati", "Monster", 2019)
Ejemplo n.º 25
0
def test_car_error_message():
    with pytest.raises(ValueError) as ve:
        my_car = Car("Ducati", "Monster", 2019)
    assert str(ve.value) == "Ducati does not make cars!"
Ejemplo n.º 26
0
class Game:
    def __init__(self, width, height, obs, bun, show_game=True):
        self.width = width
        self.height = height
        self.show_game = show_game
        self.num_of_obstacles = obs
        self.num_of_bunkers = bun

        self.car = None
        self.target = Target(width, height)
        self.obstacles = None
        self.bunkers = None

        self.total_reward = 0.
        self.current_reward = 0.
        self.total_game = 0
        self.total_success = 0

    def _get_state(self):
        cstate = np.zeros((self.width, self.height))
        vstate = np.zeros((self.width, self.height))
        hstate = np.zeros((self.width, self.height))
        bstate = np.zeros((self.width, self.height))
#        mstate = np.zeros((self.width, self.height))

        cstate[self.car.row, self.car.col] = 1
        for o in self.obstacles:
            if o.dr != 0:
                vstate[o.row, o.col] = 1
            else:
                hstate[o.row, o.col] = 1
        for b in self.bunkers:
            bstate[b.row, b.col] = 1
#        for r in range(self.height):
#            for c in range(self.width):
#                if r + c <= self.car.max:
#                    mstate[r, c] = 1
#                else:
#                    break

        r = np.append(cstate, vstate, axis=0)
        r = np.append(r, hstate, axis=0)
        r = np.append(r, bstate, axis=0)
#        r = np.append(r, mstate, axis=0)
        return r

    def _draw_screen(self):
        os.system("clear")

        title = str(self.total_success) + " SUCCESSES / " + str(self.total_game) + " GAMES"
        print(title)

        for r in range(self.height):
            for c in range(self.width):
                pos = GameObj(r, c)

                if self.car.row == r and self.car.col == c:
                    print("o", end="")
                elif self.target.row == r and self.target.col == c:
                    print("O", end="")
                elif list(filter(lambda o: o.same_pos(pos), self.obstacles)):
                    print("X", end="")
                elif list(filter(lambda b: b.same_pos(pos), self.bunkers)):
                    print("B", end="")
                else:
                    print("_", end="")
            print()

        if self._is_gameover():
            print("GAME OVER!!")
        elif self._is_success():
            print("SUCCESS!!")

    def reset(self):
        self.steps = 0
        self.current_reward = 0
        self.total_game += 1

        self.car = Car()
        self.obstacles = []
        self.bunkers = []
        
        l = list(itertools.product(range(self.height), range(self.width)))
        random.shuffle(l)
        i = 0
        n = 0
        while n < self.num_of_obstacles + self.num_of_bunkers:
            r, c = l[i]
            if (r == 0 and c == 0) or (r == self.height - 1 and c == self.width - 1):
                pass
            else:
                if n < self.num_of_obstacles:
                    self.obstacles.append(Obstacle(r, c))
                else:
                    self.bunkers.append(Bunker(r, c))
                n += 1
            i += 1

        return self._get_state()

    def _update_car(self, action):
        return self.car.move(action, self.width, self.height)

    def _update_obstacles(self):
        objs = self.bunkers + [self.target]
        for o in self.obstacles:
            o.move(self.width, self.height, objs)

    def _is_gameover(self):
        return list(filter(lambda o: o.same_pos(self.car), self.obstacles))

    def _is_success(self):
        return self.car.same_pos(self.target)

    def step(self, action):
        move_reward = self._update_car(action)
        gameover = self._is_gameover()
        success = self._is_success()

        if (not gameover) and (not success):
            self._update_obstacles()
        gameover = self._is_gameover()

        if gameover:
            reward = -(self.height + self.width)
        elif success:
            self.total_success += 1
            reward = (self.height + self.width)
        else:
            reward = move_reward
        self.current_reward += reward

        end = gameover or success
        if end:
            self.total_reward += self.current_reward

        if self.show_game:
            self._draw_screen()

        return self._get_state(), reward, end, success
Ejemplo n.º 27
0
clock = pygame.time.Clock()
basicfont = pygame.font.SysFont(None, 12)


#GROUPS OF SPRITES
allSpritesList = pygame.sprite.Group()
carList = pygame.sprite.Group()
enemyCarList = pygame.sprite.Group()
lasersList = pygame.sprite.Group()
enemyLasersList = pygame.sprite.Group()


#HOW CAR LOOKS IN GAME
widthOfCar = 65
heightOfCar = 80
playerCar = Car(widthOfCar, heightOfCar, 445, 520, carList, 25, 1)
carList.add(playerCar)
allSpritesList.add(playerCar)


#First Enemy Car
widthOfCar = 120
heightOfCar = 80
howOftenCarShoots = random.randrange(4, 8)
enemyCar = EnemyCar(widthOfCar, heightOfCar, howOftenCarShoots)
randomX = random.randrange(200, 700)
randomY = random.randrange(20, 50)
enemyCar.rect.x = randomX
enemyCar.rect.y = randomY
enemyCarList.add(enemyCar)
allSpritesList.add(enemyCar)
Ejemplo n.º 28
0
def main():

    menu()

    choice = input("Your choice:")

    print("\n")

    if choice == "1":
        '''Input data '''

        nfile = "carpark.txt"

        if not os.path.exists("carParkSort.txt"):

            carstore = open("carParkSort.txt", "w+")

        else:

            carstore = open("carParkSort.txt", "a")

        carInCarPark = Car.carInput(infile)

        carstore.write(str(carInCarPark))

        carstore.close()

        infile = "carParkSort.txt"

        outfile = "carparkMod.txt"

        lines = readInList(infile)

        lines.sort()

        reWrite(infile, outfile, lines)

        print("\n")

        main()

    elif choice == "2":
        '''Search specific data '''

        carIdSearch = input('Enter the search parameter: ')
        #carParam = input('Enter the parameter: ')

        lines = []

        with open('carParkSort.txt') as f:

            for row in f:

                lines.append(row)

            for line in lines:

                if carIdSearch in line:
                    print(line)

        main()

    elif choice == "3":
        '''See all data '''

        infile = "carParkSort.txt"

        outfile = "carparkMod.txt"

        lines = readInList(infile)

        lines.sort()

        with open(outfile, "w") as f1:

            with open(infile, "r+") as f:

                for line in lines:

                    f1.write(line)

            f1.close()

        f.close()

        os.rename(outfile, infile)

        carstore = open("carParkSort.txt", "r")

        carstore_display = carstore.read()

        print(carstore_display)

        print("\n")

        main()

    elif choice == "4":
        ''' Modify data '''

        carIdSearch = input('Enter the ID : ')

        modlist = []

        infile = "carParkSort.txt"

        outfile = "carparkMod.txt"

        sortId = idSearch(infile)

        lines = readInList(infile)

        lines.sort()

        with open(outfile, "w") as f1:

            with open(infile, "r+") as f:

                for line in lines:

                    if carIdSearch in line and carIdSearch in sortId:

                        print(line)

                        modlist.append(input("Field to modify: "))

                        newfield = input("New data: ")

                    for word in modlist:

                        line = line.replace(word, newfield)

                    f1.write(line)

                f1.close()

            f.close()

        os.rename(outfile, infile)

        main()

    elif choice == "5":
        ''' Delete data '''

        infile = "carParkSort.txt"

        outfile = "carparkMod.txt"

        carIdSearch = input('Enter the ID : ')

        sortId = idSearch(infile)

        lines = readInList(infile)

        lines.sort()

        for line in range(len(lines)):

            if carIdSearch in lines[line] and carIdSearch in sortId[line]:

                print(lines[line])

                deleteDesicion = input(
                    "Do you want to delete the record? Y/N: ")

                if deleteDesicion == 'y' or deleteDesicion == 'Y':

                    lines.remove(lines[line])

                    sortId.remove(sortId[line])

                    reWrite(infile, outfile, lines)

                    reWrite("idList.txt", "idListMod.txt", sortId)

                    print("\nDone.\n ")

                    main()

                elif deleteDesicion == 'n' or deleteDesicion == 'N':

                    main()

                else:

                    print("Wrong button pressed. Returning to main menu.")

                    main()

    elif choice == "6":
        ''' Exit '''

        print("Bye!")

        exit()

    else:

        print("Wrong button pressed.")

        main()
Ejemplo n.º 29
0
Archivo: test.py Proyecto: ih19708/REP4
#!/usr/bin/env python3

from objects import Car
from model import BridgeSystem
from animation import animate_model

cars = [
    Car(1, 1, 1),
    Car(2, 1, 1),
    Car(3, 1, 1),
    Car(4, 1, 1),
    Car(5, 1, 1),
    Car(6, 1, 1),
    Car(1, -1, 1),
    Car(2, -1, 1),
    Car(3, -1, 1),
    Car(4, -1, 1),
    Car(5, -1, 1),
    Car(6, -1, 1)
]

model = BridgeSystem(10, cars)

animate_model(model)
Ejemplo n.º 30
0
pygame.mixer.init()
window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT), WINDOW_SURFACE)
pygame.display.set_caption('Driving Game Prototype')

road_image = pygame.image.load('track.png')
background = pygame.transform.smoothscale(road_image,
                                          (WINDOW_WIDTH, WINDOW_HEIGHT))
car_image = pygame.image.load('car_image.png').convert_alpha()

car_size = car_image.get_size()
smaller_car = pygame.transform.scale(
    car_image, (int(car_size[0] / 7), int(car_size[1] / 7)))

car_spawn_x = WINDOW_WIDTH // 5
car_spawn_y = WINDOW_HEIGHT // 5
car1 = Car(smaller_car, car_spawn_x, car_spawn_y)
#car1 = Car(car_image, WINDOW_WIDTH//2, WINDOW_HEIGHT//2)

car_sprites = pygame.sprite.Group()
car_sprites.add(car1)

clock = pygame.time.Clock()
done = False
while not done:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True
        elif event.type == pygame.VIDEORESIZE:
            WINDOW_WIDTH = event.w
            WINDOW_HEIGHT = event.h
            window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT),