def actualizar(self, time, pala, pala_cpu, puntos): """ Actualiza la posición de la pelota en tantos pixeles determinado por TIME. Además permite identificar si interactua con PALA y PALA_CPU. En caso de que existan puntos, actualiza los valores de PUNTOS. """ self.rect.centerx += self.speed[0] * time self.rect.centery += self.speed[1] * time if self.rect.left <= 0: puntos[1] += 1 if self.rect.right >= ANCHO: puntos[0] += 1 if self.rect.left <= 0 or self.rect.right >= ANCHO: self.speed[0] = -self.speed[0] self.rect.centerx += self.speed[0] * time if self.rect.top <= 0 or self.rect.bottom >= ALTO: self.speed[1] = -self.speed[1] self.rect.centery += self.speed[1] * time if self.rect.left == 0 or self.rect.right == ANCHO: self.sound.play() if self.rect.top == 0 or self.rect.bottom == ALTO: self.sound.play() if collide_rect(self, pala): self.speed[0] = -self.speed[0] self.rect.centerx += self.speed[0] * time self.sound.play() if collide_rect(self, pala_cpu): self.speed[0] = -self.speed[0] self.rect.centerx += self.speed[0] * time self.sound.play() return puntos
def update(self): # Функция для перемешения и столкновения global spawn_boss, score for el in tiles_group: if collide_rect(self, el) and el.type in ['wall', 'box']: self.kill() for en in enemy_group: if collide_rect(self, en): self.kill() en.kill() kills.change() score.score += KILL_SCORE for boss in boss_enemy_group: if collide_rect(self, boss) and spawn_boss: self.kill() boss.hit_count += 1 boss.health -= 5 for boll in fireBoll_group: if boll.direction == 'right': boll.rect.x += 1 elif boll.direction == 'left': boll.rect.x -= 1 elif boll.direction == 'up': boll.rect.y -= 1 elif boll.direction == 'down': boll.rect.y += 1 else: boll.kill()
def updete(self): # Функция проверки столкновений global damage_take, boss, spawn_boss for el in tiles_group: if collide_rect(self, el) and el.type in ['wall', 'box']: self.rect.x = beforex self.rect.y = beforey for en in enemy_group: if collide_rect(self, en): if self.health > 0: self.health -= 1 break if spawn_boss: if collide_mask(self, boss): if self.health > 0 and damage_take: self.health -= 5 damage_take = False else: self.take_damage(boss, 60) for f in fruit_group: if collide_rect(self, f): if self.health < 100: self.health += 5 f.kill()
def collision(self, player, bug_police, screen): if collide_rect(self, player): screen.fill((115, 43, 23)) self.remove(bug_police) player.bug_kill -= 2 for z in bug_police: if collide_rect(self, z): self.rect.x -= 20 z.rect.x += 20
def update(self, player1, player2): ##### Se calculan los atributos necesarios para las colisiones. Da igual si es 0 o 1, ya que sólo varía el color self.move() self.rect = self.image.get_rect() self.rect.center = (self.x, self.y) if sprite.collide_rect(self, player1): player1.getHurt() self.y = 900 if sprite.collide_rect(self, player2): player2.getHurt() self.y = 900
def collide_paddles(self): pr = self.board.pr pl = self.board.pl v = self.speed vx, vy = v #if collide_rect(self, pr) or collide_rect(self, pl): if collide_rect(self, pl) and vx < 0: cx, cy = pl.rect.center cx -= PADDLE_RADIUS elif collide_rect(self, pr) and vx > 0: cx, cy = pr.rect.center cx += PADDLE_RADIUS else: return bx, by = self.rect.center nx = bx - cx ny = by - cy n = np.array([nx, ny]) # The new axis of reflectios for the trajectory n = n / np.linalg.norm(n) v = v - 2 * np.dot(v, n) * n # Avoid the ball to move close to 90 and 270 degrees (pi/2 and 3 pi/2) #angle_limit = 0.2 # About 11.5 degrees #if abs(angle - pi/2) < 0.2: # if angle < pi/2: # angle = pi/2 - angle_limit # else: # angle = pi/2 + angle_limit #if abs(angle - 3*pi/2) < 0.2: # if angle < 3*pi/2: # angle = 3*pi/2 - angle_limit # else: # angle = 3*pi/2 + angle_limit #vx = -vx # Speed up a bit the ball v *= 1.1 self.set_speed(v)
def check(self): # Функция проверки столкновения шипов global player, spikes_move for t in tiles_group: if t.type == 'wall' and collide_rect(self, t): self.kill() spikes_move = False elif collide_rect(self, player): spikes_move = False self.kill() player.health -= SPIKES_DAMAGE break
def collide(self, sprites, bullets_group): for b in sprites: if collide_rect(self, b): if b.type != self.type and not (self.type == 'f' and b.type == 'flag'): b.lifes -= 1 bullets_group.remove(self) break for b in bullets_group: if collide_rect(self, b) and b != self: bullets_group.remove(b) bullets_group.remove(self)
def check_hit_enemies(self): # checks if fireball hits enemy for g_enemy in self.goomba: if collide_rect(self, g_enemy): g_enemy.kill() self.active = False return for k_enemy in self.koopa: if collide_rect(self, k_enemy): k_enemy.kill() self.active = False return
def collision(self, player, bug_army, suriken_move): if collide_rect(self, player): self.remove(bug_army) player.bug_kill += 1 for z in bug_army: if collide_rect(self, z): self.rect.x -= 20 z.rect.x += 20 for i in suriken_move: if collide_rect(self, i): self.remove(bug_army) i.remove(suriken_move) player.bug_kill += 1
def collision(self, player, bomb_group, screen): # If bomb collide with player we remove -2 from player`s killed bugs if collide_rect(self, player): screen.fill((115, 43, 23)) self.kill() player.bug_kill -= 2 return # If bomb collide between we resolve it. for z in bomb_group: if collide_rect(self, z): self.rect.x -= 20 z.rect.x += 20
def check_hit_enemies(self): """Check if the fireball has hit any enemies""" for g_enemy in self.goomba: if collide_rect( self, g_enemy): # FIXME: change kill() when animation works g_enemy.kill() self.active = False return for k_enemy in self.koopa: if collide_rect(self, k_enemy): k_enemy.kill() self.active = False return
def collide(self, x_vel, y_vel, platforms, portals, magmas): global JUMP_POWER for pl in platforms: if collide_rect(self, pl): if x_vel > 0: self.rect.right = pl.rect.left if x_vel < 0: self.rect.left = pl.rect.right if y_vel > 0: self.rect.bottom = pl.rect.top self.underground = True self.y_vel = 0 if y_vel < 0: self.rect.top = pl.rect.bottom if JUMP_POWER != 10: JUMP_POWER = 10 for pr in portals: if collide_rect(self, pr): if x_vel > 0: self.rect.right = pr.rect.left self.level += 1 if x_vel < 0: self.rect.left = pr.rect.right self.level += 1 if y_vel > 0: self.rect.bottom = pr.rect.top self.underground = True self.y_vel = 0 if y_vel < 0: self.rect.top = pr.rect.bottom for mg in magmas: if collide_rect(self, mg): if x_vel > 0: self.rect.right = mg.rect.left if x_vel < 0: self.rect.left = mg.rect.right if y_vel > 0: self.rect.bottom = mg.rect.top self.underground = True self.y_vel = 0 if y_vel < 0: self.rect.top = mg.rect.bottom if JUMP_POWER != 6: JUMP_POWER = 6 self.magma_sound.play() self.hp -= 1
def units_collide(unit, units_list, day_no): for other_unit in units_list: # если юнит из списка не текущий, не встречался и в списке соседей проверяем на пересечение if unit != other_unit and unit not in other_unit.today_meeted_unit: if collide_rect(unit, other_unit) or Intersect(unit, other_unit) == True: # если двигается вправо if unit.xvel > 0: unit.rect.right = other_unit.rect.left unit.xvel *= -1 # двигается влево elif unit.xvel < 0: unit.rect.left = other_unit.rect.right unit.xvel *= -1 # вниз elif unit.yvel > 0: unit.rect.bottom = other_unit.rect.top unit.yvel *= -1 # вверх elif unit.yvel < 0: unit.rect.top = other_unit.rect.bottom unit.yvel *= -1 unit_rebound(unit) # Действия при встрече # Если у кого нить началась беременность if start_preg(unit, other_unit): if emu_settings.log_type == 'short': emu_settings.day_log_msg += 'P' # print(f'У {unit.unitno} {unit.family} и {other_unit.unitno} {other_unit.family} будет малыш, уи-уи') unit, other_unit = units_relations(unit, other_unit) # print(f'На {day_no} день юнит {unit.unitno} встретил юнита {other_unit.unitno}') unit.today_meeted_unit.append(other_unit)
def update(self, plitki=[]): if len(plitki) > 1: for pl in plitki: if self != pl: if collide_rect(self, pl): if self.rect.x < pl.rect.x: self.rect.x -= 1 pl.rect.x += 1 elif self.rect.x > pl.rect.x: self.rect.x += 1 pl.rect.x -= 1 if self.rect.y < pl.rect.y: self.rect.y -= 1 pl.rect.y += 1 elif self.rect.y > pl.rect.y: self.rect.y += 1 pl.rect.y -= 1 surf = get_surface() if self.rect.x <= 0: self.rect.x += 1 if self.rect.y <= 0: self.rect.y += 1 if self.rect.x+self.rect.w >= surf.get_width(): self.rect.x -= 1 if self.rect.y+self.rect.h >= surf.get_height(): self.rect.y -= 1 if self.mouse_on_button(): self.image.fill((255-self.color[0], 255-self.color[1], 255-self.color[2])) rect(self.image, (125, 125, 125), (0, 0, self.rect.width, self.rect.height), 1) self.image.blit(self.font.render(self.text, 1, self.color), (3, 3)) else: self.image.fill(self.color) rect(self.image, (255, 255, 255), (0, 0, self.rect.width, self.rect.height), 1) self.image.blit(self.font.render(self.text, 1, (255-self.color[0], 255-self.color[1], 255-self.color[2])), (3, 3))
def collide(self, xSpeed, ySpeed, platdorms): for object in platdorms: if collide_rect(self, object): if ySpeed > 0: self.rect.bottom = object.rect.top self.__onGround = True self.__ySpeed = 0
def collide(self, xVel, yVel, platforms): """ Check, is object colliding with something. """ for p in platforms: if sprite.collide_rect(self, p): if xVel > 0: self.rect.left = self.rect.right self.xVel = 0 self.realX += -1.5 if p.realX > self.realX \ else 1.5 if xVel < 0: self.rect.right = self.rect.left self.xVel = 0 self.realX += -1.5 if p.realX > self.realX \ else 1.5 if yVel < 0: self.rect.top = p.rect.bottom self.yVel = 0 self.realY += -1.5 if p.realY > self.realY \ else 1.5 if yVel > 0: self.rect.bottom = p.rect.top self.yVel = 0 self.realY += -1.5 if p.realY > self.realY \ else 1.5
def detonate(self, sprites): clock = get_ticks() dirs = self.hero.dirs.copy() (x, y) = self.rect.x, self.rect.y for j in range(self.strength + 1): if j > 0: i = 0 while i < len(dirs): dir = dirs[i] i += 1 dx = x + dir[0] * 40 * j dy = y + dir[1] * 40 * j exp = Explosion(dx, dy, clock, self.l) ok = True for sp in sprites: if collide_rect(exp, sp): dirs.remove(dir) if sp.can: sp.kill() exp.clear_time -= 20 else: ok = False i -= 1 break if ok: self.hero.explosions.add(exp) else: self.hero.explosions.add(Explosion(self.rect.x, self.rect.y, clock, self.l)) self.hero.bombs_on_ground.remove((x, y)) self.kill()
def update(self, time, scene): self.floatX += self.speedX * time * GRENADE_SPEED self.floatY += self.speedY * time * GRENADE_SPEED self.rect.x = roundToInt(self.floatX) self.rect.y = roundToInt(self.floatY) self.timeToBoom -= time if self.timeToBoom <= 0: scene.bulletGroup.remove(self) scene.bulletGroup.add(Explosion(self.rect.x, self.rect.y)) # Kill people! originalRect = self.rect.copy() self.rect.inflate_ip(80, 80) # 80x80 area damage enemies_hit = sprite.spritecollide(self, scene.enemyGroup, False) for enemy in enemies_hit: # Friendly fire if self.creator.__class__.__name__ == enemy.__class__.__name__: continue enemy.receive_attack(self.atk) if sprite.collide_rect(self, scene.player): scene.player.receive_attack(self.atk) self.rect = originalRect # Restore the real rect self.timeToStop -= time if self.timeToStop <= 0: self.speedX = 0 self.speedY = 0
def update(self, game_scene): self.rect.x += self.dx1 self.rect.y += self.dy1 if self.rect.x + 2 * c.radius1 >= c.screen_resolution[0] + 10: self.rect.x = c.screen_resolution[0] - 2 * c.radius1 self.dx1 *= -1 elif self.rect.x <= -10: self.rect.x = c.radius1 self.dx1 *= -1 if collide_rect(self, game_scene.block): if self.dy1 > 0 and self.rect.y + self.rect.height <= c.screen_resolution[ 1] - c.screen_resolution[1] / 10 + 10: self.dy1 *= -1 mixer.music.play(0) game_scene.score_label.add_one() elif self.rect.y >= c.screen_resolution[1]: c.final_score = game_scene.score_label.score self.f = open("highscore.txt", "r") highscore_str = self.f.readline() self.f.close() print(highscore_str[0]) if int(highscore_str) < c.final_score: self.f = open("highscore.txt", "w") self.f.write(str(c.final_score)) self.f.close() game_scene.manager.go_to(GameOverScene()) elif self.rect.y <= 0: self.rect.y = c.radius1 self.dy1 *= -1
def collide(self, xvel, yvel, obstructions): for p in obstructions: if sprite.collide_rect(self, p): # если есть пересечение платформы с игроком #если пуля не начала взрываться, то начинаем взрывать ее if self.bum == 0: self.rect.left -= 8 self.rect.top -= 8 self.bum = 1 who_die = p.die(self.shutdirection) # сообщаем объекту, в который попали, что в него попали if who_die == 1: # если взорвали танк, то прибавляем фраг стрелявшему self.shooter.frag += 1 if xvel > 0: # если движется вправо self.rect.right -= xvel # то не движется вправо if xvel < 0: # если движется влево self.rect.left -= xvel # то не движется влево if yvel > 0: # если падает вниз self.rect.bottom -= yvel # то не падает вниз if yvel < 0: # если движется вверх self.rect.top -= yvel # то не движется вверх self.shutdirection = "stop"
def interaction(self, vx, vy, environment): ''' Логика взаимодействия персонажа с заданным окружением. ''' for pl in environment.platforms_group: ''' Мы проходим по коллекции платформ из среды уровня и проверяем взаимодействия персонажа с ними. ''' if collide_rect(self, pl): if vx > 0: self.rect.right = pl.rect.left if vx < 0: self.rect.left = pl.rect.right if vy > 0: self.rect.bottom = pl.rect.top self.isFalling = False self.isJumping = False # очевидно, что тут же можно написать условие: # если есть превышение скорости, то те забавные анимации if vy >= 35: self.isDuck = True self.velocity[1] = 0 if vy < 0: self.rect.top = pl.rect.bottom self.velocity[1] = 0
def enemyCollide(self, enemyGroup, thisGameScreen): key = PY.key.get_pressed() for enemy in enemyGroup: if PS.collide_rect(self, enemy): self.health -= 1 if self.health == 0: Globals.STATE = LoseScreen.LoseScreen(0)
def eventCollide(self, spriteGroup, thisGameScreen): for p in spriteGroup: if PS.collide_rect(self, p): if isinstance(p, TriggerBlockSand) and p.event == 1 \ and Globals.STATE.events[1]: dialogue = DB.Dialogue_box("cutscene2_dialogue.txt") while dialogue.isOpen: dialogue.update() Globals.STATE.events[1] = False elif isinstance(p, TriggerBlockSand) and p.event == 2 \ and not Globals.STATE.events[1] \ and Globals.STATE.events[2] \ and self.elderCount == 0: dialogue = DB.Dialogue_box("cutscene3_dialogue.txt") while dialogue.isOpen: dialogue.update() self.elderCount = 1 elif isinstance(p, TriggerBlockSand) and p.event == 2 \ and not Globals.STATE.events[1] \ and Globals.STATE.events[2] \ and self.elderCount == 1 \ and self.firewood >= 3: dialogue = DB.Dialogue_box("cutscene4_dialogue.txt") while dialogue.isOpen: dialogue.update() Globals.STATE.events[2] = False elif isinstance(p, TriggerBlockSand) and p.event == 3 \ and not Globals.STATE.events[2] \ and Globals.STATE.events[3]: Globals.STATE.events[3] = False else: pass
def update(self, time, player): self.move(time) self.rect = self.image.get_rect() self.rect.center = (self.x, self.y) if sprite.collide_rect(self, player): self.be_caught(player) elif self.y >= BOTTOM_LIMIT: self.kill()
def colli_kill_l(l, r): # testfunction for collision callbacks if (sprite.collide_rect(l, r)): l.destroy() del l return True else: return False
def colli_los(l, r): # testfunction for collision callbacks if (sprite.collide_rect(l, r)): l.destroy() print("hit") return True else: return False
def update(self): if not self.stay: self.move() else: if self.timer - self.last_timer >= 30: self.kill() for spr in [*self.wall_sprites, *self.wall_sprites.bonus_sprites, *self.wall_sprites.saves_sprites, *self.wall_sprites.damage_sprites, *self.wall_sprites.enemies_sprites]: if sprite.collide_rect(self, spr) and spr.can_be_broken: del self.wall_sprites.maps[tuple(spr.cords)] spr.kill() if sprite.collide_rect(self, self.player): self.player.gui_sprites.set_hearts(self.player.gui_sprites.hp - 1) self.player.last_timer_damage = self.player.timer self.timer += 1
def update_bullets(screen, bullets_list): """Update the bullets' position and speed, and remove bullets outside the screen.""" for bullets in bullets_list: bullets.update() for bullet in bullets.copy(): if not collide_rect(bullet, screen): bullets.remove(bullet)
def colli_clip(l, r): # testfunction for collision callbacks if (sprite.collide_rect(l, r)): x = min(0.5, max(-0.5, l.rect[0] - r.rect[0])) y = min(0.5, max(-0.5, l.rect[1] - r.rect[1])) l.source.source.moveOnce((x, y)) return True else: return False
def collecting(self, environment, item): ''' Проходим по коллекции ключей и смотрим, стоит ли их убирать. Если да, то складываем их в сумку, запоминая цвет. ''' if collide_rect(self, item): item.remove(environment.items_group) item.remove(environment.whole_group) self.bag.append(item.sign)
def render(self): self.anim.blit(Explode.screen, Explode.camera.get_pos(self.x - 64, self.y - 64)) for n in Explode.enemy: if sprite.collide_rect(self, n): n.hp -= 1 if self.anim.currentFrameNum == 15: Explode.explode.remove(self)
def collisions(self) -> None: """ Checks for collisions with level. Should be called in Player.update(). """ lvl = Level.instance if not lvl: return for platform in lvl.platforms: # check falling and colliding <=> isGrounded ? if self._velocity.y > .5: # check collisions with platform's spring bonus if platform.bonus and collide_rect(self, platform.bonus): self.onCollide(platform.bonus) self.jump(platform.bonus.force) # check collisions with platform if collide_rect(self, platform): self.onCollide(platform) platform.onCollide()
def autsave(self, d, autsave_blocks, sprite_group): for i in range(len(autsave_blocks)): if collide_rect(self, autsave_blocks[i]): # Данная сохранялка переcтает отрисовываться, а место сохранения героя становится соответствующим значению "i + 1". sprite_group.remove(autsave_blocks[i]) return (i + 1) # Иначе место сохранения героя остается прежним. return d
def _findleafs(self, node, rect): #Stop if there are now more sub nodes if len(node[1]) == 0: if node[2]: #it was a leaf yield node[0] #Check all child nodes for child in node[1]: if collide_rect(child[0], rect): for node1 in self._findleafs(child, rect): yield node1
def collide(self, xvel, yvel, wallMap): FADEOUTTIME = 0.2 for p in wallMap: if PS.collide_rect(self, p): if xvel > 0: self.rect.right = p.rect.left elif xvel < 0: self.rect.left = p.rect.right elif yvel > 0: self.rect.bottom = p.rect.top elif yvel < 0: self.rect.top = p.rect.bottom else: continue
def collide(self, xvel, yvel, platforms): for pl in platforms: if collide_rect(self, pl): if xvel > 0: self.rect.right = pl.rect.left if xvel < 0: self.rect.left = pl.rect.right if yvel > 0: self.rect.bottom = pl.rect.top self.onGround = True self.yvel = 0 if yvel < 0: self.rect.top = pl.rect.bottom self.yvel = 0
def check_collisions(self): """ Sees if any objects collide, preps them to be handled if so. """ grid = self.grid for i, j in combinations(self.objects, 2): # For all possible combinations of objects that can touch... if (i.__class__, j.__class__) not in _do_not_compare and sprite.collide_rect(i, j): # If these two objects are allowed to touch, and they do... if not grid.spare_collisions: # If we don't have any spare Collision objects... grid.spare_collisions.append(Collision()) grid.collisions.append(grid.spare_collisions.pop().update(i, j))
def kill_people(self, scene): if sprite.collide_rect(self, scene.player) and not self.creator.__class__.__name__ == scene.player.__class__.__name__: scene.player.receive_attack(self.atk) scene.bulletGroup.remove(self) hitted_players = sprite.spritecollide(self, scene.enemyGroup, False) # scene.bulletGroup.remove(self) for player in hitted_players: # Friendly fire if self.creator.__class__.__name__ == player.__class__.__name__: continue player.receive_attack(self.atk) # A bullet should not be capable of going through an infinite amount of bodies scene.bulletGroup.remove(self) break
def update(self, targetSpriteGroup = None): # If reached max range if self.distance >= MAX_DISTANCE: self.kill() # If there are enemies if targetSpriteGroup != None: for targetSprite in targetSpriteGroup: # If collided if PS.collide_rect(self, targetSprite): # Removes this sprite from all groups. # Should delete from screen self.kill() if isinstance(targetSprite, Player.Player): Globals.HERO.health -= 10 self.hurtSound.play() else: targetSprite.health -= 4 targetSprite.status = "burn" if self.isPlayer: # Move the projectile if self.direction == 0 or self.direction == "moveup": # up self.update_image(self.image_tracker*4 + 2) self.rect.centery -= PROJECTILE_SPEED elif self.direction == 1 or self.direction == "moveright": # right self.update_image(self.image_tracker*4) self.rect.centerx += PROJECTILE_SPEED elif self.direction == 2 or self.direction == "movedown": # down self.update_image(self.image_tracker*4 + 3) self.rect.centery += PROJECTILE_SPEED elif self.direction == 3 or self.direction == "moveleft": # left self.update_image(self.image_tracker*4 + 1) self.rect.centerx -= PROJECTILE_SPEED else: if self.direction == 0 or self.direction == "moveup": # up # self.update_image(self.image_tracker*4 + 2) self.rect.centery -= PROJECTILE_SPEED elif self.direction == 1 or self.direction == "moveright": # right # self.update_image(self.image_tracker*4) self.rect.centerx += PROJECTILE_SPEED elif self.direction == 2 or self.direction == "movedown": # down # self.update_image(self.image_tracker*4 + 3) self.rect.centery += PROJECTILE_SPEED elif self.direction == 3 or self.direction == "moveleft": # left # self.update_image(self.image_tracker*4 + 1) self.rect.centerx -= PROJECTILE_SPEED self.update_image(self.image_tracker) self.distance += PROJECTILE_SPEED
def update(self): if self.unit.action == ID_HARVEST: if self.harvest_progress <= 0: self.unit.changeImage("with_mineral") self.with_mineral = True self.mineral_target.hp -= self.harvest_amount self.unit.action = ID_STOP # ID_STOP else: self.harvest_progress -= self.harvest_speed else: for target_unit in groups.unitgroup: if sprite.collide_rect(self.unit, target_unit): if ID_MINERAL in target_unit.types and self.with_mineral == False: self.harvest(target_unit) elif ID_WAREHOUSE in target_unit.types and target_unit.owner == self.unit.owner and self.with_mineral == True: self.returnCargo(target_unit.owner)
def collide(self, xvel, yvel, platforms): for p in platforms: if sprite.collide_rect(self, p): if isinstance(p, ExitBlock): event.post(event.Event(QUIT)) if xvel > 0: self.rect.right = p.rect.left if xvel < 0: self.rect.left = p.rect.right if yvel > 0: self.rect.bottom = p.rect.top self.onGround = True self.yvel = 0 self.can_use_space = True if yvel < 0: self.rect.top = p.rect.bottom self.yvel /= 2 # reduce speed on vertical hit
def collide(self, xvel, yvel, platforms): for p in platforms: if sprite.collide_rect(self, p): # если есть пересечение платформы с игроком if self.xvel > 0: # если движется вправо self.rect.right = p.rect.left # то не движется вправо if xvel < 0: # если движется влево self.rect.left = p.rect.right # то не движется влево if yvel > 0: # если падает вниз self.rect.bottom = p.rect.top # то не падает вниз self.onGround = True # и становится на что-то твердое self.yvel = 0 # и энергия падения пропадает if yvel < 0: # если движется вверх self.rect.top = p.rect.bottom # то не движется вверх self.yvel = 0 # и энергия прыжка пропадает
def place_random_blocks(self): """ Creates additional random blocks and places them :return: """ amount = randint(1, 4) for _ in xrange(0, amount): x = randint(0, BLOCK_NUM_WIDTH - 1) y = randint(0, BLOCK_NUM_HEIGHT - 1) new_block = BlockMultiHit(x * Block.WIDTH + PLAYFIELD_PADDING[0], y * Block.HEIGHT + PLAYFIELD_PADDING[1]) while self.blocks[y][x] is not None or sprite.collide_rect(new_block, self.ball): x = randint(0, BLOCK_NUM_WIDTH - 1) y = randint(0, BLOCK_NUM_HEIGHT - 1) new_block.rect.x = x * Block.WIDTH + PLAYFIELD_PADDING[0] new_block.rect.y = y * Block.HEIGHT + PLAYFIELD_PADDING[1] self.blocks[y][x] = new_block self.block_count += 1 self.blocks_surface_dirty = True
def collide(self, xvel, yvel, obstructions): # проверяем столкновения с препятствиями for p in obstructions: if p != self: if sprite.collide_rect(self, p): # если есть пересечение чего-то с танком if xvel > 0: # если движется вправо self.rect.right -= xvel # то не движется вправо if xvel < 0: # если движется влево self.rect.left -= xvel # то не движется влево if yvel > 0: # если падает вниз self.rect.bottom -= yvel # то не падает вниз if yvel < 0: # если движется вверх self.rect.top -= yvel # то не движется вверх
def collide(self, xvel, yvel, spriteGroup, thisGameScreen, item): FADEOUTTIME = 0.2 key = PY.key.get_pressed() for p in spriteGroup: if PS.collide_rect(self, p): print 'hi' print 1 if isinstance(p, Grey_brick) and item != None and item.isPickedUp: spriteGroup.remove(p) #elif isinstance(p, ExitBlock): # Globals.STATE = WinScreen.WinScreen(100) elif xvel > 0: self.rect.right = p.rect.left elif xvel < 0: self.rect.left = p.rect.right elif yvel > 0: self.rect.bottom = p.rect.top elif yvel < 0: self.rect.top = p.rect.bottom else: continue
def _coll(self, node1, node2): if collide_rect(node1[0], node2[0]): #Check if node1 and node2 are hit leafs if node1[2] and node2[2]: print "found" return True self.collide_boxes.append(node1[0]) if len(node1[1]) and len(node2[1]): for nodex in node1[1]: for nodey in node2[1]: return self._coll(nodex, nodey) elif len(node1[1]) and False: print "node1" for nodex in node1[1]: return self._coll(nodex, node2) elif len(node2[1]) and False: print "node2" for nodex in node2[1]: return self._coll(nodex, node1)
def update(self, heroSprite, targetSprite): # If reached max range if self.distance >= MAX_DISTANCE: self.kill() # If collided if PS.collide_rect(self, targetSprite): # Removes this sprite from all groups. # Should delete from screen self.kill() targetSprite.health -= 10 # Move the projectile if self.direction == 0 or self.direction == "moveup": # up self.rect.centery = heroSprite.rect.centery - 16 elif self.direction == 1 or self.direction == "moveright": # right self.rect.centerx = heroSprite.rect.centerx + 16 elif self.direction == 2 or self.direction == "movedown": # down self.rect.centery = heroSprite.rect.centery + 16 elif self.direction == 3 or self.direction == "moveleft": # left self.rect.centerx = heroSprite.rect.centerx - 16 self.distance += 1
def __init__(self): """ Init pygame """ pygame.init() # Boolean values to know where we are in the game self.game_started = False self.game_paused = False self.game_ended = False self.text = "Too bad !" # Clock self.clock = pygame.time.Clock() # Setting up the display pygame.display.set_caption('Frozen Water Maze') icon_path = os.path.dirname(__file__) + os.sep + "assets/ico.png" pygame.display.set_icon(pygame.image.load(icon_path)) self.screen = pygame.display.set_mode((64 * 18, 64 * 12)) self.font = pygame.font.Font(None, 36) # Load data tmxpath = os.path.dirname(__file__) + os.sep + "assets/map.tmx" tmxdata = pytmx.load_pygame(tmxpath) self.game_tiles = [] self.game_fires = [] self.game_waters = [] self.game_collectibles = [] self.game_grids = [] for coord_x in range(18): for coord_y in range(12): img = tmxdata.get_tile_image(coord_x, coord_y, 0) if img is not None: self.game_tiles.append(GameTile(img, coord_x, coord_y)) fire = tmxdata.get_tile_image(coord_x, coord_y, 1) if fire is not None: self.game_fires.append(Fire(coord_x, coord_y)) water = tmxdata.get_tile_image(coord_x, coord_y, 2) if water is not None: self.game_waters.append(Water(water, coord_x, coord_y)) collectible = tmxdata.get_tile_image(coord_x, coord_y, 3) if collectible is not None: self.game_collectibles.append(Collectible(coord_x, coord_y)) grid = tmxdata.get_tile_image(coord_x, coord_y, 4) if grid is not None: self.game_grids.append(Grid(grid, coord_x, coord_y)) # Init music music_path = os.path.dirname(__file__) + os.sep + "assets/sfx/bg_music.ogg" pygame.mixer.music.load(music_path) pygame.mixer.music.set_volume(0.25) pygame.mixer.music.play(-1) # Init ambient motor sound ambient_motor_path = os.path.dirname(__file__) + os.sep + "assets/sfx/motor.ogg" ambient_motor = pygame.mixer.Sound(ambient_motor_path) ambient_motor.set_volume(0.15) ambient_motor.play(loops=-1) # Init ambient droplet fall sound droplet_path = os.path.dirname(__file__) + os.sep + "assets/sfx/droplet.ogg" self.ambient_droplet = pygame.mixer.Sound(droplet_path) self.ambient_droplet.set_volume(0.3) # Init get sound get_path = os.path.dirname(__file__) + os.sep + "assets/sfx/get.ogg" self.get_sfx = pygame.mixer.Sound(get_path) self.get_sfx.set_volume(0.2) # Init game # ground bg_path = os.path.dirname(__file__) + os.sep + "assets/bg.jpg" self.background_img = pygame.image.load(bg_path) # Init player self.player = Player() # Init score self.score = 0 self.score_image = self.font.render(str(self.score), True, (255, 255, 255)) self.score_rect = self.score_image.get_rect() self.score_rect.top = 5 self.score_rect.left = 64 # Init timer self.timer = 20 timer_path = os.path.dirname(__file__) + os.sep + "assets/timer.png" self.timer_image = pygame.image.load(timer_path) self.timer_rect = self.timer_image.get_rect() self.timer_rect.top = 5 self.timer_rect.left = self.screen.get_width() - 64 self.timer_text_image = self.font.render(str(self.timer), True, (255, 255, 255)) self.timer_text_rect = self.timer_text_image.get_rect() self.timer_text_rect.top = 24 self.timer_text_rect.left = self.screen.get_width() - 92 # Startup screen display startup_img_path = os.path.dirname(__file__) + os.sep + "assets/title.jpg" self.startup_image = pygame.image.load(startup_img_path) self.screen.fill((0, 0, 0)) startup_screen_display = True while startup_screen_display: self.screen.blit(self.startup_image, Rect(0, 0, self.screen.get_width(), self.screen.get_height())) pygame.display.flip() pygame.time.wait(3000) startup_screen_display = False # Init internal event -> droplet fall pygame.time.set_timer(pygame.USEREVENT, 5000) # Init internal event -> timer decrease pygame.time.set_timer(pygame.USEREVENT + 1, 1000) # Game loop while not self.game_ended: self.screen.fill((0, 0, 0)) self.check_game_event() self.screen.blit(self.background_img, Rect(0, 0, 64 * 18, 64 * 12)) self.screen.blit(self.score_image, self.score_rect) self.screen.blit(self.timer_image, self.timer_rect) self.screen.blit(self.timer_text_image, self.timer_text_rect) is_player_falling = False if self.player.current_shape != Player.PLAYER_CLOUD: is_player_falling = True for tile in self.game_tiles: tile.display(self.screen) if self.player.rect.bottom == tile.rect.top and self.player.rect.left == tile.rect.left: is_player_falling = False for tile in self.game_grids: tile.display(self.screen) if self.player.rect.bottom == tile.rect.top and self.player.rect.left == tile.rect.left and self.player.current_shape == Player.PLAYER_ICE: is_player_falling = False for danger in self.game_waters: danger.display(self.screen) if self.player.rect.bottom == danger.rect.top and self.player.rect.left == danger.rect.left: if self.player.current_shape != Player.PLAYER_CLOUD: self.game_ended = True is_player_falling = False elif collide_rect(self.player, danger): self.game_ended = True is_player_falling = False if is_player_falling: self.player.fall() for danger in self.game_fires: danger.display(self.screen) if collide_rect(self.player, danger): self.game_ended = True for point in self.game_collectibles: point.display(self.screen) if collide_rect(self.player, point): self.score += 1 self.get_sfx.play() self.game_collectibles.remove(point) self.score_image = self.font.render(str(self.score), True, (255, 255, 255)) if self.game_collectibles.__len__()==0: self.game_ended=True self.text = "Congrat's !!" self.player.display(self.screen) pygame.time.wait(50) self.clock.tick(60) pygame.display.flip() self.startup_screen_display = True cpt = 0 while self.startup_screen_display: self.screen.blit(self.background_img, (0, 0)) # Endscreen text ( by default text is "Too bad !" ) # ( if game_collectibles(len) == 0: "Congrat's!" ) font = pygame.font.SysFont('Arial', 100, True) text= font.render(self.text, True, (255, 255, 255)) text_rect = text.get_rect() text_rect.midtop = ( 550, 300) self.screen.blit(text, text_rect) pygame.time.wait(300) pygame.display.flip() cpt += 1 if cpt ==10: self.startup_screen_display = False pygame.quit()
def attack(self,wallMap, hero): currTime = time.time() if not self.attacking: if self.phase == False: self.attackVal = random.randint(0,100) else: self.attackVal = random.randint(0,110) self.attacking = True y_dist = abs(self.rect.centery - hero.rect.centery) x_dist = abs(self.rect.centerx - hero.rect.centerx) if self.attackVal < 30: if self.dash_time == 0: self.align(hero,x_dist, y_dist) if (x_dist >= 250 or y_dist >= ATTACK_OFFSET) and (y_dist >= 250 or x_dist >= ATTACK_OFFSET): self.isMoving = True self.move(wallMap) else: self.dash_time +=1 else: if self.dash_time < 50: self.dash(currTime, wallMap) if PS.collide_rect(hero,self): hero.health -= 1 self.hurtSound.play() else: self.attacking = False self.speed = 2 self.dash_time = 0 elif self.attackVal < 60: self.align(hero, x_dist, y_dist) if (x_dist >= 250 or y_dist >= ATTACK_OFFSET) and (y_dist >= 250 or x_dist >= ATTACK_OFFSET): self.isMoving = True self.move(wallMap) else: if self.aligned: Globals.WORLD.addEntity(self.shoot_projectile (Globals.STATE.enemyProjectileGroup)) self.attacking = False elif self.attackVal < 80: self.align(hero, x_dist, y_dist) if (x_dist >= 250 or y_dist >= ATTACK_OFFSET) and (y_dist >= 250 or x_dist >= ATTACK_OFFSET): self.isMoving = True self.move(wallMap) else: temp = Projectile.Whirlpool(self.rect,hero,self.direction) Globals.WORLD.addEntity(temp) Globals.STATE.enemyProjectileGroup.add(temp) self.attacking = False elif self.attackVal < 100: spawn = random.randint(0,2) + 1 for i in range(spawn): x_rand = random.randint(-30,30) + self.rect.centerx y_rand = random.randint(-30, 30) + self.rect.centery attack_type = random.randint(0,1) enemy = Enemy(x_rand, y_rand, True, attack_type, 0, 40.0) enemy.speed = 2 Globals.WORLD.addEntity(enemy) Globals.STATE.enemyGroup.add(enemy) self.attacking = False
def collide(self, tree): for leaf in self.collision_leafs(tree): for other in tree.collision_leafs(self): if collide_rect(leaf, other): return True return False
def collide4(): collide_rect(tag_cool, tag_aero)
def collide_rect_circ(left, right): return 1 if collide_rect(left, right) and collide_circle(left, right) else 0
def pickedUp(self, targetSprite): if PS.collide_rect(self, targetSprite): self.kill() self.isPickedUp = True
def check_collision(self): """ Called after input handling and movement of the object, to check and solve collisions :return: """ # ball vs paddle if self.ball.rect.y < self.paddle.rect.y and \ sprite.collide_rect(self.paddle, self.ball): self.ball.vy = -1 # ball.vy # ball vs bottom if not self.ball.dead and self.ball.rect.y + self.ball.radius * 2 > LEVEL_HEIGHT: self.player.lives -= 1 if self.player.lives < 1: self.ball.dead = True else: self.ball.rect.x = self.paddle.rect.x + self.paddle.rect.width/2 - self.ball.radius self.ball.rect.y = self.paddle.rect.y - self.ball.radius * 2 self.ball.docked = True self.paddle.change_size(PADDLE_WIDTHS[PADDLE_DEFAULT_WIDTH_INDEX]) self.paddle.attachments = [] # ball vs blocks coll_num = [0, 0, 0] coll_num_val = (4, 2, 1) ball_grid_x = (self.ball.rect.x - PLAYFIELD_PADDING[0] + self.ball.radius) / Block.WIDTH ball_grid_y = (self.ball.rect.y - PLAYFIELD_PADDING[1] + self.ball.radius) / Block.HEIGHT for y in range(ball_grid_y - 1, ball_grid_y + 2): for x in range(ball_grid_x - 1, ball_grid_x + 2): if 0 <= x < BLOCK_NUM_WIDTH and 0 <= y < BLOCK_NUM_HEIGHT: if self.blocks[y][x] is not None and not self.blocks[y][x].dead and \ sprite.collide_rect(self.blocks[y][x], self.ball): self.block_destruction(self.blocks[y][x], self.items[y][x], self.blocks[y][x].on_collide) coll_num[y - ball_grid_y + 1] += coll_num_val[x - ball_grid_x + 1] self.ball.on_collide(coll_num) # entities for entity in self.entities: if not entity.dead: # paddle vs items if isinstance(entity, Item) and sprite.collide_rect(self.paddle, entity): entity.on_collect(self.paddle) entity.dead = True # self.player.lives += 1 # explosion vs blocks elif isinstance(entity, Explosion) and entity.state > 0: entity_block_x = (entity.rect.x - PLAYFIELD_PADDING[0] + Explosion.WIDTH/2) / Block.WIDTH entity_block_y = (entity.rect.y - PLAYFIELD_PADDING[1] + Explosion.HEIGHT/2) / Block.HEIGHT for y in xrange(entity_block_y - 1, entity_block_y + 2): for x in xrange(entity_block_x - 1, entity_block_x + 2): if 0 <= x < BLOCK_NUM_WIDTH and 0 <= y < BLOCK_NUM_HEIGHT: if self.blocks[y][x] is not None and not self.blocks[y][x].dead: self.block_destruction(self.blocks[y][x], self.items[y][x], self.blocks[y][x].kill) elif isinstance(entity, Projectile): entity_block_x = (entity.rect.x - PLAYFIELD_PADDING[0] + entity.rect.width/2) / Block.WIDTH entity_block_y = (entity.rect.y - PLAYFIELD_PADDING[1] + entity.rect.height/2) / Block.HEIGHT for y in xrange(entity_block_y - 1, entity_block_y + 2): for x in xrange(entity_block_x - 1, entity_block_x + 2): if 0 <= x < BLOCK_NUM_WIDTH and 0 <= y < BLOCK_NUM_HEIGHT: if self.blocks[y][x] is not None and not self.blocks[y][x].dead \ and sprite.collide_rect(self.blocks[y][x], entity): self.block_destruction(self.blocks[y][x], self.items[y][x], self.blocks[y][x].kill) entity.on_collide()
def collide_rect_mask(left, right): return 1 if collide_rect(left, right) and collide_mask(left, right) else 0