Beispiel #1
0
def goal_scenario(simulation_variables: Dict) -> World:
    world = World(WORLD_WIDTH, WORLD_HEIGHT)

    for i in range(CAR_COUNT):
        car_x = randrange(1, WORLD_WIDTH / 3)
        car_y = randrange(1, WORLD_HEIGHT)
        car_angle = randrange(0, 360)
        new_car = Car(CAR_LENGTH,
                      CAR_WIDTH,
                      CAR_WHEELBASE,
                      CAR_MAX_VELOCITY,
                      CAR_MAX_ACCELERATION,
                      CAR_MAX_STEERING_ANGLE,
                      CAR_MAX_STEERING_CHANGE,
                      x=car_x,
                      y=car_y,
                      acceleration=2,
                      steering_angle=0,
                      angle=car_angle)
        world.cars.append(new_car)

    world.goal = Goal(WORLD_WIDTH * 5 / 6, WORLD_HEIGHT / 2, True)

    return world
        plt.title('Location of Agents and Goals')
        plt.xticks(range(self.grid_width))
        plt.yticks(range(self.grid_height))
        plt.grid()
        plt.legend(loc=2)
        plt.show()

    def summary(self):
        agent_summary = [agent.summary() for agent in self.agents]
        goal_summary = [goal.summary() for goal in self.goals]
        return agent_summary, goal_summary


if __name__ == '__main__':
    # Test this class
    agent1 = Agent(pos_x=0, pos_y=0, capacity=10)
    agent2 = Agent(pos_x=1, pos_y=3, capacity=10)
    goal1 = Goal(pos_x=5, pos_y=5, capacity=10)
    goal2 = Goal(pos_x=5, pos_y=5, capacity=10)

    grid = Grid(agents=[agent1, agent2], goals=[goal1, goal2])
    '''    print('Initial grid')
        print(grid.summary())
        grid = grid.move([agent1], ['UP'], [goal1])
        print('Final grid')
        print(grid.summary())
    '''
    central_planner = CentralPlanner()
    central_planner.get_strategy(grid)
Beispiel #3
0
VIEW CONFIGURATION
------------------
"""
"""
Simulation (View)
"""
PIXEL_METER_RATIO = 8
"""
World (View)
"""
WORLD_COLOR = Color('white')
"""
Wall (View)
"""
WALL_COLOR = Color('black')
"""
Goal (View)
"""
GOAL_COLOR = Color('blue')
"""
Car (View)
"""
CAR_IMAGE_PATH = "car.png"
"""
Vector (View)
"""
VECTOR_COLOR = Color('red')


def open_scenario(simulation_variables: Dict) -> World:
    world = World(WORLD_WIDTH, WORLD_HEIGHT)
Beispiel #4
0
def gameLoop(
        level):  # allows for separate handling of exit bomber and bomber over

    gameExit = False
    gameOver = False
    win = False

    time1 = time.time()

    bomb_list = []
    primed_bomb_queue = []
    bomb_expl_queue = []
    wall_list = []
    bullet_list = []
    enemy_list = []
    x = 0
    y = 0

    for row in level.load_lvl():

        for col in row:
            if col == "W":  # denotes a wall
                #print(x)
                wall_list.append(Wall(x, y, 15))  # stores a list of all walls
            elif col == "H":  # denotes an enemy that moves horizontally
                enemy_list.append(EnemyHori(x, y))
            elif col == "V":
                enemy_list.append(EnemyVert(x, y))
            elif col == "G":
                goal = Goal(x, y)
            elif col == "P":
                player = Player(x, y)
            elif col == "C":
                wall_list.append(Cracked_Wall(x, y, 15))
                #crack_wall_list.append(Cracked_Wall(x, y, 15))
            elif col == "B":
                bullet_list.append(Bullet(x, y, "west"))
            elif col == "+":
                enemy_list.append(EnemyShooterCross(x, y))
            elif col == "c":
                enemy_list.append(EnemyCharger(x, y))
            x += 15
        y += 15
        x = 0
    #camera = Camera(level.get_map_width(), level.get_map_height(), display_width, display_height)

    while not gameExit:  # event handler
        #if pygame.key.get_repeat() != (1,30):
        #   pygame.key.set_repeat(1,30)
        pygame.event.pump()

        for event in pygame.event.get():
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_q:
                    gameExit = True
                    win = False

        while gameOver == True:

            message_to_screen("Game over, press C to continue or Q to quit",
                              red)
            pygame.display.update()

            for event in pygame.event.get():
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_q:
                        gameExit = True
                        gameOver = False
                    if event.key == pygame.K_c:  # restart bomber
                        print("hi")
                        gameOver = False
                        pygame.event.clear()
                        gameLoop(level)
        while win == True:
            message_to_screen("You win! Press C to play again or Q to quit",
                              green)
            pygame.display.update()

            for event in pygame.event.get():
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_q:

                        gameExit = True
                        win = False

                    if event.key == pygame.K_c:  # restart bomber
                        win = False
                        level.next_lvl()
                        gameLoop(level)

        #keys = pygame.key.get_pressed()  # checking pressed keys

        #controls player movement
        player.get_key_press(wall_list, bomb_list, primed_bomb_queue,
                             bomb_expl_queue)

        #bullet behavior
        for bullet in bullet_list:
            bullet.move(bullet_list, wall_list)

        # enemy behavior
        for enemy in enemy_list:
            time2 = time.time()
            elaspe_time = time2 - time1
            if type(enemy) is EnemyCharger:
                enemy.move(wall_list, player, elaspe_time)
            elif type(enemy) is not EnemyShooterCross:
                enemy.move(wall_list)
            if enemy.touch_explosion(bomb_expl_queue):
                enemy_list.remove(enemy)

        for enemy in enemy_list:
            time2 = time.time()
            elaspe_time = time2 - time1
            if type(enemy) is EnemyShooterCross:
                #print (elaspe_time%3)
                # this controls how fast the bullets are fired. Lower the mod, the faster the rate of fire
                # changed bounds to control number of bullets fired at once
                if (elaspe_time) % 2 >= 1 and elaspe_time % 2 < 1.15:
                    # t = Timer(.5, enemy.shoot, [bullet_list])
                    # t.start()
                    enemy.shoot(bullet_list)

        # Game Over and level end conditions
        if player.touch_explosion(bomb_expl_queue):
            gameOver = True
        if player.touch_enemy(enemy_list) and player.player_health < 0:
            gameOver = True
        if player.touch_bullet(bullet_list) and player.player_health < 0:
            gameOver = True
        if player.touch_goal(goal):
            win = True

        for wall in wall_list:
            if type(wall) is Cracked_Wall:
                if wall.touch_explosion(bomb_expl_queue):

                    wall_list.remove(wall)

        # Render things

        gameDisplay.fill(white)  # can use to clear stuff

        for wall in wall_list:
            if type(wall) is Cracked_Wall:
                gameDisplay.blit(brick_wall__crack_img,
                                 (wall.get_xpos(), wall.get_ypos()))
                #gameDisplay.blit(brick_wall__crack_img, (camera.apply(wall)))

            #gameDisplay.fill(wall.get_color(), rect=wall.rect)
            else:
                gameDisplay.blit(brick_wall_img,
                                 (wall.get_xpos(), wall.get_ypos()))
                #gameDisplay.blit(brick_wall_img,(camera.apply(wall)))

        display_primed_bomb(primed_bomb_queue)

        for enemy in enemy_list:
            if type(enemy) is EnemyCharger:
                enemy.sight(gameDisplay)
            #gameDisplay.fill(enemy.get_color(), rect=enemy.rect)
            #gameDisplay.blit(enemy.image,camera.apply(enemy))
        for bullet in bullet_list:

            gameDisplay.fill(bullet.get_color(), rect=bullet.rect)
            print(gameDisplay.fill(bullet.get_color(), rect=bullet.rect))
        gameDisplay.fill(goal.get_color(), rect=goal.rect)
        #gameDisplay.fill(blue, rect=player.rect)  # where we draw guy. superior way of drawing rectangles
        gameDisplay.blit(player.image,
                         (player.get_player_posx(), player.get_player_posy()))

        for explosion in bomb_expl_queue:
            explosion.display_explosion(bomb_expl_queue, gameDisplay)
        player.draw_health(gameDisplay)
        #camera.update(player)
        pygame.display.update()

        clock.tick(FPS)

    pygame.quit()
    quit()
Beispiel #5
0
    def __init__(self):
        self.checkErrors = pygame.init()
        if self.checkErrors[1] > 0:
            print("(!) Had {0} initializign errors...exiting".format(
                self.checkErrors[1]))
            sys.exit(-1)
        else:
            print("(+) Game initialized successfully")
        self.background = pygame.image.load("bg1.png")
        # Screen
        size = (800, 600)
        self.screen = pygame.display.set_mode(size)
        pygame.display.set_caption("Car Game")
        # List for all the sprites in the game

        self.all_sprites_list = pygame.sprite.Group()
        self.all_blocks_list = pygame.sprite.Group()
        self.all_goals_list = pygame.sprite.Group()

        # The player sprite

        self.playerCar = Car("car.png", (300, 500))
        self.all_sprites_list.add(self.playerCar)
        self.goals = Goal("track_goal.png", (300, 120))
        self.all_sprites_list.add(self.goals)
        self.all_goals_list.add(self.goals)

        self.obstacles = {}
        # The obstacle sprite
        """self.obstacles[0] = Obstacle("obstacleType1.png", (300, 200))
        self.all_sprites_list.add(self.obstacles[0])
        self.all_blocks_list.add(self.obstacles[0])

        for i in range(1, 6):
            self.obstacles[i] = Obstacle("obstacleType1.png", self.obstacles[i - 1].rect.topright)
            self.all_sprites_list.add(self.obstacles[i])
            self.all_blocks_list.add(self.obstacles[i])
        self.obstacles[10] = Obstacle("obstacleType1.png", self.obstacles[5].rect.bottomleft)
        self.all_sprites_list.add(self.obstacles[10])
        self.all_blocks_list.add(self.obstacles[10])
        for i in range(11, 14):
            self.obstacles[i] = Obstacle("obstacleType1.png", self.obstacles[i - 1].rect.bottomleft)
            self.all_sprites_list.add(self.obstacles[i])
            self.all_blocks_list.add(self.obstacles[i])"""

        self.obstacles[16] = Obstacle("obstacleType1.png", (0, 0), "top")
        self.all_sprites_list.add(self.obstacles[16])
        self.all_blocks_list.add(self.obstacles[16])
        for i in range(17, 36):
            self.obstacles[i] = Obstacle("obstacleType1.png",
                                         self.obstacles[i - 1].rect.topright,
                                         "top")
            self.all_sprites_list.add(self.obstacles[i])
            self.all_blocks_list.add(self.obstacles[i])

        self.obstacles[37] = Obstacle("obstacleType1.png",
                                      self.obstacles[16].rect.bottomleft,
                                      "left")
        self.all_sprites_list.add(self.obstacles[37])
        self.all_blocks_list.add(self.obstacles[37])
        for i in range(38, 51):
            self.obstacles[i] = Obstacle("obstacleType1.png",
                                         self.obstacles[i - 1].rect.bottomleft,
                                         "left")
            self.all_sprites_list.add(self.obstacles[i])
            self.all_blocks_list.add(self.obstacles[i])

        self.obstacles[51] = Obstacle("obstacleType1.png",
                                      self.obstacles[50].rect.topright,
                                      "bottom")
        self.all_sprites_list.add(self.obstacles[51])
        self.all_blocks_list.add(self.obstacles[51])
        for i in range(52, 70):
            self.obstacles[i] = Obstacle("obstacleType1.png",
                                         self.obstacles[i - 1].rect.topright,
                                         "bottom")
            self.all_sprites_list.add(self.obstacles[i])
            self.all_blocks_list.add(self.obstacles[i])
        self.obstacles[70] = Obstacle("obstacleType1.png",
                                      self.obstacles[35].rect.bottomleft,
                                      "right")
        self.all_sprites_list.add(self.obstacles[70])
        self.all_blocks_list.add(self.obstacles[70])
        for i in range(71, 83):
            self.obstacles[i] = Obstacle("obstacleType1.png",
                                         self.obstacles[i - 1].rect.bottomleft,
                                         "right")
            self.all_sprites_list.add(self.obstacles[i])
            self.all_blocks_list.add(self.obstacles[i])
        """self.obstacles[84] = Obstacle("obstacleType1.png", (40, 400))
        self.all_sprites_list.add(self.obstacles[84])
        self.all_blocks_list.add(self.obstacles[84])
        for i in range(85, 88):
            self.obstacles[i] = Obstacle("obstacleType1.png", self.obstacles[i - 1].rect.bottomleft)
            self.all_sprites_list.add(self.obstacles[i])
            self.all_blocks_list.add(self.obstacles[i])
        self.obstacles[88] = Obstacle("obstacleType1.png", (80, 440))
        self.all_sprites_list.add(self.obstacles[88])
        self.all_blocks_list.add(self.obstacles[88])
        for i in range(89, 91):
            self.obstacles[i] = Obstacle("obstacleType1.png", self.obstacles[i - 1].rect.bottomleft)
            self.all_sprites_list.add(self.obstacles[i])
            self.all_blocks_list.add(self.obstacles[i])
        self.obstacles[91] = Obstacle("obstacleType1.png", (120, 480))
        self.all_sprites_list.add(self.obstacles[91])
        self.all_blocks_list.add(self.obstacles[91])
        for i in range(92, 93):
            self.obstacles[i] = Obstacle("obstacleType1.png", self.obstacles[i - 1].rect.bottomleft)
            self.all_sprites_list.add(self.obstacles[i])
            self.all_blocks_list.add(self.obstacles[i])
        self.obstacles[93] = Obstacle("obstacleType1.png", (160, 520))
        self.all_sprites_list.add(self.obstacles[93])
        self.all_blocks_list.add(self.obstacles[93])
        self.obstacles[94] = Obstacle("obstacleType1.png", (720, 40))
        self.all_sprites_list.add(self.obstacles[94])
        self.all_blocks_list.add(self.obstacles[94])
        for i in range(95, 98):
            self.obstacles[i] = Obstacle("obstacleType1.png", self.obstacles[i - 1].rect.bottomleft)
            self.all_sprites_list.add(self.obstacles[i])
            self.all_blocks_list.add(self.obstacles[i])
        self.obstacles[98] = Obstacle("obstacleType1.png", (680, 40))
        self.all_sprites_list.add(self.obstacles[98])
        self.all_blocks_list.add(self.obstacles[98])
        for i in range(99, 101):
            self.obstacles[i] = Obstacle("obstacleType1.png", self.obstacles[i - 1].rect.bottomleft)
            self.all_sprites_list.add(self.obstacles[i])
            self.all_blocks_list.add(self.obstacles[i])
        self.obstacles[101] = Obstacle("obstacleType1.png", (640, 40))
        self.all_sprites_list.add(self.obstacles[101])
        self.all_blocks_list.add(self.obstacles[101])
        for i in range(102, 103):
            self.obstacles[i] = Obstacle("obstacleType1.png", self.obstacles[i - 1].rect.bottomleft)
            self.all_sprites_list.add(self.obstacles[i])
            self.all_blocks_list.add(self.obstacles[i])"""
        """self.obstacles[104] = Obstacle("obstacleType1.png", (240, 40))
        self.all_sprites_list.add(self.obstacles[104])
        self.all_blocks_list.add(self.obstacles[104])
        self.obstacles[105] = Obstacle("obstacleType1.png", (280, 40))
        self.all_sprites_list.add(self.obstacles[105])
        self.all_blocks_list.add(self.obstacles[105])
        self.obstacles[106] = Obstacle("obstacleType1.png", (240, 80))
        self.all_sprites_list.add(self.obstacles[106])
        self.all_blocks_list.add(self.obstacles[106])
        self.obstacles[107] = Obstacle("obstacleType1.png", (280, 80))
        self.all_sprites_list.add(self.obstacles[107])
        self.all_blocks_list.add(self.obstacles[107])"""
        self.obstacles[108] = Obstacle("obstacleType1.png", (300, 200))
        self.all_sprites_list.add(self.obstacles[108])
        self.all_blocks_list.add(self.obstacles[108])
        self.obstacles[109] = Obstacle("obstacleType1.png", (300, 240))
        self.all_sprites_list.add(self.obstacles[109])
        self.all_blocks_list.add(self.obstacles[109])

        self.carryOn = True  # Game state variable

        self.clock = pygame.time.Clock()
Beispiel #6
0
        old_pitch = 0
        old_roll = 0
        
        # Create world
        world = World()
        
        # create obstacle
        lava = Lava(15)
        lava1 = Lava(30)
        
        # create hero
        hero = Hero(22)
        hero.vel = 0
        
        #create goal
        goal = Goal()
        goal.width = 4
        
        #for tracking time
        start_time = time.time()
        frame = 0
        
####################### led painting happens here ####################     
        while True:
            # Create a new driver config (for setup purposes)
            driver_config_proto = driver_pb2.DriverConfig()
            img.clear_all()
            
            # Painting obstacles
            img.set_led(int(lava.pos), int(lava.r),int(lava.g),int(lava.b),int(lava.w))
            img.set_led(int(lava1.pos), int(lava1.r),int(lava1.g),int(lava1.b),int(lava1.w))
Beispiel #7
0
 def add_goal(self, name, amt, balance=0):
     goal = Goal(name, amt, balance)
     self.goals.append(goal)
Beispiel #8
0
 def setUp(self):
     self.test_goal = Goal(2, 2)
Beispiel #9
0
    def __init__(self, cam, menu, parent=None):
        QGraphicsScene.__init__(self, parent)

        self.prices = []
        self.time = 0
        self.menu = menu

        # Tallennetaan painetut nappaimet
        self.keys_pressed = set()

        self.timer = QBasicTimer()
        self.timer.start(globals.FRAME_SPEED, self)

        bg = QGraphicsRectItem()
        bg.setRect(0, 0, globals.SCREEN_WIDTH * 4, globals.SCREEN_HEIGHT)
        bg.setBrush(QBrush(QtGui.QColor(128, 191, 255)))
        self.addItem(bg)

        self.player = Player()
        self.addItem(self.player)

        #Luodaan maailma
        self.map = Map()
        for i in range(int(globals.SCREEN_HEIGHT / 40)):
            for j in range(int((globals.SCREEN_WIDTH * 4) / 40)):
                if self.map.map[i][j] > 0:
                    self.platform = Platform(j * 40, i * 40,
                                             self.map.map[i][j])
                    self.addItem(self.platform)

        self.enemy = Enemy(500, 200)
        self.addItem(self.enemy)

        #Luodaan palkinnot
        self.price1 = Price(250, 350)
        self.addItem(self.price1)
        self.prices.append(self.price1)

        self.price2 = Price(750, 500)
        self.addItem(self.price2)
        self.prices.append(self.price2)

        self.price3 = Price(650, 300)
        self.addItem(self.price3)
        self.prices.append(self.price3)

        self.price4 = Price(1330, 250)
        self.addItem(self.price4)
        self.prices.append(self.price4)

        self.price5 = Price(1455, 500)
        self.addItem(self.price5)
        self.prices.append(self.price5)

        self.price6 = Price(1830, 250)
        self.addItem(self.price6)
        self.prices.append(self.price6)

        self.price7 = Price(2100, 100)
        self.addItem(self.price7)
        self.prices.append(self.price7)

        self.price8 = Price(2490, 500)
        self.addItem(self.price8)
        self.prices.append(self.price8)

        self.price9 = Price(2770, 200)
        self.addItem(self.price9)
        self.prices.append(self.price9)

        self.price10 = Price(3100, 205)
        self.addItem(self.price10)
        self.prices.append(self.price10)

        self.font = QtGui.QFont()
        self.font.setPointSize(15)

        self.points = QtWidgets.QGraphicsTextItem('Prices: ' +
                                                  str(self.player.points) +
                                                  '/' + str(len(self.prices)))
        self.points.setDefaultTextColor(QtGui.QColor(38, 38, 38))
        self.points.setFont(self.font)
        self.addItem(self.points)

        self.display = QtWidgets.QGraphicsTextItem('Time: ' +
                                                   str(int(self.time)))
        self.display.setDefaultTextColor(QtGui.QColor(38, 38, 38))
        self.display.setFont(self.font)
        self.display.setPos(200, 1)
        self.addItem(self.display)

        self.goal = Goal(3000, 440)
        self.addItem(self.goal)

        self.view = cam
        self.view.update_scene(self)
Beispiel #10
0
from specification.atom.pattern.basic import Init
from specification.atom.pattern.robotics.coremovement.surveillance import Patrolling
from world.abcd_gridworld import ABCDGridworld
from world.simple_gridworld import SimpleGridWorld
"""Let us instantiate a variables"""
sw = SimpleGridWorld()
""""
    A   B   
      X
    C   D
"""
t = sw.typeset
"""Definition of a goals"""

g1 = Goal(name="patrol_a_b",
          description="Patrolling of locations a and b and init a",
          specification=Patrolling([t["a"], t["b"]]))

try:
    g1.realize_to_controller()
except GoalException as e:
    pass

g1 = Goal(name="patrol_a_b_init_a_and_b",
          description="Patrolling of locations a and b and init a and b",
          specification=Patrolling([t["a"], t["b"]]) & Init(t["a"]))

try:
    g1.realize_to_controller()
except GoalException as e:
    raise e
Beispiel #11
0
 def goal_start(self):
     self.status = Game.GOAL
     self.goal = Goal(Game.GOAL_TIME)
Beispiel #12
0
    def scan_game_page(self, game_page):

        soup = BeautifulSoup(game_page, 'html.parser')

        scoring = soup.find(id='all_scoring')
        penalty = soup.find(id='all_penalty')

        period_start = 0

        # Scan through game information section
        # Get link, date, away, home
        link = soup.find('link', {'rel': 'canonical'}).get('href')

        date = soup.find('div', {'class': 'scorebox_meta'}).find_all('div')
        date = date[0].get_text().split(',')
        date = (date[0] + ', ' + date[1])

        # home and visitor done in steps to hopefully make it more readable
        visitor = soup.find(id='inner_nav').find('section').find_all('p')
        visitor = visitor[1].find('a').get('href')
        visitor = visitor.split('/')
        visitor = visitor[2]

        home = soup.find(id='inner_nav').find('section').find_all('p')
        home = home[2].find('a').get('href')
        home = home.split('/')
        home = home[2]

        #print(link + ' ' + date + ' ' + visitor + ' @ ' + home)

        # Create game
        game = Game(link, date, visitor, home)
        print(game)

        # Scan through the scoring section
        print('Goals')
        scoring_rows = scoring.find_all('tr')
        for row in scoring_rows:
            cells = row.find_all(['td', 'th'])

            # If row is a period header or not
            if (cells[0].name == 'th'):
                period_start = self.find_period_start(cells[0].get_text())

                print('period starts: ' + str(period_start))

                # Skip shootout data
                if period_start == -2:
                    print("Skipping Shootout")
                    break

                # Error check period_start
                if period_start == -1:
                    print("error with period")
                    exit()

            # else it should be a 'td' and be a goal summary
            # time | team | PP/SH | Goal Scorer | Assits
            else:
                time = cells[0].get_text()
                seconds = self.convert_score_clock_to_seconds(
                    time) + period_start

                team = cells[1].get_text()

                type = ''

                if 'PP' in cells[2].get_text():
                    type = 'PP'
                elif 'SH' in cells[2].get_text():
                    type = 'SH'

                player = cells[3].get_text().split('(')[0].strip('\n')

                goal_row = (str(seconds) + ', ' + team + ', ' + type + ', ' +
                            player)

                print(goal_row)
                game.goals.append(Goal(int(seconds), team, player, type))

        # Scan through the penalty section
        print('Penalties')
        period_start = 0
        penalty_rows = penalty.find_all('tr')
        for row in penalty_rows:
            cells = row.find_all(['td', 'th'])

            # If row is a period header or not
            if (cells[0].name == 'th'):
                period_start = self.find_period_start(cells[0].get_text())

                print('period starts: ' + str(period_start))

                # Error check period_start
                if period_start == -1:
                    print("error with period")
                    exit()

            # else it should be a 'td' and be a goal summary
            # time | team | player | infraction | duration
            else:
                time = cells[0].get_text()
                seconds = self.convert_score_clock_to_seconds(
                    time) + period_start

                team = cells[1].get_text()
                player = cells[2].get_text()
                infraction = cells[3].get_text()
                if cells[4].get_text().endswith('min'):
                    duration = int(cells[4].get_text().split(' ')[0]) * 60
                else:
                    duration = 0

                print(
                    str(seconds) + ', ' + team + ', ' + player + ', ' +
                    infraction + ', ' + str(duration))

                game.penalties.append(
                    Penalty(int(seconds), team, player, infraction, duration))

        #print(game)
        return game
Beispiel #13
0
                            expected_sender_mb,
                            expected_goal_mb,
                            goal_only=goal_only)


script_path, WALLET = sys.argv
ppath = PurePath(script_path)

CWD, SCRIPT = ppath.parent, ppath.name
TEAL_DIR = CWD / "tealprogs"

stamp = datetime.now().strftime("%Y%m%d_%H%M%S")
print(f"Running {SCRIPT} inside {CWD} @ {stamp}")

# Initialize goal
goal = Goal(WALLET, autosend=True)
rest_endpoints = get_endpoint_info(goal)
print(f"Python Goal cennected to {rest_endpoints}")

joe = goal.new_account()
flo = goal.new_account()

print(f"Joe & Flo: {joe}, {flo}")

txinfo, err = goal.pay(goal.account, joe, amt=50_000_000, send=True)
txinfo, err = goal.pay(goal.account, flo, amt=100_000_000, send=True)

expected_goal_mb = CONSENSUS_MIN_BALANCE + APP_MIN_BALANCE

# starting out, should be at global min
assert_min_balance(goal, flo, CONSENSUS_MIN_BALANCE, expected_goal_mb)
def goalWidth(image):
    gol = Goal()
    tol = gol.find_goal_single_image(image)
    goal_width = tol[2]

    return goal_width
    def __init__(self, worldDrawScale, TIME_STEP):
        self.world = world(gravity=(0, 0), doSleep=True)

        self.ticks = 0
        self.worldDrawScale = worldDrawScale

        self.contactListener = ContactListener()
        self.world.contactListener = self.contactListener

        self.TIME_STEP = TIME_STEP

        self.goals = [Goal(self.world, "goal", 300, 300)]

        self.goalsBodies = []
        for goal in self.goals:
            self.goalsBodies.append(goal.body)

        self.horizontal_ground_body_fixDef = b2FixtureDef(
                shape=b2PolygonShape(box=(1270, 5)),
                userData = "wall",
            )

        self.vertical_ground_body_fixDef = b2FixtureDef(
                        shape=b2PolygonShape(box=(5, 710)),
                        userData = "wall",
                    )
        # And a static body to hold the ground shape
        self.h1_ground_body = self.world.CreateStaticBody(
            position=(5, 0),
            fixtures=self.horizontal_ground_body_fixDef,
        )
        self.h2_ground_body = self.world.CreateStaticBody(
            position=(5, 715),
            fixtures=self.horizontal_ground_body_fixDef,
        )
        self.v1_ground_body = self.world.CreateStaticBody(
            position=(0, 5),
            fixtures=self.vertical_ground_body_fixDef,
        )
        self.v2_ground_body = self.world.CreateStaticBody(
            position=(1275, 5),
            fixtures=self.vertical_ground_body_fixDef,
        )

        # car = Car(world, 15, 15, 15)
        self.car = TDCar(self.world)

        self.carLastPosition = self.car.body.worldCenter

        
        self.totalRunnedDistance = 0
        self.numberContactWall = 0
        self.ticksOnCrashToWall = []
        self.ticksOnGetObjective = []
        self.gameover = False
        self.lastTotalDistance = 0

        self.laserPoints = []
        self.laserImpactPoints = []

        self.rightOrLeft = 0
        self.backwardOrForward = 0

        self.colors = {
            staticBody: (0, 0, 255, 255),
            dynamicBody: (127, 127, 127, 255),
        }
def getGoalCord(image):
    gol = Goal()
    x, y, w, h = gol.find_goal_single_image(image)
    return x, y, w, h
def getGoals(rYear):

    rounds = {
        'r2l1': ["R16 L1", 8],
        'r2l2': ["R16 L2", 8],
        's0l1': ["Quarters L1", 4],
        's0l2': ["Quarters L2", 4],
        't0l1': ["Semis L1", 2],
        't0l2': ["Semis L2", 4],
        'u0': ["Finals", 1]
    }

    goalArray = []

    temp = rYear - 2000
    year = str(temp) + str(temp + 1)

    goalTimeArray = {}
    rx = {}
    teamNo = 0
    htSquad = []
    atSquad = []
    homeTeam = ""
    awayTeam = ""
    hScore = 0
    aScore = 0

    for r in rounds.keys():

        #print "Parsing Round: " + rounds[r][0]

        url = "http://www.soccerassociation.com/CL/%s/%s.htm" % (year, r)
        #get request that ish
        while True:
            try:
                toScrape = requests.get(url)
                break
            except ConnectionError:
                print "Connection Error. Will try again"

        #soup it too
        soup = BeautifulSoup(toScrape.content)

        #this will give us the results section
        results = soup.findAll('table', {
            "cellspacing": "1",
            "cellpadding": "1"
        })[0]

        #this gives us the
        teamsAndPlayers = results.findAll('td')

        #get all the teams playing
        #all the data we need is in 'td' tags but they aren't ordered by match
        rows = results.findAll('td')

        acount = 0
        hcount = 0
        awayGoal = False
        homeGoal = False

        #now we have each match to iterate through
        #if a 'td' tag with attributes align center and colspan is found, the a tags within have the team name

        for row in rows:

            if row.has_attr('align') and row.has_attr('colspan'):
                if row['align'] == 'center' and row['colspan'] == '2':

                    #if we're here, we're looking at a new match (or the first one)
                    #so now we make the goal objects and add to goalArray
                    if teamNo % 2 == 0:
                        while len(goalTimeArray) > 0:

                            #this will give us the min key in the array
                            #this is also the first goal
                            gt = 120
                            for key in goalTimeArray.keys():
                                #print goalTimeArray[key]
                                if key <= gt:
                                    gt = key

                            #now we have the smallest remaining value in the array at key = gt
                            minScorer = goalTimeArray.pop(gt)
                            rnd = rx.pop(gt)

                            #if (homeTeam == 'Real Madrid'):
                            #	print goalTimeArray[19]

                            if any(minScorer in names for names in htSquad):

                                print "Scorer: " + minScorer + " at minute " + str(
                                    gt)

                                #for final, assume both teams are away
                                if rounds[r][0] == 'Finals':
                                    newGoal = Goal(minScorer, gt, False,
                                                   hScore, aScore, rnd)
                                else:
                                    newGoal = Goal(minScorer, gt, True, hScore,
                                                   aScore, rnd)
                                goalArray.append(newGoal)

                                hScore += 1

                            elif any(minScorer in names for names in atSquad):

                                print "Scorer: " + minScorer + " at minute " + str(
                                    gt)

                                newGoal = Goal(minScorer, gt, False, aScore,
                                               hScore, rnd)
                                goalArray.append(newGoal)

                                aScore += 1

                    #if teamNo%2 is 0 then home team, else away team. increment every time team is found
                    #update homeTeam & awayTeam and get their squads
                    #also set the scores to 0-0

                    hScore = 0
                    aScore = 0
                    #goalTimeArray = {}

                    teamName = row.find('a')

                    strTeamName = str(teamName)
                    strTeamName = re.sub('<[^<]+?>', '', strTeamName)

                    if (teamNo % 2 == 0):
                        homeTeam = strTeamName
                        htSquad = getRoster(homeTeam, rYear)
                    else:
                        awayTeam = strTeamName
                        atSquad = getRoster(awayTeam, rYear)

                    teamNo += 1

            #if 'td' tag has attributes align right, then its a goal - this contains the goal time
            elif row.has_attr('align') and row['align'] == 'right':

                #for the name, look at the td tag immediately after the goal time thing
                #the a tags within that have the name of the team
                #check if player name is in htSquad or atSquad and increment scores accordingly
                #then create new instance of Goal class and add to array

                goalTime = str(row)
                goalTime = re.sub('<[^<]+?>', '', goalTime)
                goalTime = goalTime.replace('(p)', '')

                #we dont want own goals to count for anything
                if ('(og)' not in goalTime):
                    gTime = int(goalTime)

            elif (len(row.findAll('a')) > 0) and not row.has_attr('bgcolor'):

                scorer = row.find('a')

                scorer = str(scorer)
                scorer = re.sub('<[^<]+?>', '', scorer)

                if any(scorer in names for names in atSquad):
                    #make the goal object now - note that it requires the score BEFORE the goal is scored
                    #if this is the finals, assume Away

                    if acount % 2 == 0:
                        goalTimeArray[gTime] = scorer
                        rx[gTime] = rounds[r][0]
                        #print "Scorer: " + scorer + " at minute " + str(gTime)
                        #add time of the goal and the scorer to the goaltimearray
                        #we need this because goals are not ordered by time on the website we're scraping from

                    awayGoal = True
                    homeGoal = False

                elif any(scorer in names for names in htSquad):

                    if hcount % 2 == 0:
                        #print "Scorer: " + scorer + " at minute " + str(gTime)
                        goalTimeArray[gTime] = scorer
                        rx[gTime] = rounds[r][0]
                        #print goalTimeArray[scorer]

                    awayGoal = False
                    homeGoal = True

                #all of this shpiel is because scorers get counted twice for some odd reason
                if awayGoal:
                    acount += 1
                elif homeGoal:
                    hcount += 1

    return goalArray
Beispiel #18
0
from individual import Individual
from goal import Goal
from obstacle import Obstacle
from population import Population
import time
from tkinter import *

window = Tk()

can = Canvas(window, width=500, height=500, bg='white')
can.master.title("Genetic Algorithm")
can.pack(side=TOP, padx=0, pady=0)

goal = Goal(500 / 2 - 4, 40)
goal_graph = can.create_oval(goal.x,
                             goal.y,
                             goal.x + 16,
                             goal.y + 16,
                             outline='green',
                             fill='green')

obstacle = Obstacle(50, 500 / 2 - 6, 500 - 50 * 2, 16)
can.create_rectangle(obstacle.x,
                     obstacle.y,
                     obstacle.x + obstacle.width,
                     obstacle.y + obstacle.height,
                     outline='blue',
                     fill='blue')

b1 = Button(window,
            text='Start',
Beispiel #19
0
    def run_level(self, level_obj):

        self.press_en = True

        self.mrd = DOWN

        self.hud_key_array = HudKeyArray()

        self.clicked = 0
        self.selected_key = []
        self.hovered_shrine = []
        self.last_hover = []

        self.cur_level = level_obj

        self.then = time.time()

        self.player_pos = level_obj.player_start_pos()
        self.cam.set_center((self.player_pos[0] * TILE_WIDTH,
                             self.player_pos[1] * TILE_WIDTH - TILE_WIDTH))

        self.player = Player(self.player_pos)

        self.goal = Goal(level_obj.goal_pos())
        self.blocks = []
        for item in level_obj.block_pos():
            self.blocks.append(Block(item))

        self.set_starting_hud()

        self.shrines = []
        self.doors = []
        if self.cur_level.shrine_count() > 0:
            self.shrine_0 = Shrine(self.cur_level.shrine_0_pos(), num=0)
            self.door_0 = Door(self.cur_level.door_0_pos(), self.shrine_0)
            self.shrines.append(self.shrine_0)
            self.doors.append(self.door_0)

        shadow = pygame.Surface(WINDOW_SIZE)
        shadow.fill((0, 0, 0))
        shadow_opacity = 255.0
        shadow_fade_rate = 255.0
        self.shadow_dir = 1
        self.level_start = time.time()
        msg_not_said_yet = 1

        while True:

            now = time.time()
            dt = now - self.then
            self.then = now
            dt = self.cam.time_step(dt)

            if msg_not_said_yet and self.level_counter <= 5:
                self.press_en = 0

            if shadow_opacity < 80 and self.shadow_dir == 1:
                self.test_keydowns()
            else:
                pygame.event.get()

            self.screen.fill((0, 0, 0))

            pypos = self.player.pos[1]

            items_to_draw = self.blocks + self.shrines + self.doors + [
                self.player
            ] + [self.goal]
            self.draw_items(items_to_draw)

            self.cam.capture(self.screen)

            self.draw_tools(self.screen_commit)

            self.update_objects(dt)
            self.mouse_triggers()

            if shadow_opacity > 0 or self.shadow_dir == -1:
                shadow_opacity = max(
                    0,
                    shadow_opacity - self.shadow_dir * shadow_fade_rate * dt)
                shadow.set_alpha(shadow_opacity)
                self.screen_commit.blit(shadow, (0, 0))
            pygame.display.flip()

            if self.player_hit_goal(level_obj) and self.shadow_dir == 1:
                self.collect_gem.play()
                self.cam.set_zoom_pid(5, 1, -0.2)
                self.cam.set_target_zoom(1.5)
                self.goal.sprite.start_animation("collect")
                self.shadow_dir = -1

            if shadow_opacity > 255 and self.shadow_dir == -1:
                break

            level_to_msg = {
                0: "Welcome to Master Key!\nUse the arrow keys to move.",
                1: "Hold Z while moving to dash.",
                2: "Hold X to push objects.",
                3: "Hold C to hop up ledges.",
                4:
                "Altars require you to\nsacrifice your controls!\n\nStand in front of the book, and\n drag a key onto it with the mouse.",
                5: "You're on your own now.\n Good Luck!"
            }

            self.level_to_hint = {
                0: "Move around with the arrow keys.",
                1:
                "Hold Z while moving to dash.\nThis allows you to cross short gaps.",
                2:
                "Hold X while moving to push.\nYou can push cubes into holes.",
                3:
                "Hold C while moving to jump.\nThis lets you get up short platforms.",
                4:
                "Try standing next to the book, and\n drag a key onto it with the mouse.",
                5:
                "You can replace the key on an altar\nby dragging a different key onto it.",
                6: "Don't forget you can sacrifice\nyour movement keys, too!",
                7: "Don't forget you can sacrifice\nyour movement keys, too!",
                8: ""
            }

            if time.time(
            ) - self.level_start > 0.75 and msg_not_said_yet and self.level_counter in level_to_msg and self.shadow_dir != -1:
                self.tooltip(level_to_msg[self.level_counter])
                self.then = time.time()
                msg_not_said_yet = 0
                self.press_en = True
Beispiel #20
0
 def loadLevel(self):
    try:
       f = open("data/levels/%03d"%self.level)
    except IOError:
       self.gameEngine.scene = GameOver(self.gameEngine)
       return
    
    del self.objects[:]
    x=y=0   
    
    while 1:
       row = f.readline()
       if not row:
          break
          
       for col in row:
          
          obj=None
          
          #S == start
          if col == "S":
             self.player = Player(self,x,y)
             self.spawn = (x,y)
             
          #E == end
          if col == "E":
             obj = Goal(self,x,y)
          
          #walls
          if col == "W":
             obj = Wall(self,x,y,(255,255,255))
          if col == "R":
             obj = Wall(self,x,y,(255,0,0))
          if col == "G":
             obj = Wall(self,x,y,(0,255,0))
          if col == "B":
             obj = Wall(self,x,y,(0,0,255))
          if col == "M":
             obj = Wall(self,x,y,(255,0,255))
          if col == "C":
             obj = Wall(self,x,y,(0,255,255))
          if col == "Y":
             obj = Wall(self,x,y,(255,255,0))
             
          #spikes
          if col == "w":
             obj = Spike(self,x,y,(255,255,255))
          if col == "r":
             obj = Spike(self,x,y,(255,0,0))
          if col == "g":
             obj = Spike(self,x,y,(0,255,0))
          if col == "b":
             obj = Spike(self,x,y,(0,0,255))
          if col == "m":
             obj = Spike(self,x,y,(255,0,255))
          if col == "c":
             obj = Spike(self,x,y,(0,255,255))
          if col == "y":
             obj = Spike(self,x,y,(255,255,0))
          
             
          if obj is not None:
             self.objects.append(obj)
          x+=16
       y+=16
       x=0
Beispiel #21
0
#!/usr/bin/env python

import os
import sys
from goal import Goal

import algosdk.future.transaction as txn
from datetime import datetime

stamp = datetime.now().strftime("%Y%m%d_%H%M%S")
print(f"{os.path.basename(sys.argv[0])} start {stamp}")

goal = Goal(sys.argv[1])

joe = goal.new_account()
flo = goal.new_account()

# Pays

pay = goal.pay(goal.account, receiver=joe, amt=10000)  # under min balance
txid, err = goal.send(pay, confirm=False)              # errors early
assert err

pay = goal.pay(goal.account, receiver=joe, amt=500_000)
txinfo, err = goal.send(pay)
assert not err, err
tx = txinfo['txn']['txn']
assert tx['amt'] == 500_000
assert tx['fee'] == 1000
assert goal.balance(joe) == 500_000
Beispiel #22
0
GOAL_REWARD = 25
OUT_OF_BOUNDS_PENALTY = 200
OBSTACLE_HIT_PENALTY = 300
EPS_DECAY = 0.9999
LEARNING_RATE = 0.1
DISCOUNT = 0.95
Q_TABLE_SIZE = (SCREEN_WIDTH // BLOCK_SIZE[0] + 2,
                SCREEN_HEIGHT // BLOCK_SIZE[1] + 2, 4)
epsilon = 0.5
q_table = np.zeros(Q_TABLE_SIZE)

screen = pygame.display.set_mode(SCREEN_SIZE)
clock = pygame.time.Clock()
font = pygame.font.Font(None, font_size)

goal = Goal(SCREEN_WIDTH, SCREEN_HEIGHT, GREEN)
goal_rect = goal.get_rect()
obstacle_rects = [
    pygame.Rect((random.randrange(0, SCREEN_WIDTH, BLOCK_SIZE[0]),
                 random.randrange(0, SCREEN_HEIGHT, BLOCK_SIZE[1])),
                BLOCK_SIZE) for i in range(NUM_OBSTACLES)
]
while goal_rect in obstacle_rects:
    goal.change_pos(SCREEN_WIDTH, SCREEN_HEIGHT)
    goal_rect = goal.get_rect()


def gameInit():
    global player
    global player_rect
    global goal_reached
Beispiel #23
0
    def gameLoop(self):

        color_white = (255, 255, 255)
        field = 0  # representa os estados possiveis
        selecting = 1
        attack = 2
        draft = 3
        i = 0
        while i < self.n_players:  #rotina para selecao de personagem dos players
            i += 1
            new_player = Player(self.volEffect, self.volMain, self.ratioE)
            if new_player.exists:
                self.player_list.append(new_player)
            new_player.mission = Goal(
                self.n_players)  #selecao de objetivos, provisorio
            if new_player.mission.opponent > i:
                new_player.mission.opponent = i + 1

        while (pygame.mouse.get_pressed()[0]):
            pygame.event.get()
            time.sleep(0.03)
        self.showing = selecting
        ##Ativa a variavel para quando for chamado de mais uma vez, voltar a executar o loop
        self.active = True
        ##Variavel usada para retornar o valor de pause
        pause = "pause"
        final = "final"
        self.distribution()  #etapa onde se escolhem os territorios
        self.commands.distribution = False
        self.game_started = 0
        i = 0

        while self.active:  ##enquanto o jogo estiver valendo

            while i < len(self.player_list):  ##o turno de cada jogador
                if i == 0:
                    self.roundCurrent += 1
                end_turn = False
                self.player_list[i].money += int(self.player_list[i].earnings)
                while (end_turn == False):
                    self.screen.fill(color_white)
                    events = pygame.event.get(
                    )  #variavel que controla o estado da intel. em "campo", ainda nao foi decidido se o player vai atacar ou recrutar
                    self.showGameScreen(
                        events)  #mostra o campo com os exagonos
                    operation = self.commands.execute(
                        self.screen, events, self.player_list[i],
                        self.chosenHex, self.showing
                    )  ##imprime o menu, verifica os clicks e retorna o indice do botao retornado
                    self.drawRound(self.roundCurrent)
                    self.showClock()

                    ##Verifica se o retorno foi pause (cliclado na tecla esc), se sim, retorna o valor (para o loop)
                    if (operation == pause):
                        self.active = False
                        print(pause)
                        return pause

                    if (operation == 3 and self.showing == selecting
                        ):  #verifica se foi pressionado o end turn
                        end_turn = True
                    if (self.commands.hidden == True and operation
                            == 0):  #verifica se o menu deve ser "desescondido"
                        self.showing = selecting
                        self.commands.hidden = False

                    elif (operation == 0
                          ):  #verifica se o menu deve ser escondido
                        #self.showing = field
                        self.commands.hidden = True

                    elif (operation == 4):  # x do papiro preto?
                        self.chosenHex = 0

                    elif (self.showing == selecting):
                        if pygame.mouse.get_pressed()[0]:
                            territory = self.map.check_click(
                            )  #verifica o hexagono clicado
                            if (territory):
                                self.chosenHex = territory
                            else:
                                self.chosenHex = 0
                        if (operation == 1
                            ):  #verifica se foi escolhida a opcao recrutar
                            self.showing = draft
                            self.chosenHex = 0
                        if (operation == 2):  # atacar
                            self.showing = attack
                            self.chosenHex = 0

                    elif (self.showing == attack):  ##opção 1: atacar
                        self.attackProcedure(self.player_list[i],
                                             events)  #realiza o ataque

                    elif (self.showing == draft):  ##opção 1: atacar
                        self.draftProcedure(self.player_list[i],
                                            events)  #realiza o recrutamento

                    pygame.display.flip()
                    pygame.display.update()

                status = self.player_list[i].check_goal(
                    self.player_list, self.map)
                i = (i + 1) % self.n_players

                if status != 0:  #em caso positivo, retorna o vencedor
                    self.active = False  #em caso negativo, acaba o jogo

                time.sleep(0.03)
                self.current_player = (self.current_player +
                                       1) % self.n_players
def main():
    # pygame initialize
    pygame.init()
    # BOTS turn True to turn on all bots. ---01Variables
    winner = ""
    loser = ""
    time_elapsed = 0
    dt = pygame.time.get_ticks()
    if settings.AUDIO == True:
        sfxc = SoundEffect(settings.CJ, 1.0)
        sfxc.play()
    # Players health
    scoreA = 3
    scoreB = 3
    scoreC = 3
    scoreD = 3
    # window size and initialization + Title "Title is not showing because FPS is on"
    size = (700, 700)
    screen = pygame.display.set_mode(size)
    pygame.display.set_caption("Paddle Royale")

    # Paddle Initialization
    paddleA = Paddle(settings.RED, (10, 80), (20, 200))
    paddleB = Paddle(settings.BLUE, (10, 80), (670, 200))
    paddleC = Paddle(settings.YELLOW, (80, 10), (200, 15))
    paddleD = Paddle(settings.GREEN, (80, 10), (250, 680))

    # Goal initialization "sprite"
    goalA = Goal(settings.RED, (5, 800), (0, 0))
    goalB = Goal(settings.BLUE, (5, 735), (695, 1))
    goalC = Goal(settings.YELLOW, (700, 5), (0, 0))
    goalD = Goal(settings.GREEN, (700, 5), (0, 695))

    ball = Ball(settings.WHITE, (10, 10),
                (randint(300, 400), randint(300, 400)))

    # group sprites
    all_sprites_list = pygame.sprite.Group()

    # add all the sprites to the window
    all_sprites_list.add(paddleA)
    all_sprites_list.add(paddleB)
    all_sprites_list.add(paddleC)
    all_sprites_list.add(paddleD)
    all_sprites_list.add(goalA)
    all_sprites_list.add(ball)
    all_sprites_list.add(goalB)
    all_sprites_list.add(goalC)
    all_sprites_list.add(goalD)

    # looping if it breaks out we could have restart or switch between screens
    carryOn = True

    # initialize clock for frame counting
    clock = pygame.time.Clock()

    # START
    while carryOn:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                carryOn = False
                # exit game with p
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_p:
                    carryOn = False
                #might just make variable or something.
            elif event.type == pygame.KEYUP:
                if event.key == pygame.K_SPACE:
                    print("space up")
                    ball.bounce
        # Controls
        ball.update()
        keys = pygame.key.get_pressed()
        if keys[pygame.K_t]:
            ball.bouncedouble3()
        if keys[pygame.K_w]:
            paddleA.moveUp(5)
        if keys[pygame.K_s]:
            paddleA.moveDown(5)
        if keys[pygame.K_UP]:
            paddleB.moveUp(5)
        if keys[pygame.K_DOWN]:
            paddleB.moveDown(5)
        if keys[pygame.K_a]:
            paddleC.moveLeft(5)
        if keys[pygame.K_d]:
            paddleC.moveRight(5)
        if keys[pygame.K_LEFT]:
            paddleD.moveLeft(5)
        if keys[pygame.K_RIGHT]:
            paddleD.moveRight(5)
        if settings.BOTS == True:
            # Blue Paddle AI
            if paddleB.rect.y + 40 > ball.rect.y:
                paddleB.moveUp(randint(1, 3))
            if paddleB.rect.y + 40 < ball.rect.y:
                paddleB.moveDown(randint(1, 3))
            # Paddle red AI
            if paddleA.rect.y + 40 > ball.rect.y:
                paddleA.moveUp(randint(1, 3))
            if paddleA.rect.y + 40 < ball.rect.y:
                paddleA.moveDown(randint(1, 3))
            # Paddle Yellow AI
            if paddleC.rect.x + 40 < ball.rect.x:
                paddleC.moveRight(randint(1, 3))
            if paddleC.rect.x + 40 > ball.rect.x:
                paddleC.moveLeft(randint(1, 3))
            # Paddle Green AI
            if paddleD.rect.x + 40 < ball.rect.x:
                paddleD.moveRight(randint(1, 3))
            if paddleD.rect.x + 40 > ball.rect.x:
                paddleD.moveLeft(randint(1, 3))
        # update sprites in real time while the game plays.
        all_sprites_list.update()
        # Ball bounce of walls (not yet goals) score point

        if ball.rect.x >= settings.RIGHT_WALL:
            scoreB -= 1
            ball.bounce()
            if scoreB > -1:
                ball.sound_effect()
        if ball.rect.x <= settings.LEFT_WALL:
            scoreA -= 1
            ball.bounce()
            if scoreA > -1:
                ball.sound_effect()
        if ball.rect.y > settings.BOTTOM_WALL:
            scoreD -= 1
            ball.bounce2()
            if scoreD > -1:
                ball.sound_effect()
        if ball.rect.y < settings.TOP_WALL:
            scoreC -= 1
            ball.bounce2()
            if scoreC > -1:
                ball.sound_effect()

        if ball.rect.y < -10:
            all_sprites_list.remove(ball)
            ball = Ball(settings.WHITE, (10, 10),
                        (randint(300, 400), randint(300, 400)))
            all_sprites_list.add(ball)
        if ball.rect.y > 710:
            all_sprites_list.remove(ball)
            ball = Ball(settings.WHITE, (10, 10),
                        (randint(300, 400), randint(300, 400)))
            all_sprites_list.add(ball)
        if ball.rect.x < -10:
            all_sprites_list.remove(ball)
            ball = Ball(settings.WHITE, (10, 10),
                        (randint(300, 400), randint(300, 400)))
            all_sprites_list.add(ball)
        if ball.rect.y > 710:
            all_sprites_list.remove(ball)
            ball = Ball(settings.WHITE, (10, 10),
                        (randint(300, 400), randint(300, 400)))
            all_sprites_list.add(ball)
        # ball physics to push ball away if it gets behind the paddle
        if (pygame.sprite.collide_mask(ball, paddleB) and scoreB >= 1):
            ball.bounce()
            ball.rect.x = 660
            ball.sound_effect2()
        if (pygame.sprite.collide_mask(ball, paddleA) and scoreA >= 1):
            ball.bounce()
            ball.rect.x = 30
            ball.sound_effect2()
        if (pygame.sprite.collide_mask(ball, paddleD) and scoreD >= 1):
            ball.bounce2()
            ball.rect.y = 670
            ball.sound_effect2()
        if (pygame.sprite.collide_mask(ball, paddleC) and scoreC >= 1):
            ball.bounce2()
            ball.rect.y = 25
            ball.sound_effect2()
        #
        #
        #
        #
        #Ball velocity in straight line #OOGBERROR
        #if (
        #    ball.velocity[1] < 1.0
        #    and ball.velocity[1] > -1.0
        #):
        #    ball.bounce()
        #if (
        #    ball.velocity[0] < 1.0
        #    and ball.velocity[0] > -1.0
        #):
        #    ball.bounce()
        #
        # ball physics to bounce on collision with paddles checks for score to disable bouncing as paddle object stays in game its just sprite that stops rendering.
        ######
        #Issue 1
        #if ball.rect.right == paddleB.rect.left:
        #    ball.bounce()
        #
        # What happens when ball hits Paddle
        #if pygame.sprite.collide_mask(ball, paddleA) and scoreA >= 1:
        #    ball.bounce()
        #if ball.rect.right == paddleB.rect.left:
        #    if ball.velocity[0] == +ball.velocity[0] and ball.velocity[1] == -ball.velocity[1]:
        #        ball.velocity[0] = -ball.velocity[0]
        #        ball.velocity[1] = -ball.velocity[1]
        #
        #
        # BEGIN removing the sprite of each paddle once player dies.
        if scoreA == 0:
            paddleA.sound_effect()
            scoreA -= 1
        if scoreB == 0:
            paddleB.sound_effect()
            scoreB -= 1
        if scoreC == 0:
            paddleC.sound_effect()
            scoreC -= 1
        if scoreD == 0:
            paddleD.sound_effect()
            scoreD -= 1
        if scoreA <= 0:
            all_sprites_list.remove(paddleA)
        if scoreB <= 0:
            all_sprites_list.remove(paddleB)
        if scoreC <= 0:
            all_sprites_list.remove(paddleC)
        if scoreD <= 0:
            all_sprites_list.remove(paddleD)
        # screen color or backdrop
        screen.fill(settings.BLACK)
        # draw the sprites from the group onto the scene
        all_sprites_list.draw(screen)
        # update me please anytime i move
        # scoring logic
        font = pygame.font.Font(None, 50)
        if settings.DEBUG == True:
            text = font.render(str(ball.direction), 1, settings.RED)
            screen.blit(text, (200, 250))
            text = font.render(str(ball.speed), 1, settings.RED)
            screen.blit(text, (200, 450))
            text = font.render(str(ball.rect.x), 1, settings.WHITE)
            screen.blit(text, (200, 350))
            text = font.render(str(ball.rect.y), 1, settings.WHITE)
            screen.blit(text, (200, 550))
            text = font.render(str('X:'), 1, settings.WHITE)
            screen.blit(text, (160, 350))
            text = font.render(str('Y:'), 1, settings.WHITE)
            screen.blit(text, (160, 550))
            text = font.render(str('bounce count'), 1, settings.PURPLE)
            screen.blit(text, (400, 500))
            text = font.render(str(ball.bouncecount), 1, settings.PURPLE)
            screen.blit(text, (400, 540))
        if scoreA >= 1 and winner != "red":
            text = font.render(str(scoreA), 1, settings.RED)
            screen.blit(text, (25, 10))
        elif scoreA <= 0 and winner != "red":
            text = font.render(str(loser), 1, settings.RED)
            screen.blit(text, (25, 10))
        if scoreB >= 1 and winner != "blue":
            text = font.render(str(scoreB), 1, settings.BLUE)
            screen.blit(text, (640, 620))
        elif scoreB <= 0 and winner != "blue":
            text = font.render(str(loser), 1, settings.BLUE)
            screen.blit(text, (640, 620))
        if scoreC >= 1 and winner != "yellow":
            text = font.render(str(scoreC), 1, settings.YELLOW)
            screen.blit(text, (640, 10))
        elif scoreC <= 0 and winner != "yellow":
            text = font.render(str(loser), 1, settings.YELLOW)
            screen.blit(text, (640, 10))
        if scoreD >= 1 and winner != "green":
            text = font.render(str(scoreD), 1, settings.GREEN)
            screen.blit(text, (25, 620))
        elif scoreD <= 0 and winner != "green":
            text = font.render(str(loser), 1, settings.GREEN)
            screen.blit(text, (25, 620))
        if scoreA >= 1 and scoreB <= 0 and scoreC <= 0 and scoreD <= 0:
            winner = "red"
            scoreA += 100
        elif scoreB >= 1 and scoreA <= 0 and scoreC <= 0 and scoreD <= 0:
            winner = "blue"
            scoreB += 100
        elif scoreC >= 1 and scoreA <= 0 and scoreB <= 0 and scoreD <= 0:
            winner = "yellow"
            scoreC += 100
        elif scoreD >= 1 and scoreA <= 0 and scoreB <= 0 and scoreC <= 0:
            winner = "green"
            scoreD += 100

        if winner == "red":
            text = font.render(str("winner"), 1, settings.RED)
            screen.blit(text, (250, 250))
        # carryOn = False
        elif winner == "blue":
            text = font.render(str("winner"), 1, settings.BLUE)
            screen.blit(text, (250, 250))
        elif winner == "yellow":
            text = font.render(str("winner"), 1, settings.YELLOW)
            screen.blit(text, (250, 250))
        elif winner == "green":
            text = font.render(str("winner"), 1, settings.GREEN)
            screen.blit(text, (250, 250))
        pygame.display.flip()
        # framers per /s
        clock.tick(60)
        # display FPS instead of title
        # pygame.display.set_caption("fps: " + str(clock.get_fps()))
        if winner != '':
            restart()

    # goodybe
    pygame.quit()
Beispiel #25
0
from goal import Goal
from cgg import Node
from cgg.exceptions import CGGException
from goal.exceptions import GoalException
from specification.atom.pattern.basic import Init
from specification.atom.pattern.robotics.coremovement.surveillance import Patrolling
from world.simple_gridworld import SimpleGridWorld
"""Let us instantiate a variables"""
sw = SimpleGridWorld()
t = sw.typeset
"""Definition of a goals"""

g1_a = Goal(name="init_a",
            description="Begin from location a",
            specification=Init(t["a"]))

g1_b = Goal(name="patrol_a_b",
            description="Patrolling of locations a and b",
            specification=Patrolling([t["a"], t["b"]]) & Init(t["a"]))

try:
    g1 = Goal.composition({g1_a, g1_b})
    print(g1)
except GoalException as e:
    raise e

g1 = Goal(
    name="patrol_a_b_init_a",
    description="Patrolling of locations a and b, beginning from location a",
    specification=Patrolling([t["a"], t["b"]]) & Init(t["a"]))
Beispiel #26
0
#!/usr/bin/env python

import os
import sys
from goal import Goal

from datetime import datetime

stamp = datetime.now().strftime("%Y%m%d_%H%M%S")
print(f"{os.path.basename(sys.argv[0])} start {stamp}")

goal = Goal(sys.argv[1], autosend=True)

joe = goal.new_account()
flo = goal.new_account()

txinfo, err = goal.pay(goal.account, joe, amt=500_000)
assert not err, err

# Turn off rewards for precise balance checking
txinfo, err = goal.keyreg(joe, nonpart=True)
assert not err, err
joeb = goal.balance(joe)

txinfo, err = goal.pay(goal.account, flo, amt=500_000)
assert not err, err

teal = """
#pragma version 6
 txn ApplicationID
 bz end
Beispiel #27
0
 def test_str(self):
     goal1 = Goal(RColors.RED, (0, 0))
     goal2 = Goal(RColors.GREEN, (7, 7))
     print(" Test de la classe goal")
     print(goal1)
     print(goal2)