Exemple #1
0
def allseatings(sofar, lst):
    if len(lst) == 0:
        return sofar
    lst.sort()
    lst.reverse()
    if (lst[0] > 150):
        return False
    if len(sofar) == 0:
        b = Boat.Boat3()
        b.seat(lst[0])
        return allseatings([[b]], lst[1:])
    head = lst[0]
    tail = lst[1:]
    newsols = []
    for sol in sofar:
        for i in range(0,len(sol)):
            b = sol[i]
            if b.fits(head):
                ns = []
                nb = b.clone()
                nb.seat(head)
                for j in range(0,len(sol)):
                    if j != i:
                        ns.append(sol[j])
                    else:
                        ns.append(nb)
                newsols.append(ns)
        ns = sol[:]
        nb = Boat.Boat3()
        nb.seat(head)
        ns.append(nb)
        newsols.append(ns)
    return allseatings(newsols, tail)
Exemple #2
0
def Main():
    start = time.time()

    entities = Node(Car(entry_road.Value, car_texture), Empty)
    entities = Node(Boat(entry_rivers.Value, boat_texture), entities)

    while True:
        pygame.event.wait()
        screen.fill(green)

        #here we draw the board, do not move
        _board = entry_road
        while not _board.IsEmpty:
            _board.Value.Draw(screen, False)
            _board = _board.Tail

        #here we draw the bridges, do not move
        _board = bridges
        while not _board.IsEmpty:
            _board.Value.Draw(screen, True)
            _board = _board.Tail

        entities = Update(entities)
        Draw(entities)

        if random.randint(0, 100) < 5:
            entities = Node(Car(entry_road.Value, car_texture), entities)
        if random.randint(0, 100) < 5:
            entities = Node(Boat(entry_rivers.Value, boat_texture), entities)

        pygame.display.flip()
        time.sleep(0.1)
Exemple #3
0
def reset_boats():
    global BOATS, CONTROLLERS, WAYPOINT_QUEUE, WAYPOINTS_INDEX, WAYPOINTS_BEFORE_RESET, LAST_COMPLETED_WP_TIME, LAST_TIME, FIRST_TIME, TEXT_BOXES
    BOATS = {"pid": Boat.Boat(design=Designs.AirboatDesign()),
             "q": Boat.Boat(design=Designs.TankDriveDesign())}
    # generate all the random waypoints
    generate_random_waypoints_queue()
    waypoint = WAYPOINT_QUEUE[0]
    px, py = xy_location_to_pixel_location(waypoint[0], waypoint[1])
    LAST_TIME = 0
    FIRST_TIME = ptime.time()
    for k in BOATS:
        boat = BOATS[k]
        WAYPOINTS_INDEX[k] = 0
        LAST_COMPLETED_WP_TIME[k] = 0
        boat.state = np.zeros((6,))
        boat.time = 0
        boat.name = k + " boat"
        NAVIGATION_LINES[k].set_data(pos=np.array([(px, py), xy_location_to_pixel_location(boat.state[0], boat.state[1])], dtype=np.float32))
        TEXT_BOXES["waypoint_symbol"][k].pos = (px, py)
        TEXT_BOXES["waypoint_text"][k].text = "[{:.0f}, {:.0f}]".format(px, py)
        TEXT_BOXES["waypoint_count"][k].text = "#{} of {}".format(WAYPOINTS_INDEX[k] + 1, WAYPOINTS_BEFORE_RESET)
        #boat.strategy = Strategies.DestinationOnly(boat, waypoint, controller_name=CONTROLLERS[k])
        #boat.strategy = Strategies.LineFollower(boat, waypoint, controller_name=CONTROLLERS[k])
        if (k == "pid"):
            boat.strategy = Strategies.PseudoRandomBalancedHeading(boat, fixed_thrust=0.2, angle_divisions=8)
        else:
            boat.strategy = Strategies.DoNothing(boat)

        boat.sourceLocation = boat.state[0:2]
        boat.destinationLocation = waypoint
        boat.calculateQState()  # need to initialize the state for Q learning
Exemple #4
0
def setShips(shipList1, shipList2, board):
    # Declare ships for Team 1
    ship1 = Boat.Ship(1, 1)
    ship2 = Boat.Ship(1, 2)
    ship3 = Boat.Ship(1, 3)
    ship4 = Boat.Ship(1, 4)
    ship5 = Boat.Ship(1, 5)

    # Declare ships for Team 2
    ship6 = Boat.Ship(2, 1)
    ship7 = Boat.Ship(2, 2)
    ship8 = Boat.Ship(2, 3)
    ship9 = Boat.Ship(2, 4)
    ship10 = Boat.Ship(2, 5)


    # Team 1 Ships input
    print("Team 1 place your ships")
    for ship in [ship1, ship2, ship3, ship4, ship5]:
        shipInputLoop(shipList1, ship, board)

    # Team 2 Ships input
    print("Team 2 place your ships")
    for ship in [ship6, ship7, ship8, ship9, ship10]:
        shipInputLoop(shipList2, ship, board)
Exemple #5
0
 def event_mousebuttondown(self, event, occupied_spaces, vertical, i):
     x_disp, y_disp = event.pos
     x_grid, y_grid = (x_disp // 80), (y_disp // 80)
     if vertical and y_grid <= 9 - i + 1:  # bateau vertical
         points_list = []
         flag = True
         for k in range(i):  # test de validité de l'emplacement
             if (x_grid, y_grid + k) in occupied_spaces:
                 flag = False
                 break
             points_list.append((x_grid, y_grid + k))
         if flag:
             self.floating_boat.append(Boat(
                 i, points_list))  # creation du bateau
             self.grid[x_grid, y_grid:y_grid + i] = [i] * i
             for k in range(i):  # actualisation des emplacements occupés
                 occupied_spaces.append((x_grid, y_grid + k))
             return False
     if not vertical and x_grid <= 9 - i + 1:  # bateau horizontal
         points_list = []
         flag = True
         for k in range(i):  # test de validité de l'emplacement
             if (x_grid + k, y_grid) in occupied_spaces:
                 flag = False
                 break
             points_list.append((x_grid + k, y_grid))
         if flag:
             self.floating_boat.append(Boat(
                 i, points_list))  # creation du bateau
             self.grid[x_grid:x_grid + i, y_grid] = [i] * i
             for k in range(i):  # actualisation des emplacements occupés
                 occupied_spaces.append((x_grid + k, y_grid))
             return False
     return True
    def place_boats(self):
        """
        :return listofboards:
         Function to place boat in the board. The function performs a validation(See validation function description below)
         If the validation returns True, the boat is placed on the board, using random generated numbers for column and row.
         The place function is described below.

        """
        boatclass = Boat()
        boardclass = Board()
        boardlist = boardclass.create_two_boards()
        fullboatlist = boatclass.create_boats()
        newboardlist = []
        for boardindex, board in enumerate(boardlist):
            for boatlists in fullboatlist:
                for boat in boatlists:
                    vertical_or_horizontal = random.randint(0, 1)
                    placement_ok = False
                    while not placement_ok:
                        a = random.randint(1, 10) - 1
                        b = random.randint(1, 10) - 1
                        placement_ok = self.validate_placement_coordinates(
                            board, boat, vertical_or_horizontal, a, b)
                    board, placement_ok = self.place_out_boats(
                        board, boat, vertical_or_horizontal, a, b)
            newboardlist.append(board)
        return newboardlist
Exemple #7
0
 def __init__(self):
     InstructionsScene.__init__(self)
     #Back button
     self.xCoordB = 10
     self.yCoordB = self.yCoordC
     self.initX, self.initY, self.initAngle = (40,300,-90)
     self.boat = Boat(self.initX, self.initY, self.initAngle)
Exemple #8
0
 def __init__(self):
     #Player's boat
     EasyRace.buoyList = []
     EasyRace.autoBoats = []
     self.boat = Boat(50,150,-90)
     DemoScene.__init__(self)
     
     #AI Boats
     autoBoat1 = AutoBoat(50,300, -90,1,1)
     EasyRace.autoBoats.append(autoBoat1)
     autoBoat2= AutoBoat(50,230,-90,1,3)
     EasyRace.autoBoats.append(autoBoat2)
     
     #Start and ending coordinates
     self.xStart = 100
     self.yStart = 100
     self.yEnd = 500
     
     #Create new buoys
     buoy1 = Buoy(600,200,False,True,False,True)
     EasyRace.buoyList.append(buoy1)
     buoy2 = Buoy(400,450,True,False,True,True)
     EasyRace.buoyList.append(buoy2)
     
     self.started = False
     self.finished = False
     self.nextScene = TitleScene()
     
     self.text = "Let's go!"
Exemple #9
0
def TwoChildrenSol(lst):
    lst.sort()
    N = len(lst)
    if N == 0:
        return []
    if N == 1:
        b = Boat.Boat(1)
        b.seat(lst[0])
        return [b]
    sol = []
    sol2 = TwoBoysCanoe.canoes(lst)
    for (x, y) in sol2:
        b = Boat.Boat(2)
        b.seat(x)
        if y:
            b.seat(y)
        sol.append(b)
    return sol
Exemple #10
0
def iterate(event):  # event is unused
    global FIRST_TIME, LAST_TIME, BOATS, CANVAS, TIME_DILATION, LAST_COMPLETED_WP_TIME, FAILED_WAYPOINT_TIMEOUT, WAYPOINTS_INDEX, CONTROLLERS, WAYPOINT_QUEUE
    global TEXT_BOXES, EXPERIENCES, TOTAL_ITERATIONS, NAVIGATION_LINES, TOTAL_BATCHES
    if TOTAL_ITERATIONS < 1:
        FIRST_TIME = ptime.time()  # there is a huge gap in time as the window opens, so we need this manual time reset for the very first iteration
    TOTAL_ITERATIONS += 1
    current_time = TIME_DILATION*(ptime.time() - FIRST_TIME)
    # print "Total iterations = {}, t = {}".format(TOTAL_ITERATIONS, current_time)
    TEXT_BOXES["time"].text = "t = {}".format(format_time_string(current_time, 2))
    # USE ODE TO PROPAGATE BOAT STATE
    times = np.linspace(LAST_TIME, current_time, 100)
    for k in BOATS:
        boat = BOATS[k]
        boat.control()
        # if the boat actually changes action, we should create a Q learning experience
        # (i.e. BEFORE we change actions here, the state before ode is s' in (s, a, r, s')
        # The experience is created in boat.control() right before new actions are selected
        boat.time = current_time
        states = spi.odeint(Boat.ode, boat.state, times, (boat,))
        boat.state = states[-1]
        boat.state[4] = Boat.wrapToPi(boat.state[4])
        px, py = xy_location_to_pixel_location(states[-1][0], states[-1][1])
        heading = Boat.wrapTo2Pi(states[-1][4])
        BOAT_VISUALS[k].new_pose(px, py, heading)
        if boat.strategy.finished or current_time - LAST_COMPLETED_WP_TIME[k] > FAILED_WAYPOINT_TIMEOUT:
            WAYPOINTS_INDEX[k] += 1
            LAST_COMPLETED_WP_TIME[k] = current_time
            if WAYPOINTS_INDEX[k] < len(WAYPOINT_QUEUE):
                waypoint = WAYPOINT_QUEUE[WAYPOINTS_INDEX[k]]
                px, py = xy_location_to_pixel_location(waypoint[0], waypoint[1])
                NAVIGATION_LINES[k].set_data(pos=np.array([(px, py), xy_location_to_pixel_location(boat.state[0], boat.state[1])], dtype=np.float32))
                TEXT_BOXES["waypoint_symbol"][k].pos = (px, py+15)  # py-0.5*fontsize to center the text vertically
                TEXT_BOXES["waypoint_text"][k].text = "[{:.0f}, {:.0f}]".format(px, py)
                TEXT_BOXES["waypoint_count"][k].text = "#{} of {}".format(WAYPOINTS_INDEX[k]+1, WAYPOINTS_BEFORE_RESET)
                #boat.strategy = Strategies.DestinationOnly(boat, waypoint, controller_name=CONTROLLERS[k])
                boat.strategy = Strategies.LineFollower(boat, waypoint, controller_name=CONTROLLERS[k])
                boat.sourceLocation = boat.state[0:2]
                boat.destinationLocation = waypoint
    if not WAYPOINTS_INDEX["pid"] < WAYPOINTS_BEFORE_RESET or not WAYPOINTS_INDEX["q"] < WAYPOINTS_BEFORE_RESET:
        TOTAL_BATCHES += 1
        reset_boats()
    else:
        LAST_TIME = current_time
    CANVAS.update()
Exemple #11
0
def fillboat(lst, indices):
    b = Boat.Boat(len(indices))
    leftover = lst[:]
    offset = 0
    for i in indices:
        if b.fits(lst[i]):
            b.seat(lst[i])
            del leftover[i - offset]
            offset += 1
    return b, leftover
Exemple #12
0
def basecase(N, lst):
    if N == 0:
        return []
    if lst[N - 1] > 150:
        return False
    if N == 1:
        b = Boat.Boat3()
        b.seat(lst[0])
        return [b]
    if N == 2:
        b = Boat.Boat3()
        b.seat(lst[0])
        if b.fits(lst[1]):
            b.seat(lst[1])
            return [b]
        else:
            b2 = Boat.Boat3()
            b2.seat(lst[1])
            return [b, b2]
Exemple #13
0
def TwoChildrenSol(lst):
    lst.sort()
    sol = []
    sol2 = TwoBoysCanoe.canoes(lst)
    for (x, y) in sol2:
        b = Boat.Boat3()
        b.seat(x)
        if y:
            b.seat(y)
        sol.append(b)
    return sol
Exemple #14
0
def fillboat(lst, i, j, k):
    b = Boat.Boat3()
    b.seat(lst[i])
    leftover = lst[:]
    del leftover[i]
    if b.fits(lst[j]):
        b.seat(lst[j])
        del leftover[j - 1]
        if b.fits(lst[k]):
            b.seat(lst[k])
            del leftover[k - 2]
    return b, leftover
Exemple #15
0
 def __init__(self):
     #Instantiate boat
     self.boat = Boat(30,180,-90)
     self.autoBoat = AutoBoat(30,240,-90,"tutorials",1)
     DemoScene.__init__(self)
     
     #Starting line
     self.xStart = 100
     self.xEnd = 700
     self.yTop = 10
     self.yBottom = 300
     
     self.nextScene = ReachDemo2()
Exemple #16
0
    def Update(self):
        kaas = random.randint(0, 7)
        if kaas == 0 and self.Tile.Right != None and self.Tile.Right.River or kaas == 0 and self.Tile.Right != None and self.Tile.Right.River and self.Tile.Right.Bridge:
            boatLoc = self.Tile.Right
        elif kaas == 1 and self.Tile.Left != None and self.Tile.Left.River or kaas == 1 and self.Tile.Left != None and self.Tile.Left.River and self.Tile.Left.Bridge:
            boatLoc = self.Tile.Left
        elif kaas == 2 and self.Tile.Up != None and self.Tile.Up.River or kaas == 2 and self.Tile.Up != None and self.Tile.Up.River and self.Tile.Up.Bridge:
            boatLoc = self.Tile.Up
        elif kaas == 3 and self.Tile.Down != None and self.Tile.Down.River or kaas == 3 and self.Tile.Down != None and self.Tile.Down.River and self.Tile.Down.Bridge:
            boatLoc = self.Tile.Down
        else:
            boatLoc = self.Tile

        return Boat(boatLoc, self.Texture)
Exemple #17
0
    def __init__(self, frame):
        self.width = 0
        self.height = 0
        self.frame = frame
        self.width, self.height = pygame.display.get_surface().get_size()

        pygame.display.set_caption("Fishin' Mission")
        self.frame.fill((135, 206, 235))
        self.cloud = Clouds.Clouds(self.frame)
        self.fisher = Fisher.Fisher(self.frame)
        self.boat = Boat.Boat(self.frame)
        self.rod = Rod.Rod(self.frame)
        self.wave = Waves.Waves(self.frame)
        self.score = Score.Score(self.frame)
        self.upgrades = Upgrades.Upgrades(self.frame)
        self.trash_list = []
        self.trash_interval = 6
        self.start_time = time.time()
        self.fish1_list = []
        self.fish2_list = []
        self.fish3_list = []
        self.fish1_interval = 10
        self.fish2_interval = 5
        self.fish3_interval = 20
        self.trashCount = 0
        self.fish1Count = 0
        self.fish2Count = 0
        self.fish3Count = 0

        # Load Fish Images
        self.image1 = pygame.image.load('images/small fish.png')
        self.image2 = pygame.image.load('images/medium sized fish.png')
        self.image3 = pygame.image.load('images/big fish.png')
        self.fish1width = 117
        self.fish1height = 117
        self.fish2width = 146
        self.fish2height = 146
        self.fish3width = 176
        self.fish3height = 176
        self.image1 = pygame.transform.scale(
            self.image1, (self.fish1width, self.fish1height))
        self.image2 = pygame.transform.scale(
            self.image2, (self.fish2width, self.fish2height))
        self.image3 = pygame.transform.scale(
            self.image3, (self.fish3width, self.fish3height))
Exemple #18
0
def fullest_boat(k, lst):
    N = len(lst)
    if N == 0:
        return Boat(k), lst
    if k == 0:
        return False, lst
    if N < k:
        b, lo = fullest_boat(k - 1, lst)
        if b == False:
            return False, lo
        else:
            b.expand(k)
            return b, lo
    # In this case no combination of children can fill a boat
    if sum(map(lambda (x): lst[x], range(0, k))) > 150:
        b, lo = fullest_boat(k - 1, lst)
        b.expand(k)
        return b, lo
Exemple #19
0
from Vehicle_parent import *
from car_class import *
from Bike_class import *
from Boat import *
print('////////////////////////////////////////////////////////////////')
vehicle_1 = Vehicle(4, 6, 'blue', 1996)
print(vehicle_1.wheels)
print(vehicle_1.capacity)
print(vehicle_1.colour)
print(vehicle_1.accelerate())
print(vehicle_1.make_sound())
print('////////////////////////////////////////////////////////////////')

car_1 = Car(4, 5, 'pink', 2005, 'peagueot', '305tdi', 'ee45thg', 'yes')
print(car_1.wheels)
print(car_1.capacity)

print(car_1.accelerate())
print('////////////////////////////////////////////////////////////////')
bike_1 = Bike(2, 1, 'green', 2012, 21, 'professional', 'small')

print(bike_1.make_sound())
print('////////////////////////////////////////////////////////////////')
boat_1 = Boat(0, 1000, 'red', 1830, 100000000, 'jet')

print(boat_1.make_sound())
print(boat_1.wave())
print('////////////////////////////////////////////////////////////////')

print(car_1.turn('left'))
Exemple #20
0
 def init_bot(self):
     occupied_places = []
     for i in range(5, 1, -1):
         for j in range(list_boats[i - 2]):
             flag = True
             m = 0
             while flag and m < 10000:
                 x, y, alpha = randint(0, 9), randint(0, 9), randint(0, 1)
                 for k in range(4):
                     if (k + alpha) % 4 == 0:
                         if y + i < 10 and (self.grid[x, y:y + i]
                                            == np.zeros(i)).all():
                             flag2 = True
                             for n in range(i):
                                 if (x, y + n) in occupied_places:
                                     flag2 = False
                             if flag2:
                                 flag = False
                                 points_list = []
                                 for n in range(i):
                                     points_list.append((x, y + n))
                                     occupied_places.append((x, y + n))
                                 self.floating_boat.append(
                                     Boat(i, points_list))
                                 self.grid[x, y:y + i] = [i] * i
                                 break
                     if k + alpha == 1:
                         if x + i < 10 and (self.grid[x:x + i, y]
                                            == np.zeros(i)).all():
                             flag2 = True
                             for n in range(i):
                                 if (x + n, y) in occupied_places:
                                     flag2 = False
                             if flag2:
                                 flag = False
                                 points_list = []
                                 for n in range(i):
                                     points_list.append((x + n, y))
                                     occupied_places.append((x + n, y))
                                 self.floating_boat.append(
                                     Boat(i, points_list))
                                 self.grid[x:x + i, y] = [i] * i
                                 break
                     if k + alpha == 2:
                         if y - i >= 0 and (self.grid[x, y - i:y]
                                            == np.zeros(i)).all():
                             flag2 = True
                             for n in range(i):
                                 if (x, y - n) in occupied_places:
                                     flag2 = False
                             if flag2:
                                 flag = False
                                 points_list = []
                                 for n in range(i):
                                     points_list.append(
                                         (x, y - n)
                                     )  # coordonnées distribuées à l'envers
                                     occupied_places.append((x, y - n))
                                 self.floating_boat.append(
                                     Boat(i, points_list))
                                 self.grid[x, y - i:y] = [i] * i
                                 break
                     if (k + alpha) == 3:
                         if x - i >= 0 and (self.grid[x - i:x, y]
                                            == np.zeros(i)).all():
                             flag2 = True
                             for n in range(i):
                                 if (x - n, y) in occupied_places:
                                     flag2 = False
                             if flag2:
                                 flag = False
                                 points_list = []
                                 for n in range(i):
                                     points_list.append((x - n, y))
                                     occupied_places.append((x - n, y))
                                 self.floating_boat.append(
                                     Boat(i, points_list))
                                 self.grid[x - i:x, y] = [i] * i
                                 break
                 m += 1
Exemple #21
0
class EasyRace(DemoScene):
    
    buoyList = []
    autoBoats = []
    
    def __init__(self):
        #Player's boat
        EasyRace.buoyList = []
        EasyRace.autoBoats = []
        self.boat = Boat(50,150,-90)
        DemoScene.__init__(self)
        
        #AI Boats
        autoBoat1 = AutoBoat(50,300, -90,1,1)
        EasyRace.autoBoats.append(autoBoat1)
        autoBoat2= AutoBoat(50,230,-90,1,3)
        EasyRace.autoBoats.append(autoBoat2)
        
        #Start and ending coordinates
        self.xStart = 100
        self.yStart = 100
        self.yEnd = 500
        
        #Create new buoys
        buoy1 = Buoy(600,200,False,True,False,True)
        EasyRace.buoyList.append(buoy1)
        buoy2 = Buoy(400,450,True,False,True,True)
        EasyRace.buoyList.append(buoy2)
        
        self.started = False
        self.finished = False
        self.nextScene = TitleScene()
        
        self.text = "Let's go!"
        
    def timerFired(self):
        #Store old position in case of collision
        self.oldX = self.boat.x
        self.oldY = self.boat.y
        self.boat.updatePosition()
        self.checkCollide()
        self.checkFinish()
        for autoBoat in EasyRace.autoBoats:
            autoBoat.updatePosition()
            
        #For autoboats
        for boat in xrange(len(EasyRace.autoBoats)):
            self.timeElapsed = pygame.time.get_ticks() - self.startTime
            path = EasyRace.autoBoats[boat].movements
            
            if len(path) != 0 and self.timeElapsed > int(path[0][4]):
                EasyRace.autoBoats[boat].x = float(path[0][0])
                EasyRace.autoBoats[boat].y = float(path[0][1])
                EasyRace.autoBoats[boat].boatAngle = float(path[0][2])
                EasyRace.autoBoats[boat].sailAngle = float(path[0][3])
                if len(path)!= 0:
                     EasyRace.autoBoats[boat].movements = path[1:]

    def processInput(self, events, pressed_keys):
        DemoScene.processInput(self,events,pressed_keys)
 
    def checkStarted(self): #check if boat crossed start line
        margin = 50
        if not self.started:
            if self.boat.x > self.xStart:
                if self.boat.y > self.yStart - margin:
                    if self.boat.y < self.yStart + margin:
                        self.started = True
                        
    def checkFinished(self): #check if boat crossed finish line
        margin = 50
        if self.boat.x < self.xStart:
            if self.boat.y > self.yStart - margin:
                if self.boat.y < self.yEnd + margin:
                    return True
        return False
    
    def checkFinish(self): #wrapper function for mark rounding and finishing
        margin = 50
        self.checkStarted()
        if self.started:
            for buoys in EasyRace.buoyList:
                if buoys.hasRounded(self.boat.x,self.boat.y) == False:
                    return False
            if self.checkFinished():
                self.finished = True
                return True

    def checkCollide(self):
        for buoy in EasyRace.buoyList:
            if pygame.sprite.collide_rect(buoy,self.boat):
                self.boat.x = self.oldX
                self.boat.y = self.oldY
        for autoboat in EasyRace.autoBoats:
            if pygame.sprite.collide_rect(autoboat,self.boat):
                self.boat.x = self.oldX
                self.boat.y = self.oldY
 
    def drawStartEnd(self,screen):
        xStart = self.xStart
        yStart = self.yStart
        yEnd = self.yEnd
        thick = 10
        #start and finish line same
        if self.started:
            color = (0,255,0) #green
        else:
            color = self.black
        pygame.draw.line(screen,color,(xStart,yStart),(xStart,yEnd),thick)
  
    def drawBuoys(self,screen):
        for i in xrange(len(EasyRace.buoyList)):
            buoy = EasyRace.buoyList[i]
            buoy.drawBuoy(screen,i)

    def drawBoat(self,screen):
        self.boat.drawBoat(screen)
        for autoBoat in EasyRace.autoBoats:
            autoBoat.drawBoat(screen)
  
    def drawSail(self,screen):
        self.boat.drawSail(screen)
        for autoBoat in EasyRace.autoBoats:
           autoBoat.drawSail(screen)
    
    def updateScreen(self,screen): 
        self.drawBG(screen)
        self.drawInstruct(screen)
        self.drawStartEnd(screen)
        self.drawWin(screen)
        self.drawBoat(screen)
        self.drawLoose(screen)
        self.drawSail(screen)
        self.drawBuoys(screen)
        self.drawReturnButton(screen)
        pygame.display.update()
Exemple #22
0
class ReachDemo1(DemoScene):
    def __init__(self):
        #Instantiate boat
        self.boat = Boat(30,180,-90)
        self.autoBoat = AutoBoat(30,240,-90,"tutorials",1)
        DemoScene.__init__(self)
        
        #Starting line
        self.xStart = 100
        self.xEnd = 700
        self.yTop = 10
        self.yBottom = 300
        
        self.nextScene = ReachDemo2()
        
    def processInput(self, events, pressed_keys):
        #Handle key and mouse press events
        for event in events:
            if event.type == pygame.KEYUP:
                if event.key == pygame.K_UP:
                    #sail moves clockwise
                    self.boat.moveSailCCW = False
                elif event.key == pygame.K_DOWN:
                    #sail moves anticlockwise
                    self.boat.moveSailCW = False
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_UP:
                    #sail moves clockwise
                    self.boat.moveSailCCW = True
                elif event.key == pygame.K_DOWN:
                    #sail moves anticlockwise
                    self.boat.moveSailCW = True
                elif event.key == pygame.K_RETURN and self.finished:
                    self.switchToScene(ReachDemo2())
                    
            elif event.type == pygame.MOUSEBUTTONDOWN:
                (x,y) = pygame.mouse.get_pos()
                if x > self.xCoord and x < self.xCoord + self.but2Width:
                    if y > self.yCoord and y < self.yCoord + self.but2Height:
                        self.switchToScene(TitleScene())
        
    def checkFinish(self):
        margin = 30
        if self.boat.x > self.xEnd and self.boat.y < self.yBottom + margin:
            self.finished = True
            return True
        return False
    
    def timerFired(self):
        self.boat.updatePosition()
        self.checkFinish()
        self.checkLose()
        #Demo boat
        self.timeElapsed = pygame.time.get_ticks() - self.startTime
        path = self.autoBoat.movements
            
        if len(path) != 0 and self.timeElapsed > int(path[0][4]):
            self.autoBoat.x = float(path[0][0])
            self.autoBoat.y = float(path[0][1])
            self.autoBoat.boatAngle = float(path[0][2])
            self.autoBoat.sailAngle = float(path[0][3])
            if len(path)!= 0:
                 self.autoBoat.movements = path[1:]
        self.autoBoat.updatePosition()
    
    def drawStartEnd(self,screen):
        thickness = 10
        #Start line
        (xStart, xEnd) = (self.xStart,self.xEnd)
        (yTop, yBottom) = (self.yTop,self.yBottom)
        pygame.draw.line(screen,(self.black),
                         (xStart,yTop),(xStart,yBottom),thickness)
        #Finish line
        pygame.draw.line(screen,(self.black),
                         (xEnd,yTop),(xEnd,yBottom),thickness)
        
        #Start line label
        fontSize = 20
        (xAdj, yAdj) = (15,20) #Make it centered where lines are
        font = pygame.font.Font("data/font/BradBunR.ttf",fontSize)
        text1 = "Start"
        label1 = font.render(text1,1,self.black)
        screen.blit(label1,(xStart-xAdj,yBottom+yAdj))
        
        #End line label
        (xAdj,yAdj) = (10, 20)
        text2 = "End"
        label2 = font.render(text2,1,self.black)
        screen.blit(label2,(xEnd-xAdj,yBottom+yAdj))
Exemple #23
0
class InstructionsScene2(InstructionsScene):
    def __init__(self):
        InstructionsScene.__init__(self)
        #Back button
        self.xCoordB = 10
        self.yCoordB = self.yCoordC
        self.initX, self.initY, self.initAngle = (40,300,-90)
        self.boat = Boat(self.initX, self.initY, self.initAngle)

    def processInput(self, events, pressed_keys):
        InstructionsScene.processInput(self,events,pressed_keys)
        for event in events:
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_BACKSPACE:
                    self.switchToScene(InstructionsScene())
                elif event.key == pygame.K_RETURN:
                    self.switchToScene(InstructionsScene3())
            elif event.type == pygame.MOUSEBUTTONDOWN:
                (x,y) = pygame.mouse.get_pos()
                if x > self.xCoordB and x < self.xCoordB + self.but2Width:
                    if y>self.yCoordB and y <self.yCoordB+self.but2Height:
                        self.switchToScene(InstructionsScene())
                elif x > self.xCoordC and x < self.xCoordC+self.but2Width:
                    if y>self.yCoordB and y < self.yCoordB+self.but2Height:
                        self.switchToScene(InstructionsScene3())
    
    def timerFired(self):
        optimumAngle = -45
        demoWidth = 800
        if self.boat.sailAngle <= optimumAngle:
            self.boat.sailAngle += 1
        if self.boat.x <= demoWidth:
            self.boat.updatePosition()
            self.boat.x += 2 #force boat to move straight across screen
            self.boat.y = self.initY
        else: #restart boat movement
            self.boat.sailAngle = self.initAngle
            self.boat.x = self.initX
            
    def chooseColor(self):
        butWidth = 180
        (x,y) = pygame.mouse.get_pos()
        if x > self.xCoordB and x < self.xCoordB + butWidth:
            if y > self.yCoordC and y < self.yCoordC + butWidth:
                return self.buttonHover
        return self.buttonImg
                        
    def drawDemo(self,screen):
        img = pygame.image.load(self.path+"example.png")
        xCoord = 0
        yCoord = 140
        screen.blit(img,(xCoord,yCoord))
        self.boat.drawBoat(screen)
        self.boat.drawSail(screen)
        
    def drawInstructions(self,screen):
        text = "Aim: Propel your boat to the finish line with the wind's help!"
        font = pygame.font.Font("data/font/BradBunR.ttf",30)
        label = font.render(text,1,self.white)
        xCoord,yCoord = 80,100
        screen.blit(label,(xCoord,yCoord))
        self.drawDemo(screen)
    
    def drawButtons(self,screen):
        InstructionsScene.drawButtons(self,screen)
        #Back button
        screen.blit(self.chooseColor(),(self.xCoordB,self.yCoordB))
        text = "Back"
        label2 = self.font.render(text,1,self.white)
        xAdj = 50
        yAdj = 25
        screen.blit(label2,(self.xCoordB+xAdj,self.yCoordB+yAdj))
        SceneBase.updateScreen(self,screen)
Exemple #24
0
                "q": BoatNode(ARENA_CENTER[0], ARENA_CENTER[1], 0, 20, 40, COLORS["q"], parent=CANVAS.scene)}

NAVIGATION_LINES = {"pid": scene.visuals.Line(pos=np.zeros((2, 2), dtype=np.float32), color=COLORS["pid"], parent=CANVAS.scene),
                    "q": scene.visuals.Line(pos=np.zeros((2, 2), dtype=np.float32), color=COLORS["q"], parent=CANVAS.scene)}
NAVIGATION_LINES["pid"].transform = scene.transforms.STTransform()
NAVIGATION_LINES["q"].transform = scene.transforms.STTransform()

TEXT_BOXES = {"time": TextNode("t = ", pos=(ARENA_WIDTH + 100, 30), parent=CANVAS.scene, bold=True, font_size=30),
              "waypoint_symbol": {"pid": TextNode("+", pos=(0, 0), parent=CANVAS.scene, bold=True, font_size=40, color=COLORS["pid"]),
                                  "q": TextNode("o", pos=(0, 0), parent=CANVAS.scene, bold=True, font_size=30, color=COLORS["q"])},
              "waypoint_text": {"pid": TextNode("[]", pos=(ARENA_WIDTH + 100, 70), parent=CANVAS.scene, bold=True, font_size=30, color=COLORS["pid"]),
                                "q": TextNode("[]", pos=(ARENA_WIDTH + 300, 70), parent=CANVAS.scene, bold=True, font_size=30, color=COLORS["q"])},
              "waypoint_count": {"pid": TextNode("#", pos=(ARENA_WIDTH + 100, 110), parent=CANVAS.scene, bold=True, font_size=30, color=COLORS["pid"]),
                                 "q": TextNode("#", pos=(ARENA_WIDTH + 300, 110), parent=CANVAS.scene, bold=True, font_size=30, color=COLORS["q"])}}

BOATS = {"pid": Boat.Boat(),
         "q": Boat.Boat()}

WAYPOINTS_INDEX = {"pid": 0,
                   "q": 0}

CONTROLLERS = {"pid": "PointAndShoot",
               "q": "QLearnPointAndShoot"}

EXPERIENCES = {"pid": list(),
               "q": list()}

WAYPOINT_QUEUE = list()

TOTAL_ITERATIONS = 0
TOTAL_BATCHES = 0