class Explosion(Hideable, GameObject): """Model a temporary explosion.""" BIG = "media/images/explosao.gif" SMALL = "media/images/explosion.gif" def __init__(self, position, type=SMALL, **kwargs): """Initialize the object.""" Hideable.__init__(self) GameObject.__init__(self, GameObject.Priority.DEFAULT) ts = kwargs.get('time_scale', 1.0) self.__sprite = Sprite(type, animate=True, time_scale=ts, loop=True) self.__ttl = self.__sprite.duration + pygame.time.get_ticks() _, _, w, h, *_ = list(map(lambda i: i // 2, self.__sprite.bounds)) x, y = position self.__position = (x - w, y - h) self.should_collide = False def update(self, bounds): """Update object.""" if pygame.time.get_ticks() > self.__ttl: self.hide() def draw(self, screen): """Draw object.""" self.__sprite.draw(screen, self.__position)
def __init__(self, pos, scale=1, **kw): """Initialize the game object.""" Collider.__init__(self, kw.get('shape', Collider.ELLIPSE)) Controllable.__init__(self, ConstantController(-1, 0)) Movable.__init__(self, pos) GameObject.__init__(self, GameObject.Priority.BOSS) self.__sprite = Sprite('media/images/asteroid.png', scale=scale, rotate=0)
def __init__(game, self): self.pos_x = 57 self.pos_y = 14 self.animation_input_yes = Sprite('input_yes', self.pos_x, self.pos_y) self.animation_input_no = Sprite('input_no', self.pos_x, self.pos_y) self.option = 'yes' self.animation = self.animation_input_yes self.texture = self.animation.texture
class UI: def __init__(self, game): self.game = game self.dialogueActive = False # Create sprites self.ui = Sprite(game, 'ui', 0, 0, transparent=True) self.hp = Bar(game, 23, 21, 10) self.mp = Bar(game, 37, 21, 10) self.name = Text(game, 2, 21, '', width=16, justify='center') self.location = Text(game, 49, 21, '', width=16, justify='center') self.title = Text(game, 3, 1, '', width=61, justify='center') # Add sprites to layers self.ui.add(layer='ui') self.hp.add(layer='ui') self.mp.add(layer='ui') self.name.add(layer='ui') self.location.add(layer='ui') self.title.add(layer='ui') def setHP(self, value): self.hp.setValue(value) def setMP(self, value): self.mp.setValue(value) def setName(self, value): self.name.update(value) def setLocation(self, value): self.location.update(value) def setTitle(self, value): self.title.update(value) def startConversation(self, text): if self.dialogueActive == False: self.dialogueActive = True self.dialogue = Conversation(self.game, text).sprite self.dialogue.add(layer='ui') def updateConversation(self, text): if self.dialogueActive == True: next = Conversation(self.game, text).sprite self.dialogue.remove() self.dialogue = next self.dialogue.add(layer='ui') def endConversation(self): if self.dialogueActive == True: self.dialogue.remove() self.dialogueActive = False
def __init__(self, position, type=SMALL, **kwargs): """Initialize the object.""" Hideable.__init__(self) GameObject.__init__(self, GameObject.Priority.DEFAULT) ts = kwargs.get('time_scale', 1.0) self.__sprite = Sprite(type, animate=True, time_scale=ts, loop=True) self.__ttl = self.__sprite.duration + pygame.time.get_ticks() _, _, w, h, *_ = list(map(lambda i: i // 2, self.__sprite.bounds)) x, y = position self.__position = (x - w, y - h) self.should_collide = False
def __init__(self, canvas, image, **kw): """Initialize Enemy object.""" Controllable.__init__(self, kw.get('controller', ConstantController(-1, 0))) Collider.__init__(self, kw.get('bounding_shape', Collider.RECT)) Movable.__init__( self, kw.get('position', (canvas[0] + 10, randint(50, canvas[1] - 50)))) GameObject.__init__(self, kw.get('priority', GameObject.Priority.NPC)) self.__sprite = Sprite(image, **kw) x, y, *_ = self.__sprite.bounds self.move(x, y)
def __init__(self, canvas, image, **kw): """Initialize Enemy object.""" Controllable.__init__(self, kw.get('controller', ConstantController(-1, 0))) Collider.__init__(self, kw.get('shape', Collider.RECT)) Movable.__init__(self, kw.get('position', (canvas[0] + 10, randint(50, canvas[1] - 50)))) Killable.__init__(self, Explosion.SMALL, time_scale=0.5) GameObject.__init__(self, GameObject.Priority.NPC) self. __sprite = Sprite(image, animate=kw.get('animate', False), cast_shadow=kw.get('cast_shadow', True))
def __init__(self, position, speed=5, controller=ConstantController(0, 0)): """Initialize the object.""" Collider.__init__(self, Collider.RECT) Controllable.__init__(self, controller) Movable.__init__(self, position) Killable.__init__(self, Explosion.BIG) GameObject.__init__(self, GameObject.Priority.PLAYER) self.__original_position = position self.__sprite = Sprite('media/images/f18.png') self.__lives = 3 self.__points = 0 self.__speed = speed self.__move = (0, 0)
class Asteroid(Collider, Controllable, Movable, GameObject): """Model an asteroid game object.""" def __init__(self, pos, scale=1, **kw): """Initialize the game object.""" Collider.__init__(self, kw.get('shape', Collider.ELLIPSE)) Controllable.__init__(self, ConstantController(-1, 0)) Movable.__init__(self, pos) GameObject.__init__(self, GameObject.Priority.BOSS) self.__sprite = Sprite('media/images/asteroid.png', scale=scale, rotate=0) def update(self, bounds): """Update object position.""" try: self.move(*next(self.controller)) self.offlimits(bounds) except Exception as e: pass def draw(self, screen): """Draw object on the screen.""" self.__sprite.draw(screen, self.position) # pygame.draw.ellipse(screen, (255, 0, 255), self.__sprite.bounds, 2) def offlimits(self, limits): """Take action when object is off-limits, return if needs update.""" wx, wy, ww, wh = limits x, y, w, h = self.bounds if x + w < wx: self.hide() def collide_with(self, object): """Asteroids are imune to collision.""" pass @property def bounds(self): """Query object bounds.""" x, y = self.position _, _, rx, ry = list(map(lambda n: n // 2, self.__sprite.bounds)) return (x + rx, y + ry, rx, ry)
def __init__(self, game): self.game = game self.dialogueActive = False # Create sprites self.ui = Sprite(game, 'ui', 0, 0, transparent=True) self.hp = Bar(game, 23, 21, 10) self.mp = Bar(game, 37, 21, 10) self.name = Text(game, 2, 21, '', width=16, justify='center') self.location = Text(game, 49, 21, '', width=16, justify='center') self.title = Text(game, 3, 1, '', width=61, justify='center') # Add sprites to layers self.ui.add(layer='ui') self.hp.add(layer='ui') self.mp.add(layer='ui') self.name.add(layer='ui') self.location.add(layer='ui') self.title.add(layer='ui')
def buildSprite(self, text): s = Sprite(self.game, 'textbox', self.pos_x, self.pos_y) header = list( '──────────────────────────────────────────────────────────────') if len(text) < 61: line1 = text[0:61] line2 = '' elif len(text) >= 61: line1 = text[0:61] line2 = text[61:122] # Add leading space to line to add space line1 = ' ' + line1 line2 = ' ' + line2 # Pad lines to width line1 = line1.ljust(61) line2 = line2.ljust(61) # Convert to lists line1 = list(line1) line2 = list(line2) # Build final texture s.texture = [header, line1, line2] return s
def __init__(self, game, pos_x, pos_y): super().__init__(game, 'blank', pos_x, pos_y, transparent=True) self.direction = 'right' self.speechbubble = SpeechBubble( game, self) # Initialize empty speech bubble self.animation_walk_left = Animation([ Sprite(self.game, 'character_walk1', self.pos_x, self.pos_y, invert=True), Sprite(self.game, 'character_walk2', self.pos_x, self.pos_y, invert=True) ]) self.animation_walk_right = Animation([ Sprite(self.game, 'character_walk1', self.pos_x, self.pos_y), Sprite(self.game, 'character_walk2', self.pos_x, self.pos_y) ]) self.animation_idle_right = Animation( [Sprite(self.game, 'character_idle', self.pos_x, self.pos_y)]) self.animation_idle_left = Animation([ Sprite(self.game, 'character_idle', self.pos_x, self.pos_y, invert=True) ]) self.animation = self.animation_idle_right self.texture = self.animation.texture
from engine import Window from engine import InputManager from engine import Sprite from entity import Entity from entity import SpriteRendererComponent import time window = Window(1280, 720, "tkinter game engine") inputManager = InputManager(window) testSprite = Sprite("test.png", 1) entityTest = Entity(window, 100, 100) entityTest.addComponent(SpriteRendererComponent(testSprite)) while True: if inputManager.getKey("w"): entityTest.translate(0, 1) if inputManager.getKey("s"): entityTest.translate(0, -1) if inputManager.getKey("d"): entityTest.translate(1, 0) if inputManager.getKey("a"): entityTest.translate(-1, 0) window.update() time.sleep(1 / 240)
class Enemy(Controllable, Collider, Movable, GameObject): """Models a simple NPC.""" def __init__(self, canvas, image, **kw): """Initialize Enemy object.""" Controllable.__init__(self, kw.get('controller', ConstantController(-1, 0))) Collider.__init__(self, kw.get('bounding_shape', Collider.RECT)) Movable.__init__( self, kw.get('position', (canvas[0] + 10, randint(50, canvas[1] - 50)))) GameObject.__init__(self, kw.get('priority', GameObject.Priority.NPC)) self.__sprite = Sprite(image, **kw) x, y, *_ = self.__sprite.bounds self.move(x, y) def update(self, bounds): """Update enemy position.""" try: dx, dy = next(self.controller) dx *= -1 self.move(dx, dy) self.offlimits(bounds) except Exception as e: pass x, _, w, *_ = self.bounds if x + 2 * w < 0: self.destroy() def draw(self, screen): """Draw enemy on the screen.""" self.__sprite.draw(screen, self.position) def offlimits(self, limits): """Take action when object is off-limits, return if needs update.""" wx, wy, ww, wh = limits x, y, w, h = self.bounds if x + w < wx: self.hide() dy = wy if y < wy else y dy = (wy + wh) - h if (y + h) > (wy + wh) else dy dy -= y self.move(0, dy) def collide_with(self, object): """Indestructible enemy.""" pass @property def center(self): """Query object bounds.""" return tuple( map(lambda e: sum(e), zip(self.position, self.__sprite.center))) @property def rotation(self): """Return the sprite rotation.""" return self.__sprite.rotation @property def dimension(self): """Return the object dimension.""" _, _, w, h, *_ = self.__sprite.bounds return (w, h)
class Player(Collider, Controllable, Movable, Killable, GameObject, NonRemovable): """Models the player objec.""" def __init__(self, position, speed=5, controller=ConstantController(0, 0)): """Initialize the object.""" Collider.__init__(self, Collider.RECT) Controllable.__init__(self, controller) Movable.__init__(self, position) Killable.__init__(self, Explosion.BIG) GameObject.__init__(self, GameObject.Priority.PLAYER) self.__original_position = position self.__sprite = Sprite('media/images/f18.png') self.__lives = 3 self.__points = 0 self.__speed = speed self.__move = (0, 0) def collide_with(self, object): """Enemy wal killed.""" if isinstance(object, Projectile) and \ isinstance(self, object.creator): return if self.should_update: self.__lives -= 1 self.should_collide = False self.die() def update(self, bounds): """Update object position.""" if self.should_update: try: mv = next(self.controller) self.move(*list(map(lambda n: self.__speed * n, mv))) self.offlimits(bounds) except StopIteration as si: pass else: Killable.update(self, bounds) def draw(self, screen): """Draw enemy on the screen.""" if self.should_update: self.__sprite.draw(screen, self.position) else: Killable.draw(self, screen) def add_points(self, points): """Add points to player.""" if points > 0: self.__points += points def accelerate(self): """Make the player faster.""" if self.__speed < 7.5: self.__speed += 0.5 def offlimits(self, limits): """Take action when object is off-limits, return if needs update.""" wx, wy, ww, wh = limits x, y, w, h = self.bounds dx = wx if x < wx else x dx = (wx + ww) - w if (x + w) > (wx + ww) else dx dx -= x dy = wy if y < wy else y dy = (wy + wh) - h if (y + h) > (wy + wh) else dy dy -= y self.move(dx, dy) def respawn(self): """Respawn player.""" x, y = self.position ox, oy = self.__original_position self.move(ox - x, oy - y) self.should_collide = True self.show() Killable.respawn(self) @property def bounds(self): """Query object bounds.""" x, y = self.position _, _, w, h = self.__sprite.bounds return (x, y, w, h) @property def lives(self): """Query player lives.""" return self.__lives @property def points(self): """Query player points.""" return self.__points
def __init__(self): self.engine = Engine(24, 69) ui = UI(self) ui.setName('Taki The Dwarf') ui.setLocation('City of Id') ui.setHP(3) ui.setMP(8) ui.setTitle('Objective: Find Train Station') # platform = Sprite(self, 'ground', 10, 10, transparent=True) # platform.add(layer='bg') cloud1 = Sprite(self, 'cloud', 0, 0, transparent=True) cloud1.add(layer='bg') background = Sprite(self, 'background', -3, 0, transparent=True) background.add(layer='bg') cloud2 = Sprite(self, 'cloud', 25, 0, transparent=True) cloud2.add(layer='bg') player = Character(self, 14, 8) player.add(layer='obj') boss = Sprite(self, 'boss_idle', 21, 8) boss.add(layer='obj') dock = Sprite(self, 'dock', 0, 11, transparent=True) dock.add(layer='fg') wave = Sprite(self, 'wave', 0, 15) wave.add(layer='fg') # scroll = Sprite(self, 'scroll', 2, 2) # scroll.add(layer='fg') # girl = Sprite(self, 'girl', 21, -10) # girl.add(layer='fg') kb = Controller() self.engine.tick() dialoge = 0 while True: time.sleep(1 / 60) self.engine.tick() if kb.kbhit(): c = kb.getch() if ord(c) == 27: # ESC break elif ord(c) == 13: # ENTER pass elif c == 'w': player.pos_y -= 1 elif c == 'a': # player.pos_x -= 1 player.move_L(1) elif c == 's': player.pos_y += 1 elif c == 'd': # player.pos_x += 1 player.move_R(1) elif c == 'm': # ui.startConversation('Hak: Good morning fellow traveler!') dialoge += 1 if dialoge == 1: player.speak('Good morning!') # ui.startConversation('Hak: Good morning fellow traveler!') elif dialoge == 2: player.speak('Would you like to buy something?') # ui.updateConversation('Hak: Would you like to buy something?') elif dialoge == 3: player.speak('Ha, maybe next time. Farewell! ') # ui.updateConversation('Hak: Ha, maybe next time. Farewell! ') elif dialoge == 4: player.speak('...') # ui.updateConversation('Hak: Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test') else: # ui.endConversation() dialoge = 0 elif c == 'n': ui.endConversation() else: input(ord(c)) else: player.idle() if abs(wave.pos_x) > 60: wave.pos_x = 0 if abs(cloud1.pos_x) > 120: cloud1.pos_x = 0 if abs(cloud1.pos_x) > 60: cloud1.pos_x = 10 wave.pos_x -= 0.1 cloud1.pos_x += 0.05 cloud2.pos_x += 0.025 kb.set_normal_term()
def __init__(self): self.engine = Engine(24, 68) gravity = 0.25 maxfallspeed = 200 maxspeed = 80 jumpforce = 300 acceleration = 10 # Sprites # thing = Thing(self) # ui = Sprite('ui', 0, 0) ui = UI(self) ui.setName('Fin The Human') ui.setLocation('Land of Ooo') ui.setHP(10) ui.setMP(10) background = Sprite(self, 'background', 0, 0) cloud = Sprite(self, 'cloud', 0, 0) ground = Sprite(self, 'ground', 0, 14) character = Character(self, 2, 8) background.add(layer='bg') cloud.add(layer='bg') ground.add(layer='fg') character.add(layer='fg') kb = Controller() self.engine.tick() while True: time.sleep(1 / 60) character.down(gravity) cloud.pos_x += 0.05 self.engine.tick() if kb.kbhit(): c = kb.getch() if ord(c) == 27: # ESC break elif c == 'w': character.jump() elif c == 'a': character.move_L(1) elif c == 's': character.pos_y += 1 elif c == 'd': character.move_R(1) else: character.idle() kb.set_normal_term()
class Enemy(Controllable, Collider, Movable, Killable, GameObject): """Models a simple NPC.""" def __init__(self, canvas, image, **kw): """Initialize Enemy object.""" Controllable.__init__(self, kw.get('controller', ConstantController(-1, 0))) Collider.__init__(self, kw.get('shape', Collider.RECT)) Movable.__init__(self, kw.get('position', (canvas[0] + 10, randint(50, canvas[1] - 50)))) Killable.__init__(self, Explosion.SMALL, time_scale=0.5) GameObject.__init__(self, GameObject.Priority.NPC) self. __sprite = Sprite(image, animate=kw.get('animate', False), cast_shadow=kw.get('cast_shadow', True)) def update(self, bounds): """Update enemy position.""" if self.should_update: try: dx, dy = next(self.controller) dx *= -1 self.move(dx, dy) self.offlimits(bounds) except Exception as e: pass else: Killable.update(self, bounds) def draw(self, screen): """Draw enemy on the screen.""" if self.should_update: self.__sprite.draw(screen, self.position) else: Killable.draw(self, screen) def offlimits(self, limits): """Take action when object is off-limits, return if needs update.""" wx, wy, ww, wh = limits x, y, w, h = self.bounds if x + w < wx: self.hide() dy = wy if y < wy else y dy = (wy + wh) - h if (y + h) > (wy + wh) else dy dy -= y self.move(0, dy) def collide_with(self, object): """Enemy wal killed.""" if self.should_update: will_die = isinstance(object, Projectile) and \ not isinstance(self, object.creator) if will_die or isinstance(object, Player): self.die() self.should_collide = False @property def bounds(self): """Query object bounds.""" x, y = self.position _, _, w, h = self.__sprite.bounds return (x, y, w, h)