Ejemplo n.º 1
0
def main():
    global Ticks, loopCount
    while True:
        clock.tick(60)
        if loopCount % 90 == 0:
            toppos = random.randint(0, height // 2) - 400
            platforms.add(Platform((width + 100, toppos + gapSize + 800)))
            platforms.add(Platform((width + 100, toppos), True))
            Ticks = pygame.time.get_ticks()
        for event in pygame.event.get():
            if event.type == QUIT:
                sys.exit()
            if event.type == KEYDOWN:
                if event.key == K_SPACE:
                    Player.speed[1] = -10
        screen.fill(color)
        Player.update()
        platforms.update()
        gets_hit = pygame.sprite.spritecollide(Player, platforms, False) \
            or Player.rect.center[1] > height or Player.rect.center[1] < 15
        screen.blit(background, [0, 0])
        platforms.draw(screen)
        screen.blit(Player.image, Player.rect)
        pygame.display.flip()
        loopCount += 1

        if gets_hit:
            lose()
Ejemplo n.º 2
0
def Plot_Social_Welfare(task_n, provider_n, max_value, max_alpha, max_deadline, max_task_size, max_mu, max_provider_bid, max_provider_skill, task_columns, provider_columns):
  
  tasks = TaskCreator(task_n, max_value, max_alpha, max_deadline, max_task_size)
  providers = ProviderCreator(provider_n, max_mu, max_provider_bid, max_provider_skill)
  
  pro_exp_social = []
  exp_social = []
  pro_real_social = []
  real_social = []
  
  for i in range(1,11):
    capacity = 20*i
    
    auctioneer = Platform(capacity)

  #platform에서 winners를 선택한다. 
    W_requesters, req_threshold = auctioneer.WinningRequesterSelection(tasks)
    W_providers, pro_threshold = auctioneer.WinningProviderSelection(providers)

  #혹시 모르니깐 requesters와 providers의 숫자를 맞춘다.
    W_requesters, W_providers = auctioneer.Trimming(W_requesters, W_providers)

  #requesters와 providers의 preference ordering을 만든다.
    requester_preference_ordering = auctioneer.ordering_matrix(W_providers,provider_columns)
    provider_preference_ordering = auctioneer.ordering_matrix(W_requesters,task_columns)

    b_rank, b_mean_rank = benchmark_satisfaction_level(requester_preference_ordering)
    b_pdf, b_cdf = bench_distribution(b_rank)

    match = auctioneer.SMA(requester_preference_ordering, provider_preference_ordering)
    #In match, requester: keys, providers: values

    #expected social welfare comparison
    social_welfare = SocialWelfare(W_requesters, W_providers, 0.01, match)
    benchmark = SystemExpectedSocialwelfare(W_requesters, W_providers, 0.01)
    
    pro_exp_social.append(social_welfare)
    exp_social.append(benchmark)
    
    rank, mean_rank = auctioneer.satisfaction_level(match, requester_preference_ordering)
    pdf, cdf = auctioneer.satisfaction_distribution(rank)
    
    #real social welfare
    welfare, t_sub = Proposed_SocialWelfare(W_requesters, W_providers, 0.01, match)
    bench_welfare = Existing_SocialWelfare(W_requesters, W_providers, 0.01)
    
    pro_real_social.append(welfare)
    real_social.append(bench_welfare)
  
  x_axis = np.array(range(1,11))*20
  bar_width = 10
  fig, ax = plt.subplots(nrows = 1, ncols = 2)
  ax[0].bar(x_axis, pro_exp_social, width = bar_width, label = 'proposed exp.SW', color = 'b')
  ax[0].bar(x_axis+bar_width, exp_social, width = bar_width, label = 'benchmark exp.SW', color = 'r')
  ax[0].legend(loc = 'best')
  
  ax[1].bar(x_axis, pro_real_social, width = bar_width, label = 'proposed real.SW', color = 'b')
  ax[1].bar(x_axis+bar_width, real_social, width = bar_width, label = 'benchmark real.SW', color = 'r')
  ax[1].legend(loc = 'best')
  plt.show()  
Ejemplo n.º 3
0
 def createExit(self, j, i):
     self.stageScale = 50
     x = self.stageScale * (j)
     y = self.stageScale * (i)
     sprite = Platform()
     sprite.rect = pygame.Rect((x, y), (self.stageScale, self.stageScale))
     sprite.image = self.imageDictionary["exit"]
     sprite.image = pygame.transform.scale(sprite.image, (self.stageScale, self.stageScale))
                                            
     self.exitGroup.add(sprite);
Ejemplo n.º 4
0
def main():
    global loopCount, points
    while True:
        clock.tick(60)
        if loopCount % 90 == 0:
            toppos = random.randint(0, height / 2) - 400
            platforms.add(Platform((width + 100, toppos + gapSize + 800)))
            platforms.add(Platform((width + 100, toppos), True))
            scorecounters.add(scoreCounter((width + 100, 0)))

        elif loopCount % 30 == 0 and random.randint(0, 2) == 1:
            coins.add(
                coinItem((width + 100,
                          random.randint(height / 4, height - (height / 4)))))

        for event in pygame.event.get():
            if event.type == QUIT:
                sys.exit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE:
                    player.speed[1] = -10

        screen.fill(color)
        player.update()
        platforms.update()
        coins.update()
        scorecounters.update()


        gets_hit = pygame.sprite.spritecollide(player, platforms, False) \
            or player.rect.center[1] > height

        gets_score = pygame.sprite.spritecollide(player, scorecounters, False)

        gets_coins = pygame.sprite.spritecollide(player, coins, False)

        if gets_coins.__len__() > 0:
            points += 3
            coins.remove(gets_coins)

        if gets_score.__len__() > 0:
            points += 1
            scorecounters.remove(gets_score)

        screen.blit(background, [0, 0])
        scorecounters.draw(screen)
        platforms.draw(screen)
        coins.draw(screen)
        screen.blit(player.image, player.rect)
        displayScore(points)
        pygame.display.flip()
        loopCount += 1

        if gets_hit:
            lose()
Ejemplo n.º 5
0
def main():
    global loopCount, score
    while True:
        clock.tick(45)
        if loopCount % 70 == 0:
            toppos = random.randint(0, height / 2) - 400
            platforms.add(Platform((width + 100, toppos + GapSize + 800)))
            platforms.add(Platform((width + 100, toppos), True))
            scorecounters.add(ScoreCounter((width + 100, 0)))
        elif loopCount % 35 == 0 and random.randint(0, 2) == 1:
            coins.add(
                Coin((width + 100,
                      random.randint(height / 4, height - (height / 4)))))

        for event in pygame.event.get():
            if event.type == QUIT:
                sys.exit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE:
                    Player.speed[1] = -10
            # if event.type == pygame.KEYUP:
            #     Player.speed[1] = 10
        screen.fill(color)
        Player.update()
        platforms.update()
        coins.update()
        scorecounters.update()

        gets_hit = pygame.sprite.spritecollide(Player, platforms, False) \
                   or Player.rect.center[1] > height

        score_counters_hit = pygame.sprite.spritecollide(
            Player, scorecounters, False)

        if score_counters_hit.__len__() > 0:
            score += 1
            scorecounters.remove(score_counters_hit)

        coins_collected = pygame.sprite.spritecollide(Player, coins, False)

        if coins_collected.__len__() > 0:
            score += 5
            coins.remove(coins_collected)

        screen.blit(background, [0, 0])
        platforms.draw(screen)
        scorecounters.draw(screen)
        coins.draw(screen)
        displayScore(score)
        screen.blit(Player.image, Player.rect)
        pygame.display.flip()
        loopCount += 1

        if gets_hit:
            lose()
Ejemplo n.º 6
0
def run_game():
    """
    Initialize pygame, make player and platform objects, and run the game loop.
    """
    pygame.init()
    sett = Settings()
    stats = GameStats(sett)
    screen = pygame.display.set_mode((sett.swidth, sett.sheight))
    pygame.display.set_caption("Arena-brawler Roguelike")
    score_display = ScoreDisplay(screen, stats.score)

    player = Player(screen, sett)
    lives = PlayerLives(screen)
    platforms = Group()
    enemies = Group()
    enemy_movement = EnemyMovement()
    start_button = StartButton(screen, "Start... and die.")

    player_attack_right = PlayerFistAttackRight(player, screen)
    player_attack_left = PlayerFistAttackLeft(player, screen)

    platform_1 = Platform(screen, 100, sett.sheight - 200)
    platform_2 = Platform(screen, sett.swidth - platform_1.rect.width - 100,
                          sett.sheight - 200)
    platform_3 = Platform(screen,
                          (sett.swidth / 2) - (platform_1.rect.width / 2),
                          sett.sheight - 400)
    platform_4 = Platform(screen, 100, sett.sheight - 550)
    platform_5 = Platform(screen, sett.swidth - platform_1.rect.width - 100,
                          sett.sheight - 550)

    # Add platform_x to platforms
    platforms.add(platform_1)
    platforms.add(platform_2)
    platforms.add(platform_3)
    platforms.add(platform_4)
    platforms.add(platform_5)

    enemy_counter = sett.enemy_counter
    enemy_counter_threshold = sett.enemy_counter_threshold

    while True:
        # Game loop.
        enemy_counter += 1
        player.player_gravity(platforms, sett, player)
        gf.check_events(player, platforms, sett, player_attack_left,
                        player_attack_right, stats, start_button)
        gf.update_screen(screen, sett, player, platforms, enemies,
                         enemy_counter, enemy_counter_threshold, stats,
                         player_attack_left, player_attack_right,
                         enemy_movement, lives, start_button, score_display)
        if enemy_counter == enemy_counter_threshold:
            enemy_counter = sett.enemy_counter
Ejemplo n.º 7
0
 def render(self):
     """When the game starts, create these first and play music,
        then go to the game loop in events(). Here the class Shark() is
        imported from sprites and becomes the player variable"""
     self.sprites.add(self.player)
     pg.mixer.music.load("FadeNCS.ogg")
     pg.mixer.music.play(-1)
     ground = Platform(0, SCR_HEIGHT - 30, SCR_WIDTH, 30)
     plat_1 = Platform(SCR_WIDTH / 2, 400, 200, 30)
     plat_2 = Platform(100, 600, 200, 30)
     plat_3 = Platform(100, 200, 200, 30)
     self.sprites.add(ground, plat_1, plat_2, plat_3)
     self.platforms.add(ground, plat_1, plat_2, plat_3)
     self.events()
Ejemplo n.º 8
0
	def parse_map(self, filename, enemies, callback):
		with open(path.join(get_levels_dir(), filename), "r") as f:
			x = y = 0
			for line in f:
				for block in line.rstrip():
					if block != " ":
						#need a trigger block image
						if block in enemies:
							callback(self, enemies[block](40, 40, x, y))
						elif block == "E":
							trigger = Trigger(x, y)
							self.trigger_list.add(trigger)
						elif block == "w":
							walltrigger = WallTrigger(x, y)
							self.wallTrigger_list.add(walltrigger)
						elif block == "^":
							moving_platformsUD = MplatformUD(x, y)
							self.platform_list.add(moving_platformsUD)
						elif block == "v":
							vine = Vine(x, y)
							self.platform_list.add(vine)
						elif block == "V":
							vinetrigger = VineTrigger(x, y)
							self.vinetrigger_list.add(vinetrigger)
						elif block == ">":
							moving_platformsLR = MplatformLR(x, y)
							self.platform_list.add(moving_platformsLR)

						elif block == "P":
							self.Px = x
							self.Py = y 
						elif block == "A":
							self.Ax = x
							self.Ay = y 
						elif block == "y":
							self.ground_level = y
						else:
							platform = Platform(x, y)
							platform.image = self.mapdict[block]
							self.platform_list.add(platform)
					x += BLOCK_WIDTH


				if x > self.level_width:
					self.level_width = x
				x = 0
				y += BLOCK_HEIGHT

			self.level_height = y
Ejemplo n.º 9
0
 def createLimitWall(self, j, i):
     self.stageScale = 50
     x = self.stageScale * (j)
     y = self.stageScale * (i)
     
     sprite = Platform()
     sprite.rect = pygame.Rect((x, y), (self.stageScale, self.stageScale))
     
     # Define rectangulos que serviran para delimitar etapa y limitar movimiento de la camara
     if i == 0 and j == 0:
         self.firstRect = pygame.Rect((x, y), (self.stageScale, self.stageScale))
     elif i == (self.height - 1) and j == (self.width - 1):
         self.lastRect = pygame.Rect((x, y), (self.stageScale, self.stageScale))
         
     self.zGroup.add(sprite)
Ejemplo n.º 10
0
    def __init__(self, player):
        Level.__init__(self, player)

        self.level_limit = -1500

        # Array with width, height, x, and y of platform
        level = [
            [210, 70, 500, 500],
            [210, 70, 800, 400],
            [210, 70, 1000, 500],
            [210, 70, 1120, 280],
        ]

        # Go through the array above and add platforms
        for platform in level:
            block = Platform(platform[0], platform[1])
            block.rect.x = platform[2]
            block.rect.y = platform[3]
            self.level_elements.add(block)

        trampoline = Trampoline()
        trampoline.rect.x = 400
        trampoline.rect.y = GROUND_HEIGHT - 3
        self.level_elements.add(trampoline)

        self.level_elements.add(coins.Coin((400, GROUND_HEIGHT - 100)))
        self.level_elements.add(coins.Coin((800, 350)))
Ejemplo n.º 11
0
    def __init__(self):
        super().__init__()

        self.health = 50
        health_width = 5 * self.health
        health_height = 20
        self.health_bar = Platform(health_width, health_height)
        self.health_bar.rect.x = constants.SCREEN_WIDTH - health_width - 20
        self.health_bar.rect.y = constants.SCREEN_HEIGHT - health_height - 20
        self.health_bar.image.fill(constants.RED)
        self.attack_counter = 0

        width = 112
        height = 300

        self.defineAnimations()
        self.image = self.idle[0]
        self.frame_counter = 0
        self.currentAnimation = self.idle

        self.rect = self.image.get_rect()
        self.rect.x = constants.SCREEN_WIDTH - width
        self.rect.y = constants.GROUND_HEIGHT - height

        self.defineWinScreen()

        self.game = None
Ejemplo n.º 12
0
    def test_platform_collision(self):
        platform = Platform()
        self.assertEquals(True, CollisionsFinder.platform_collision(self.get_test_players(
            1), platform), "Should be a True because both x and y are inside/ right on platform")

        self.assertEquals(False, CollisionsFinder.platform_collision(self.get_test_players(
            2), platform), "Should be False becuase x coordinate is outside platform")

        self.assertEquals(False, CollisionsFinder.platform_collision(self.get_test_players(
            3), platform), "Should be False becuase y coordinate is outside platform")
Ejemplo n.º 13
0
def SW1(tasks, providers, capacity_unit, capacity_range): #simple greedy approach

    result = []

    for idx in range(1, capacity_range + 1):

        #create an auctioneer
        capacity = capacity_unit*idx
        auctioneer = Platform(capacity)

        start_time = time.process_time()
        #winner selection process
        W_requesters, req_threshold = auctioneer.WinningRequesterSelection(tasks)
        W_providers, pro_threshold = auctioneer.WinningProviderSelection(providers)

        #trimming process: make the # of selected requesters and providers equal
        W_requesters, W_providers, req_threshold, pro_threshold = auctioneer.Trimming(W_requesters, W_providers, req_threshold, pro_threshold)

        #cost calculation
        task_size = TaskSizer(W_requesters)
        cost = CostCalculator(W_providers, task_size)

        #calculate the payment to providers which guarantees truthfulness of providers
        payment = auctioneer.WPS_payment(W_providers, pro_threshold) #unit payment
        payment = payment*task_size #effective payment

        #calculate the fee for requesters which guarantees their truthfulness
        fee = auctioneer.WRS_payment(W_requesters, req_threshold)

        #mere social welfare: simple summation of task values without considering task depreciation after deadline
        mere_SW = MereSW(W_requesters) - cost

        #expected social welfare: summation of task values considering task depreciation after deadline
        expected_SW = ExpectedSW(W_requesters, W_providers) - cost

        #actually realized social welfare
        realized_SW, t_sub = PostSW(W_requesters, W_providers)
        realized_SW = realized_SW - cost

        #budget balance check before submission
        pre_budget = BudgetBalanceCheck(fee, payment)

        #budget balance after submission
        changed_fee, changed_payment = TimeVariantMoney(t_sub, W_requesters, W_providers, fee, payment)

        post_budget = BudgetBalanceCheck(changed_fee, changed_payment) #without consideration to alpha, mu and preference

        end_time = time.process_time()

        running_time = end_time - start_time

        #budget balance check
        if pre_budget < 0: #budget balance not met. Note that we can only check the budget balance before providers' actual submission
            result.append([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, running_time]) #return all zeros
        else: #budget balance met
            result.append([mere_SW, expected_SW, realized_SW, pre_budget, post_budget, payment.sum(), fee.sum(), changed_payment.sum(), changed_fee.sum(), cost, running_time])

    return np.array(result)
Ejemplo n.º 14
0
def SW2(tasks, providers, capacity_unit, capacity_range, power4requester, power4provider):

    result = []

    for idx in range(1, capacity_range + 1):

        #create an auctioneer
        capacity = capacity_unit*idx
        auctioneer = Platform(capacity)

        start_time = time.process_time()
        #winner selection process with consideration to alpha and mu
        W_requesters, req_threshold = auctioneer.New_WinningRequesterSelection(tasks, power4requester)
        W_providers, pro_threshold = auctioneer.New_WinningProviderSelection(providers, power4provider)

        #trimming process
        W_requesters, W_providers, req_threshold, pro_threshold = auctioneer.Trimming(W_requesters, W_providers, req_threshold, pro_threshold)

        #cost calculation
        task_size = TaskSizer(W_requesters)
        cost = CostCalculator(W_providers, task_size)

        #payment calculation
        payment = auctioneer.New_WPS_payment(W_providers, pro_threshold, power4provider)
        payment = payment*task_size

        #fee calculation
        fee = auctioneer.New_WRS_payment(W_requesters, req_threshold, power4requester)

        #mere social welfare
        mere_SW = MereSW(W_requesters) - cost

        #expected social welfare
        expected_SW = ExpectedSW(W_requesters, W_providers) - cost

        #actually realized social welfare
        realized_SW, t_sub = PostSW(W_requesters, W_providers)
        realized_SW = realized_SW - cost

        #budget balance check before submission
        pre_budget = BudgetBalanceCheck(fee, payment)

        #budget balance after submission
        changed_fee, changed_payment = TimeVariantMoney(t_sub, W_requesters, W_providers, fee, payment)

        post_budget = BudgetBalanceCheck(changed_fee, changed_payment)

        end_time = time.process_time()

        running_time = end_time - start_time

        #budget balance check
        if pre_budget < 0: #budget balance not met
            result.append([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, running_time]) #return all zeros
        else: #budget balance met
            result.append([mere_SW, expected_SW, realized_SW, pre_budget, post_budget, payment.sum(), fee.sum(), changed_payment.sum(), changed_fee.sum(), cost, running_time])#proposed heuristic approach

    return np.array(result)
Ejemplo n.º 15
0
    def __init__(self):
        pygame.init()

        #graphics dimenions: width and height
        self.screenW = 900
        self.screenH = 600
        self.charR = 50  #image radius
        self.charW = 50  #15 * 3.5
        self.charH = 100  #25 * 4
        self.score = 0
        self.lastBulletTime = 0

        self.groundH = 50  #ground height

        #player
        self.cat = Player(self.screenW, self.screenH, self.charW, self.charH,
                          self.groundH)

        #positions of platforms
        self.platforms = [
            Platform(200, 400),
            Platform(700, 500),
            Platform(500, 350)
        ]

        self.enemies = [Enemy(200, 300), Enemy(400, 200)]  #list of enemies
        self.bullets = []  #list of bullets

        #gameState
        self.gameover = False

        #manage how fast the screen updates
        self.clock = pygame.time.Clock()

        #set window width and height [width/2, height/2]
        self.screen = pygame.display.set_mode((self.screenW, self.screenH))

        #loop until the user clicks close button.
        self.done = False

        self.myfont = pygame.font.SysFont('arial bold', 40)
Ejemplo n.º 16
0
    def generate_platform(platforms: Platform, player: Player, gravity):
        # IMPORTANT: order has to be height, lengths, y_coordinate, x_coordinate, randomize_platform_terrain()
        # Length and height dictate y_coordinate, y_coordinate dictates x_coordinate, and randomize_platform_terrain()
        # Changes the length so it can't be changed back by the generate_platform_length()
        # TODO change back
        # new_platform = Platform()
        last_platform = platforms[len(platforms) - 1]
        # new_platform.height = generate_platform_height()
        # new_platform.length = generate_platform_length()
        # new_platform.y_coordinate = generate_platform_y_coordinate(player, last_platform, new_platform)

        # new_platform.platform_color = (0, 250, 0)
        # players_time_in_air = player.time_in_air(new_platform.y_coordinate, last_platform.y_coordinate, gravity)
        # new_platform.x_coordinate = generate_platform_x_coordinate(players_time_in_air, player.running_velocity, last_platform, new_platform)
        # randomize_platform_terrain(new_platform)

        # platforms.append(new_platform)
        new_platform = Platform()
        new_platform.x_coordinate = last_platform.right_edge
        platforms.append(new_platform)
        return platforms
Ejemplo n.º 17
0
    def test_on_platform(self):
        platform = Platform()
        player = Player()
        player.y_coordinate = 400 - player.height
        player.x_coordinate = platform.x_coordinate

        self.assertEquals(True, CollisionsFinder.on_platform(
            platform, player, 399), "Want true since player on platform")

        player.x_coordinate = platform.x_coordinate - 1
        player.y_coordinate = 400 - player.height - 1
        self.assertEquals(False, CollisionsFinder.on_platform(platform, player, False),
                          f"Want false since player at ({player.x_coordinate},{player.y_coordinate}) and platform at ({platform.x_coordinate}, {platform.y_coordinate})")
Ejemplo n.º 18
0
    def search_platform(self, title, ddate):
        # search the target_target_movie on itunes according its title and date
        title = title.lower()
        string = "&term=" + title
        new_date = datetime.strptime(ddate, '%Y-%m-%d')

        response = requests.get(self._link + string)
        result_dictionary = response.json()
        # no result found
        if (result_dictionary['resultCount'] == 0):
            return None

        # get the result list from the json
        results_list = result_dictionary['results']

        for item in results_list:

            date = self.date_convert(item['releaseDate'])
            # compare title and the date in result list
            if item['trackName'].lower() == title.lower() and date == new_date:
                #print("target_movie name: %s track name %s date %s target_movie date %s" % (target_movie.getTitle(),item['trackName'],date,target_movie.getDate()))
                # get the price of itunes
                if 'trackRentalPrice' in item.keys():
                    return Platform("itunes", item['trackRentalPrice'],
                                    item['trackViewUrl'])

                elif 'trackPrice' in item.keys():

                    return Platform("itunes", item['trackPrice'],
                                    item['trackViewUrl'])
                else:
                    for item_key in item.keys():
                        if 'Price' in item_key:

                            return Platform("itunes", item[item_key],
                                            item['trackViewUrl'])

                break
Ejemplo n.º 19
0
 def defineWinScreen(self):
     self.win_screen = Level()
     Level.level_list.pop(self.win_screen.level_num)
     self.win_screen.background.fill(constants.BLACK)
     self.win_screen.start_pos = (50, -120)
     platform0 = Platform(constants.SCREEN_WIDTH, 60)
     platform0.rect.x = 0
     platform0.rect.y = -60
     self.win_screen.platform_list.add(platform0)
     font = pygame.font.SysFont('Helvetica', 64, True, False)
     text = font.render("You Win", True, constants.WHITE)
     x = constants.SCREEN_WIDTH/2 - text.get_rect().width/2
     y = 250
     self.win_screen.background.blit(text, [x, y])
Ejemplo n.º 20
0
    def reset_variables():
        enemy = SimpleEnemy(GameRunner.doggo)
        # TODO change back
        # enemy.is_within_screen = False
        GameRunner.enemies = []
        platform = Platform()
        # TODO change back, but just wanna test movements
        platform.x_coordinate = 0
        platform.length = screen_length

        enemy.platform_on = platform
        GameRunner.platforms = [platform]
        GameRunner.doggo = Player()
        GameRunner.doggo.y_coordinate = platform.y_coordinate + 70 + GameRunner.doggo.height
        Player.attributes = GameObject.find_all_attributes(Player())
        print(Player.attributes)
        SimpleEnemy.attributes = GameObject.find_all_attributes(SimpleEnemy())
        Platform.attributes = GameObject.find_all_attributes(Platform())
        GameRunner.doggo.y_coordinate = GameRunner.platforms[
            0].y_coordinate - GameRunner.doggo.height - 100
        WallOfDeath.reset()
        ScoreKeeper.reset()
        HistoryKeeper.reset()
Ejemplo n.º 21
0
    def __init__(self, param):
        self.seed = np.random.RandomState(param['SEED'])
        self.param = param
        self.users = list()
        self.platforms = list()
        self.advertisers = list()
        self.schedule = RandomActivationByBreed(self)

        for i in range(param['N_USERS']):
            new_user = User(unique_id=i, model=self)
            self.users.append(new_user)
            self.schedule.add(new_user)

        for j in range(param['N_PLATFORMS']):
            new_platform = Platform(unique_id=j, model=self)
            for m in range(param['PAGES_PER_PLATFORM']):
                new_platform.create_page()
            self.platforms.append(new_platform)
            self.schedule.add(new_platform)

        for k in range(param['N_ADVERTISERS']):
            new_advertiser = Advertiser(unique_id=k, model=self)
            self.advertisers.append(new_advertiser)
            self.schedule.add(new_advertiser)
Ejemplo n.º 22
0
    def __init__(self, player):
        Map.__init__(self, player)

        # The length of the map make it negative to act as a positive
        self.map_limit = -3000

        # Create an array holding (width,height,x,y) I will randomly generate these later

        map = [[210, 20, 500, 450],
               [510, 70, 680, 490],
               [210, 70, 990, 360],
               [210, 70, 1230, 320],
               [210, 70, 1460, 190],
               [210, 70, 1790, 420]]

        for platform in map:
            # Pass the width and height to the Platform Class
            plat = Platform(platform[0], platform[1])
            plat.rect.x = platform[2]
            plat.rect.y = platform[3]
            # Put it in the player class so it can be applied to collisions
            plat.player = self.player
            # add it to the platforms list of collisions
            self.platforms.add(plat)
Ejemplo n.º 23
0
 def get_test_players(self, number):
     """Number 1 is player that equals platform coordinates 2 is changed x coordinate
     3 is changed y coordinate"""
     player = Player()
     platform = Platform()
     player.x_coordinate = platform.x_coordinate
     player.y_coordinate = platform.y_coordinate
     if number == 1:
         return player
     if number == 2:
         player.x_coordinate = platform.x_coordinate - player.height - 1
         return player
     if number == 3:
         player.y_coordinate = platform.y_coordinate - platform.height - 1
         return player
Ejemplo n.º 24
0
    def test_platform_boundaries(self):
        platform = Platform()
        player = self.get_test_players(1)
        last_player_x_coordinate = platform.x_coordinate - 3
        self.assertEquals(False, CollisionsFinder.platform_right_boundary(player, platform, last_player_x_coordinate), f"Should be False since last_player_x_coordinate" +
                          f" {last_player_x_coordinate} is less than platform right edge {platform.length + platform.x_coordinate}")

        self.assertEquals(True, CollisionsFinder.platform_left_boundary(player, platform, last_player_x_coordinate - player.height), f"Should be True since last_player_x_coordinate" +
                          f" {last_player_x_coordinate - player.height} is less than platform start {platform.x_coordinate + player.height}")

        last_player_x_coordinate = platform.x_coordinate + platform.length + 3
        self.assertEquals(True, CollisionsFinder.platform_right_boundary(player, platform, last_player_x_coordinate), f"Should be True since last_player_x_coordinate" +
                          f" {last_player_x_coordinate} is greater than platforms right edge {platform.length + platform.x_coordinate}")

        self.assertEquals(False, CollisionsFinder.platform_left_boundary(player, platform, last_player_x_coordinate - player.height), f"Should be False since last_player_x_coordinate" +
                          f" {last_player_x_coordinate - player.height} is greater than platforms start {platform.x_coordinate}")
Ejemplo n.º 25
0
    def __init__(self):
        pygame.init()

        #Obsługa głównej petli
        self.run = True

        #Ustawienia ekranu gry
        self.SCREEN_WIDTH = 500
        self.SCREEN_HEIGHT = 500
        self.screen = pygame.display.set_mode((self.SCREEN_WIDTH, self.SCREEN_HEIGHT))

        #Ustawienia gry
        self.PLATFORM_NUMBER = 5
        self.SKELETON_NUMBER = 4

        #Zegar
        self.clock = pygame.time.Clock()

        #Tworzenie instancji gracza
        self.player = Adventurer(250,250, self.screen,self.SCREEN_WIDTH, self.SCREEN_HEIGHT )

        #Zmienna do obsługi kolizji gracza z wrogiem
        self.hit_delay = 0

        #Tworzenie grup sprite
        self.all_sprites = pygame.sprite.Group()
        self.all_platforms = pygame.sprite.Group()
        self.all_enemies = pygame.sprite.Group()

        #Platformy startowe
        self.PLATFORM_LIST = [(0,self.SCREEN_HEIGHT - 40,self.SCREEN_WIDTH, 40),
                         (300, 430, 100, 10),
                         (100, 400, 100, 10),
                         (430,350,100,10),
                         (150, 270,100,10),
                         (200,200,100,10),
                         (250, 130, 100,10),
                         (50,50,200,20)]


        #Dodawanie spritów do grup
        self.all_sprites.add(self.player)
        for plat in self.PLATFORM_LIST:
            p = Platform(*plat) #wpisanie argumentów do argumentów klasy
            self.all_sprites.add(p)
            self.all_platforms.add(p)
Ejemplo n.º 26
0
def run_game():
    clock = pygame.time.Clock()
    pygame.init()
    settings = Settings()
    screen = pygame.display.set_mode(
        (settings.screen_width, settings.screen_height))
    pygame.display.set_caption("Cube Bro")

    platform = Platform(screen)
    player = Player(settings, screen, platform)
    player.place_player()

    while True:
        clock.tick(60)
        gf.check_events(settings, player, platform)
        player.update(settings, screen, platform)
        gf.update_screen(screen, settings, player, platform)
Ejemplo n.º 27
0
    def __init__(self, platformLoc, skeletonLoc, zombieLoc, player, endLoc):
        self.endLoc = endLoc
        self.background = Background()
        self.platformSprites = pygame.sprite.RenderPlain()
        self.enemySprites = pygame.sprite.RenderPlain()
        self.arrowSprites = pygame.sprite.RenderPlain()
        self.playerSprite = pygame.sprite.RenderPlain(player)
        self.laserSprites = player.laserSprites
        self.swordBoxSprites = player.swordBoxSprites

        for platform in platformLoc:
            self.platformSprites.add(Platform(platform[0], platform[1], platform[2]))
        for skeleton in skeletonLoc:
            self.enemySprites.add(Skeleton(skeleton[0], skeleton[1], self.arrowSprites, self.platformSprites))
        for zombie in zombieLoc:
            self.enemySprites.add(Zombie(zombie[0], zombie[1], self.platformSprites))

        self.camera = Camera(self.enemySprites, self.platformSprites, self.arrowSprites, self.laserSprites, player, self.background)
Ejemplo n.º 28
0
 def test_generate_platform_x_coordinate(self):
     last_platform = Platform()
     last_platform.x_coordinate = 100
     new_platform = Platform()
     new_platform.length = 100
     for x in range(250):
         last_platform.length = random.randint(50, 340)
         time_spent_in_air = 1
         new_platform_x_coordinate = generate_platform_x_coordinate(time_spent_in_air, Player.running_velocity, last_platform, new_platform)
         max_distance = time_spent_in_air * Player.running_velocity
         got_distance = new_platform_x_coordinate - (last_platform.x_coordinate + last_platform.length)
         jump_makeable =  max_distance >= got_distance
         self.assertTrue(jump_makeable, f"The jump should be makeable for the player max: {max_distance} vs got: {got_distance}")
         
         players_location = screen_length * .2
         last_platform_midpoint = last_platform.length * .5
         max_space_apart = screen_length - players_location - new_platform.length - last_platform_midpoint
         gotten_space_apart = new_platform_x_coordinate - (last_platform.x_coordinate + last_platform.length)
         platform_on_screen = gotten_space_apart <= max_space_apart
         self.assertTrue(platform_on_screen, f"The next platform should be on the screen when the player reaches the halfway point of the first platform want: {max_space_apart} vs gotten: {gotten_space_apart}")
Ejemplo n.º 29
0
    def define_levels(self, level_num, init):
        # Define Level 0
        if init or level_num == 0:
            if init:
                level0 = Level()
                level0.start_pos = (100,
                                    constants.GROUND_HEIGHT - Player.HEIGHT)
                x = constants.SCREEN_WIDTH - self.player.rect.width
                y = constants.GROUND_HEIGHT - Player.HEIGHT
                level0.end_pos = (x, y)
            else:
                level0 = Level.level_list[0]
                level0.platform_list.empty()
                level0.enemy_list.empty()
                level0.tripped_projectiles.empty()

            platform0 = Platform(constants.SCREEN_WIDTH, 60)
            platform0.rect.x = 0
            platform0.rect.y = constants.SCREEN_HEIGHT - platform0.rect.height
            level0.platform_list.add(platform0)

            for i in range(4, 8):
                tp0 = TrippedProjectile()
                tp0.player = self.player
                tp0.rect.x = i * 100
                tp0.rect.y = constants.GROUND_HEIGHT - 250
                level0.tripped_projectiles.add(tp0)

            hidden_wall = Platform(20, constants.SCREEN_HEIGHT)
            hidden_wall.rect.x = -20
            hidden_wall.rect.y = 0
            level0.platform_list.add(hidden_wall)

        # Define Level 1
        if init or level_num == 1:
            if init:
                level1 = Level()
                level1.start_pos = (0, constants.GROUND_HEIGHT - Player.HEIGHT)
                x = constants.SCREEN_WIDTH - self.player.rect.width
                y = constants.GROUND_HEIGHT - Player.HEIGHT
                level1.end_pos = (x, y)
            else:
                level1 = Level.level_list[1]
                level1.platform_list.empty()
                level1.enemy_list.empty()
                level1.tripped_projectiles.empty()

            platform0 = Platform(200, 60)
            platform0.rect.x = 0
            platform0.rect.y = constants.SCREEN_HEIGHT - platform0.rect.height
            level1.platform_list.add(platform0)

            platform1 = MovingPlatform(100, 20)
            platform1.player = self.player
            right = constants.SCREEN_WIDTH - platform1.rect.width - 140
            platform1.rect.x = right
            platform1.rect.y = constants.SCREEN_HEIGHT - 140
            platform1.x_change = -4
            platform1.boundary_left = 140
            platform1.boundary_right = right
            level1.platform_list.add(platform1)

            platform2 = Platform(200, 60)
            platform2.rect.x = constants.SCREEN_WIDTH - platform2.rect.width
            platform2.rect.y = constants.SCREEN_HEIGHT - platform2.rect.height
            level1.platform_list.add(platform2)

        # Define Level 2
        if init or level_num == 2:
            if init:
                level2 = Level()
                level2.start_pos = (0, constants.GROUND_HEIGHT - Player.HEIGHT)
                x = constants.SCREEN_WIDTH - self.player.rect.width
                y = constants.GROUND_HEIGHT - Player.HEIGHT
                level2.end_pos = (x, y)
            else:
                level2 = Level.level_list[2]
                level2.platform_list.empty()
                level2.enemy_list.empty()
                level2.tripped_projectiles.empty()

            platform0 = Platform(constants.SCREEN_WIDTH, 60)
            platform0.rect.x = 0
            platform0.rect.y = constants.SCREEN_HEIGHT - platform0.rect.height
            level2.platform_list.add(platform0)

            platform1 = Platform(20, constants.SCREEN_HEIGHT - 100)
            platform1.rect.x = constants.SCREEN_WIDTH / 2
            platform1.rect.y = 100
            level2.platform_list.add(platform1)

            platform2 = MovingPlatform(100, 20)
            platform2.player = self.player
            right = constants.SCREEN_WIDTH - platform2.rect.width - 140
            platform2.rect.x = right
            platform2.rect.y = constants.SCREEN_HEIGHT - 140
            platform2.x_change = -4
            platform2.boundary_left = 40
            platform2.boundary_right = right + 100
            level2.platform_list.add(platform2)

            platform3 = MovingPlatform(100, 20)
            platform3.player = self.player
            platform3.rect.x = 200
            platform3.rect.y = 300
            platform3.y_change = -2
            platform3.boundary_bottom = constants.GROUND_HEIGHT - 140
            platform3.boundary_top = 100
            level2.platform_list.add(platform3)

            cannon0 = Cannon("left")
            cannon0.game = self
            cannon0.rect.x = constants.SCREEN_WIDTH - Cannon.WIDTH
            cannon0.rect.y = constants.GROUND_HEIGHT - 80
            level2.platform_list.add(cannon0)

            cannon1 = Cannon("left")
            cannon1.game = self
            cannon1.rect.x = constants.SCREEN_WIDTH - Cannon.WIDTH
            cannon1.rect.y = cannon0.rect.y - 60
            cannon1.fire_counter = 45
            level2.platform_list.add(cannon1)

            tp0 = TrippedProjectile()
            tp0.player = self.player
            tp0.rect.x = 700
            tp0.rect.y = 50
            level2.tripped_projectiles.add(tp0)

        # define final level
        if init or level_num == len(Level.level_list) - 1:
            if init:
                final_level = Level()
                x = 100
                y = constants.GROUND_HEIGHT - Player.HEIGHT
                final_level.start_pos = (x, y)
                x = constants.SCREEN_WIDTH - self.player.rect.width
                final_level.end_pos = (x, y)
            else:
                final_level = Level.level_list[level_num]
                final_level.platform_list.empty()
                final_level.enemy_list.empty()
                final_level.tripped_projectiles.empty()

            platform0 = Platform(constants.SCREEN_WIDTH, 60)
            platform0.rect.x = 0
            platform0.rect.y = constants.SCREEN_HEIGHT - platform0.rect.height
            final_level.platform_list.add(platform0)

            hidden_wall = Platform(20, constants.SCREEN_HEIGHT)
            hidden_wall.rect.x = -20
            hidden_wall.rect.y = 0
            final_level.platform_list.add(hidden_wall)

            cannon0 = Cannon("left")
            cannon0.game = self
            cannon0.rect.x = constants.SCREEN_WIDTH - Cannon.WIDTH - 112
            cannon0.rect.y = constants.GROUND_HEIGHT - Cannon.HEIGHT
            final_level.platform_list.add(cannon0)

            boss = Boss()
            boss.game = self
            final_level.enemy_list.add(boss)
            final_level.platform_list.add(boss.health_bar)
Ejemplo n.º 30
0
    def __init__(self, win, W, H, BG):
        self.WINDOW = win
        self.W = W
        self.H = H
        self.WH = (W + H) / 2
        self.BG = BG

        self.server_funcs = ServerClass()

        # Colours
        self.white = (255, 255, 255)
        self.button_colour = (217, 215, 126, 140)
        self.button_colour_selected = (217, 215, 126, 190)
        self.black = (0, 0, 0)
        self.black_transparent = (0, 0, 0, 150)
        self.green = (0, 255, 0)
        self.red = (255, 0, 0, 180)

        # Menu variables
        self.playing = True
        self.menu_open = True
        self.interface = False
        self.create = False
        self.join = False
        self.pause = False
        self.show_prompt = False
        self.main_menu = False
        self.waiting_for_other = False
        self.keys = {}
        self.keys_2 = {}
        self.key_events = {pygame.KEYDOWN: [[], []], pygame.KEYUP: [[], []]}
        self.key_events_to_send = {
            pygame.KEYDOWN: [[], []],
            pygame.KEYUP: [[], []]
        }
        self.mouse_events = {
            pygame.MOUSEBUTTONDOWN: [[], []],
            pygame.MOUSEBUTTONUP: [[], []]
        }
        self.mouse_events_to_send = {
            pygame.MOUSEBUTTONDOWN: [[], []],
            pygame.MOUSEBUTTONUP: [[], []]
        }
        self.mouse_buttons = {}
        self.mouse_buttons_2 = {}

        # Platforms
        self.platforms = pygame.sprite.Group()
        surface = pygame.surface.Surface(
            (round(self.W * 0.139), round(W * 0.056)), pygame.SRCALPHA)
        surface.fill((0, 0, 0, 150))
        self.platform_1 = Platform(
            surface,
            pygame.rect.Rect(round(W * 0.174), round(H * 0.611),
                             round(W * 0.139), round(H * 0.056)))
        self.platform_2 = Platform(
            surface,
            pygame.rect.Rect(round(W * 0.694), round(H * 0.611),
                             round(W * 0.139), round(H * 0.056)))
        surface = pygame.surface.Surface((W, round(H * 0.0602)),
                                         pygame.SRCALPHA)
        surface.set_colorkey((0, 0, 0))
        self.ground = Platform(
            surface, pygame.rect.Rect(0, round(H * 0.942), W, H * 0.0602))
        self.platforms.add(self.platform_1, self.platform_2, self.ground)

        # Players
        self.character_class = {0: Mage, 1: Boxer}
        self.player = None
        self.player_2 = None
        self.players = [
            'Mage', 'Boxer', 'Dwarf', 'Soldier', 'Gorgone', 'Tenniswoman'
        ]
        self.character = -7
        self.character_2 = 0
        self.character_selected = -6
        self.descriptions = open('media/descriptions.txt', 'r').readlines()
        self.stats = [['70', '5', '15', '25'], ['85', '8', '15', '30'],
                      ['10', '1', '1', '2'], ['70', '5', '15', '25'],
                      ['70', '5', '15', '25'], ['70', '5', '15', '25']]
        self.stats_max = [100, 10, 20, 35]
        self.stats_names = [['Health', 'Punch', 'Fireball', 'Lightning'],
                            ['Health', 'Punch', 'Spring Punch', 'Air KO'],
                            ['Health', 'Punch', 'Axe', 'Rage'],
                            ['Health', 'Punch', 'Words', 'Bear'],
                            ['Health', 'Punch', 'Snake', 'Stone'],
                            ['Health', 'Punch', 'Racket', 'Smash']]
        self.attacks_dict = [
            'media/Mage_animation/', 'media/Boxer_animation/',
            'media/Dwarf_animation/', 'media/Soldier_animation/',
            'media/Gorgone_animation/', 'media/Tenniswoman_animation/'
        ]
        self.player_sprites = pygame.sprite.Group()

        # Menu values
        self.info_font = pygame.font.SysFont('toonaround',
                                             round(self.WH * 0.0154))
        self.menu_characters_dict = {}
        for i in range(6):
            self.menu_characters_dict[self.players[i]] = [
                self.descriptions[i][:-1], self.stats[i], self.stats_names[i]
            ]
        self.title_font = pygame.font.SysFont('toonaround',
                                              round(self.WH * 0.154))
        self.title_font1 = self.title_font.render('Pygomania', True,
                                                  (255, 255, 255))
        self.title_font2 = self.title_font.render('Pygomania', True, (0, 0, 0))

        self.prompt_font = pygame.font.SysFont('toonaround',
                                               round(self.WH * 0.043))
        self.prompt1 = self.prompt_font.render('Press Space to Continue', True,
                                               (255, 255, 255))
        self.prompt2 = self.prompt_font.render('Press Space to Continue', True,
                                               (0, 0, 0))
        self.start_button = pygame.image.load('media/start_button.png')
        self.start_button = pygame.transform.scale(
            self.start_button, (round(W * 0.16), round(H * 0.094)))
        self.start_button_hovering = pygame.image.load(
            'media/start_button_hovering.png')
        self.start_button_hovering = pygame.transform.scale(
            self.start_button_hovering, (round(W * 0.16), round(H * 0.094)))
        self.start_rect = pygame.Rect(round(W * 0.42), round(H * 0.8),
                                      round(W * 0.16), round(H * 0.094))
        self.start = False

        self.join_text = self.text('toonaround', round(self.WH * 0.128),
                                   "Join",
                                   (round(W * 0.486), round(H * 0.278)))
        self.join_rect = self.join_text[0].get_rect(topleft=self.join_text[1])
        self.create_text = self.text('toonaround', round(self.WH * 0.128),
                                     "Create",
                                     (round(W * 0.486), round(H * 0.556)))
        self.create_rect = self.create_text[0].get_rect(
            topleft=self.create_text[1])
        self.waiting = self.text("toonaround", round(self.WH * 0.128),
                                 "Waiting for another player...",
                                 (round(W / 2), round(H * 0.444)))

        self.title_text = self.text('toonaround', round(self.WH * 0.077),
                                    'Pygomania',
                                    (round(W / 2), round(H * 0.078)))
        self.rect_surface = pygame.surface.Surface(
            (round(W * 0.139), round(H * 0.144)), pygame.SRCALPHA)
        self.rect_surface.fill(self.button_colour)
        self.rect_surfaces = []
        for i in range(6):
            self.rect_surfaces.append(self.rect_surface.copy())
        self.name_surfaces = []
        for x in range(2):
            for y in range(3):
                i = 3 * x + y
                self.name_surfaces.append(
                    self.text('toonaround', round(self.WH * 0.0256),
                              self.players[i],
                              (round(W * 0.653) * x + round(W * 0.174),
                               round(H * 0.2 * y + H * 0.45))))
        self.menu_rects = []
        for x in range(2):
            for y in range(3):
                self.menu_rects.append(
                    pygame.rect.Rect(
                        round(W * 0.653) * x + round(W * 0.104),
                        round(self.H * 0.2 * y + H * 0.3),
                        self.rect_surface.get_width(),
                        self.rect_surface.get_height()))
        self.info_box = pygame.Surface((round(W * 0.313), round(H * 0.389)),
                                       pygame.SRCALPHA)
        self.info_box.fill(self.black_transparent)
        self.x_start = round(W * 0.344) + round(self.W / 144)
        self.time = 0

        self.prev_time = time.time()

        # Temporary values
        self.tmp = 1

        # Server values
        self.connected = False
        SERVER = socket.gethostbyname(socket.gethostname())
        # SERVER = '192.168.1.126'
        self.HEADER = 16
        PORT = 10632
        self.ADDR = (SERVER, PORT)
        self.FORMAT = 'utf-8'
        self.DISCONNECT_MSG = '!DISCONNECT'
        self.receive_object = [{
            pygame.KEYDOWN: [[], []],
            pygame.KEYUP: [[], []]
        }, {
            pygame.MOUSEBUTTONDOWN: [[], []],
            pygame.MOUSEBUTTONUP: [[], []]
        }, (0, 0)]
        # toutes les touches vraies, les touches event, les boutons de la souris,
        # les boutons event, la position de la souris
        self.internal_time_stamp = pygame.time.get_ticks()
Ejemplo n.º 31
0
    def update(self):

        #Platformy
        self.all_platforms.update()

        # Utrzymanie odpowiedniej ilosci wrogów na ekranie
        self.create_enemy()

        # Wrogowie
        self.all_enemies.update()

        #Sprawdzenie kolizji player-platform
        platform_colide = pygame.sprite.spritecollide(self.player,self.all_platforms, False )

        if platform_colide:
            self.player.y = platform_colide[0].rect.top - self.player.height #ustawienie gracza na platformie w przypadku kolizji
            self.player.vel[1] = 0 #usunięcie przemieszczenia pionowego

        # Przesuwanie "ekranu" w góre jeżeli gracz osiagnie 3/4 wysokości ekranu
        if self.player.rect.y <= self.SCREEN_HEIGHT /4:
            self.player.y += abs(self.player.vel[1])
            for plat in self.all_platforms:
                plat.rect.y += abs(self.player.vel[1])
                #Usunięcie platform poniżej dolnej granicy ekranu
                if plat.rect.top >= self.SCREEN_HEIGHT:
                    plat.kill()
                    self.player.score += 10 #Zwiekszenie punktacji wraz z każdą pokonaną platformą

            #Powtórzenie operacji w przypadku wrogów
            for enemy in self.all_enemies:
                enemy.rect.y += abs(self.player.vel[1])
                if enemy.rect.top >= self.SCREEN_HEIGHT:
                    enemy.kill()


        #Utrzymanie odpowieniej ilosci platform na ekranie
        while len(self.all_platforms) < self.PLATFORM_NUMBER:
            width = random.randrange(100,300)
            height = random.randrange(5,30)
            p = Platform(random.randrange(0,self.SCREEN_WIDTH - width),random.randrange(-30,-10),width,height)
            self.all_platforms.add(p)
            self.all_sprites.add(p)

        #Gracz
        self.player.update(self.all_platforms)

        #Sprawdzanie czy gracz ciagle pozostaje na ekranie "GAME OVER CONDITION"
        if self.player.rect.bottom >= self.SCREEN_HEIGHT:
            for sprite in self.all_sprites:
                sprite.rect.y -= max(self.player.vel[1],10) #efekt spadania gracza oraz platform
                if sprite.rect.bottom < 0:
                    sprite.kill() #usuwanie obiektów opuszczających ekran
        if len(self.all_platforms) == 0:
            self.game_over_screen()

        #Sprawdzenie poziomu zycia gracza
        if self.player.health <= 0:
            self.game_over_screen()

        #Sprawdzenie kolizji gracz-wrog
        self.collision_check()
Ejemplo n.º 32
0
    '  --  --  ',
    '   ----   ',
    '    --    ']

sprite_group = pygame.sprite.Group()
sprite_group.add(ball)
sprite_group.add(arcanoid)
platf = []

x = 25
y = 25
i=0
for row in level:
    for col in row:
        if col == '-':
            pl = Platform (x, y)
            sprite_group.add(pl)
            platf.append(pl)
            i+=1
        x += 35
    y += 40
    x = 25

done = True
pygame.key.set_repeat(1, 1) #Залипание клавиш

while done:
    for e in pygame.event.get():
        if e.type == pygame.QUIT:
            done = False
Ejemplo n.º 33
0
def SW(time_unit, task_n, provider_n, max_value, max_deadline, max_alpha, max_task_size, max_provider_bid, max_provider_skill, max_mu, task_columns, provider_columns, iteration, capacity, output):

#mere social welfare
  mere1 = []
  mere2 = []

#expected social welfare
  expected1 = []
  expected2 = []
  expected3 = []

#real social welfare
  real1 = []
  real2 = []
  real3 = []

#budget before submission
  before1 = []
  before2 = []
  before3 = []

#budget after submission
  after1 = []
  after2 = []
  after3 = []

#payment before submission
  p_before1 = []
  p_before2 = []
  
#fee before submission
  f_before1 = []
  f_before2 = []

#payment after submission
  p_after1 = []
  p_after2 = []
  p_after3 = []
  
#fee after submission 
  f_after1 = []
  f_after2 = []
  f_after3 = []

#cost
  cost1 = []
  cost2 = []
  
  
  for _ in range(iteration):
    
#participants creation
    tasks = TaskCreator(task_n, max_value, max_alpha, max_deadline, max_task_size)
    providers = ProviderCreator(provider_n, max_mu, max_provider_bid, max_provider_skill)

    auctioneer = Platform(capacity)

#winner selection
#without consideration to alpha and mu
    W_requesters, req_threshold = auctioneer.WinningRequesterSelection(tasks)
    W_providers, pro_threshold = auctioneer.WinningProviderSelection(providers)

#with consideration to alpha and mu
    New_W_requesters, New_req_threshold = auctioneer.New_WinningRequesterSelection(tasks)
    New_W_providers, New_pro_threshold = auctioneer.New_WinningProviderSelection(providers)

#trimming process
    W_requesters, W_providers = auctioneer.Trimming(W_requesters, W_providers)
    New_W_requesters, New_W_providers = auctioneer.Trimming(New_W_requesters, New_W_providers)

    c1 = cost_calculator(W_providers)
    c2 = cost_calculator(New_W_providers)
    
#payment
#temporary payment without consideration to alpha, mu
    payment1 = auctioneer.WPS_payment(W_providers, pro_threshold)
#temporary fee
    fee1 = auctioneer.WRS_payment(W_requesters, req_threshold)
    
    
    
    
    
#temporary payment with consideration to alpha, mu
    payment2 = auctioneer.New_WPS_payment(New_W_providers, New_pro_threshold)
#temporary fee
    fee2 = auctioneer.New_WRS_payment(New_W_requesters, New_req_threshold)



#1. preference ordering
    

#satisfaction level without consideration of preference but with alpha, mu: 2
    New_requester_preference_ordering = auctioneer.ordering_matrix(New_W_providers,provider_columns)
    New_provider_preference_ordering = auctioneer.ordering_matrix(New_W_requesters,task_columns)

    New_r_rank, New_r_mean_rank = benchmark_satisfaction_level(New_requester_preference_ordering)
    New_p_rank, New_p_mean_rank = benchmark_satisfaction_level(New_provider_preference_ordering)

    New_r_pdf, New_r_cdf = bench_distribution(New_r_rank)
    New_p_pdf, New_p_cdf = bench_distribution(New_p_rank)


#Run Stable Marriage Algorithm: In match, requester: keys, providers: values
    match = auctioneer.SMA(New_requester_preference_ordering, New_provider_preference_ordering)

#mere social welfare---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    result = mere_social_welfare(W_requesters) #without consideration to alpha, mu
    result1 = mere_social_welfare(New_W_requesters) #with consideration to alpha, mu
#print('mere social welfare 1: %f' %result)
#print('mere social welfare 2: %f' %result1)

#expected social welfare---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    social_welfare1 = SystemExpectedSocialwelfare(W_requesters, W_providers, time_unit) #without consideration to preference & alpha, mu
    social_welfare2 = SystemExpectedSocialwelfare(New_W_requesters, New_W_providers, time_unit) #with consideration to alpha, mu but without preference
    social_welfare3 = SocialWelfare(New_W_requesters, New_W_providers, time_unit, match) #With consideration to preference & alpha, mu

#print('expected social welfare 1: %f' %social_welfare1)
#print('expected social welfare 2: %f' %social_welfare2)
#print('expected social welfare 3: %f' %social_welfare3)

#print('D 1:%f' %(result-social_welfare1))
#print('D 2:%f' %(result1-social_welfare2))
#print('D 3:%f' %(result1-social_welfare3))


#real social welfare with submission time---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    post_social_welfare1, t_sub1 = Existing_SocialWelfare(W_requesters, W_providers, time_unit) #without consideration to preference, alpha, mu
    post_social_welfare2, t_sub2 = Existing_SocialWelfare(New_W_requesters, New_W_providers, time_unit) #with consideration to alpha, mu
    post_social_welfare3, t_sub3 = Proposed_SocialWelfare(New_W_requesters, New_W_providers, time_unit, match) #with consideration to preference & alpha, mu

#print('real social welfare 1:%f' %post_social_welfare1)
#print('real social welfare 2:%f' %post_social_welfare2)
#print('real social welfare 3:%f' %post_social_welfare3)


#difference between expected social welfare and real social welfare
#print('difference 1: %f' %(social_welfare1-post_social_welfare1))
#print('difference 2: %f' %(social_welfare2-post_social_welfare2))
#print('difference 3: %f' %(social_welfare3-post_social_welfare3))


#budget balance check before submission---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    net_budget1 = budget_balance_check(fee1, payment1) #without consideration to alpha, mu
    net_budget2 = budget_balance_check(fee2, payment2) #with consideration to alpha, mu
    net_budget3 = budget_balance_check(fee2, payment2) #with consideration to alpha, mu and preference

#print('budget before submission(without alpha, mu, preference): %f' %net_budget1)
#print('budget before submission(with alpha and mu): %f' %net_budget2)
#print('budget before submission(with alpha, mu and preference): %f' %net_budget3)

#budget balance after submission---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    changed_fee1, changed_payment1 = bench_time_variant_money(t_sub1, W_requesters, W_providers, fee1, payment1, time_unit)
    changed_fee2, changed_payment2 = bench_time_variant_money(t_sub2, New_W_requesters, New_W_providers, fee2, payment2, time_unit)
    changed_fee3, changed_payment3 = time_variant_money(t_sub3, New_W_requesters, New_W_providers, fee2, payment2, match, time_unit)
    
    
    
    changed_budget1 = budget_balance_check(changed_fee1, changed_payment1) #without consideration to alpha, mu and preference
    changed_budget2 = budget_balance_check(changed_fee2, changed_payment2) #with consideration to alpha, mu
    changed_budget3 = budget_balance_check(changed_fee3, changed_payment3) #with consideration to alpha, mu and preference

#print('budget after submission(without alpha,mu, preference): %f' %changed_budget1)
#print('budget after submission(with alpha,mu): %f' %changed_budget2)
#print('budget after submission(with alpha,mu, preference): %f' %changed_budget3)
 
    #print('iteration: %f, capacity: %f' %(it, unit*(ran+1))) 
 
#budget balance check 
    if net_budget1 < 0:
      result = 0
      social_welfare1 = 0
      post_social_welfare1 = 0
      net_budget1 = 0
      changed_budget1 = 0
      payment1 = 0
      fee1 = 0
      changed_payment1 = 0
      changed_fee1 = 0
      c1 = 0
    
    if net_budget2 < 0:
      result1 = 0
      social_welfare2 = 0; social_welfare3 = 0
      post_social_welfare2 = 0; post_social_welfare3 = 0
      net_budget2 = 0; net_budget3 = 0
      changed_budget2 = 0; changed_budget3 = 0 
      payment2 = 0; fee2 = 0
      changed_payment2 = 0; changed_payment3 = 0
      changed_fee2 = 0; changed_fee3 = 0 
      c2 = 0
      
#mere social welfare
    mere1.append(result)
    mere2.append(result1)

#expected social welfare
    expected1.append(social_welfare1)
    expected2.append(social_welfare2)
    expected3.append(social_welfare3)

#real social welfare
    real1.append(post_social_welfare1)
    real2.append(post_social_welfare2)
    real3.append(post_social_welfare3)

#budget before submission
    before1.append(net_budget1)
    before2.append(net_budget2)
    before3.append(net_budget3)

#budget after submission
    after1.append(changed_budget1)
    after2.append(changed_budget2)
    after3.append(changed_budget3) 
    
#payment before submission
    p_before1.append(np.sum(payment1))
    p_before2.append(np.sum(payment2))
    
#fee before submission   
    f_before1.append(np.sum(fee1))
    f_before2.append(np.sum(fee2))
    
#payment after submission   
    p_after1.append(np.sum(changed_payment1))
    p_after2.append(np.sum(changed_payment2))
    p_after3.append(np.sum(changed_payment3))

#fee after submission    
    f_after1.append(np.sum(changed_fee1))  
    f_after2.append(np.sum(changed_fee2))   
    f_after3.append(np.sum(changed_fee3)) 
    
#cost 
    cost1.append(c1)
    cost2.append(c2)
  
  
  
  
  
  
  #mere social welfare
  mere1 = [x for x in mere1 if x != 0]
  mere2 = [x for x in mere2 if x != 0]#
  if len(mere2) == 0:
    mere2 = 0
#expected social welfare
  expected1 = [x for x in expected1 if x != 0]
  expected2 = [x for x in expected2 if x != 0]#
  expected3 = [x for x in expected3 if x != 0]#
  if len(expected2) == 0:
    expected2 = 0
  if len(expected3) == 0:
    expected3 = 0    
#real social welfare
  real1 = [x for x in real1 if x != 0]
  real2 = [x for x in real2 if x != 0]#
  real3 = [x for x in real3 if x != 0]#
  if len(real2) == 0:
    real2 = 0
  if len(real3) == 0:
    real3 = 0    
#budget before submission
  before1 = [x for x in before1 if x != 0]
  before2 = [x for x in before2 if x != 0]#
  before3 = [x for x in before3 if x != 0]#
  if len(before2) == 0:
    before2 = 0
  if len(before3) == 0:
    before3 = 0    
#budget after submission
  after1 = [x for x in after1 if x != 0]
  after2 = [x for x in after2 if x != 0]#
  after3 = [x for x in after3 if x != 0]#
  if len(after2) == 0:
    after2 = 0
  if len(after3) == 0:
    after3 = 0    
#payment before submission
  p_before1 = [x for x in p_before1 if x != 0]
  p_before2 = [x for x in p_before2 if x != 0]#
  if len(p_before2) == 0:
    p_before2 = 0
#fee before submission
  f_before1 = [x for x in f_before1 if x != 0]
  f_before2 = [x for x in f_before2 if x != 0]#
  if len(f_before2) == 0:
    f_before2 = 0
    
#payment after submission
  p_after1 = [x for x in p_after1 if x != 0]
  p_after2 = [x for x in p_after2 if x != 0]#
  p_after3 = [x for x in p_after3 if x != 0]#
  if len(p_after3) == 0:
    p_after3 = 0
  if len(p_after2) == 0:
    p_after2 = 0
    
#fee after submission 
  f_after1 = [x for x in f_after1 if x != 0]
  f_after2 = [x for x in f_after2 if x != 0]#
  f_after3 = [x for x in f_after3 if x != 0]#
  if len(f_after3) == 0:
    f_after3 = 0
  if len(f_after2) == 0:
    f_after2 = 0  
    
#cost
  cost1 = [x for x in cost1 if x != 0]
  cost2 = [x for x in cost2 if x != 0]#
  
  if len(cost2) == 0:
    cost2 = 0
  
  
  
  #output.put((mere1,mere2,expected1,expected2,expected3,real1,real2,real3,before1,before2, before3, after1, after2, after3, p_before1, p_before2, f_before1, f_before2, p_after1, p_after2, p_after3,
  #f_after1, f_after2, f_after3, cost1, cost2))
   
  output.put((np.mean(mere1), np.mean(mere2), np.mean(expected1), np.mean(expected2), np.mean(expected3), np.mean(real1), np.mean(real2), np.mean(real3), 
  np.mean(before1), np.mean(before2), np.mean(before3), np.mean(after1), np.mean(after2), np.mean(after3), np.mean(p_before1), np.mean(p_before2), np.mean(f_before1), 
  np.mean(f_before2), np.mean(p_after1), np.mean(p_after2), np.mean(p_after3), np.mean(f_after1), np.mean(f_after2), np.mean(f_after3), np.mean(cost1), np.mean(cost2)))
Ejemplo n.º 34
0
    def createSprite(self,lines, j, i, character):
        self.stageScale = 50
        
        # Para que player aparezca en esquina superior izquierda
        x = self.stageScale * (j)
        y = self.stageScale * (i)

        sprite = Platform()
        sprite.i = i
        sprite.j = j

        if character == "a":
            sprite.image = self.imageDictionary["topCement"]
            sprite.imagen2 = self.imageDictionary["topCement"]
        elif character == "t":
            sprite.image = self.imageDictionary["lowEarth"]
            sprite.imagen2 = self.imageDictionary["lowEarth"]
        elif character == "n":
            sprite.image = self.imageDictionary["grass"]
            sprite.imagen2 = self.imageDictionary["grass"]
        elif character == "ñ":
            sprite.image = self.imageDictionary["topGrass"]
            sprite.imagen2 = self.imageDictionary["topGrass"]
        elif character == "s":
            sprite.image = self.imageDictionary["sand"]
            sprite.imagen2 = self.imageDictionary["sand"]
        elif character == "b":##################
            sprite.image = self.imageDictionary["blueAlpha"]##################
            sprite.imagen2 = self.imageDictionary["blue"]##################
            sprite.color = "Blue"     ##################
        elif character == 'r':##################
            sprite.image = self.imageDictionary["lava"]##################
            sprite.imagen2 = self.imageDictionary["lava"]##################
            #sprite.color = "Green"##################
        elif character == "O":
             sprite.image = self.imageDictionary["blueAlpha"]
             sprite.imagen2 = self.imageDictionary["blue"]



             sprite.id = "Horizontal"
             sprite.color = "Blue" 


        elif character == "P":
            sprite.image = self.imageDictionary["greenAlpha"]
            sprite.imagen2 = self.imageDictionary["green"]
            #sprite.delta_x = 5
            #sprite.lim_x = 20
            #sprite.delta_y = 5
            #sprite.lim_y = 20
            #sprite.delta_y = 5
            #sprite.tipo_movimiento = "0"
            sprite.id = "Horizontal"
            sprite.color = "Green"
        elif character == "Q":
            sprite.image = self.imageDictionary["blueAlpha"]
            sprite.imagen2 = self.imageDictionary["blue"]

            sprite.id = "Vertical"
            sprite.color = "Blue" 
        elif character == "F":
            sprite.image = self.imageDictionary["greenAlpha"]
            sprite.imagen2 = self.imageDictionary["green"]
            sprite.id = "Vertical"
            sprite.color = "Green"    

        else: 
            sprite.image = self.imageDictionary["grass"]
            sprite.imagen2 = self.imageDictionary["grass"]
            sprite.color = "Green"

        if character == "P" or character == "O":
            colorlargo = self.createPlatform(lines,j,i,"H")
            color = colorlargo[0]
            scale_x = colorlargo[1]
            scale_y = colorlargo[2]
            sprite.color = color
            #scale = 2
            x = self.stageScale * (j)
            y = self.stageScale * (i)
            sprite.scale_x = scale_x
            sprite.scale_y = scale_y
            sprite.x_scale = self.stageScale *scale_x
            sprite.y_scale = self.stageScale*scale_y
            sprite.image = pygame.transform.scale(sprite.image, (int(scale_x*self.stageScale), int(scale_y*self.stageScale)))
            sprite.imagen2 = pygame.transform.scale(sprite.imagen2, (int(scale_x*self.stageScale), int(scale_y*self.stageScale)))
            sprite.rect = pygame.Rect((x, y), (scale_x*self.stageScale, scale_y*self.stageScale))
            sprite.imagenoriginal = sprite.image
        elif character == "F" or character == "Q":
            sprite.x_scale = self.stageScale 
            sprite.y_scale = self.stageScale
            sprite.image = pygame.transform.scale(sprite.image, (int(0.5*self.stageScale), 5*self.stageScale))
            sprite.imagen2 = pygame.transform.scale(sprite.imagen2, (int(0.5*self.stageScale), 5*self.stageScale))
            sprite.rect = pygame.Rect((x, y), (int(0.5*self.stageScale), 5*self.stageScale))
            sprite.imagenoriginal = sprite.image   
        else:
            sprite.x_scale = self.stageScale 
            sprite.y_scale = self.stageScale
            sprite.image = pygame.transform.scale(sprite.image, (self.stageScale, self.stageScale))
            sprite.imagen2 = pygame.transform.scale(sprite.imagen2, (self.stageScale, self.stageScale))
            sprite.rect = pygame.Rect((x, y), (self.stageScale, self.stageScale))
            sprite.imagenoriginal = sprite.image

        # Define rectangulos que serviran para delimitar etapa y limitar movimiento de la camara
        if i == 0 and j == 0:
            self.firstRect = pygame.Rect((x, y), (self.stageScale, self.stageScale))
        elif i == (self.height - 1) and j == (self.width - 1):
            self.lastRect = pygame.Rect((x, y), (self.stageScale, self.stageScale))
        sprite.colororiginal = sprite.color

        self.group.add(sprite)
Ejemplo n.º 35
0
    def CheckCollision(self, player, group, x1, y1):

        newPos = pygame.Rect(x1, y1, player.sprite.rect.width, player.sprite.rect.height)
        playerMoved = pygame.sprite.Sprite()
        playerMoved.rect = newPos

        spriteListaux = pygame.sprite.spritecollide(playerMoved, group, False)
        self.spriteList = spriteListaux

        if len(spriteListaux) >= 1:
            
            for sprite in spriteListaux:
                    
                if sprite.color == player.color or sprite.color == "Todos" or sprite.activada :
                    rect = sprite.rect
                    self.topY = rect.top 
                    self.bottomY = rect.top + rect.height 
                    self.rightX = rect.left + rect.width 
                    self.leftX = rect.left 
                    if sprite.color == player.color:
                        sprite.activada = True
                    player.colisionada = sprite                  
                    return True
                
                elif sprite.activada == False and sprite.tipo == "Color":
                    companeroPos = pygame.Rect(player.companero.X, player.companero.Y+1, player.companero.sprite.rect.width, player.companero.sprite.rect.height)
                    companeroMoved = Platform()
                    companeroMoved.color = player.companero.color
                    companeroMoved.rect = companeroPos

                    if companeroMoved.color == sprite.color and pygame.sprite.collide_rect(sprite,companeroMoved):
                        rect = sprite.rect
                        self.topY = rect.top 
                        self.bottomY = rect.top + rect.height 
                        self.rightX = rect.left + rect.width 
                        self.leftX = rect.left                   
                        sprite.activada = True
                        player.colisionada = sprite
                        
                        return True
                    else:
                        sprite.activada = False

                    companeroPos = pygame.Rect(player.companero.X+1, player.companero.Y, player.companero.sprite.rect.width, player.companero.sprite.rect.height)
                    companeroMoved = Platform()
                    companeroMoved.color = player.companero.color
                    companeroMoved.rect = companeroPos

                    if companeroMoved.color == sprite.color and pygame.sprite.collide_rect(sprite,companeroMoved):
                        rect = sprite.rect
                        self.topY = rect.top 
                        self.bottomY = rect.top + rect.height 
                        self.rightX = rect.left + rect.width 
                        self.leftX = rect.left                
                        sprite.activada = True
                        player.colisionada = sprite
                   
                        return True
                    else:
                        sprite.activada = False

                    companeroPos = pygame.Rect(player.companero.X-1, player.companero.Y+1, player.companero.sprite.rect.width, player.companero.sprite.rect.height)
                    companeroMoved = Platform()
                    companeroMoved.color = player.companero.color
                    companeroMoved.rect = companeroPos

                    if companeroMoved.color == sprite.color and pygame.sprite.collide_rect(sprite,companeroMoved):
                        rect = sprite.rect
                        self.topY = rect.top 
                        self.bottomY = rect.top + rect.height 
                        self.rightX = rect.left + rect.width
                        self.leftX = rect.left              
                        sprite.activada = True
                        player.colisionada = sprite
                     
                        return True
                    else:
                     sprite.activada = False

            sprite.activada = False       
            return False

        else:
            return False