def __init__(self): Monster.__init__(self) self.level = 3 self.exp_value = 250 monsters = SpriteSheet( 'instant_dungeon_artpack/By Scott Matott/monsters.png') self.image = self.enlarge( monsters.image_at([0, 128, 16, 16]).convert()) # pygame.Surface self.image.set_colorkey((0, 0, 0)) monster_images = monsters.load_strip([0, 128, 16, 16, 8], 8) self.load_images(monster_images) # Speed is used for finding direction. Velocity already contains that direction. self.speed = [5, 5] self.velocity = pygame.math.Vector2(self.speed) self.health = 150 + (30 * self.level) self.max_health = 150 + (30 * self.level) self.cooldown = 500 self.uses_caps = True self.offset = (-40, -30) self.healthbar = Bar(self.offset, self.uses_caps, False, 'health')
def __init__(self): Monster.__init__(self) monsters = SpriteSheet( 'instant_dungeon_artpack/By Scott Matott/monsters.png') pick_monster = monsters.image_at([0, 64, 16, 16]).convert() self.scale_factor = [64, 64] self.enlarge = lambda x: pygame.transform.smoothscale( x, self.scale_factor) self.image = self.enlarge(pick_monster) # pygame.Surface self.image.set_colorkey((0, 0, 0)) monster_images = monsters.load_strip([0, 64, 16, 16, 8], 8) self.load_images(monster_images) self.direction = randrange(1, 9) # Refer to Mover.update method self.walk_counter = 0 # Keep monsters from changing directions constantly # Speed is used for finding direction. Velocity already contains that direction. self.speed = [2, 2] self.velocity = pygame.math.Vector2(self.speed) self.health = 80 + (10 * self.level) self.max_health = self.health
def __init__(self): self.tile_size = 64 self.map_dim = 16 self.map_size = self.tile_size * self.map_dim self.screen = pygame.display.set_mode((self.map_size, self.map_size)) self.sheet = SpriteSheet("allSprites_default.png", "allSprites_default.xml") self.map = GameMap("map.txt", self.map_dim, self.tile_size) self.players = [] self.init_tanks()
def load_transform_image(self): ''' :action: Loads image of sword and scales it accordingly, and rotates it in the correct direction. ''' sword_images = SpriteSheet('instant_dungeon_artpack/By Voytek Falendysz/shield_knife_and_scrolls.png') image = sword_images.image_at([86, 0, 5, 16]) self.image = pygame.transform.smoothscale(image, [20, 64]) # Rotate sword to go in direction of click. Minus 90 because sword originally points upwards. self.image = pygame.transform.rotate(self.image, self.angle - 90)
def load_transform_image(self): ''' :action: Loads image of sword and scales it accordingly, and rotates it in the correct direction. ''' sword_images = SpriteSheet( 'instant_dungeon_artpack/By Voytek Falendysz/shield_knife_and_scrolls.png' ) image = sword_images.image_at([86, 0, 5, 16]) self.image = pygame.transform.smoothscale(image, [20, 64]) # Rotate sword to go in direction of click. Minus 90 because sword originally points upwards. self.image = pygame.transform.rotate(self.image, self.angle - 90)
class Preview(object): def __init__(self): self.tile_size = 64 self.map_dim = 16 self.map_size = self.tile_size * self.map_dim self.screen = pygame.display.set_mode((self.map_size, self.map_size)) self.sheet = SpriteSheet("allSprites_default.png", "allSprites_default.xml") self.map = GameMap("map.txt", self.map_dim, self.tile_size) self.players = [] self.init_tanks() def init_tanks(self): for t in range(4): tank = self.map.get_initial_tank_state(t + 1) if tank is None: break image = self.sheet.get_image_name(tank.image_name()) player = Player(tank, image, self.tile_size, DummyController()) player.set_animation(Move(self.tile_size, "up", "forward")) self.players.append(player) def render_sand(self): base_tile = "tileSand1.png" for y in range(self.map_dim): off_y = y * self.tile_size for x in range(self.map_dim): off_x = x * self.tile_size self.screen.blit(self.sheet.get_image_name(base_tile), (off_x, off_y)) def render_obstacles(self): for y in range(self.map_dim): for x in range(self.map_dim): self.map.blit(self.screen, self.sheet, x, y) def render_tanks(self, delta_ms): for player in self.players: player.step(delta_ms) angle = player.angle() image = pygame.transform.rotate(player.canvas_image(), angle) pos = (player.canvas_x(), player.canvas_y()) self.screen.blit(image, pos) def render(self, delta_ms): self.render_sand() self.render_obstacles() self.render_tanks(delta_ms)
class UFO(Alien): sprite_sheet = SpriteSheet('images/UFO.png') image1 = sprite_sheet.image_at((0, 0, 64, 64)) image2 = sprite_sheet.image_at((0, 64, 64, 64)) frames = [image1, image2] def __init__(self, ai_settings, screen): super().__init__(ai_settings=ai_settings, screen=screen) self.reset() self.alive = True for x in UFO.frames: x = pygame.transform.scale(x, (48, 48)).convert_alpha() timer = Timer(frames=frames) def reset(self): self.rect.centery = 50 self.rect.centerx = 0 self.alive = True def dead(self): self.alive = False def imagerect(self): return self.timer.imagerect() def update(self): """Move the alien right or left""" self.x += ( (self.ai_settings.alien_speed_factor + random.randint(0, 3)) * self.ai_settings.UFO_direction) self.rect.x = self.x
def __init__(self, gsm): self.gsm = gsm self.background = Background( os.path.join("res", "PlayState", "background.png")) self.camera = Camera(self) self.HUD = HUD(self.gsm) # Key handling self.leftKeyDown = False self.rightKeyDown = False self.upKeyDown = False self.spriteSheet = SpriteSheet( os.path.join("res", "PlayState", "Spritesheet.png"), 1) # Holds all the objects in the game self.allObjectList = pygame.sprite.Group() self.activeObjectList = pygame.sprite.Group() self.terrainList = pygame.sprite.Group() self.interactableList = pygame.sprite.Group() self.enemyList = pygame.sprite.Group() self.enemyAIList = pygame.sprite.Group() self.player = None self.level = currentLevel # Sets the current level self.loadLevel(self.level) # Loads the level
class Ship(Sprite): sprite_sheet = SpriteSheet('images/Jet.png') width = sprite_sheet.width() height = sprite_sheet.height() frames = [] for i in range(3): for j in range(3): frames.append(sprite_sheet.image_at((int(j * width/3), int(i * height/3), width/3, height/3))) timer = Timer(frames=[frames[0], frames[1]]) explosion = frames[2:7] explosion_timer = Timer(frames=explosion, looponce=True) def __init__(self, ai_settings, screen): """Initialize the ship and set its starting position""" super().__init__() self.screen = screen self.ai_settings = ai_settings # load the ship image and get it's rect self.image = Ship.frames[0] self.rect = self.image.get_rect() self.screen_rect = screen.get_rect() # start each new ship at the bottom center of the screen self.rect.centerx = self.screen_rect.centerx self.rect.bottom = self.screen_rect.bottom # Store a decimal value for the ship's center self.center = float(self.rect.centerx) # Movement flag self.moving_right = False self.moving_left = False def update(self): """Update the ship's position based on the movment flag """ # Update the ship's center value, not the rect if self.moving_right and self.rect.right < self.screen_rect.right: self.rect.centerx += self.ai_settings.ship_speed_factor if self.moving_left and self.rect.left > 0: self.rect.centerx -= self.ai_settings.ship_speed_factor # self.rect.centerx = self.center def blitme(self): """ Draw the ship at it's current location""" self.screen.blit(self.imagerect(), self.rect) def center_ship(self): """Center the ship on the screen""" self.center = self.screen_rect.centerx def imagerect(self): return Ship.timer.imagerect() def explode(self): self.screen.blit(self.explosion_timer.imagerect(), self.rect) pygame.display.flip()
def __init__(self, filename, rects, count, loop=False, frames=1): """construct a SpriteAnimation rects is a list of rectangels on the spritesheet loop is a bool that casuses next to return to the origional sprite when it has reached the last sprite count is the number of sprites frames is the number of frames per sprite""" self.filename = filename ss = SpriteSheet(filename) self.images = ss.getImages(rects) self.counter = 0 self.loop = loop self.frames = frames
def __init__(self, position): pygame.sprite.Sprite.__init__(self) self.CarSprites = SpriteSheet("Sprites/SuperCar.png") ############# POWER UPS ############# self.powerups = { "None": 999, "SpecialWeapon": 3, "FireMissile": 0, "HomingMissile": 0, "PowerMissile": 0, "Napalm": 0, "RearMines": 0, "FreezeMissile": 0, "RicochetBombs": 0, "Health": 0, "Satellite": 0, "Shotgun": 0, "Grenade": 0 } self.CurrentPowerUp = self.powerups["SpecialWeapon"] ############# POWER UPS ############# self.src_image = self.CarSprites.get_image(15, 201, 35, 60) self.rect = self.src_image.get_rect() self.position = position self.speed = self.direction = 0 self.k_left = self.k_right = self.k_down = self.k_up = 0 self.machinegunsound = pygame.mixer.Sound("Sounds/machine_guns.wav") self.specialweaponsound = pygame.mixer.Sound( "Sounds/hammerhead_special.wav") self.enginesound = pygame.mixer.Sound("Sounds/engine4.wav") self.powerupsound = pygame.mixer.Sound("Sounds/power_up.wav") self.powerupsound.set_volume(.1) self.turning = pygame.mixer.Sound("Sounds/skid.wav") self.enginesound.play(-1) self.MachineGunOn = False self.specialon = False
def __init__(self): Mover.__init__(self) monsters = SpriteSheet( 'instant_dungeon_artpack/By Scott Matott/monsters.png') pick_monster = monsters.image_at([0, 112, 16, 16]).convert() self.exp_value = 100 self.level = 2 self.scale_factor = [64, 64] self.enlarge = lambda x: pygame.transform.smoothscale( x, self.scale_factor) self.image = self.enlarge(pick_monster) # pygame.Surface self.image.set_colorkey((0, 0, 0)) monster_images = monsters.load_strip([0, 112, 16, 16, 8], 8) self.load_images(monster_images) self.rect = self.image.get_rect() # pygame.Rect self.rect = self.rect.move( [randrange(700, 3670), randrange(700, 2160)]) # Random spawn location self.direction = randrange(1, 9) # Refer to Mover.update method self.walk_counter = 0 # Keep monsters from changing directions constantly # Speed is used for finding direction. Velocity already contains that direction. self.speed = [3, 3] self.velocity = pygame.math.Vector2(self.speed) self.health = 90 + (25 * self.level) self.max_health = self.health self.timer = pygame.time.get_ticks() self.cooldown = 800 self.uses_caps = False self.offset = [5, -15] self.healthbar = Bar(self.offset, self.uses_caps, False, 'health')
def regImages(self): self.images["PIECES"] = GUIImage( "../img/sprites/450px-Chess_Pieces_Sprite.svg.png") self.spriteSheets["PIECES"] = SpriteSheet(self.images["PIECES"], self.TILE_SIZE, self.TILE_SIZE, self.spritePos, self.spriteColorPos) self.AppIcon = GUIImage("../img/icons/queen75x75.png")
def __init__(self, objectHandler, window): # Init self.objectHandler = objectHandler self.window = window self.mapsFile = JsonHandler('./assets/data/maps.json') self.mapsData = self.mapsFile.getJson() self.tileSize = 16 * self.window.scaleFactor # Creating spritesheet self.tileSpriteSheet = SpriteSheet('./assets/art/overworld.png') self.objectSpriteSheet = SpriteSheet('./assets/art/objects.png') # Get sprite array's # Tile X - 40 # Tile Y - 36 self._tileSprites = self.tileSpriteSheet.getImageArray( 16, 16, self.tileSize, self.tileSize) self._objectSprites = self.objectSpriteSheet.getImageArray( 16, 16, self.tileSize, self.tileSize)
def __init__(self, x, y, acceleration): super().__init__() self.run_sheet = SpriteSheet(CYBORG_RUN_FILENAME) self.idle_sheet = SpriteSheet(CYBORG_IDLE_FILENAME) self.death_sheet = SpriteSheet(CYBORG_DEATH_FILENAME) self.idle = False self.running = False self.dying = False self.done_dying = False self.current_frame = 0 self.last_update = 0 self.idle_frames = [] self.run_frames_r = [] self.run_frames_l = [] self.death_frames = [] self.load_images() self.pos = vec(x, y) self.vel = vec(0, 0) self.acc = vec(0, 0) self.count = 0 self.image = self.idle_frames[0] self.rect = self.image.get_rect() self.rect.center = SCREEN_WIDTH / 2, 526 self.rect.bottom = 381 self.acceleration = acceleration
def __init__(self, gsm): print("MenuState initialized") # GameStateManager reference self.gsm = gsm # Background Image # FIND A WAY TO ADD ANIMATION TIME SO THAT IT DOESNT PLAY TOO FAST self.bgSpriteSheet = SpriteSheet( os.path.join("res", "MapState", "menu background.png"), 4) self.bgImage = None self.bgIndex = 1 # Menu Option self.currentOption = 0 self.maxOptions = 3 self.boat = pygame.image.load( os.path.join("res", "MapState", "menu boat.png")) self.boatX = 175 self.boatY = 0 self.animationTimer = 0 self.animationTime = 10
def __init__(self, level, x, y): self.level = level self.startX = x self.startY = y self.x = x self.y = y self.w = 24 self.h = 40 self.WALK_SPEED = 440 self.JUMP_FORCE = -16 self.spriteSheet = SpriteSheet("res/player.png", self.w, self.h) self.idle_sprites_right = self.spriteSheet.getImages(0) self.idle_sprites_left = [] for sprite in self.idle_sprites_right: self.idle_sprites_left.append( pygame.transform.flip(sprite, True, False)) self.running_sprites_right = self.spriteSheet.getImages(1) self.running_sprites_left = [] for sprite in self.running_sprites_right: self.running_sprites_left.append( pygame.transform.flip(sprite, True, False)) self.air_sprites_right = self.spriteSheet.getImages(2) self.air_sprites_left = [] for sprite in self.air_sprites_right: self.air_sprites_left.append( pygame.transform.flip(sprite, True, False)) self.vx = 0 self.vy = 0 self.grounded = False self.facingRight = True self.spriteDT = 0.1 self.spriteTime = 0.0 self.spriteIndex = 0 self.timeInAir = 0.0
def __init__(self, x, y, direction, objectHandler, window): # Init self.x = x self.y = y self.direction = direction self.objectHandler = objectHandler self.window = window self.width = 32 * self.window.scaleFactor self.height = 32 * self.window.scaleFactor # Personalized self.ID = 'Enemy' self.velX = 0 self.velY = 0 self.enemyState = EnemyState.WALKING self.player = None # Create Sprite Sheet self.spriteSheet = SpriteSheet('./assets/art/log.png') self._sprites = self.spriteSheet.getImageArray(32, 32, self.width, self.height) # Active Sprite self.activeSprite = self._sprites[0][0] # Collision self.colliderOffsetX = 32 self.colliderOffsetY = 32 self.colliderWidth = 64 self.colliderHeight = 64 self.collider = pygame.Rect(self.x + self.colliderOffsetX, self.y + self.colliderOffsetY, self.colliderWidth, self.colliderHeight) self.lastTick = 0 self.animationFrame = 0
def __init__(self): pygame.sprite.Sprite.__init__(self) standing_imgs = SpriteSheet( os.path.join('resources', 'gerald_standing.png'), os.path.join('resources', 'gerald_standing.json')).sprite_images_list stand_sprite_list = self.__create_gerald_sprite_list(standing_imgs) # Starting Gerald sprite self.image = stand_sprite_list[0] self.rect = self.image.get_rect() self.width = self.rect[2] self.height = self.rect[3] self.x = self.rect[0] self.y = self.rect[1]
class Alien3(Alien): sprite_sheet = SpriteSheet('images/shark.png') width = sprite_sheet.width() height = sprite_sheet.height() frames = [] for i in range(2): frames.append(sprite_sheet.image_at((0, int(i * height / 2), width, int(height / 2)))) for x in frames: x = pygame.transform.scale(x, (48, 48)) timer = Timer(frames=frames) def __init__(self, ai_settings, screen): super().__init__(ai_settings=ai_settings, screen=screen) def imagerect(self): return Alien3.timer.imagerect()
def __init__(self): super().__init__() self.attack_sheet = SpriteSheet(CHAR_ATTACK_FILENAME) self.run_sheet = SpriteSheet(CHAR_RUN_FILENAME) self.idle_sheet = SpriteSheet(CHAR_IDLE_FILENAME) self.death_sheet = SpriteSheet(CHAR_DEATH_FILENAME) self.idle = True self.attacking = False self.dying = False self.running = False self.colliding = False self.right_face = True self.shooting = False self.current_frame = 0 self.last_update = 0 self.start_time = 0 self.idle_frames = [] self.idle_frames_l = [] self.run_frames_r = [] self.run_frames_l = [] self.attack_frames = [] self.attack_frames_l = [] self.death_frames = [] self.load_images() self.image = self.idle_frames[0] self.rect = self.image.get_rect() self.rect.center = SCREEN_WIDTH / 2, 526 self.speed_x, self.speed_y = 0, 0 self.pos = vec(SCREEN_WIDTH / 2, 500) self.vel = vec(0, 0) self.acc = vec(0, 0) self.count = 0 self.lives = PLAYER_LIVES
class Alien(Sprite): """A class to represent a single aline in the fleet""" frames = [] explosion_sheet = SpriteSheet('images/Explosion.png') explosion_width = explosion_sheet.width() explosion_height = explosion_sheet.height() explosion_frames = [] for i in range(2): for j in range(2): explosion_frames.append( explosion_sheet.image_at( (int(j * explosion_width / 2), int(i * explosion_height / 2), explosion_width / 2, explosion_height / 2))) for j in explosion_frames: j = pygame.transform.scale(j, (48, 48)) explosion_timer = Timer(frames=explosion_frames, wait=100) def __init__(self, ai_settings, screen): """ Initialize the alien and set its starting position""" super().__init__() self.screen = screen self.ai_settings = ai_settings # load the alien image and set its rect attribute # self.image = pygame.image.load('images/alien-1.png') self.image = self.imagerect() self.rect = pygame.Rect((0, 0), (48, 48)) # Start each new aline near the top left of the screen self.rect.x = self.rect.width self.rect.y = self.rect.height # Store the alien's exact position self.x = float(self.rect.x) def blitme(self): """Draw the alien at it's current location""" self.screen.blit(self.imagerect(), self.rect) def check_edges(self): """Return True if alien is at edge of screen""" screen_rect = self.screen.get_rect() if self.rect.right >= screen_rect.right: return True elif self.rect.left <= 0: return True def imagerect(self): raise NotImplementedError def update(self): """Move the alien right or left""" self.x += (self.ai_settings.alien_speed_factor * self.ai_settings.fleet_direction) self.rect.x = self.x def explode(self): for _ in range(4): self.screen.blit(Alien.explosion_timer.imagerect(), self.rect) pygame.display.flip()
class Enemy(): def __init__(self, x, y, direction, objectHandler, window): # Init self.x = x self.y = y self.direction = direction self.objectHandler = objectHandler self.window = window self.width = 32 * self.window.scaleFactor self.height = 32 * self.window.scaleFactor # Personalized self.ID = 'Enemy' self.velX = 0 self.velY = 0 self.enemyState = EnemyState.WALKING self.player = None # Create Sprite Sheet self.spriteSheet = SpriteSheet('./assets/art/log.png') self._sprites = self.spriteSheet.getImageArray(32, 32, self.width, self.height) # Active Sprite self.activeSprite = self._sprites[0][0] # Collision self.colliderOffsetX = 32 self.colliderOffsetY = 32 self.colliderWidth = 64 self.colliderHeight = 64 self.collider = pygame.Rect(self.x + self.colliderOffsetX, self.y + self.colliderOffsetY, self.colliderWidth, self.colliderHeight) self.lastTick = 0 self.animationFrame = 0 def tick(self, ticks): # Set Player if not player if self.player == None: self.player = self.objectHandler.getObjectByID('Player') # Move Enemy if player in distance if math.sqrt( (self.x - self.player.x)**2 + (self.y - self.player.y)**2) <= 5 * 16 * self.window.scaleFactor: self.enemyState = EnemyState.WALKING self.velX = (self.player.x - self.x) / 100 self.velY = (self.player.y - self.y) / 100 else: self.velX = 0 self.velY = 0 self.enemyState = EnemyState.IDLE self.animationFrame = 0 # Set Direction To Moving if abs(self.velX) > abs(self.velY): if self.velX < 0: self.direction = Direction.LEFT elif self.velX > 0: self.direction = Direction.RIGHT elif abs(self.velY) > abs(self.velX): if self.velY < 0: self.direction = Direction.UP elif self.velY > 0: self.direction = Direction.DOWN if self.velX > 1: self.velX = 1 if self.velX < -1: self.velX = -1 if self.velY > 1: self.velY = 1 if self.velY < -1: self.velY = -1 self.x += self.velX self.y += self.velY self.collider.x = self.x + self.colliderOffsetX self.collider.y = self.y + self.colliderOffsetY self.animate(ticks) def render(self, scrollX, scrollY): # Render Enemy self.window.drawSprite(self.x - scrollX, self.y - scrollY, self.activeSprite) def animate(self, ticks): if self.enemyState == EnemyState.IDLE: if self.direction == Direction.UP: self.activeSprite = self._sprites[1][0] elif self.direction == Direction.LEFT: self.activeSprite = self._sprites[3][0] elif self.direction == Direction.DOWN: self.activeSprite = self._sprites[0][0] elif self.direction == Direction.RIGHT: self.activeSprite = self._sprites[2][0] elif self.enemyState == EnemyState.WALKING: if self.animationFrame == 0: self.lastTick = ticks self.animationFrame += 1 if self.animationFrame == 1: if self.direction == Direction.UP: self.activeSprite = self._sprites[1][1] elif self.direction == Direction.LEFT: self.activeSprite = self._sprites[3][1] elif self.direction == Direction.DOWN: self.activeSprite = self._sprites[0][1] elif self.direction == Direction.RIGHT: self.activeSprite = self._sprites[2][1] elif self.direction == Direction.LEFT_UP: self.activeSprite = self._sprites[3][1] elif self.direction == Direction.LEFT_DOWN: self.activeSprite = self._sprites[3][1] elif self.direction == Direction.RIGHT_UP: self.activeSprite = self._sprites[2][1] elif self.direction == Direction.RIGHT_DOWN: self.activeSprite = self._sprites[2][1] elif self.animationFrame == 2: if self.direction == Direction.UP: self.activeSprite = self._sprites[1][2] elif self.direction == Direction.LEFT: self.activeSprite = self._sprites[3][2] elif self.direction == Direction.DOWN: self.activeSprite = self._sprites[0][2] elif self.direction == Direction.RIGHT: self.activeSprite = self._sprites[2][2] elif self.direction == Direction.LEFT_UP: self.activeSprite = self._sprites[3][2] elif self.direction == Direction.LEFT_DOWN: self.activeSprite = self._sprites[3][2] elif self.direction == Direction.RIGHT_UP: self.activeSprite = self._sprites[2][2] elif self.direction == Direction.RIGHT_DOWN: self.activeSprite = self._sprites[2][2] elif self.animationFrame == 3: if self.direction == Direction.UP: self.activeSprite = self._sprites[1][3] elif self.direction == Direction.LEFT: self.activeSprite = self._sprites[3][3] elif self.direction == Direction.DOWN: self.activeSprite = self._sprites[0][3] elif self.direction == Direction.RIGHT: self.activeSprite = self._sprites[2][3] elif self.direction == Direction.LEFT_UP: self.activeSprite = self._sprites[3][3] elif self.direction == Direction.LEFT_DOWN: self.activeSprite = self._sprites[3][3] elif self.direction == Direction.RIGHT_UP: self.activeSprite = self._sprites[2][3] elif self.direction == Direction.RIGHT_DOWN: self.activeSprite = self._sprites[2][3] elif self.animationFrame == 4: if self.direction == Direction.UP: self.activeSprite = self._sprites[1][0] elif self.direction == Direction.LEFT: self.activeSprite = self._sprites[3][0] elif self.direction == Direction.DOWN: self.activeSprite = self._sprites[0][0] elif self.direction == Direction.RIGHT: self.activeSprite = self._sprites[2][0] elif self.direction == Direction.LEFT_UP: self.activeSprite = self._sprites[3][0] elif self.direction == Direction.LEFT_DOWN: self.activeSprite = self._sprites[3][0] elif self.direction == Direction.RIGHT_UP: self.activeSprite = self._sprites[2][0] elif self.direction == Direction.RIGHT_DOWN: self.activeSprite = self._sprites[2][0] if ticks - self.lastTick == 20: self.lastTick = ticks self.animationFrame += 1 if self.animationFrame == 5: self.animationFrame = 0
class Player: # Initialiserer alle bildene av spilleren og andre verdier def __init__(self, level, x, y): self.level = level self.startX = x self.startY = y self.x = x self.y = y self.w = 24 self.h = 40 self.WALK_SPEED = 440 self.JUMP_FORCE = -16 self.spriteSheet = SpriteSheet("res/player.png", self.w, self.h) self.idle_sprites_right = self.spriteSheet.getImages(0) self.idle_sprites_left = [] for sprite in self.idle_sprites_right: self.idle_sprites_left.append( pygame.transform.flip(sprite, True, False)) self.running_sprites_right = self.spriteSheet.getImages(1) self.running_sprites_left = [] for sprite in self.running_sprites_right: self.running_sprites_left.append( pygame.transform.flip(sprite, True, False)) self.air_sprites_right = self.spriteSheet.getImages(2) self.air_sprites_left = [] for sprite in self.air_sprites_right: self.air_sprites_left.append( pygame.transform.flip(sprite, True, False)) self.vx = 0 self.vy = 0 self.grounded = False self.facingRight = True self.spriteDT = 0.1 self.spriteTime = 0.0 self.spriteIndex = 0 self.timeInAir = 0.0 #Oppdaterer hvert bilde def update(self, dt, events): #Bestemmer hvilket bilde i animasjonen som skal spilles self.prevY = self.y self.spriteTime += dt if self.spriteTime > self.spriteDT: self.spriteTime -= self.spriteDT self.spriteIndex += 1 if self.spriteIndex >= len(self.idle_sprites_right): self.spriteIndex = 0 # Dersom man trykker på piltastene eller A/D lagrer den hvor spilleren skal flytte seg keys = pygame.key.get_pressed() dx = 0 if not self.level.finished: if keys[pygame.K_LEFT] or keys[pygame.K_a]: dx -= 1 if keys[pygame.K_RIGHT] or keys[pygame.K_d]: dx += 1 self.vx = dx * self.WALK_SPEED * dt if abs(self.vx) < 0.1: self.vx = 0 # Legger til tyngdekraften i farten til spilleren self.vy += self.level.GRAVITY * dt if not self.grounded: self.timeInAir += dt # Sjekker om man kan hoppe if not self.level.finished: if keys[pygame.K_SPACE] and self.timeInAir < 0.03: self.vy = self.JUMP_FORCE elif keys[pygame.K_SPACE]: self.level.restart() for event in events: if event.type == pygame.KEYUP and event.key == pygame.K_SPACE: if self.vy < 0: self.vy /= 2 # Sjekker for kollisjon med der spilleren ønsker å flytte seg til og bakken def checkCollisions(self, tiles): self.grounded = False # Sjekker under spilleren dersom han/hun beveger seg nedover if self.vy > 0: yCheck = self.y + self.h + self.vy xCheck1 = self.x xCheck2 = self.x + self.w - 1 tile1 = self.level.game.getTile( int(xCheck1 / self.level.game.TILE_SIZE), int(yCheck / self.level.game.TILE_SIZE), tiles) tile2 = self.level.game.getTile( int(xCheck2 / self.level.game.TILE_SIZE), int(yCheck / self.level.game.TILE_SIZE), tiles) if (tile1 is not 0 and tile1 is not None) or (tile2 is not 0 and tile2 is not None): self.timeInAir = 0 self.grounded = True self.vy = 0 self.y = int(yCheck / self.level.game.TILE_SIZE ) * self.level.game.TILE_SIZE - self.h elif self.vy < 0: # Sjekker under spilleren dersom han/hun beveger seg oppover yCheck = self.y + self.vy xCheck1 = self.x xCheck2 = self.x + self.w - 1 tile1 = self.level.game.getTile( int(xCheck1 / self.level.game.TILE_SIZE), int(yCheck / self.level.game.TILE_SIZE), tiles) tile2 = self.level.game.getTile( int(xCheck2 / self.level.game.TILE_SIZE), int(yCheck / self.level.game.TILE_SIZE), tiles) if (tile1 is not 0 and tile1 is not None) or (tile2 is not 0 and tile2 is not None): self.vy = 0 self.y = int(yCheck / self.level.game.TILE_SIZE + 1) * self.level.game.TILE_SIZE # Sjekker til siden av spilleren dersom han/hun beveger seg til høyre if self.vx > 0: xCheck = self.x + self.w + self.vx yCheck1 = self.y yCheck2 = self.y + self.h - 1 tile1 = self.level.game.getTile( int(xCheck / self.level.game.TILE_SIZE), int(yCheck1 / self.level.game.TILE_SIZE), tiles) tile2 = self.level.game.getTile( int(xCheck / self.level.game.TILE_SIZE), int(yCheck2 / self.level.game.TILE_SIZE), tiles) if (tile1 is not 0 and tile1 is not None) or (tile2 is not 0 and tile2 is not None): self.vx = 0 self.x = int(xCheck / self.level.game.TILE_SIZE ) * self.level.game.TILE_SIZE - self.w elif self.vx < 0: # Sjekker til siden av spilleren dersom han/hun beveger seg til venstre xCheck = self.x + self.vx yCheck1 = self.y yCheck2 = self.y + self.h - 1 tile1 = self.level.game.getTile( int(xCheck / self.level.game.TILE_SIZE), int(yCheck1 / self.level.game.TILE_SIZE), tiles) tile2 = self.level.game.getTile( int(xCheck / self.level.game.TILE_SIZE), int(yCheck2 / self.level.game.TILE_SIZE), tiles) if (tile1 is not 0 and tile1 is not None) or (tile2 is not 0 and tile2 is not None): self.vx = 0 self.x = int(xCheck / self.level.game.TILE_SIZE + 1) * self.level.game.TILE_SIZE # Etter at det har blitt sjekket for kollisjon flytter spilleren på seg så lenge den ikke treffer på noe def lateUpdate(self): self.x += self.vx self.y += self.vy if self.vx < 0: self.facingRight = False if self.vx > 0: self.facingRight = True # Begrenser spilleren til å være innenfor banen if self.x < 0: self.x = 0 if self.x > len( self.level.tiles[0]) * self.level.game.TILE_SIZE - self.w: self.x = len( self.level.tiles[0]) * self.level.game.TILE_SIZE - self.w # Starter på nytt dersom spilleren er under banen if self.y > len(self.level.tiles) * self.level.game.TILE_SIZE: self.level.restart() # Sjekker om man er i mål if self.level.goalRect.colliderect(Rect(self.x, self.y, self.w, self.h)): self.level.complete() # Tegner spilleren med den riktige animasjonen def draw(self, screen): if self.prevY != self.y: index = 1 if self.timeInAir < 0.1: index = 0 elif self.vy > 0: index = 2 if self.facingRight: sprite = self.air_sprites_right[index] else: sprite = self.air_sprites_left[index] elif self.vx > 0: sprite = self.running_sprites_right[self.spriteIndex] elif self.vx < 0: sprite = self.running_sprites_left[self.spriteIndex] elif self.facingRight: sprite = self.idle_sprites_right[self.spriteIndex] else: sprite = self.idle_sprites_left[self.spriteIndex] screen.blit( sprite, (self.x - self.level.camera.x, self.y - self.level.camera.y))
pygame.mixer.music.play(-1) pygame.mixer.music.set_volume(.5) gameStart = False #boolean to check if player has started the game gameEnd = False #boolean to check if player has reached the win condition #setup player sprite spriteList = pygame.sprite.Group() player = Sprite("sprite/PlayerShip.png", .5 * screenW - 40, .75 * screenH, 80, 80, 1) #setup enemy sprite enemy = Sprite("sprite/EnemyShip.png", .5 * screenW - ((screenW)/2), 0, screenW, 250, 2) #setup other sprites background = Sprite("sprite/Background.png", 0, 0, screenW, screenH, 0) menuBackground = Sprite("sprite/MainMenu.png", 0, 0, screenW, screenH, 0) ExplosionSheet = SpriteSheet("sprite/ExplosionSheet.png") #fonts gameFont = pygame.font.Font("font/space.ttf", 40) #cool title font! insFont = pygame.font.Font("font/space2.ttf", 18) #easier to read font for instructions. p2Font = pygame.font.Font("font/space2.ttf", 14) #font for further clarification. scoreFont = pygame.font.Font("font/space.ttf", 20) #score font titleText = "Rhythm Pilot" title = gameFont.render(titleText, True, (255, 255, 255)) gameInsP1 = "Use W,A,S,D to move. You can also shoot with SPACE." gameInsP2 = "You can increase your movement speed with SHIFT." gameInsP3 = "Use + or - to control volume. M will mute the music." gameInsP4 = "Press ENTER or RETURN to begin." gameInsP4p2 = "(Use the first few seconds to get use to the controls)"
def __init__(self): # Setter noen standard-variabler self.TILE_SIZE = 32 self.GREEN = (0, 255, 0) self.BLUE = (0, 0, 255) self.SCREEN_WIDTH = 800 self.SCREEN_HEIGHT = 600 self.LEVEL_COUNT = 4 # Laster inn rekordene fra filen self.records = [] self.loadRecords() # Initialiserer pygame pygame.init() self.screen = pygame.display.set_mode( (self.SCREEN_WIDTH, self.SCREEN_HEIGHT)) pygame.display.set_caption("EasyGame") self.clock = pygame.time.Clock() # Initialiserer musikken pygame.mixer.init() pygame.mixer.music.load("sounds/music.mp3") pygame.mixer.music.play(-1, 0.0) pygame.font.init() self.font = pygame.font.SysFont('Arial', 40) # Laster inn alle sprites (bilder) spriteSheet = SpriteSheet("res/sprites.png", self.TILE_SIZE, self.TILE_SIZE) self.TILE_GRASS_TOP = Tile(self, 2, spriteSheet.getImageAt(1, 0)) self.TILE_GRASS_TOP_LEFT = Tile(self, 1, spriteSheet.getImageAt(0, 0)) self.TILE_GRASS_TOP_RIGHT = Tile(self, 3, spriteSheet.getImageAt(2, 0)) self.TILE_GRASS_LEFT = Tile(self, 9, spriteSheet.getImageAt(0, 1)) self.TILE_DIRT = Tile(self, 10, spriteSheet.getImageAt(1, 1)) self.TILE_GRASS_RIGHT = Tile(self, 11, spriteSheet.getImageAt(2, 1)) self.TILE_GRASS_BOTTOM = Tile(self, 18, spriteSheet.getImageAt(1, 2)) self.TILE_GRASS_BOTTOM_LEFT = Tile(self, 17, spriteSheet.getImageAt(0, 2)) self.TILE_GRASS_BOTTOM_RIGHT = Tile(self, 19, spriteSheet.getImageAt(2, 2)) self.ALL_TILES = [ self.TILE_GRASS_TOP, self.TILE_GRASS_TOP_LEFT, self.TILE_GRASS_TOP_RIGHT, self.TILE_GRASS_LEFT, self.TILE_DIRT, self.TILE_GRASS_RIGHT, self.TILE_GRASS_BOTTOM, self.TILE_GRASS_BOTTOM_LEFT, self.TILE_GRASS_BOTTOM_RIGHT ] self.DECORATION_GRASS = Tile(self, 4, spriteSheet.getImageAt(3, 0)) self.DECORATION_SIGN_5 = Tile(self, 5, spriteSheet.getImageAt(4, 0)) self.DECORATION_SIGN_6 = Tile(self, 6, spriteSheet.getImageAt(5, 0)) self.DECORATION_SIGN_7 = Tile(self, 7, spriteSheet.getImageAt(6, 0)) self.DECORATION_SIGN_8 = Tile(self, 8, spriteSheet.getImageAt(7, 0)) self.DECORATION_SIGN_13 = Tile(self, 13, spriteSheet.getImageAt(4, 1)) self.DECORATION_SIGN_14 = Tile(self, 14, spriteSheet.getImageAt(5, 1)) self.DECORATION_SIGN_15 = Tile(self, 15, spriteSheet.getImageAt(6, 1)) self.DECORATION_SIGN_16 = Tile(self, 16, spriteSheet.getImageAt(7, 1)) self.DECORATION_SIGN_21 = Tile(self, 21, spriteSheet.getImageAt(4, 2)) self.DECORATION_SIGN_22 = Tile(self, 22, spriteSheet.getImageAt(5, 2)) self.DECORATION_GOAL_23 = Tile(self, 23, spriteSheet.getImageAt(6, 2)) self.DECORATION_GOAL_31 = Tile(self, 31, spriteSheet.getImageAt(6, 3)) self.ALL_DECORATIONS = [ self.DECORATION_GRASS, self.DECORATION_SIGN_5, self.DECORATION_SIGN_6, self.DECORATION_SIGN_7, self.DECORATION_SIGN_8, self.DECORATION_SIGN_13, self.DECORATION_SIGN_14, self.DECORATION_SIGN_15, self.DECORATION_SIGN_16, self.DECORATION_SIGN_21, self.DECORATION_SIGN_22, self.DECORATION_GOAL_23, self.DECORATION_GOAL_31 ] # Laster inn menyen self.isPlaying = False self.menu = Menu(self)
def __init__(self, gamestate_area): Mover.__init__(self) self.level = 1 self.experience = 1 self.level_experience = 1000 self.ability_levels = {S.Attack: 1, S.Sweep: 0, S.Arrow: 0, S.SplitShot: 0, S.Lightning: 0, S.FireStorm: 0, S.ToughenUp: 0, S.Wisen: 0} left_ability_boundary = 40 self.ability_manager = AbilityManager(40) left_inventory_boundary = 880 self.inventory = Inventory(left_inventory_boundary) self.from_player = True scale_factor = [64, 64] enlarge = lambda x: pygame.transform.smoothscale(x, scale_factor) characters = SpriteSheet('instant_dungeon_artpack/By Jos Luis Peir Lima/players-mages.png') self.image = enlarge(characters.image_at([64, 0, 16, 16])).convert() # pygame.Surface self.rect = self.image.get_rect() # pygame.Rect # Start character at center of screen. center_character = list(gamestate_area.center) center_character = list(map(lambda x, y: x - (y/2), center_character, scale_factor)) self.rect = self.rect.move(center_character[0], center_character[1]) # Used to face different direction when walking that way. player_images = characters.load_strip([0, 0, 16, 16], 8) self.down_image = enlarge(player_images[0]).convert() self.up_image = enlarge(player_images[2]).convert() self.right_image = enlarge(player_images[4]).convert() self.left_image = enlarge(player_images[6]).convert() # Get rid of green box around player. self.image.set_colorkey((0, 255, 0)) self.down_image.set_colorkey((0, 255, 0)) self.up_image.set_colorkey((0, 255, 0)) self.right_image.set_colorkey((0, 255, 0)) self.left_image.set_colorkey((0, 255, 0)) # Used for movement. self.speed = [.1, .1] # pixels per millisecond self.velocity = [0, 0] # Used to limit attacks per second. self.timer = pygame.time.get_ticks() self.start_max_health = 700 self.start_max_energy = 250 self.max_health = 700 self.health = 700 self.max_energy = 250 self.energy = 250 self.base_health_regen = .01 self._base_energy_regen = .01 self.uses_caps = True # Drawing health bar utility. health_bar_offset = [-570, -320] energy_bar_offset = [-570, -280] experience_bar_offset = [-200, 340] self.healthbar = Bar(health_bar_offset, self.uses_caps, True, 'health') self.energybar = Bar(energy_bar_offset, self.uses_caps, True, 'energy') self.experiencebar = Bar(experience_bar_offset, self.uses_caps, True, 'experience')
def __init__ (self, filename, numColumns, numRows, numImages, coverIndex): SpriteSheet.__init__ (self,filename,numColumns,numRows,numImages,coverIndex) print ( 'Done in Deck.init' )
class Player(): def __init__(self, playerFile, window): # Init self.window = window # Personalized self.playerFile = playerFile self.playerData = self.playerFile.getJson() self.ID = 'Player' self.width = 16 * self.window.scaleFactor self.height = 32 * self.window.scaleFactor self.velX = 0 self.velY = 0 self.map = self.playerData['map'] self.x = self.playerData['x'] self.y = self.playerData['y'] self.speed = self.playerData['speed'] self.health = self.playerData['health'] self.maxHealth = self.playerData['maxHealth'] # State self.playerState = PlayerState.IDLE self.direction = Direction(self.playerData['direction']) # Creating Spritesheet self.spriteSheet = SpriteSheet('./assets/art/character.png') # Load sprites into array self._sprites = self.spriteSheet.getImageArray(16, 32, self.width, self.height) # Active sprites self.activeSprite = None # Collision | Must set offsets and width/height for colliders self.colliderOffsetX = 20 self.colliderOffsetY = 90 self.colliderWidth = 25 self.colliderHeight = 10 self.swordColliderOffsetX = [0, -5, 0, 45] self.swordColliderOffsetY = [25, 50, 90, 50] self.collider = pygame.Rect(self.x + self.colliderOffsetX, self.y + self.colliderOffsetY, self.colliderWidth, self.colliderHeight) self.topCollider = pygame.Rect( self.collider.x + self.collider.width * 0.1, self.collider.y, self.collider.width * 0.8, self.collider.height * 0.1) self.leftCollider = pygame.Rect( self.collider.x, self.collider.y + self.collider.height * 0.1, self.collider.width * 0.1, self.collider.height * 0.8) self.bottomCollider = pygame.Rect( self.collider.x + self.collider.width * 0.1, self.collider.y + self.collider.height * 0.9, self.collider.width * 0.8, self.collider.height * 0.1) self.rightCollider = pygame.Rect( self.collider.x + self.collider.width * 0.9, self.collider.y + self.collider.height * 0.1, self.collider.width * 0.1, self.collider.height * 0.8) self.swordColliderTop = pygame.Rect( self.x + self.swordColliderOffsetX[0], self.y + self.swordColliderOffsetY[0], self.width, 30) self.swordColliderLeft = pygame.Rect( self.x + self.swordColliderOffsetX[1], self.y + self.swordColliderOffsetY[1], 30, 50) self.swordColliderBottom = pygame.Rect( self.x + self.swordColliderOffsetX[2], self.y + self.swordColliderOffsetY[2], self.width, 30) self.swordColliderRight = pygame.Rect( self.x + self.swordColliderOffsetX[3], self.y + self.swordColliderOffsetY[3], 30, 50) # Animation Setup self.lastTick = 0 self.animationFrame = 0 # Knockback Setup self.knockLastTick = 0 self.knockTicks = 0 self.knockBack = False def tick(self, ticks): # Check if moving and set player state if self.playerState == PlayerState.IDLE: if not self.velX == 0 or not self.velY == 0: self.playerState = PlayerState.WALKING # Move player by vel and set player state if stopped walking if self.playerState == PlayerState.WALKING: self.x += self.velX * self.speed self.y += self.velY * self.speed if self.velX == 0 and self.velY == 0: self.playerState = PlayerState.IDLE # Set collider's to x and y value self.collider.x = self.x + self.colliderOffsetX self.collider.y = self.y + self.colliderOffsetY self.swordColliderTop.x = self.x + self.swordColliderOffsetX[0] self.swordColliderTop.y = self.y + self.swordColliderOffsetY[0] self.swordColliderLeft.x = self.x + self.swordColliderOffsetX[1] self.swordColliderLeft.y = self.y + self.swordColliderOffsetY[1] self.swordColliderBottom.x = self.x + self.swordColliderOffsetX[2] self.swordColliderBottom.y = self.y + self.swordColliderOffsetY[2] self.swordColliderRight.x = self.x + self.swordColliderOffsetX[3] self.swordColliderRight.y = self.y + self.swordColliderOffsetY[3] # Animate player self.animate(ticks) # Knockback if neeeded if self.knockBack: self.knockback(ticks) def render(self, scrollX, scrollY): # Render Collider on bottom #self.window.drawRect(self.collider.x - scrollX, self.collider.y - scrollY, self.collider.width, self.collider.height, 0, 0, 255) # Render Sprite self.window.drawSprite(self.x - scrollX, self.y - scrollY, self.activeSprite) # Render Collider on top #self.window.drawRect(self.collider.x - scrollX, self.collider.y - scrollY, self.collider.width, self.collider.height, 0, 0, 255) #self.window.drawRect(self.swordColliderTop.x - scrollX, self.swordColliderTop.y - scrollY, self.swordColliderTop.width, self.swordColliderTop.height, 0, 0, 255) #self.window.drawRect(self.swordColliderBottom.x - scrollX, self.swordColliderBottom.y - scrollY, self.swordColliderBottom.width, self.swordColliderBottom.height, 0, 0, 255) #self.window.drawRect(self.swordColliderLeft.x - scrollX, self.swordColliderLeft.y - scrollY, self.swordColliderLeft.width, self.swordColliderLeft.height, 0, 0, 255) #self.window.drawRect(self.swordColliderRight.x - scrollX, self.swordColliderRight.y - scrollY, self.swordColliderRight.width, self.swordColliderRight.height, 0, 0, 255) # Check Animation def animate(self, ticks): if self.playerState == PlayerState.IDLE: if self.direction == Direction.UP: self.activeSprite = self._sprites[2][0] elif self.direction == Direction.LEFT: self.activeSprite = self._sprites[3][0] elif self.direction == Direction.DOWN: self.activeSprite = self._sprites[0][0] elif self.direction == Direction.RIGHT: self.activeSprite = self._sprites[1][0] if self.playerState == PlayerState.WALKING: if self.animationFrame == 0: self.lastTick = ticks self.animationFrame += 1 if self.animationFrame == 1: if self.direction == Direction.UP: self.activeSprite = self._sprites[2][1] elif self.direction == Direction.LEFT: self.activeSprite = self._sprites[3][1] elif self.direction == Direction.DOWN: self.activeSprite = self._sprites[0][1] elif self.direction == Direction.RIGHT: self.activeSprite = self._sprites[1][1] elif self.direction == Direction.LEFT_UP: self.activeSprite = self._sprites[3][1] elif self.direction == Direction.LEFT_DOWN: self.activeSprite = self._sprites[3][1] elif self.direction == Direction.RIGHT_UP: self.activeSprite = self._sprites[1][1] elif self.direction == Direction.RIGHT_DOWN: self.activeSprite = self._sprites[1][1] elif self.animationFrame == 2: if self.direction == Direction.UP: self.activeSprite = self._sprites[2][2] elif self.direction == Direction.LEFT: self.activeSprite = self._sprites[3][2] elif self.direction == Direction.DOWN: self.activeSprite = self._sprites[0][2] elif self.direction == Direction.RIGHT: self.activeSprite = self._sprites[1][2] elif self.direction == Direction.LEFT_UP: self.activeSprite = self._sprites[3][2] elif self.direction == Direction.LEFT_DOWN: self.activeSprite = self._sprites[3][2] elif self.direction == Direction.RIGHT_UP: self.activeSprite = self._sprites[1][2] elif self.direction == Direction.RIGHT_DOWN: self.activeSprite = self._sprites[1][2] elif self.animationFrame == 3: if self.direction == Direction.UP: self.activeSprite = self._sprites[2][3] elif self.direction == Direction.LEFT: self.activeSprite = self._sprites[3][3] elif self.direction == Direction.DOWN: self.activeSprite = self._sprites[0][3] elif self.direction == Direction.RIGHT: self.activeSprite = self._sprites[1][3] elif self.direction == Direction.LEFT_UP: self.activeSprite = self._sprites[3][3] elif self.direction == Direction.LEFT_DOWN: self.activeSprite = self._sprites[3][3] elif self.direction == Direction.RIGHT_UP: self.activeSprite = self._sprites[1][3] elif self.direction == Direction.RIGHT_DOWN: self.activeSprite = self._sprites[1][3] elif self.animationFrame == 4: if self.direction == Direction.UP: self.activeSprite = self._sprites[2][0] elif self.direction == Direction.LEFT: self.activeSprite = self._sprites[3][0] elif self.direction == Direction.DOWN: self.activeSprite = self._sprites[0][0] elif self.direction == Direction.RIGHT: self.activeSprite = self._sprites[1][0] elif self.direction == Direction.LEFT_UP: self.activeSprite = self._sprites[3][0] elif self.direction == Direction.LEFT_DOWN: self.activeSprite = self._sprites[3][0] elif self.direction == Direction.RIGHT_UP: self.activeSprite = self._sprites[1][0] elif self.direction == Direction.RIGHT_DOWN: self.activeSprite = self._sprites[1][0] if ticks - self.lastTick == 20: self.lastTick = ticks self.animationFrame += 1 if self.animationFrame == 5: self.animationFrame = 0 elif self.playerState == PlayerState.ATTACKING: if self.animationFrame == 0: self.lastTick = ticks self.animationFrame += 1 if self.animationFrame == 1: if self.direction == Direction.UP: self.activeSprite = self._sprites[5][0] elif self.direction == Direction.LEFT: self.activeSprite = self._sprites[7][0] elif self.direction == Direction.DOWN: self.activeSprite = self._sprites[4][0] elif self.direction == Direction.RIGHT: self.activeSprite = self._sprites[6][0] elif self.direction == Direction.LEFT_UP: self.activeSprite = self._sprites[7][0] elif self.direction == Direction.LEFT_DOWN: self.activeSprite = self._sprites[7][0] elif self.direction == Direction.RIGHT_UP: self.activeSprite = self._sprites[6][0] elif self.direction == Direction.RIGHT_DOWN: self.activeSprite = self._sprites[6][0] elif self.animationFrame == 2: if self.direction == Direction.UP: self.activeSprite = self._sprites[5][1] elif self.direction == Direction.LEFT: self.activeSprite = self._sprites[7][1] elif self.direction == Direction.DOWN: self.activeSprite = self._sprites[4][1] elif self.direction == Direction.RIGHT: self.activeSprite = self._sprites[6][1] elif self.direction == Direction.LEFT_UP: self.activeSprite = self._sprites[7][1] elif self.direction == Direction.LEFT_DOWN: self.activeSprite = self._sprites[7][1] elif self.direction == Direction.RIGHT_UP: self.activeSprite = self._sprites[6][1] elif self.direction == Direction.RIGHT_DOWN: self.activeSprite = self._sprites[6][1] elif self.animationFrame == 3: if self.direction == Direction.UP: self.activeSprite = self._sprites[5][2] elif self.direction == Direction.LEFT: self.activeSprite = self._sprites[7][2] elif self.direction == Direction.DOWN: self.activeSprite = self._sprites[4][2] elif self.direction == Direction.RIGHT: self.activeSprite = self._sprites[6][2] elif self.direction == Direction.LEFT_UP: self.activeSprite = self._sprites[7][2] elif self.direction == Direction.LEFT_DOWN: self.activeSprite = self._sprites[7][2] elif self.direction == Direction.RIGHT_UP: self.activeSprite = self._sprites[6][2] elif self.direction == Direction.RIGHT_DOWN: self.activeSprite = self._sprites[6][2] elif self.animationFrame == 4: if self.direction == Direction.UP: self.activeSprite = self._sprites[5][3] elif self.direction == Direction.LEFT: self.activeSprite = self._sprites[7][3] elif self.direction == Direction.DOWN: self.activeSprite = self._sprites[4][3] elif self.direction == Direction.RIGHT: self.activeSprite = self._sprites[6][3] elif self.direction == Direction.LEFT_UP: self.activeSprite = self._sprites[7][3] elif self.direction == Direction.LEFT_DOWN: self.activeSprite = self._sprites[7][3] elif self.direction == Direction.RIGHT_UP: self.activeSprite = self._sprites[6][3] elif self.direction == Direction.RIGHT_DOWN: self.activeSprite = self._sprites[6][3] if self.animationFrame == 5: if not self.velX == 0 or not self.velY == 0: self.playerState = PlayerState.WALKING else: self.playerState = PlayerState.IDLE self.animationFrame = 0 else: if ticks - self.lastTick == 5: self.lastTick = ticks self.animationFrame += 1 def move(self, isKeyDown, velX, velY): if isKeyDown: if velY == -1: self.velY = -1 self.animationFrame = 0 if self.velX == -1: self.direction = Direction.LEFT_UP elif self.velX == 1: self.direction = Direction.RIGHT_UP else: self.direction = Direction.UP if velX == -1: self.velX = -1 self.animationFrame = 0 if self.velY == -1: self.player = Direction.LEFT_UP elif self.velY == 1: self.player = Direction.LEFT_DOWN else: self.direction = Direction.LEFT if velY == 1: self.velY = 1 self.animationFrame = 0 if self.velX == -1: self.direction = Direction.LEFT_DOWN elif self.velX == 1: self.direction = Direction.RIGHT_DOWN else: self.direction = Direction.DOWN if velX == 1: self.velX = 1 self.animationFrame = 0 if self.velY == -1: self.direction = Direction.RIGHT_UP elif self.velY == 1: self.direction = Direction.RIGHT_DOWN else: self.direction = Direction.RIGHT else: if velX == 1: self.velX = 0 if self.velY == -1: self.direction = Direction.UP elif self.velY == 1: self.direction = Direction.DOWN if velY == 1: self.velY = 0 if self.velX == -1: self.direction = Direction.LEFT elif self.velX == 1: self.direction = Direction.RIGHT self.animationFrame = 0 def knockback(self, ticks): if self.knockTicks == 0: self.knockLastTick = ticks self.knockTicks += 1 if self.knockTicks == 1: if self.direction == Direction.UP: self.y += 2 elif self.direction == Direction.LEFT or self.direction == Direction.LEFT_DOWN or self.direction == Direction.LEFT_UP: self.x += 2 elif self.direction == Direction.DOWN: self.y -= 2 elif self.direction == Direction.RIGHT or self.direction == Direction.RIGHT_DOWN or self.direction == Direction.RIGHT_UP: self.x -= 2 if self.knockTicks == 2: if self.direction == Direction.UP: self.y += 2 elif self.direction == Direction.LEFT or self.direction == Direction.LEFT_DOWN or self.direction == Direction.LEFT_UP: self.x += 2 elif self.direction == Direction.DOWN: self.y -= 2 elif self.direction == Direction.RIGHT or self.direction == Direction.RIGHT_DOWN or self.direction == Direction.RIGHT_UP: self.x -= 2 if self.knockTicks == 3: if self.direction == Direction.UP: self.y += 2 elif self.direction == Direction.LEFT or self.direction == Direction.LEFT_DOWN or self.direction == Direction.LEFT_UP: self.x += 2 elif self.direction == Direction.DOWN: self.y -= 2 elif self.direction == Direction.RIGHT or self.direction == Direction.RIGHT_DOWN or self.direction == Direction.RIGHT_UP: self.x -= 2 if self.knockTicks == 4: if self.direction == Direction.UP: self.y += 2 elif self.direction == Direction.LEFT or self.direction == Direction.LEFT_DOWN or self.direction == Direction.LEFT_UP: self.x += 2 elif self.direction == Direction.DOWN: self.y -= 2 elif self.direction == Direction.RIGHT or self.direction == Direction.RIGHT_DOWN or self.direction == Direction.RIGHT_UP: self.x -= 2 if self.knockTicks == 5: if not self.velX == 0 or not self.velY == 0: self.playerState = PlayerState.WALKING else: self.playerState = PlayerState.IDLE self.knockTicks = 0 self.knockBack = False else: if ticks - self.knockLastTick == 5: self.knockLastTick = ticks self.knockTicks += 1 # Attack def attack(self, objectHandler): self.animationFrame = 0 self.playerState = PlayerState.ATTACKING if self.direction == Direction.UP: collideObjects = objectHandler.getCollision(self.swordColliderTop) if not collideObjects == []: for tmpObject in collideObjects: if tmpObject.ID == 'Enemy': objectHandler.removeObject(tmpObject) elif self.direction == Direction.LEFT or self.direction == Direction.LEFT_DOWN or self.direction == Direction.LEFT_UP: collideObjects = objectHandler.getCollision(self.swordColliderLeft) if not collideObjects == []: for tmpObject in collideObjects: if tmpObject.ID == 'Enemy': objectHandler.removeObject(tmpObject) elif self.direction == Direction.DOWN: collideObjects = objectHandler.getCollision( self.swordColliderBottom) if not collideObjects == []: for tmpObject in collideObjects: if tmpObject.ID == 'Enemy': objectHandler.removeObject(tmpObject) elif self.direction == Direction.RIGHT or self.direction == Direction.RIGHT_DOWN or self.direction == Direction.RIGHT_UP: collideObjects = objectHandler.getCollision( self.swordColliderRight) if not collideObjects == []: for tmpObject in collideObjects: if tmpObject.ID == 'Enemy': objectHandler.removeObject(tmpObject) # Interact def interact(self, objectHandler): collideObjects = objectHandler.getCollision(self.collider) if not collideObjects == []: for tmpObject in collideObjects: if tmpObject.ID == 'Sign': if self.playerState == PlayerState.INTERACTING: self.playerState = PlayerState.IDLE tmpObject.textActive = False else: self.playerState = PlayerState.INTERACTING tmpObject.textActive = True # Player Getting Hit def hit(self, objectThatHit, ticks): self.health -= 10 self.knockBack = True self.playerState = PlayerState.KNOCKED # Recieves detected collision def collide(self, collision): # Updates positions of side collisions self.topCollider.x = self.collider.x + self.collider.width * 0.1 self.topCollider.y = self.collider.y self.leftCollider.x = self.collider.x self.leftCollider.y = self.collider.y + self.collider.height * 0.1 self.bottomCollider.x = self.collider.x + self.collider.width * 0.1 self.bottomCollider.y = self.collider.y + self.collider.height * 0.9 self.rightCollider.x = self.collider.x + self.collider.width * 0.9 self.rightCollider.y = self.collider.y + self.collider.height * 0.1 if (self.topCollider.colliderect(collision.collider)): self.y = collision.y + collision.height - self.colliderOffsetY if (self.leftCollider.colliderect(collision.collider)): self.x = collision.x + collision.width - self.colliderOffsetX if (self.bottomCollider.colliderect(collision.collider)): self.y = collision.y - self.collider.height - self.colliderOffsetY if (self.rightCollider.colliderect(collision.collider)): self.x = collision.x - self.collider.width - self.colliderOffsetX def saveSettings(self): self.playerData['map'] = self.map self.playerData['x'] = self.x self.playerData['y'] = self.y self.playerData['direction'] = self.direction.value self.playerData['speed'] = self.speed self.playerData['health'] = self.health self.playerData['maxHealth'] = self.maxHealth self.playerFile.saveJson(self.playerData)
class MenuState: def __init__(self, gsm): print("MenuState initialized") # GameStateManager reference self.gsm = gsm # Background Image # FIND A WAY TO ADD ANIMATION TIME SO THAT IT DOESNT PLAY TOO FAST self.bgSpriteSheet = SpriteSheet( os.path.join("res", "MapState", "menu background.png"), 4) self.bgImage = None self.bgIndex = 1 # Menu Option self.currentOption = 0 self.maxOptions = 3 self.boat = pygame.image.load( os.path.join("res", "MapState", "menu boat.png")) self.boatX = 175 self.boatY = 0 self.animationTimer = 0 self.animationTime = 10 def update(self): #Runs the animation for the background self.bgImage = self.bgSpriteSheet.grabImage(1, self.bgIndex, 800, 600) if self.animationTimer >= self.animationTime: if self.bgIndex < self.bgSpriteSheet.amountOfSprites: self.bgIndex += 1 self.animationTimer = 0 else: self.bgIndex = 1 self.animationTimer = 0 else: self.animationTimer += 1 # Calculates the position of the boat according to the current option if self.currentOption == 0: self.boatY = 150 + (100 * self.currentOption) if self.currentOption == 1: self.boatY = 150 + (100 * self.currentOption) if self.currentOption == 2: self.boatY = 150 + (100 * self.currentOption) def draw(self, window): window.blit(self.bgImage, (0, 0)) window.blit(self.boat, (self.boatX, self.boatY)) # Text # Title font = pygame.font.Font(os.path.join("res", "arcade.ttf"), 50) title = font.render("Treasure Hunter", True, Color.RED) titleLocationRect = title.get_rect() titleLocationRect.center = (800 / 2, 50) window.blit(title, titleLocationRect) # Menu Options for option in range(self.maxOptions): if option == 0: play = font.render("Play", True, Color.AQUA) playLocationRect = play.get_rect() playLocationRect.center = (800 / 2, 200 + (100 * option)) window.blit(play, playLocationRect) if option == 1: help = font.render("Help", True, Color.AQUA) helpLocationRect = help.get_rect() helpLocationRect.center = (800 / 2, 200 + (100 * option)) window.blit(help, helpLocationRect) if option == 2: quit = font.render("Quit", True, Color.AQUA) quitLocationRect = quit.get_rect() quitLocationRect.center = (800 / 2, 200 + (100 * option)) window.blit(quit, quitLocationRect) def keyHandler(self): for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_DOWN: if self.currentOption == self.maxOptions - 1: self.currentOption = 0 else: self.currentOption += 1 if event.key == pygame.K_UP: if self.currentOption == 0: self.currentOption = self.maxOptions - 1 else: self.currentOption -= 1 if event.key == pygame.K_RETURN: if self.currentOption == 0: self.gsm.setState(self.gsm.MAPSTATE) if self.currentOption == 1: self.gsm.setState(self.gsm.HELPSTATE) if self.currentOption == 2: pygame.quit() quit()
#TODO: render a play page and then add scores on top #TODO: add new enemy when it hits at random locations #TODO: add power ups after hitting power ups, speed goes up by 5 pygame.init() W, H = 800, 500 HW, HH, = W / 2, H / 2 Area = W * H screen = pygame.display.set_mode((W, H)) background_image_original = pygame.image.load("./images/background3.png") background_image = pygame.transform.scale(background_image_original, [800, 500]) s_original = pygame.image.load("./images/archer.png") s = SpriteSheet(s_original, 13, 1, screen) arrows = Group() bird = Enemy(screen, 5, 4, 10) bird_two = Enemy(screen, 5, 4, 650) enemy_group_left = Group() enemy_group_right = Group() enemy_group_left.add(bird) enemy_group_right.add(bird_two) def check_collision(): pygame.sprite.groupcollide(arrows, enemy_group_left, False, True) pygame.sprite.groupcollide(arrows, enemy_group_right, False, True) def message_players_name(text, name):
def __init__(self, playerFile, window): # Init self.window = window # Personalized self.playerFile = playerFile self.playerData = self.playerFile.getJson() self.ID = 'Player' self.width = 16 * self.window.scaleFactor self.height = 32 * self.window.scaleFactor self.velX = 0 self.velY = 0 self.map = self.playerData['map'] self.x = self.playerData['x'] self.y = self.playerData['y'] self.speed = self.playerData['speed'] self.health = self.playerData['health'] self.maxHealth = self.playerData['maxHealth'] # State self.playerState = PlayerState.IDLE self.direction = Direction(self.playerData['direction']) # Creating Spritesheet self.spriteSheet = SpriteSheet('./assets/art/character.png') # Load sprites into array self._sprites = self.spriteSheet.getImageArray(16, 32, self.width, self.height) # Active sprites self.activeSprite = None # Collision | Must set offsets and width/height for colliders self.colliderOffsetX = 20 self.colliderOffsetY = 90 self.colliderWidth = 25 self.colliderHeight = 10 self.swordColliderOffsetX = [0, -5, 0, 45] self.swordColliderOffsetY = [25, 50, 90, 50] self.collider = pygame.Rect(self.x + self.colliderOffsetX, self.y + self.colliderOffsetY, self.colliderWidth, self.colliderHeight) self.topCollider = pygame.Rect( self.collider.x + self.collider.width * 0.1, self.collider.y, self.collider.width * 0.8, self.collider.height * 0.1) self.leftCollider = pygame.Rect( self.collider.x, self.collider.y + self.collider.height * 0.1, self.collider.width * 0.1, self.collider.height * 0.8) self.bottomCollider = pygame.Rect( self.collider.x + self.collider.width * 0.1, self.collider.y + self.collider.height * 0.9, self.collider.width * 0.8, self.collider.height * 0.1) self.rightCollider = pygame.Rect( self.collider.x + self.collider.width * 0.9, self.collider.y + self.collider.height * 0.1, self.collider.width * 0.1, self.collider.height * 0.8) self.swordColliderTop = pygame.Rect( self.x + self.swordColliderOffsetX[0], self.y + self.swordColliderOffsetY[0], self.width, 30) self.swordColliderLeft = pygame.Rect( self.x + self.swordColliderOffsetX[1], self.y + self.swordColliderOffsetY[1], 30, 50) self.swordColliderBottom = pygame.Rect( self.x + self.swordColliderOffsetX[2], self.y + self.swordColliderOffsetY[2], self.width, 30) self.swordColliderRight = pygame.Rect( self.x + self.swordColliderOffsetX[3], self.y + self.swordColliderOffsetY[3], 30, 50) # Animation Setup self.lastTick = 0 self.animationFrame = 0 # Knockback Setup self.knockLastTick = 0 self.knockTicks = 0 self.knockBack = False