示例#1
0
文件: cell.py 项目: reiknight/ld29
 def draw(self, surface, camera):
     camerax, cameray = camera.getPosition()
     pygame.draw.rect(surface, CELL_TYPE_COLORS[self.cell_type_id], (self.x - camerax, self.y - cameray, CELL_SIZE, CELL_SIZE)) 
     if (self.material != None):
         Sprite.draw(self, surface, camera)
     if (self.treasure != None):
         self.treasure.draw(surface, camera)
示例#2
0
    def update(self):
        Sprite.update(self)

        if self.size<=0:
            self.isDead=True

        self.color=(random.random(),1,1)
        if self.posX<self.targetCell.posX:
            self.posX+=self.velX
        if self.posX>self.targetCell.posX:
            self.posX-=self.velX

        if self.posY<self.targetCell.posY:
            self.posY+=2
        if self.posY>self.targetCell.posY+self.targetCell.height:
            self.posY-=2

        self.posY+=math.sin(self.degreePosY)
        self.degreePosY+=self.deltaDegree

        distance=self.posX-self.originX
        self.power=self.originPower-(distance*0.012)
        self.size=self.power*self.originSize/self.originPower
        self.alpha=self.size

        if Sprite.is_colliding_with(self,self.targetCell):
            self.isDead=True
            if(self.targetCell.shield>0):
                self.targetCell.shield-=self.power
            else:
                self.targetCell.hp-=self.power
示例#3
0
文件: player.py 项目: morganq/udpgame
	def draw(self, screen):
		Sprite.draw(self, screen)
		x = self.position.x - 7
		y = self.position.y - 20
		w = min(max(self.health, 0) / 100.0 * 14, 13)
		if self.health > 0:
			pygame.draw.rect(screen, (39,65,62), (x-1,y-1, 16, 3), 0)
			pygame.draw.line(screen, (255, 255, 255), (x, y), (x + 13, y))
			pygame.draw.line(screen, (67,102,125), (x, y), (x + w, y))

		if self.charge > 0:
			md = 10.0
			c = int(min(self.charge+1, 2.0) * 10.0)
			#pygame.draw.line(screen, (173,0,0), (x-1,y-2),(x + c, y-2))
			p1 = self.position + self.chargeDir * md
			p2 = self.position + self.chargeDir * (md + c)
			pa1 = p2 - self.chargeDir * 3 + self.chargeDir.sideways() * 3
			pa2 = p2 - self.chargeDir * 3 - self.chargeDir.sideways() * 3
			r = 100 + self.charge * 155
			pygame.draw.line(screen, (r, 0, 0), p1.asIntTuple(), p2.asIntTuple())
			pygame.draw.line(screen, (r, 0, 0), p2.asIntTuple(), pa1.asIntTuple())
			pygame.draw.line(screen, (r, 0, 0), p2.asIntTuple(), pa2.asIntTuple())

		if self.chatTimer > 0:
			surf = self.chatFont.render(self.chatText, False, (39, 65, 62))
			if self.flipHorizontal:
				x = x - 4 - surf.get_width()
			else:
				x = x + 18
			screen.blit(surf, (x, y + 2))
示例#4
0
文件: player.py 项目: morganq/udpgame
	def update(self, dt):
		Sprite.update(self, dt)

		if self.chatTimer > 0:
			self.chatTimer -= dt

		if self.team == 0:
			self.flipHorizontal = False
		else:
			self.flipHorizontal = True			

		if self.hitTimer > 0:
			self.hitTimer -= dt
			self.serverOrSelfPlay("hit")
			self.velocity.zero()
		elif self.charge > 0:
			self.serverOrSelfPlay("charge")
			self.velocity.zero()
		else:
			self.serverOrSelfPlay("stand")
			self.velocity, animname = self.getVelocityAndAnim(self.xDirection, self.yDirection)

		self.collideWalls()

		self.throwTimer -= dt
		if self.throwingWaitForServer or self.throwTimer > 0:
			self.velocity.zero()

		if g.SERVER and self.lastAnimation != self.currentAnimation:
			g.game.net.sendAnimation(self)
		self.lastAnimation = self.currentAnimation
示例#5
0
 def __init__(self, window, x=0, y=0):
     Sprite.__init__(self, window)
     self.setDimensions(15, 120)
     self.setPOS(50, self.window.getHeight() / 2 - self.height / 2)
     self.sprite.fill(self.rcolor)
     self.spd = 10
     self.con = False
示例#6
0
 def draw(self,surface,camera,is_shadow=True):
     Sprite.draw(self,surface,camera,is_shadow)
     #surface.blit(self.team.image, camera.proj([self.pos[0],self.pos[1],self.pos[2]],self.team.image.get_width(),self.team.image.get_height()*3))
     if (self.is_saying_timer>0) and (self.is_saying!=""):
         message_pos=[]
         message_pos[:]=self.pos[:]
         surface.blit(Player.speech_image[self.is_saying], camera.proj(message_pos,-self.image.get_width(),50))
示例#7
0
文件: ship.py 项目: leguiart/PTSG
    def collide_ship_sprites(self,
                             group,
                             explosion_group,
                             explosion_image,
                             explosion_info,
                             ship=None,
                             ship_group=None):
        group_copy = set([])
        aux_copy = group.copy()
        for sprite in aux_copy:
            if self.physics.collide(sprite) is True:
                group_copy.add(sprite)
                explosion = Sprite(sprite.get_physics_component().get_pos(),
                                   [0, 0], 0, 0, explosion_image,
                                   explosion_info, self.physics.WIDTH,
                                   self.physics.HEIGHT)
                explosion_group.add(explosion)
                explosion_group.add(
                    Sprite(self.physics.get_pos(), [0, 0], 0, 0,
                           explosion_image, explosion_info, self.physics.WIDTH,
                           self.physics.HEIGHT))
                if self.life <= 0:
                    self.lives -= 1
                if ship is not None:
                    ship.score += 1

                if ship_group is not None:
                    ship_group.add(self)

        group.difference_update(group_copy)
示例#8
0
class DodgeballScene(Scene):
	def __init__(self):
		Scene.__init__(self)

		self.font = pygame.font.Font("visitor1.ttf", 20)

	def create(self):
		self.bg = Sprite(Vector2(0, 0))
		self.bg.addStaticImage(content.images["background.png"])
		self.particles = ParticleContainer(100)
		self.particles.layerIndex = 0
		self.add(self.particles)
		self.victoryMessage = ""

	def draw(self, screen):
		self.bg.draw(screen)
		map(lambda x:x.drawShadow(screen), self.sceneEntities)
		
		sortedEntities = sorted(self.sceneEntities, cmp = layeringSort)
		map(lambda x:x.draw(screen), sortedEntities)
	
		surf = self.font.render(str(g.game.score[0]) + " - " + str(g.game.score[1]), False, (255, 255, 255))
		w, h = surf.get_size()
		screen.blit(surf, (160 - w / 2, 9))

		if self.victoryMessage != "":
			surf = self.font.render(self.victoryMessage, False, (39, 65, 62))
			w, h = surf.get_size()
			w += 10
			pygame.draw.rect(screen, (39, 65, 62), (160 - w / 2 - 1, 100 - h / 2 - 1, w + 2, h + 2), 1)
			pygame.draw.rect(screen, (255, 255, 255), (160 - w / 2, 100 - h / 2, w, h), 0)
			w -= 10
			screen.blit(surf, (160 - w / 2, 100 - h / 2))
示例#9
0
文件: player.py 项目: Cynerva/jttcotm
    def __init__(self, world, pos=(0, 0)):
        self.body = world.b2world.CreateDynamicBody(
            position=pos,
            allowSleep=False
        )
        self.body.CreatePolygonFixture(
            box=(0.8, 1.6),
            density=1,
            friction=0.0,
        )
        self.body.linearDamping = 0.0
        self.body.angularDamping = 0.0
        self.sensor = self.body.CreatePolygonFixture(
            box=(0.6, 0.2, (0, -1.6), 0),
            density=1,
            friction=0.0,
            isSensor = True
        )

        self.stand_sprite = Sprite("data/art/stand.png")
        self.jump_sprite = Sprite("data/art/jump.png")
        self.fall_sprite = Sprite("data/art/fall.png")
        walksprite0 = self.stand_sprite
        walksprite1 = Sprite("data/art/walk1.png")
        walksprite2 = Sprite("data/art/walk2.png")
        self.walk_sprite = Animation((
            walksprite0, walksprite1, walksprite1,
            walksprite0, walksprite2, walksprite2
        ))
        self.sprite = self.stand_sprite
示例#10
0
class Character:

    """
    Represents an in-game character: player, npc, enemy, etc.  This class
    _should not_ be used directly!  It should rather be inherited by the classes
    that will use it.
    """

    def __init__(self, filename, spawnpoint):
        """
        The filename is simply used to generate a sprite
        Spawnpoint is used for the initial position
        """

        self.spawnpoint = spawnpoint
        self.sprite = Sprite(filename, spawnpoint)
        self.health = 100
        self.alive = True

    def draw(self):
        self.sprite.draw()

    def update(self):
        pass

    def kill(self):
        pass

    def hurt(self, dmg):
        if self.health - dmg <= 0:
            self.alive = 0
            self.health = 0
        else:
            self.health -= dmg
示例#11
0
 def update(self):
     Sprite.update(self)
     self.color=(random.random(),random.random(),random.random())
     if self.lifeTime>0:
         self.lifeTime-=1
     self.posX+=self.velX
     self.posY+=self.velY
示例#12
0
    def __init__(self, cfg, position, direction, color, res, pacmans, ghosts, random, game):
        self.cfg = cfg
        self.position = position
        self.direction = direction
        self.next_direction = self.direction
        self.color = color
        self.res = res
        self.pacmans = pacmans
        self.ghosts = ghosts
        self.state = GHOST_STATE_STOPPED
        self.frightened = False
        self.random = random
        self.game = game
        self.isdead = False # if the ghost is dead he is show as eyes,
                            # he is not colliding with anything and he
                            # returns straight to home

        self.target = pacmans[0].position
        self.sprite = [ Sprite("ghost-left-"+color, self.res, 0.1),
                        Sprite("ghost-down-"+color, self.res, 0.1),
                        Sprite("ghost-right-"+color, self.res, 0.1),
                        Sprite("ghost-up-"+color, self.res, 0.1),
                        Sprite("ghost-frightened", self.res, 0.5),
                        Sprite("ghost-frightened-blink", self.res, 0.5),
                        Sprite("eyes-left", self.res),
                        Sprite("eyes-down", self.res),
                        Sprite("eyes-right", self.res),
                        Sprite("eyes-up", self.res), ]

        self.prev_cell = position_to_cell(self.cfg.grid_cell_size, self.position)
        self.curr_cell = self.prev_cell
示例#13
0
class Entity:
    count = 1
    def __init__(self, stats, ent_type, solid, name = "", id_num=None):
        if not id_num:
            self.id_num = Entity.count
            Entity.count += 1
        else:
            self.id_num = id_num
        self.stats = stats
        self.ent_type = ent_type
        if ent_type == SHEEP:
                self.sprite = Sprite(TYPES[self.ent_type], stats.x, stats.y, 32, 32, False, 3, SHEEP_SPRITES)
        elif ent_type == GHOST1:
            self.sprite = Sprite(TYPES[self.ent_type], stats.x, stats.y, 32, 32, False, 3, GHOST1_SPRITES)
        elif ent_type == GHOST2:
            self.sprite = Sprite(TYPES[self.ent_type], stats.x, stats.y, 32, 32, False, 3, GHOST2_SPRITES)
        elif ent_type == GHOST3:
            self.sprite = Sprite(TYPES[self.ent_type], stats.x, stats.y, 32, 32, False, 3, GHOST3_SPRITES)
        elif ent_type == GHOST4:
            self.sprite = Sprite(TYPES[self.ent_type], stats.x, stats.y, 32, 32, False, 3, GHOST4_SPRITES)

        else:
            self.sprite = Sprite(TYPES[self.ent_type], stats.x, stats.y)
        self.solid = solid
        self.name = name

    def update(self, viewport):
        self.sprite.update(self.stats, viewport)

    def getUpdate(self):
        return Update(self.id_num, self.ent_type, self.stats, self.name)
示例#14
0
    def create_map(self, map):
        #карта

        #newmap = Map()

        #newmap.generate()

        #newmap.write()

        self.delete_map()

        text = open(map)
        blocks = [
            "", "tiles/block.png", "tiles/grass.png", "tiles/stone.png",
            "tiles/decor1.png", "tiles/tree.png", "tiles/decor2.png",
            "tiles/decor3.png", "tiles/spikes.png", "tiles/wall.png",
            "tiles/backwall.png", "tiles/door.png", "tiles/backblock.png",
            "tiles/roof.png"
        ]

        i = 10
        for line in text:
            j = 0
            for block in line:
                if block == " ":
                    continue
                elif block in ("1", "2", "3", "9"):
                    object = CollideObject(BLOCK_SIZE * j,
                                           SCREEN_H - BLOCK_SIZE * i,
                                           blocks[int(block)])
                    self.collide_ent.append(object)
                elif block in ("4", "5", "6", "7"):
                    decor = Sprite(BLOCK_SIZE * j, SCREEN_H - BLOCK_SIZE * i,
                                   blocks[int(block)])
                    #self.decor_ent_fore.append(decor)
                    self.decor_ent_back.append(decor)
                elif block in ("8"):
                    spikes = Spikes(BLOCK_SIZE * j, SCREEN_H - BLOCK_SIZE * i,
                                    blocks[int(block)], self)
                    self.spikes.append(spikes)
                elif block in ("B"):
                    decor = Sprite(BLOCK_SIZE * j, SCREEN_H - BLOCK_SIZE * i,
                                   blocks[10])
                    self.decor_ent_back.append(decor)
                elif block in ("D"):
                    decor = Sprite(BLOCK_SIZE * j, SCREEN_H - BLOCK_SIZE * i,
                                   blocks[11])
                    self.decor_ent_back.append(decor)
                elif block in ("C"):
                    decor = Sprite(BLOCK_SIZE * j, SCREEN_H - BLOCK_SIZE * i,
                                   blocks[12])
                    self.decor_ent_back.append(decor)
                elif block in ("R"):
                    decor = Sprite(BLOCK_SIZE * j, SCREEN_H - BLOCK_SIZE * i,
                                   blocks[13])
                    self.decor_ent_back.append(decor)

                j += 1
            i -= 1  #тк генерируем снизу (зеркально)
        text.close()
示例#15
0
文件: core.py 项目: Widdershin/PyGM
class PyGMObj(object):
	"""Generic PYGMObj"""
	instances = []

	def __init__(self, position, sprite=None):
		super(PyGMObj, self).__init__()
		self.create()
		self.position = position
		if sprite is not None:
			self.sprite = Sprite(sprite, PyGM.screen)
		PyGM.objects.append(self)

	def create(self):
		pass

	def update(self):
		if self.sprite is not None:
			self.sprite.rect.move(self.position.tuple())

	def draw(self):
		if self.sprite is not None:
			self.sprite.draw(self.position)

	@classmethod
	def instances(cls):
		"""Returns a list of all instances of type and children of type"""
		return [i for i in PyGM.objects if isinstance(i, cls)]
示例#16
0
    def __init__(self):
        Sprite.__init__(self)
        self.original_image = common.load('presents/gcoop.png', False)
        self.image = self.original_image
        self.alpha = 0
        self.rect = self.image.get_rect()
        self.rect.centerx = 1260 / 2
        self.center = self.rect.center
        self.y = 90
        w, h = self.image.get_width(), self.image.get_height()
        self.width = 0
        self.height = 0

        common.tweener.addTween(self,
                                width=w,
                                tweenTime=1700,
                                tweenType=pytweener.Easing.Elastic.easeInOut)
        common.tweener.addTween(self,
                                height=h,
                                tweenTime=1800,
                                tweenType=pytweener.Easing.Elastic.easeInOut)
        common.tweener.addTween(self,
                                alpha=255,
                                tweenTime=500,
                                tweenType=pytweener.Easing.Linear.easeNone)
        self.update()
示例#17
0
    def __init__(self, ai_settings, screen):
        """Initialize the Faceless and set its starting position"""
        super(Faceless, self).__init__()
        self.screen = screen
        self.ai_settings = ai_settings

        # filename for spritesheet
        ss_faceless = 'images/3DS - Fire Emblem Fates - Faceless.png'

        # faceless sprite row
        self.moving_left = Sprite.from_coord(6, 39, 23, 27, 10, ss_faceless, 6)
        self.moving_right = Sprite.from_coord(4, 71, 23, 27, 9, ss_faceless, 6)

        self.sprite_loop = self.moving_right

        self.sprite_index = float(0)

        # settings to change animation loop speed
        self.sprite_iter_speed = ai_settings.animation_speed

        # Load the Faceless image and set its rect attribute
        self.image = self.get_image()
        self.rect = self.image.get_rect()

        # Start each new Faceless near the top left of the screen
        self.rect.x = self.rect.width
        self.rect.y = self.rect.height

        # Store the Faceless' exact position
        self.x = float(self.rect.x)
        self.y = float(self.rect.y)
示例#18
0
 def __init__(self, world, obj):
     pygame.mixer.init(44100, -16, 2, 2048)
     if obj.gid is None:
         print >> sys.stderr, 'Player: must be created from tile object'
         sys.exit(1)
     self.left = False
     self.world = world
     self.gid = obj.gid
     tile = world.data.tiles[self.gid]
     Sprite.__init__(self, world, obj.kind,
                     '{} ({},{})'.format(obj.kind, obj.x,
                                         obj.y), tile.get_width(),
                     tile.get_height(), obj.x, obj.y, (16.0, 16.0))
     self.addForce('friction', (1.0, 0.0), 'slowdown')
     self.addForce('gravity', (0.0, 1.0), 'constant')
     self.count = 0
     self.coins = 0
     pygame.font.init()
     self.hurtSound = pygame.mixer.Sound('OOT_AdultLink_Hurt1.wav')
     self.jumpSound = pygame.mixer.Sound('OOT_AdultLink_Jump1.wav')
     self.jewelSound = pygame.mixer.Sound('LOZ_Get_Rupee.wav')
     self.dieSound = pygame.mixer.Sound('LA_Link_Dying.wav')
     self.font = pygame.font.SysFont("Times New Roman", 36)
     self.font2 = pygame.font.SysFont("Courier New", 20)
     self.text_color = (255, 225, 225)
     self.score_color = (255, 0, 0)
     self.score_x = 10
     self.score_y = 30
     self.game_x = 230
     self.game_y = 240
     self.coins = 0
     self.lives = 3
     self.newlife = 0
     self.hurt = False
     self.active = True
示例#19
0
    def __init__(self, x, y):

        # Listes des sprites pour l'animation
        self.sprites = {
            'run': Sprite('Assets/Player/run.png', 8, 1),
            'blow': Sprite('Assets/Player/joueur_souffle.png', 20, 1),
            'idle': Sprite('Assets/Player/idle.png', 4, 1),
            'chute': Sprite('Assets/Player/player_chute.png', 4, 1)
        }

        # Initialisation position
        self.setLocation(x, y)

        # Vitesse du joueur
        self.velocity = 20
        self.jumpRange = [-10, -6, -5, -4, 1, 4, 5, 6, 10]

        # Flip
        self.flip = False

        # Current plateforme
        self.currentPlatorm = None

        self.hitbox = None

        self.stream = Stream(self.x, self.y, 0)

        self.glissement = False

        self.valeurTampon = 0
示例#20
0
	def create(self):
		bg = Sprite(Vector2(0, 0))
		bg.addStaticImage(content.images["background.png"])
		self.add(bg)
		
		self.font = pygame.font.Font("visitor1.ttf", 20)
		self.playersInGame = 0
示例#21
0
	def kill_opponent(self, attacker: sprite.Sprite, victim: sprite.Sprite) -> None:
		attacker.set_tile_and_pos(victim.tile, self.terr)
		attacker.life += 1
		victim.life = 0
		for civ in self.civs:
			if victim in civ.population:
				civ.population.remove(victim)
示例#22
0
文件: world.py 项目: 16pagejonm/game
class BackgroundLayer:
    """
    Encapsulates a scrolling layer of the background.  It will move left
    at a given speed, and loop once it exits the screen.  Multiple layers
    with multiple speeds can be used to create a parallax effect, or to
    allow many-layered backgrounds
    """

    def __init__(self, filename, scroll_speed):
        pos = (0, 0)

        self.s1 = Sprite(filename, pos)
        self.s2 = Sprite(filename, (1280, pos[1]))

        self.filename = filename
        self.position = pos
        self.speed    = scroll_speed

    def draw(self):
        self.s1.draw()
        self.s2.draw()

    def update(self):
        self.s1.rect.x -= self.speed

        if self.s1.rect.x <= 0:
            self.s2.rect.x -= self.speed

        if self.s2.rect.x <= 0:
            self.s1.rect.x = 0
            self.s2.rect.x = 1280
示例#23
0
	def capture_opponent(self, attacker: sprite.Sprite, victim: sprite.Sprite) -> None:
		attacker.set_tile_and_pos(attacker.tile, self.terr)
		for civ in self.civs:
			if victim in civ.population:
				civ.population.remove(victim)
		self.civs[self.active_civ].population.append(victim)
		self.update_canvas()
示例#24
0
文件: nubes.py 项目: gcoop-libre/ayni
 def __init__(self, imagen, velocidad):
     self.image = imagen
     Sprite.__init__(self)
     self.rect = self.image.get_rect()
     self.x = random.randint(-50, int(config.WIDTH))
     self.rect.y = random.randint(-20, int(config.HEIGHT * 0.9))
     self.velocidad = velocidad
示例#25
0
class ImageMenuItem (BaseMenuItem):
    """ A menu item that shows a selectable Image """
    def __init__ (self, name, callback_func, *args, **kwargs):
        self.image = pyglet.resource.image (name)
        super (ImageMenuItem, self).__init__(callback_func, *args, **kwargs)

    def generateWidgets (self, pos_x, pos_y, font_item, font_item_selected):
        anchors = {'left': 0, 'center': 0.5, 'right': 1, 'top': 1, 'bottom': 0}
        anchor=(anchors[font_item['anchor_x']] * self.image.width,
                anchors[font_item['anchor_y']] * self.image.height)
        self.item = Sprite(self.image, anchor=anchor, opacity=255,
                           color=font_item['color'][:3])
        self.item.scale = font_item['font_size'] / float(self.item.height )
        self.item.position = int(pos_x), int(pos_y)
        self.selected_item = Sprite(self.image, anchor=anchor,
                                    color=font_item_selected['color'][:3])
        self.selected_item.scale = (font_item_selected['font_size'] /
                                     float(self.selected_item.height))
        self.selected_item.position = int(pos_x), int(pos_y)

    def draw (self):
        glPushMatrix()
        self.transform()
        if self.is_selected:
            self.selected_item.draw()
        else:
            self.item.draw()
        glPopMatrix()
示例#26
0
class ImageMenuItem (BaseMenuItem):
    """ A menu item that shows a selectable Image """
    def __init__ (self, name, callback_func, *args, **kwargs):
        self.image = pyglet.resource.image (name)
        super (ImageMenuItem, self).__init__(callback_func, *args, **kwargs)

    def generateWidgets (self, pos_x, pos_y, font_item, font_item_selected):
        anchors = {'left': 0, 'center': 0.5, 'right': 1, 'top': 1, 'bottom': 0}
        anchor=(anchors[font_item['anchor_x']] * self.image.width,
                anchors[font_item['anchor_y']] * self.image.height)
        self.item = Sprite(self.image, anchor=anchor, opacity=255,
                           color=font_item['color'][:3])
        self.item.scale = font_item['font_size'] / float(self.item.height )
        self.item.position = int(pos_x), int(pos_y)
        self.selected_item = Sprite(self.image, anchor=anchor,
                                    color=font_item_selected['color'][:3])
        self.selected_item.scale = (font_item_selected['font_size'] /
                                     float(self.selected_item.height))
        self.selected_item.position = int(pos_x), int(pos_y)

    def draw (self):
        glPushMatrix()
        self.transform()
        if self.is_selected:
            self.selected_item.draw()
        else:
            self.item.draw()
        glPopMatrix()
示例#27
0
class Level01(Scene):
    def __init__(self, background_file, ground_file):
        Scene.__init__(self, background_file, ground_file)
        _, screen_h = pygame.display.get_surface().get_size()
        ground_height = screen_h - self.ground.surface.get_height()
        self.ground.y = ground_height
        self.player = SpriteControlled(10, ground_height, 'sprite.png', True,
                                       2)
        self.cursor = Sprite(0, 0, 'cursor.png', False)
        self.warp = Warp(680, 0, 'warp.png', False, "level00")
        self.warp.y = ground_height - self.warp.surface.get_height() / 2

    def load(self):
        pass

    def inputs(self, events):
        for event in events:
            if event.type == pygame.MOUSEBUTTONDOWN:
                mouse_click = pygame.mouse.get_pos()
                self.player.move_to(mouse_click[0])

    def update(self, change_scene):
        self.cursor.set_position(pygame.mouse.get_pos())
        self.player.update()
        if self.player.intersects(self.warp):
            change_scene(self.warp.to_scene)

    def draw(self, screen):
        self.background.draw(screen)
        self.ground.draw(screen)
        self.warp.draw(screen)
        self.player.draw(screen)
        self.cursor.draw(screen)
示例#28
0
    def __init__(self, text="", fontname=None, size=32):
        self.font = Font(fontname or pygame.font.get_default_font(), size)

        Sprite.__init__(self, None)
        self.text = text
        self.color = (0, 0, 0)
        self.set_text(text)
示例#29
0
    def __init__(self):
        Sprite.__init__(self)
        self.pos=[0,0,5] #like every other thing, pos is at center bottom

        self.speed=[0,0,0]
        self.size=2 #ball radius, for goal accuracy (used in y, and 2* in z)
        self.owner=0 #0 if ball is free

        self.anim_index=0
        self.direction=1# +1: right, -1: left  TODO : add more directions ?
        self.state="roll1"
        
        self.anim={}#dictionnary for left and right
        self.anim[1]={} #dictionnary of all animation looking to the right
        self.anim[1]["roll1"]=[]
        self.anim[1]["roll1"].append(pygame.image.load("data/_ball_roll1_A.png"))
        self.anim[1]["roll1"].append(pygame.image.load("data/_ball_roll1_B.png"))
        self.anim[1]["roll1"].append(pygame.image.load("data/_ball_roll1_C.png"))
        self.anim[1]["roll1"].append(pygame.image.load("data/_ball_roll1_D.png"))
        self.anim[1]["roll1"].append(pygame.image.load("data/_ball_roll1_E.png"))
        self.anim[1]["roll1"].append(pygame.image.load("data/_ball_roll1_F.png"))
        
        #flip all anims to look left
        self.anim[-1]={}
        for key in self.anim[1]:
            self.anim[-1][key]=[]
            for img in self.anim[1][key]:
                self.anim[-1][key].append(pygame.transform.flip(img, 1, 0))
        
        self.image = self.anim[self.direction][self.state][int(self.anim_index)] #this is how we get the current picture
class SpriteTests(unittest.TestCase):

    def setUp(self):
        self.x=48
        self.y=48
        init_dna_mat=numpy.zeros((self.x, self.y))
        for n in range(48):
            for m in range(48):        
                if (n-self.x/2)**2+(m-self.y/2)**2<(self.x/2.5)**2: #only generate pixels within this circle
                    if determine_life(n,m,self.x,self.y):
                        init_dna_mat[n,m]=True
        self.sprite=Sprite(init_dna_mat)
                        

    def test_mutation(self):
        #build a sprite and assert that its mutation method works as expected
        self.assertEqual(len(self.sprite.mutation().dna), 48,'check mutation preserves matrix size')
        self.assertNotEqual(sum(sum(self.sprite.mutation().dna)), sum(sum(self.sprite.mutation().dna)),
        'check that two mutations of the same dna are different, and therefore also different to the original dna')
        #there is a small chance that the two mutations will actually be the same and throw this error. Run again.
 
    def test_draw(self):
        #build a sprite and assert that its draw method works as expected
        self.assertEqual(len(self.sprite.draw()), 48,'check drawing sprite preserves matrix size')
        self.assertNotEqual(sum(sum(self.sprite.dna)), sum(sum(self.sprite.draw())),'check that drawing does something to dna')
示例#31
0
    def init():
        for timer in Title_screen.all_timers:
            Title_screen.all_timers.replenish_timer(timer)

        title_logo_img = [universal_var.misc_images['title']]
        width, height = 500, 300
        title_logo_sprite = Sprite(universal_var.main_sprite, 0, 0, width,
                                   height, [('title', title_logo_img, 1)])
        Title_screen.title_logo = Megaman_object('title_logo',
                                                 50,
                                                 2000,
                                                 sprites=[title_logo_sprite],
                                                 width=width,
                                                 height=height,
                                                 is_active=True)

        megaman_face_img = [universal_var.misc_images['megaman_face']]
        width, height = 200, 300
        megaman_face_sprite = Sprite(universal_var.main_sprite, 0, 0, width,
                                     height, [('world', megaman_face_img, 1)])
        Title_screen.megaman_face = Megaman_object(
            'megaman_face',
            -width * 13,
            230,
            sprites=[megaman_face_sprite],
            width=width,
            height=height,
            is_active=True)

        Title_screen.is_running = True
示例#32
0
    def __init__(self):
        movement_sprite_sheet = Sprite("Resources/Sprites/player.png")

        self.right_walk_images = [
            movement_sprite_sheet.get_image(0, 0, 45, 66),
            movement_sprite_sheet.get_image(45, 0, 45, 66),
            movement_sprite_sheet.get_image(93, 0, 45, 66),
            movement_sprite_sheet.get_image(138, 0, 50, 66)
        ]

        self.left_walk_images = [
            pygame.transform.flip(image, True, False)
            for image in self.right_walk_images
        ]

        self.image = self.right_walk_images[0]
        self.image_index = 0
        self.image_rate = 0.1
        self.rect = self.image.get_rect()

        self.moving_left = False
        self.moving_right = False
        self.move_speed = 5

        self.d_y = 0
        self.gravity = 0.45
        self.jump_height = 8

        self.right_limit = public.display_dimensions[0] * 0.6
        self.left_limit = public.display_dimensions[0] * 0.4 - self.rect.width

        self.bound_exceed = 0

        self.blocks = None
示例#33
0
 def __init__(self, world_map, GRID_LOCK, coordinates=None):
     Sprite.__init__(self, world_map, self.sprite_image, GRID_LOCK,
                     coordinates)
     self.type = "deer"
     self.movable_terrain = world_map.get_all_land_tile_types()
     self.predators = ["wolf"]
     self.prey = ["plant"]
示例#34
0
文件: player.py 项目: adirksen/Python
 def __init__(self, world, obj):
     if obj.gid is None:
         print >>sys.stderr, 'Player: must be created from tile object'
         sys.exit(1)
     self.left=False
     self.world = world
     self.gid = obj.gid
     tile = world.data.tiles[self.gid]
     Sprite.__init__(self,
             world,
             obj.kind,
             '{} ({},{})'.format(obj.kind, obj.x, obj.y),
             tile.get_width(), tile.get_height(),
             obj.x, obj.y,
             (16.0, 16.0))
     self.addForce('friction', (1.0, 0.0), 'slowdown')
     self.addForce('gravity', (0.0, 1.0), 'constant')
     self.count = 0
     self.coins = 0
     pygame.font.init()
     self.font = pygame.font.SysFont("Helvetica", 36)
     self.font2 = pygame.font.SysFont("Courier New", 20)
     self.text_color = (255,255,255)
     self.score_color = (255, 0, 0)
     self.score_x = 10
     self.score_y = 30
     self.game_x = 230
     self.game_y = 240
     self.coins = 0
     self.lives = 3
     self.newlife = 0
     self.hurt = False
     self.active = True
示例#35
0
 def __init__(self, source):
     super(Background, self).__init__()
     self.image = Sprite(source=source)
     self.add_widget(self.image)
     self.size = self.image.size
     self.image_dupe = Sprite(source=source, y=self.height)
     self.add_widget(self.image_dupe)
示例#36
0
class first_scene(Scene):
    raspberry_sprite = None

    def load(self):
        self.raspberry_sprite = Sprite("art/raspberry35.png")

    def cleanup(self):
        pass

    def do_event(self, event):
        pass

    def update(self):
        self.raspberry_sprite.x = 100
        self.raspberry_sprite.y = 100
        return

        max_x = self.s.size[0] - self.raspberry_sprite.width()
        x = random.randint(0, max_x)
        max_y = self.s.size[0] - self.raspberry_sprite.height()
        y = random.randint(0, max_y)

        self.raspberry_sprite.x = x
        self.raspberry_sprite.y = y


    def draw(self):
        self.s.screen.fill((0,0,0))

        self.raspberry_sprite.blit(self.s)
示例#37
0
    def __init__(self, screen, window_size, title, background, option, **kwargs):
        self._screen = screen
        self._title = title
        self._background = background
        self._entries_sprite_dict = {}
        self._window_size = window_size
        self._arrow_positions = {}
        self._arrow_image_left = Sprite("./media/menu_arrow.png")
        self._arrow_image_right = Sprite(pygame.transform.rotate(self._arrow_image_left.get_image(), 180))
        self._arrow_image_size = self._arrow_image_left.get_size()
        self._option = option

        self.__add_text = (kwargs["add_text"],None)
        entry_size_y = 20
        start_y = window_size[1]/2 - len(self._entries) * (entry_size_y/2)
        i = 0
        item_nr = 0

        for key, item in self._entries.iteritems():
            if not item == " ":
                sprite = Sprite.from_text(item)
                size=sprite.get_size()
                sprite.move_to(window_size[0]/2 - size[0]/2, start_y + i * entry_size_y)
                self._entries_sprite_dict.update({item_nr:sprite})
                self._arrow_positions.update({item_nr:[pygame.Rect(sprite.get_pos()[0] - 110, sprite.get_pos()[1] +
                                                                  size[1]/2 - 6, 104, 12),
                                                       pygame.Rect(sprite.get_pos()[0] + size[0] + 6, sprite.get_pos()[1] +
                                                                   size[1]/2 - 6, 104, 12)]})
                self._arrow_image_left.set_rect(self._arrow_positions[0][0])
                self._arrow_image_right.set_rect(self._arrow_positions[0][1])
                item_nr += 1
            i += 1
示例#38
0
 def __init__(self):
     Sprite.__init__(self)
     self.image = common.load('presents/presents.png', False, (config.WIDTH * 0.3, 0))
     self.rect = self.image.get_rect()
     self.rect.centerx = config.WIDTH / 2
     self.rect.y = config.HEIGHT * 0.8
     self.alpha = 0
     self.update()
示例#39
0
 def __init__(self, level, pos, facing):
     Sprite.__init__(self, level, pos, facing)
     
     level.destructibles.add(self)
     level.solids.add(self)
     
     self.tile = 2, 2
     self.rotate = True
 def __init__(self):
     Sprite.__init__(self)
     self.image = common.load('continue.png', True)
     self.rect = self.image.get_rect()
     self.y = 720 + self.rect.h
     self.rect.bottom = self.y
     self.rect.centerx = 1280 / 2
     common.tweener.addTween(self, y=710, tweenTime=1700)
示例#41
0
 def __init__(self, background_picture, last_background_image=None):
     super(Background, self).__init__()
     self.image = Sprite(picture=background_picture, allow_stretch=True)
     self.image_dupe = Sprite(picture=background_picture,
                              allow_stretch=True)
     self.image_dupe.y = Window.height
     self.last_background = False
     self.last_image_str = last_background_image
示例#42
0
 def __init__(self):
     Sprite.__init__(self)
     self.image = common.load('continue.png', True, (config.WIDTH * 0.7, 0))
     self.rect = self.image.get_rect()
     self.y = config.HEIGHT + self.rect.h
     self.rect.bottom = self.y
     self.rect.centerx = config.WIDTH / 2
     common.tweener.addTween(self, y=self.y * 0.8, tweenTime=1700)
示例#43
0
class Fist:
    def __init__(self):
        self.sprite = Sprite("fist.png", (25, 25))
        self.level = 1
        print("Level 1 fist created") # for debugging

    def draw(self):
        self.sprite.draw()
示例#44
0
    def _load_sprites(self, name):

        sprites = {
            SpriteComponent.A: Sprite('_'.join((name, 'a'))),
            SpriteComponent.B: Sprite('_'.join((name, 'b')))
        }

        return sprites
示例#45
0
 def __init__(self):
     Sprite.__init__(self)
     self.image = common.load('title.png', True, (config.WIDTH * 0.3, 0))
     self.rect = self.image.get_rect()
     self.rect.right = config.WIDTH * 0.9
     self.y = config.HEIGHT
     common.tweener.addTween(self, y=self.y * 0.05, tweenTime=1700, 
             tweenType=pytweener.Easing.Elastic.easeInOut)
示例#46
0
 def __init__(self):
     Sprite.__init__(self)
     self.image = common.load('presents/presents.png', False)
     self.rect = self.image.get_rect()
     self.rect.centerx = 1280 / 2
     self.rect.y = 600
     self.alpha = 0
     self.update()
示例#47
0
文件: energy.py 项目: HieuLsw/sbfury
 def __init__(self, x, y, w, h):
     Sprite.__init__(self, x, y)
     self.model = None
     self.w = w
     self.image = pygame.Surface((w + 2, h))
     self.rect = self.image.get_rect().move(x, y)
     self.z = -1000
     self.collision_rect = None
示例#48
0
    def __init__(self, x, y, w, h, vel_x, vel_y, vel, lado, cor, imagem):

        Entidade.__init__(self, x, y, w, h, vel_x, vel_y, vel)
        Sprite.__init__(self, imagem, cor)

        self.__cor = cor
        self.lado = lado
        self.ativo = True
示例#49
0
文件: room.py 项目: derrida/shmuppy
 def __init__(self, scene):
     color = (43,73,85)
     grid_color = (170,170,170)
     self.size = (16,16)
     Sprite.__init__(self, scene, self.size, color)
     if config.DEBUG:
         offset = self.rect.move([1,1])
         draw.rect(self.image, grid_color, offset, 1)
示例#50
0
 def draw(self, surface, camera, is_shadow=True):
     Sprite.draw(self, surface, camera, is_shadow)
     #surface.blit(self.team.image, camera.proj([self.pos[0],self.pos[1],self.pos[2]],self.team.image.get_width(),self.team.image.get_height()*3))
     if (self.is_saying_timer > 0) and (self.is_saying != ""):
         message_pos = []
         message_pos[:] = self.pos[:]
         surface.blit(Player.speech_image[self.is_saying],
                      camera.proj(message_pos, -self.image.get_width(), 50))
示例#51
0
 def __init__(self, window, x=0, y=0):
     Sprite.__init__(self, window)
     self.setDimensions(30, 30)
     self.setPOS(self.window.getWidth()/2 - self.width/2, self.window.getHeight()/2 - self.height/2)
     self.sprite.fill(self.color)
     self.spdx = 10
     self.spdy = 10
     self.p1score = 0
     self.p2score = 0
示例#52
0
 def __init__(self):
     Sprite.__init__(self)
     self.image = common.load('level_complete.png', True, (config.WIDTH * 0.5, 0))
     self.rect = self.image.get_rect()
     self.rect.centerx = config.WIDTH / 2
     self.y = -self.rect.h * 2
     self.rect.y = self.y
     common.tweener.addTween(self, y=config.HEIGHT * 0.4, tweenTime=1700, 
             tweenType=pytweener.Easing.Elastic.easeInOut)
示例#53
0
文件: world.py 项目: 16pagejonm/game
    def __init__(self, filename, scroll_speed):
        pos = (0, 0)

        self.s1 = Sprite(filename, pos)
        self.s2 = Sprite(filename, (1280, pos[1]))

        self.filename = filename
        self.position = pos
        self.speed    = scroll_speed
示例#54
0
 def __init__(self, stage_objects=[]):
     Sprite.__init__(self)
     pygame.mouse.set_visible(False)
     self._load_frames()
     self.show()
     self.set_frame('normal')
     self.rect = self.image.get_rect()
     self.stage_objects = stage_objects
     self.z = -50
示例#55
0
 def __init__(self, scene, size, color, name, speed, hp):
     Sprite.__init__(self, scene, size, color)
     self.name = name
     self.speed = speed
     self.hp = hp
     self.weapon_id = 0
     self.weapon = scene.weapon_list[self.weapon_id]
     self.firing = False
     self.last_fired = 0
示例#56
0
文件: cell.py 项目: reiknight/ld29
 def draw(self, surface, camera):
     camerax, cameray = camera.getPosition()
     pygame.draw.rect(
         surface, CELL_TYPE_COLORS[self.cell_type_id],
         (self.x - camerax, self.y - cameray, CELL_SIZE, CELL_SIZE))
     if (self.material != None):
         Sprite.draw(self, surface, camera)
     if (self.treasure != None):
         self.treasure.draw(surface, camera)
示例#57
0
文件: room.py 项目: derrida/shmuppy
 def __init__(self, scene):
     color = (0,0,0)
     room_size = config.RESOLUTION
     self.tile = FloorTile(scene)
     self.num_tiles = [
         config.RESOLUTION[0] / self.tile.size[0],
         config.RESOLUTION[1] / self.tile.size[1] ]
     Sprite.__init__(self, scene, room_size, color)
     self.make_floor()
示例#58
0
 def create_character(self):
     game_canvas = self.frames['game'].canvas
     character = Sprite('peasant',
                        game_canvas,
                        dimension=(50, 50),
                        position=(0, 0),
                        speed=5)
     character.position = get_center_position(game_canvas.dimension,
                                              character.dimension)
     character.draw_on_canvas()
示例#59
0
 def __init__(self, background_file, ground_file):
     Scene.__init__(self, background_file, ground_file)
     _, screen_h = pygame.display.get_surface().get_size()
     ground_height = screen_h - self.ground.surface.get_height()
     self.ground.y = ground_height
     self.player = SpriteControlled(10, ground_height, 'sprite.png', True,
                                    2)
     self.cursor = Sprite(0, 0, 'cursor.png', False)
     self.warp = Warp(680, 0, 'warp.png', False, "level00")
     self.warp.y = ground_height - self.warp.surface.get_height() / 2