import pygame as pg from sprite import Sprite class Block(Sprite): COLOR = (0,0,255) def __init__(self, rect_t): super().__init__(rect_t[2:4]) self.map_rect = pg.Rect(rect_t) self.image.fill(self.COLOR) def update(self,map_rect): self.rect.x = self.map_rect.x - map_rect.x self.rect.y = self.map_rect.y - map_rect.y def collide_ship(self, ship): if self.map_rect.colliderect(ship.map_rect): ship.velocity = 0 if ship.map_rect.centery <= self.map_rect.top: ship.map_pos.y -= ship.map_rect.bottom - self.map_rect.top elif ship.map_rect.centery >= self.map_rect.bottom: ship.map_pos.y += self.map_rect.bottom - ship.map_rect.top if ship.map_rect.centerx <= self.map_rect.left: ship.map_pos.x -= ship.map_rect.right - self.map_rect.left elif ship.map_rect.centerx >= self.map_rect.right: ship.map_pos.x += self.map_rect.right - ship.map_rect.left if __name__=='__main__': from ship import Ship block = Block((0,0, 10, 20)) a_ship = Ship((10+Ship.SIZE/4, 20+Ship.SIZE/4), pg.Rect(0,0,100,100)) block.collide_ship(a_ship) assert a_ship.map_pos.x == 10 + Ship.SIZE/2 and a_ship.map_pos.y == 20 + Ship.SIZE/2, "bad collision" block = Block((0,0, 10, 40)) a_ship = Ship((10+Ship.SIZE/4, 20+Ship.SIZE/4), pg.Rect(0,0,100,100)) block.collide_ship(a_ship) assert a_ship.map_pos.x == 10 + Ship.SIZE/2, "bad collision"