Beispiel #1
0
class MiniGrill:
    def __init__(self):
        self.image = image.load(data_file('grill.png'))
        self.rect = Rect(500, 250, self.image)

        window.game_window.push_handlers(self.on_mouse_press)
        window.game_window.push_handlers(self.on_mouse_motion)

        self.highlighted = False

        self.active = False

    def on_mouse_motion(self, x, y, dx, dy):
        if self.rect.collide_point(x, y):
            self.highlighted = True
        else:
            self.highlighted = False

    def on_mouse_press(self, x, y, button, modifiers):
        if self.rect.collide_point(x, y):
            self.active = True

    def draw(self):
        if self.highlighted:
            glColor4f(0.5, 0.1, 1, 1)
        else:
            glColor4f(1, 1, 1, 1)

        self.image.blit(*self.rect.bottomleft)

        glColor4f(1, 1, 1, 1)
Beispiel #2
0
    def _drawKeys(self, dc):
        blackPen = wx.Pen('black')
        whiteBrush = wx.Brush('white')

        # set the font
        self.font = wx.Font(self._fontSize, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL,
                       wx.FONTWEIGHT_BOLD, False, 'Arial Rounded MT Bold')
        dc.SetFont(self.font)

        for displayKey in self._displayKeys.values():

            # draw key shadow
            shadowRect = Rect(*displayKey.scaled)
            shadowRect.OffsetXY(1, 1)
            dc.SetPen(wx.Pen('light grey', 3.5))
            dc.DrawRoundedRectangleRect(shadowRect.Get(), -.075)

            # handle selections
            if self._isKeySelected(displayKey.handle):
                if self.FindFocus() == self:
                    # TODO: Generalize this magic number from system settings.
                    #       Currently is Mac selection blue.
                    dc.SetPen(wx.Pen('#3e75d6', 2))
                else:
                    dc.SetPen(wx.Pen('dark grey', 2))
                dc.SetBrush(wx.Brush('light grey'))
            else:
                dc.SetPen(blackPen)
                dc.SetBrush(whiteBrush)

            # draw key outline
            dc.DrawRoundedRectangleRect(displayKey.scaled.Get(), -.075)

            # draw label
            self._drawLabels(dc, displayKey.labelRect, displayKey)
Beispiel #3
0
 def _refreshKey(self, displayKey):
     """
     Calculate the appropriate region of the screen to refresh based
     on the given displayKey.
     """
     refreshRect = Rect(*displayKey.scaled)
     refreshRect.Inflate(2, 2)
     self.RefreshRect(refreshRect.Get())
Beispiel #4
0
 def _getDrawingArea(self):
     """
     Return a Rect encompassing the allowable drawing area of the current client window,
     in device units.
     """
     drawingArea = Rect(*self.GetClientRect())
     drawingArea.Deflate(self._border, self._border)
     return drawingArea
 def to_pygame(self, blitable):
     """Converts object coordinates into pygame coordinates, given lower left coordinates of an
     object and the object's height."""
     # Get top left corner, and convert to pygame coordinates
     rect = Rect(blitable.image.get_rect())
     rect.offset(blitable.position)
     new_position = self.to_pygame_coords(rect.bottom_left)
     new_position = new_position + Vector(0, -blitable.image.get_height())
     return new_position
Beispiel #6
0
 def _getContentArea(self):
     """
     Based on the content size, in logical units, return, in device units,
     the rectangle encompassing the extents of the content to be drawn.
     """
     drawingArea = self._getDrawingArea()
     scale = self._getScale(drawingArea)
     contentSize = self._getContentSize() * scale
     contentArea = Rect(drawingArea.x, drawingArea.y, contentSize.width, contentSize.height)
     contentArea = contentArea.CenterIn(drawingArea)
     return contentArea
Beispiel #7
0
 def attack(self, pos, gap, orientation,team):
   
   if self.nextAttackTimer != 0.0 or self.knivesAvailable == 0:
     #print 'cooldown: ', self.nextAttackTimer, self.knivesAvailable
     return False
   
   self.knivesAvailable -= 1
   self.nextAttackTimer += self.attackCooldown
   
   #create a knife just outside the spawn location
   
   knifeShape = Rect.createAtOrigin(10,10)
       
   #TODO: how to handle diagonal movement and firing?
   # spawn outside rect, or inside?
   
   knifePos = pos + orientation.getNormalized()*gap
   
   #print orientation.getNormalized() * gap
       
   #proj = BasicProjectile(knifePos,knifeShape,team,orientation)
   proj = MagicKnife(knifePos,knifeShape,self.owner,orientation)
   proj.owner = self.owner #Set owner so it can return and keep track of unit
   
   self.knives.append(proj)
   
   glad.world.objectList.append(proj)
   
   #play sound effect
   proj.sound.play(self.owner.pos)
   
   return True
Beispiel #8
0
    def __init__(self):
        self.image_opened = image.load(data_file('garbagecan-open.png'))
        self.image_closed = image.load(data_file('garbagecan-closed.png'))
        self.image_lid = image.load(data_file('garbagecan-lid.png'))

        self.image_opened.anchor_x = self.image_opened.width/2
        self.image_opened.anchor_y = self.image_opened.height/2
        self.image_closed.anchor_x = self.image_opened.width/2
        self.image_closed.anchor_y = self.image_opened.height/2

        self.candidateLeaves = {}

        self.opened = True
        self.lid_active = False
        self.can_active = False
        self.fallen = False
        self.can_highlighted = False
        self.lid_highlighted = True

        self.can_rect = Rect(0, 0, self.image_closed)
        self.can_rect.center = (80, 90)

        self.can_sprite = Sprite(self.image_opened)
        self.can_sprite.set_position(self.can_rect.x, self.can_rect.y)

        self.lid_rect = Rect(20, 40, self.image_lid)

        window.game_window.push_handlers(self.on_mouse_release)
        window.game_window.push_handlers(self.on_mouse_press)
        window.game_window.push_handlers(self.on_mouse_drag)
        window.game_window.push_handlers(self.on_mouse_motion)

        events.AddListener(self)
Beispiel #9
0
    def __init__(self, parent, displayMode, border):
        wx.ScrolledWindow.__init__(self, parent)
        self._displayKeys = {}
        self._orderedHeyHandles = []
        self._keySize = wx.Size(4, 4)
        self._keySpacing = wx.Size(1, 1)
        self._border = border
        self._selectedKeyHandle = None
        self._contentSize = Size(200, 200)
        self._displayMode = displayMode
        self._scroll = wx.Size(0, 0)
        self._scrollUnit = wx.Size(0, 0)
        self._tooltip = wx.ToolTip("")
        self._zoom = 1
        if displayMode == DISPLAY_MODE_DYNAMIC_RESIZE:
            self._zoom = 10  # 25
        self._dragStart = None
        self._dragMode = DRAG_MODE_NONE
        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_SIZE, self.OnSize)
        self.Bind(wx.EVT_MOUSE_EVENTS, self.OnMouse)
        self.Bind(wx.EVT_CHAR, self.OnChar)
        self.Bind(wx.EVT_KILL_FOCUS, self.OnKillFocus)
        self.Bind(wx.EVT_SET_FOCUS, self.OnSetFocus)
        self.SetToolTip(self._tooltip)
        self.SetScrollRate(1, 1)

        displayRect = self._getDisplayRect()
        print "displayRect: %s" % displayRect
        #           dc.SetMapMode(wx.MM_TEXT)
        dc.SetMapMode(wx.MM_METRIC)
        contentRect = Rect(dc.DeviceToLogicalX(displayRect.x),
                           dc.DeviceToLogicalY(displayRect.y),
                           dc.DeviceToLogicalXRel(displayRect.width),
                           dc.DeviceToLogicalYRel(displayRect.height))
Beispiel #10
0
 def __init__(self, parent, sourceKey):
     KeyDisplayPane.__init__(self,
                             parent,
                             border=10,
                             displayMode=DISPLAY_MODE_WRAPPED)
     self._displayKeys = {}
     KeyDisplayPane._initKeys(self)
     self.Bind(wx.EVT_PAINT, self.OnPaint)
     self._keySize = Size(6.0, 2.5)
     self._keySpacing = Size(0.2, 0.2)
     keyRect = Rect(0, 0, *self._keySize)
     handle = None
     if sourceKey.usage:
         handle = sourceKey.usage.MakeHandle()
     elif sourceKey.mode:
         handle = "mode:%s" % sourceKey.mode
     elif len(sourceKey.macro) > 0:
         for (i, macroKey) in enumerate(sourceKey.macro):
             handle = macroKey.MakeHandle(i)
             self._displayKeys[handle] = DisplayKey(handle, keyRect)
             self._orderedKeyHandles.append(handle)
         handle = None
     if handle is not None:
         dispKey = DisplayKey(handle, keyRect)
         self._displayKeys[handle] = dispKey
         self._orderedKeyHandles.append(handle)
         self._updateKeys()
Beispiel #11
0
    def update(self, dt):
        # print(1 / dt)
        for obj in self._objects:
            obj.pos += obj.velocity * dt
            x1, y1 = obj.rect.topleft
            x2, y2 = obj.rect.bottomright
            x1 = round(x1)
            x2 = round(x2)
            y1 = round(y1)
            y2 = round(y2)
            points = [(x, y) for x in range(x1 - 2, x2 + 2) for y in range(y1 - 2, y2 + 2)]
            obj.one_ground = False
            for r in list(obj.rect.collidelistall([tuple(self.get_block(p).rect) for p in points if self.get_block(p).has_collision])):
                r: Rect = Rect(r)
                n = obj.pos - r.center
                n = n.unit

                if n.x > 0.5:
                    obj.rect.left = r.right + 0.05
                    obj.velocity.x = 0
                    obj.one_wall = True
                elif n.x < -0.5:
                    obj.rect.right = r.left - 0.05
                    obj.velocity.x = 0
                    obj.one_wall = True
                else:
                    if n.y > 0:
                        obj.rect.top = r.bottom
                        obj.velocity.y = 0
                        obj.one_ground = True
                    elif n.y < 0:
                        obj.rect.bottom = r.top
                        obj.velocity.y = 0
                        obj.one_ground = False
            obj.velocity += self.gravity * dt
Beispiel #12
0
 def attack(self, pos, gap, orientation,team):
   
   if self.nextAttackTimer != 0.0:
     return False
   
   self.nextAttackTimer += self.attackCooldown
   
   #create a knife just outside the spawn location
   
   projectileShape = Rect.createAtOrigin(self.size[0], self.size[1])
       
   #TODO: how to handle diagonal movement and firing?
   # spawn outside rect, or inside?
   
   projectilePos = pos + orientation.getNormalized()*gap
   
   proj = SlimeBall(projectilePos,projectileShape,self.owner,orientation,self.hue)
   #proj = Rock(projectilePos,projectileShape,team,orientation) 
   
   glad.world.objectList.append(proj)
   
   #play sound effect
   proj.sound.play(self.owner.pos)
   
   return True  
Beispiel #13
0
 def rect_iter(self):
     for ind in xrange(len(self.bbox_array)):
         rect = Rect(self.bbox_array[ind][0],  
                   self.bbox_array[ind][1], 
                   self.bbox_array[ind][2], 
                   self.bbox_array[ind][3], 
                   label = self.label_array[ind])
         yield rect
Beispiel #14
0
 def __init__(self, pos, **kwargs):    
   
   shape = Rect.createAtOrigin(64, 64)    
   AbstractObject.__init__(self, pos, shape, **kwargs)
   
   self.collisionType = 'UNIT'
   self.orientation = Vector(1,0)
   
Beispiel #15
0
    def __init__(self):
        GrillObject.__init__(self)
        self.image = image.load(data_file('beef.png'))
        self.rect = Rect(520, 230, self.image)

        self.cooking = False

        self.reset()
Beispiel #16
0
 def __init__(self, pos, **kwargs):
   shape = Rect.createAtOrigin(64, 64)
   
   BasicUnit.__init__(self, pos, shape, name='BIG_SLIME', slime=True, **kwargs)
   
   self.rangedWeapon = SlimeAttack(self)
   
   self.alwaysMove = True
Beispiel #17
0
 def __init__(self, pos, **kwargs):
   shape = Rect.createAtOrigin(26, 28)
   
   BasicUnit.__init__(self, pos, shape, name='GHOST', **kwargs)
   
   self.rangedWeapon = KnifeThrower(self)
   
   self.alwaysMove = True
Beispiel #18
0
 def __init__(self, pos, **kwargs):
   shape = Rect.createAtOrigin(16, 16)
   
   BasicUnit.__init__(self, pos, shape, name='FAERIE', **kwargs)
   
   self.rangedWeapon = BasicRangedAttack(self, 'sparkle')
   
   self.alwaysMove = True
Beispiel #19
0
    def _updateKeys(self):
        """
        Adjust position and scale of each display key based on current display rect.
        """
        drawingArea = self._getDrawingArea()
        self._scroll.width = self._scroll.height = 0
        self._scrollUnit = drawingArea.size
        scale = self._getScale(drawingArea)

        if self._displayMode == DISPLAY_MODE_DYNAMIC_RESIZE:
            contentArea = self._getContentArea()
            for displayKey in self._displayKeys.values():
                displayKey.scaled = displayKey.unscaled * scale
                displayKey.scaled.Offset(contentArea.origin)
                displayKey.labelRect = Rect(*displayKey.unscaled)
                displayKey.labelRect.Deflate(0.2, 0.2)
                displayKey.labelRect *= scale
                displayKey.labelRect.Offset(contentArea.origin)
            self._fontSize = scale * 0.37

        else:
            maxWidth = drawingArea.width / scale
            origin = Point(0, 0)
            for displayKeyHandle in self._orderedKeyHandles:
                displayKey = self._displayKeys[displayKeyHandle]
                if origin.x + self._keySize.width > maxWidth:
                    origin.x = 0
                    origin.y += self._keySize.height + self._keySpacing.height
                displayKey.unscaled.x = origin.x
                displayKey.unscaled.y = origin.y
                displayKey.scaled = displayKey.unscaled * scale
                self._scroll.width = max(self._scroll.width, displayKey.scaled.x + displayKey.scaled.width)
                self._scroll.height = max(self._scroll.height, displayKey.scaled.y + displayKey.scaled.height)
                displayKey.scaled.Offset(drawingArea.origin)
                displayKey.labelRect = Rect(*displayKey.unscaled)
                displayKey.labelRect.Deflate(0.2, 0.2)
                displayKey.labelRect *= scale
                displayKey.labelRect.Offset(drawingArea.origin)
                origin.x += self._keySize.width + self._keySpacing.width
                self._scrollUnit.width = min(self._scrollUnit.width, displayKey.scaled.width)
                self._scrollUnit.height = min(self._scrollUnit.height, displayKey.scaled.height)
            self._scroll.width  += self._border * 2
            self._scroll.height += self._border * 2
            self._scrollUnit.width  += self._keySpacing.width  * scale
            self._scrollUnit.height += self._keySpacing.height * scale
Beispiel #20
0
def generate_goal_area(*, snake: Snake, field: Field) -> Rect:
    collision = True
    possible_goal: Rect = Rect(x=0, y=0, w=0, h=0)
    while collision:
        possible_goal = random_rect(size=9, area=field.client_area())
        collision = False
        for point in snake:
            if rect_contains_point(possible_goal, point):
                collision = True
    return possible_goal
Beispiel #21
0
 def __init__(self, parent, sourceKey):
     KeyDisplayPane.__init__(self,
                             parent,
                             border=10,
                             displayMode=DISPLAY_MODE_DYNAMIC_RESIZE)
     self._sourceKey = sourceKey
     self._dispKey = DisplayKey(sourceKey.handle, Rect(0, 0, 1.8, 1.8))
     self._displayKeys = {sourceKey.handle: self._dispKey}
     self._updateKeys()
     KeyDisplayPane._initKeys(self)
Beispiel #22
0
 def __init__(self, pos, **kwargs):
   #For now, just use BasicUnit Defaults
   
   #default soldier size    
   shape = Rect.createAtOrigin(32, 32)
     
   BasicUnit.__init__(self, pos, shape, name='SOLDIER', **kwargs)
   
   #self.rangedWeapon = BasicRangedAttack('knife',size=(12,12))
   self.rangedWeapon = KnifeThrower(self)
Beispiel #23
0
    def __init__(self):
        self.image = image.load(data_file('grill.png'))
        self.rect = Rect(500, 250, self.image)

        window.game_window.push_handlers(self.on_mouse_press)
        window.game_window.push_handlers(self.on_mouse_motion)

        self.highlighted = False

        self.active = False
Beispiel #24
0
 def __init__(self, pos, owner, **kwargs):
   shape = Rect.createAtOrigin(32, 32)
   AbstractObject.__init__(self, pos, shape, **kwargs)
   
   self.owner = self #keep a copy of who the corpse belongs to
   
   self.collisionType = 'OBJ' #should add collision type for corpses, keys, and other stuff you can walk over
   
   self.currentAnimation = 'ANIM_BLOOD_'+str(random.randint(0,3))
   self.animationPlayer = animation.AnimationPlayer(glad.resource.resourceDict[self.currentAnimation], 0.2, True)
Beispiel #25
0
 def _initKeys(self):
     KeyDisplayPane._initKeys(self)
     self._displayKeys = {
         'left_shift': DisplayKey('left_shift', Rect(0.0, 0.0, 2.8, 1.8)),
         'left_ctrl': DisplayKey('left_ctrl', Rect(0.0, 2.0, 2.8, 1.8)),
         'left_alt': DisplayKey('left_alt', Rect(0.0, 4.0, 2.8, 1.8)),
         'left_gui': DisplayKey('left_gui', Rect(0.0, 6.0, 2.8, 1.8)),
         'right_shift': DisplayKey('right_shift', Rect(3.0, 0.0, 2.8, 1.8)),
         'right_ctrl': DisplayKey('right_ctrl', Rect(3.0, 2.0, 2.8, 1.8)),
         'right_alt': DisplayKey('right_alt', Rect(3.0, 4.0, 2.8, 1.8)),
         'right_gui': DisplayKey('right_gui', Rect(3.0, 6.0, 2.8, 1.8))
     }
     self._updateKeys()
Beispiel #26
0
 def __init__(self, pos, **kwargs):
   shape = Rect.createAtOrigin(32, 32)
       
   BasicUnit.__init__(self, pos, shape, name='FIRE_ELEM', **kwargs)
       
   #self.rangedWeapon = KnifeThrower()
   self.rangedWeapon = BasicRangedAttack(self, 'meteor')
       
   self.alwaysMove = True
   
   self.animationPlayer.timer = 0.1
Beispiel #27
0
 def __init__(self, pos, shape = Rect.createAtOrigin(32, 32), hue=180, name='SOLDIER', slime=False, **kwargs):
   AbstractObject.__init__(self, pos, shape, **kwargs)
   
   self.collisionType = 'UNIT'
 
   #Default statistics  
   self.strength = 10
   self.dexterity = 10
   self.constitution = 10
   self.intelligence = 10
   self.armor = 10    
   self.level = 1
   
   self.life = 100
   self.mana = 100
   
   self.rangedWeapon = None
   self.meleeWeapon = None
   
   self.rangedDamage = 10
   self.meleeDamage = 10
   
   self.range = 400 #range for ranged weapon (in pixels)
   
   self.moveSpeed = 200
   
   #By default, have units face 'right'
   self.orientation = Vector(1,0)
   self.directionString = self.orientationToString() #may not be needed
   
   #self.name = "SOLDIER" #might as well be soldier by default, name used to load animations with current name format
   self.name=name
   self.slime=slime
   if self.slime:
       self.currentAnimation = 'ANIM_' + self.name + '_TEAM_' + str(self.team) +'_MOVE'
   else:
       self.currentAnimation = 'ANIM_' + self.name + '_TEAM_' + str(self.team) +'_MOVE' + self.orientationToString()
   
   self.animationTime = 0.2    
   self.animationPlayer = animation.AnimationPlayer(glad.resource.resourceDict[self.currentAnimation], self.animationTime , True)
   
   self.alwaysMove = False
   
   #turning
   self.turnTime = 0.08
   
   #Attacking
   self.attacking = False
   #attack animation
   self.attackTime = 0.1 #time attack frame is up
   self.attackTimer = 0
   self.animateAttack = False
   
   self.hue = hue #I thnk this is from my old method of team coloring - can probably be removed
Beispiel #28
0
 def attack(self, pos, gap, orientation,team):
   
   if self.nextAttackTimer != 0.0:
     return False
   
   self.nextAttackTimer += self.attackCooldown
   
   #create a knife just outside the spawn location
   
   projectileShape = Rect.createAtOrigin(self.size[0], self.size[1])
       
   #TODO: how to handle diagonal movement and firing?
   # spawn outside rect, or inside?
   
   projectilePos = pos + orientation.getNormalized()*gap
   
   dict = {'rock': Rock(projectilePos,projectileShape,self.owner,orientation),
           'arrow': Arrow(projectilePos,projectileShape,self.owner,orientation),
           'firearrow': FireArrow(projectilePos,projectileShape,self.owner,orientation),
           'fireball': Fireball(projectilePos,projectileShape,self.owner,orientation),
           'hammer': Hammer(projectilePos,projectileShape,self.owner,orientation),
           'lightning': Lightning(projectilePos,projectileShape,self.owner,orientation),
           'meteor': Meteor(projectilePos,projectileShape,self.owner,orientation),
           'bone' : Bone(projectilePos,projectileShape,self.owner,orientation),
           'knife' : Knife(projectilePos,projectileShape,self.owner,orientation),
           'sparkle' : Sparkle(projectilePos,projectileShape,self.owner,orientation),
           'boulder' : Boulder(projectilePos,projectileShape,self.owner,orientation)}
   proj = dict[self.type]
   proj.owner = self.owner
   
   
   #play sound - if I do this when the projectile is created, it plays it for each entry in the above dict
   #need to play sound for each attack, right now just this, knifeThrower, and slimeAttack
   proj.sound.play(self.owner.pos)
   #if self.type == "arrow":
   #  glad.resource.resourceDict['twang'].play(self.owner.pos)
   #elif self.type == "sparkle":
   #  glad.resource.resourceDict['faerie1'].play(self.owner.pos)
   #elif self.type == "lightning":
   #  glad.resource.resourceDict['bolt1'].play(self.owner.pos)
   #elif self.type == "meteor":
   #  glad.resource.resourceDict['blast1'].play(self.owner.pos)
   #else:
   #  glad.resource.resourceDict['fwip'].play(self.owner.pos) #Just testing sound, should be for only stuff on screen or nearby,
   
   #proj = BasicProjectile(projectilePos, projectileShape, team, orientation) #basic projectile should be default
   #proj = Fireball(projectilePos,projectileShape,team,orientation)
   ##proj = Knife(projectilePos,projectileShape,team,orientation) 
   
   glad.world.objectList.append(proj)
   
   return True
Beispiel #29
0
    def __init_rect_list(self, ind, min_prob=0.5):
        """
        Returns list of Rect instances from output of neural network for a single image.

        Args
            bottom_height (int): height of image (bottom layer)
            bottom_width (int): width of image
            bbox_label_pred (ndarray): spatial map of predicted bounding 
                box coordinates at the top of neural network
            label_pred (ndaray): spatial map of probabilities of the 
                different labels
        
        """
        #bbox_label_pred = self.net.tops['bbox_label'].data[ind]
        #binary_pred = self.net.tops['binary_label'].data[ind]
        bottom_height = self.image_height
        bottom_width = self.image_width
        bbox_label_pred = self.net.tops['bbox_pred'].data[ind]
        binary_pred = self.net.tops['binary_softmax'].data[ind]
        label_pred = self.net.tops['label_softmax'].data[ind]

        (_, top_height, top_width) = bbox_label_pred.shape
        y_mul = bottom_height * 1. / top_height
        x_mul = bottom_width * 1. / top_width
        rect_list = []
        for y in xrange(top_height):
            for x in xrange(top_width):
                # corresponds to indices in original image
                cx_orig = x_mul * (x + 0.5)
                cy_orig = y_mul * (y + 0.5)

                # we predict a symbol here if p(no label) < x
                if binary_pred[0, y, x] < 0.5:
                    k = np.argmax(label_pred[:, y, x])
                    #if label_pred[k, y, x] < 0.2: continue

                    # apply offsets to get positions in original image
                    cx = cx_orig + bbox_label_pred[0, y, x]
                    cy = cy_orig + bbox_label_pred[1, y, x]
                    w = bbox_label_pred[2, y, x]
                    h = bbox_label_pred[3, y, x]
                    xmin = cx - w / 2.0
                    ymin = cy - h / 2.0
                    rect = Rect(xmin,
                                ymin,
                                xmin + w,
                                ymin + h,
                                label=k,
                                prob=label_pred[k, y, x])
                    rect_list.append(rect)

        return rect_list
Beispiel #30
0
    def rect_list(self):
        """
        List[Rect] - instances corresponding to labelled image.
        """
        rect_list_ = []
        for ind in xrange(len(self.bbox_array)):
            rect = Rect(self.bbox_array[ind][0],  
                      self.bbox_array[ind][1], 
                      self.bbox_array[ind][2], 
                      self.bbox_array[ind][3], 
                      label = self.label_array[ind])

            rect_list_.append(rect)
        return rect_list_
Beispiel #31
0
 def _initKeys(self):
     KeyDisplayPane._initKeys(self)
     self._displayKeys.clear()
     self._orderedKeyHandles = self._category.keyHandles
     for keyHandle in self._category.keyHandles:
         if not Model.sourcekeys.has_key(keyHandle):
             raise RuntimeError("Unknown key '%s' in category '%s'" %
                                (keyHandle, self._category.name))
         sourceKey = Model.sourcekeys[keyHandle]
         rect = Rect(0, 0, self._keySize.width, self._keySize.height)
         self._displayKeys[keyHandle] = DisplayKey(keyHandle, rect)
     self._updateKeys()
     self._selectKey(self._orderedKeyHandles[0])
     self._updateScrollbars()
Beispiel #32
0
    def chunkify(m):
        direction = WallDirection.horizontal
        start_chunk = Rect(0, 0, m.width, m.height)
        TowerMapGenerator.mark_room(m, start_chunk, 0)
        chunks = [start_chunk]
        minsize = 13
        minlength = 6
        while TowerMapGenerator.free_area(m) < TowerMapGenerator.total_size(m) * 0.2:
            curr = TowerMapGenerator.pop_largest(chunks)
            if direction == WallDirection.vertical and curr.width > minsize:
                start = curr.x + max(minlength, int(curr.width * 0.2))
                end = curr.x + curr.width - max(minlength, int(curr.width * 0.2))
                hallway = random.randint(start, end)
                first = Rect(curr.x, curr.y, hallway - curr.x, curr.height)
                second = Rect(hallway + 1, curr.y, curr.x + curr.width - hallway - 1, curr.height)
                new_direction = WallDirection.horizontal
            elif direction == WallDirection.horizontal and curr.height > minsize:  # horizontal
                start = curr.y + max(minlength, int(curr.height * 0.2))
                end = curr.y + curr.height - max(minlength, int(curr.height * 0.2))
                hallway = random.randint(start, end)
                first = Rect(curr.x, curr.y, curr.width, hallway - curr.y)
                second = Rect(curr.x, hallway + 1, curr.width, curr.y + curr.height - hallway - 1)
                new_direction = WallDirection.vertical
            else:  # chunk too small, done. just re-add the chunk
                chunks.append(curr)
                break

            TowerMapGenerator.mark_room(m, first, TowerMapGenerator.first_unused_room_id(m))
            chunks.append(first)

            TowerMapGenerator.mark_room(m, second, TowerMapGenerator.first_unused_room_id(m))
            chunks.append(second)

            TowerMapGenerator.mark_hallway(m, curr, hallway, direction)
            direction = new_direction

        return chunks
Beispiel #33
0
 def __init__(self):
     self.rect = Rect(0,0,70,80) #this is the *logical* rect
     self.facing = Facing.right
     self.yFacing = Facing.up
     self.velocity = [0,0]
     self.xFriction = 1
     self.yFriction = 2
     self.xAccel = 1
     self.yAccel = 1
     self.xMax = 8
     self.xMin = -8
     self.yMax = 4
     self.yMin = -4
     self.walkMask = None #level will set this
     self.triggerZones = None #level will set this
Beispiel #34
0
    def batch_data(self, image_mean):
        """
        Prepares data for ingestion by Apollo.

        Returns:
            ndarray (trans_img): transposed image in N-C-H-W caffe blob format
            ndarray (bbox_label): target bounding boxes corresponding to image, 
                bbox_label[0]: cx (center x) offset at each position
                bbox_label[1]: cy (center y) offset at each position
                bbox_label[2]: w (width) of bounding box of object at each position
                bbox_label[3]: h (height) of bounding box of object at each position
            ndarray (conf_label): target indices corresponding to different points in image
        """
        # zero label means nothing is there
        conf_label = np.zeros((1, TOP_HEIGHT, TOP_WIDTH), dtype = np.float)
        bbox_label = np.zeros((4, TOP_HEIGHT, TOP_WIDTH), dtype = np.float)
        y_mul = IMG_HEIGHT * 1. / TOP_HEIGHT
        x_mul = IMG_WIDTH * 1. / TOP_WIDTH

        # iterate over all pixels
        for y in range(TOP_HEIGHT):
            for x in range(TOP_WIDTH):
                # current distance to closest object center at coordinate
                best_dist = np.Inf
                # find object closest to coordinate (if one exists)
                for rect in self.rect_iter():
                    # makes box smaller to prevent label ambiguity 
                    # at downsampled resolution (detections get centered)
                    rect.scale_wh(0.5, 0.5)
                    x_orig = x_mul * x
                    y_orig = y_mul * y
                    obs_rect = Rect(x_orig, y_orig, x_orig + x_mul, y_orig + y_mul)
                    if rect.intersects(obs_rect):
                        center_dist = (rect.cx - obs_rect.cx) ** 2 + (rect.cy - obs_rect.cy) ** 2
                        if center_dist < best_dist:
                            best_dist = center_dist
                            conf_label[0, y, x] = rect.label
                            bbox_label[0, y, x] = rect.cx - obs_rect.cx
                            bbox_label[1, y, x] = rect.cy - obs_rect.cy
                            bbox_label[2, y, x] = rect.w
                            bbox_label[3, y, x] = rect.h

        image = self.image.copy()
        image = image.reshape(1, IMG_HEIGHT, IMG_WIDTH)

        return (image, bbox_label, conf_label)
Beispiel #35
0
 def __init__(self, pos, data=None):
     self.base_images = {}
     for n, p in self.image_paths.items():
         self.base_images[n] = pygame.image.load(p)
     self._velocity: Vec2d = Vec2d((0, 0))
     self.images: Dict[str, BodyPart] = {}
     for n, v in self.image_parts.items():
         self.images[n] = BodyPart(self.base_images[v[0]].subsurface(v[1]),
                                   v[2])
     self._data: Dict[str, Any] = None
     self._hash = None
     self._image = None
     self._rect = Rect(pos, self.size)
     self._draw_offset = None
     self.data = data or {}
     self.one_ground = False
     self.setup()
Beispiel #36
0
def main():
    pygame.init()
    screen = pygame.display.set_mode(SIZE)
    clock = pygame.time.Clock()

    noto_sans = pygame.font.Font('NotoSans-Regular.ttf', 12)

    field = Field(area=Rect(x=10, y=50, w=WIDTH - 20, h=HEIGHT - 60))
    snake = Snake(
        starting_point=random_point(offset=100, area=field.client_area()))
    score = Score(font=noto_sans, position=Point(x=10, y=10))
    goal = Goal(area=generate_goal_area(snake=snake, field=field))
    controller = KeyboardController(
        snake=snake,
        start_direction=random_direction(),
        key_map=KeyMap(
            up=pygame.K_UP,
            down=pygame.K_DOWN,
            left=pygame.K_LEFT,
            right=pygame.K_RIGHT
            # up=pygame.K_w, down=pygame.K_s, left=pygame.K_a, right=pygame.K_d
        ))

    running = True
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            controller.handle_event(event)

        if not running:
            break

        score.update(score=len(snake))

        screen.fill(BLACK)
        for go in [field, snake, score, goal]:
            go.draw_to(screen)
        pygame.display.flip()

        controller.update()
        running = check_collisions(snake, screen, goal, field)
        clock.tick(120)

    print(f'Game over! Your score: {len(snake)}')
    pygame.quit()
Beispiel #37
0
 def __init__(self, pos, tileNum, type = None, shape=Rect.createAtOrigin(32,32), **kwargs):
   
   AbstractObject.__init__(self, pos, shape, team=None, moveDir=None, **kwargs)
   
   self.collisionType = 'LAND'
   if tileNum in Tile.water:
     self.collisionType = 'WATER'
   elif tileNum in Tile.tree:
     self.collisionType = 'TREE'
   elif tileNum in Tile.wall:
     self.collisionType = 'WALL'
   elif tileNum in Tile.barrier:
     self.CollisionType = 'BARRIER'
   
   #set appropriate tile to be drawn
   self.tileNum = tileNum
   tileName = Tile.tileDict[self.tileNum]
   anim = [glad.resource.get(tileName)]
   self.currentAnimation = animation.Animation(anim)
   self.animationPlayer = animation.AnimationPlayer(self.currentAnimation, 0.2, True)
Beispiel #38
0
    def __init__(self):
        self.image = image.load(data_file('biggrill.png'))
        self.beef = Beef()
        self.spritzer = Spritzer()
        self.table = Table()
        self.exit = Exit()

        self.rect = Rect(150, 300, 300, 200)

        self.flareups = []
        self.flareup_range = (10, 50)
        self.flareup_counter = randint(*self.flareup_range) / 10.0

        window.game_window.push_handlers(self.on_mouse_press)
        window.game_window.push_handlers(self.on_mouse_release)
        window.game_window.push_handlers(self.on_mouse_motion)

        #events.AddListener(self)

        self.active = False
        self.beef_hint_done = False
        self.flareup_hint_done = False
Beispiel #39
0
    def _initKeys(self):
        self._keySpacing = wx.Size(self._kb.layout.spacing, self._kb.layout.spacing)
        self._displayKeys = {}
        selectedKey = None
        rows = self._kb.layout.rows
        for row in rows:
            if row is None:
                continue
            for keydef in row.keydefs:
                if keydef.isNullKey:
                    continue
                keyRect = Rect(keydef.origin.x, keydef.origin.y, keydef.size.width, keydef.size.height)
                location = keydef.location
                keyHandle = None
                if self._keymap and self._keymap.keys.has_key(location):
                    keyHandle = self._keymap.keys[location].keyHandle
                self._displayKeys[location] = DestDisplayKey(location, keyHandle, keyRect)
                if selectedKey == None:
                    selectedKey = location

        self._updateKeys()
        self._selectKey(selectedKey)
Beispiel #40
0
def chunkify(m):
    direction = Dir.horizontal
    start_chunk = Rect(0, 0, m.width, m.height)
    start_chunk.room = -1
    chunks = [start_chunk]
    minsize = 13
    minlength = 6
    while m.free_area < m.total_size * 0.2:
        curr = pop_largest(chunks)
        if direction == Dir.vertical and curr.width > minsize:
            start = curr.x + max(minlength, int(curr.width * 0.2))
            end = curr.x + curr.width - max(minlength, int(curr.width * 0.2))
            hallway = random.randint(start, end)
            first = Rect(curr.x, curr.y, hallway - curr.x, curr.height)
            second = Rect(hallway + 1, curr.y, curr.x + curr.width - hallway - 1, curr.height)
            new_direction = Dir.horizontal
        elif direction == Dir.horizontal and curr.height > minsize:  # horizontal
            start = curr.y + max(minlength, int(curr.height * 0.2))
            end = curr.y + curr.height - max(minlength, int(curr.height * 0.2))
            hallway = random.randint(start, end)
            first = Rect(curr.x, curr.y, curr.width, hallway - curr.y)
            second = Rect(curr.x, hallway + 1, curr.width, curr.y + curr.height - hallway - 1)
            new_direction = Dir.vertical
        else:  # chunk too small, done. just re-add the chunk
            chunks.append(curr)
            break

        mark_room(m, first, m.first_unused_room_id)
        chunks.append(first)

        mark_room(m, second, m.first_unused_room_id)
        chunks.append(second)

        mark_hallway(m, curr, hallway, direction)
        direction = new_direction

        # print_map(m)

    return chunks
Beispiel #41
0
class Beef(GrillObject):
    def __init__(self):
        GrillObject.__init__(self)
        self.image = image.load(data_file('beef.png'))
        self.rect = Rect(520, 230, self.image)

        self.cooking = False

        self.reset()

    def reset(self):
        GrillObject.reset(self)
        self.cooking_time = 15
        self.red = 1
        self.brown_time = 3
        self.cooked = False
        self.burnt = False
        self.rect.bottomleft = (580, 230)

    def handler(self, pos):
        if self.rect.collide_point(*pos):
            self.set_active()
            self.cooking = False
            self.highlighted = False
            return True
        return False

    def set_active(self):
        GrillObject.set_active(self)
        events.Fire('BeefTaken')
        #print "beef taken"

    def set_inactive(self, pos):
        GrillObject.set_inactive(self, pos)
        events.Fire('BeefDropped')
        #print "beef dropped"

    def update(self, tick):
        if self.cooking:
            self.brown_time -= tick
            if self.brown_time < 0:
                self.brown_time = 3
                self.red -= 0.1

            self.cooking_time -= tick

            if self.cooking_time < 0:
                if not self.cooked:
                    self.cooked = True
                    events.Fire('BeefCooked')
                    events.Fire('NewHint', random.choice(COOKED_PHRASES))
                elif self.cooking_time < -15 and not self.burnt:
                    events.Fire('BeefBurnt')
                    events.Fire('NewHint', random.choice(BURN_PHRASES))
                    self.burnt = True

    def draw(self):
        if self.highlighted:
            glColor4f(0.5, 0.1, 1, 1)
        else:
            glColor4f(self.red, self.red, self.red, 1)

        self.image.blit(*self.rect.bottomleft)

        glColor4f(1, 1, 1, 1)

    def on_mouse_drag(self, x, y, dx, dy, buttons, modifiers):
        if self.active:
            self.rect.center = (x, y)
Beispiel #42
0
class Grill:
    def __init__(self):
        self.image = image.load(data_file('biggrill.png'))
        self.beef = Beef()
        self.spritzer = Spritzer()
        self.table = Table()
        self.exit = Exit()

        self.rect = Rect(150, 300, 300, 200)

        self.flareups = []
        self.flareup_range = (10, 50)
        self.flareup_counter = randint(*self.flareup_range) / 10.0

        window.game_window.push_handlers(self.on_mouse_press)
        window.game_window.push_handlers(self.on_mouse_release)
        window.game_window.push_handlers(self.on_mouse_motion)

        #events.AddListener(self)

        self.active = False
        self.beef_hint_done = False
        self.flareup_hint_done = False

    def update(self, tick):
        self.beef.update(tick)
        if self.beef.cooking:
            self.flareup_counter -= tick
            #print self.flareup_counter
            if self.flareup_counter <= 0:
                if len(self.flareups) < 2:
                    if not self.flareup_hint_done:
                        events.Fire('NewHint',
                            'I can put out flare ups with the spritzer')
                        self.flareup_hint_done = True
                        #print "flare ups hint"
                    self.flareups.append(FlareUp())
                    self.flareup_counter = randint(*self.flareup_range) / 10.0
                    #print "flareup"
                    events.Fire('FlareUp')

        if self.beef.burnt:
            self.active = False

        self.spritzer.update(tick)
        for fire in self.flareups:
            fire.update(tick)

    def draw(self):
        self.image.blit(120, 100)

        self.exit.draw()
        self.table.draw()

        #self.draw_rect()

        self.beef.draw()
        for fire in self.flareups:
            fire.draw()

        self.spritzer.draw()

    def check_flareups(self, x, y):
        for fire in self.flareups:
            #x += self.spritzer.rect.width/2
            #y += self.spritzer.rect.height/2
            rect_x = x - fire.rect.x - fire.rect.width/2
            rect_y = y + self.spritzer.rect.height/2 - fire.rect.y 

            if rect_x < 100 and abs(rect_y) < 40:
                #print "hit fire"
                fire.lives -= 1
                if fire.lives <= 0:
                    self.flareups.remove(fire)
                break

    def on_mouse_press(self, x, y, button, modifiers):
        if not self.active:
            return

        if self.spritzer.active:
            if self.table.rect.collide_point(x, y):
                self.spritzer.set_inactive((x, y))
                return
            #print "spritz"
            self.spritzer.spritz((x, y))
            events.Fire('Spritz')

            self.check_flareups(x, y)

            return

        if self.exit.rect.collide_point(x, y):
            self.active = False

        if self.spritzer.handler((x, y)):
            return
        if self.beef.handler((x, y)):
            return

    def on_mouse_release(self, x, y, button, modifiers):
        if self.beef.active:
            self.beef.set_inactive((x, y))
            if self.rect.collide_point(self.beef.rect.center):
                events.Fire('BeefCooking')
                self.beef.cooking = True
                #print "cookin'!"

    def on_mouse_motion(self, x, y, dx, dy):
        if not self.beef_hint_done and self.active:
            events.Fire('NewHint', 'I need to put the steak on the grill.')
            self.beef_hint_done = True

    def draw_rect(self):
        glColor4f(0, 0, 1, .5)

        glBegin(GL_POLYGON)
        glVertex2d(*self.rect.bottomleft)
        glVertex2d(*self.rect.topleft)
        glVertex2d(*self.rect.topright)
        glVertex2d(*self.rect.bottomright)
        glEnd()

        glColor4f(1, 1, 1, 1)
Beispiel #43
0
class GarbageCan:
    def __init__(self):
        self.image_opened = image.load(data_file('garbagecan-open.png'))
        self.image_closed = image.load(data_file('garbagecan-closed.png'))
        self.image_lid = image.load(data_file('garbagecan-lid.png'))

        self.image_opened.anchor_x = self.image_opened.width/2
        self.image_opened.anchor_y = self.image_opened.height/2
        self.image_closed.anchor_x = self.image_opened.width/2
        self.image_closed.anchor_y = self.image_opened.height/2

        self.candidateLeaves = {}

        self.opened = True
        self.lid_active = False
        self.can_active = False
        self.fallen = False
        self.can_highlighted = False
        self.lid_highlighted = True

        self.can_rect = Rect(0, 0, self.image_closed)
        self.can_rect.center = (80, 90)

        self.can_sprite = Sprite(self.image_opened)
        self.can_sprite.set_position(self.can_rect.x, self.can_rect.y)

        self.lid_rect = Rect(20, 40, self.image_lid)

        window.game_window.push_handlers(self.on_mouse_release)
        window.game_window.push_handlers(self.on_mouse_press)
        window.game_window.push_handlers(self.on_mouse_drag)
        window.game_window.push_handlers(self.on_mouse_motion)

        events.AddListener(self)

    def update(self, timechange):
        pass

    def draw(self):
        if not self.can_active:
            if self.can_highlighted:
                self.can_sprite.color = (255, 20, 25)
            else:
                self.can_sprite.color = (255, 255, 255)
        else:
            self.can_sprite.color = (255, 255, 255)

        self.can_sprite.draw()

        glColor4f(1, 1, 1, 1)

        if not self.lid_active:
            if self.lid_highlighted:
                glColor4f(1, 0.1, 0.1, 1)
            else:
                glColor4f(1, 1, 1, 1)
        
        if self.opened:
            self.image_lid.blit(*self.lid_rect.bottomleft)

        glColor4f(1, 1, 1, 1)

    def on_mouse_press(self, x, y, button, modifiers):
        if self.opened and self.lid_rect.collide_point(x, y):
            self.set_lid_active()
        elif self.collides(x, y):
            self.fallen = False
            self.set_can_active()
            self.can_sprite.rotation = 0

            if self.opened:
                self.can_sprite.image = self.image_opened
            else:
                self.can_sprite.image = self.image_closed

    def set_can_active(self):
        window.game_window.set_mouse_visible(False)
        self.can_active = True
        events.Fire('CanTaken')

    def set_lid_active(self):
        window.game_window.set_mouse_visible(False)
        self.lid_active = True
        events.Fire('LidTaken')

    def collides(self, x,y):
        cs = self.can_sprite
        return (x > cs.x - cs.image.width/2 
            and x < cs.x + cs.image.width/2
            and y > cs.y - cs.image.height/2
            and y < cs.y + cs.image.height/2 )

    def on_mouse_release(self, x, y, button, modifiers):
        window.game_window.set_mouse_visible(True)
        #print "x=%d y=%d" % (x, y)
        if self.lid_active:
            if self.collides(x, y):
                self.can_sprite.image = self.image_closed
                self.opened = False
                events.Fire('LidClosed')
            else:
                self.lid_rect.x = x
                self.lid_rect.y = y
                events.Fire('LidDropped')

            self.lid_active = False

        elif self.can_active:
            self.can_sprite.rotation = 0
            #self.can_sprite.set_position(x,y)

            self.can_active = False
            events.Fire('CanDropped')

    def on_mouse_motion(self, x, y, dx, dy):
        if self.collides(x, y):
            self.can_highlighted = True
        else:
            self.can_highlighted = False

        if self.lid_rect.collide_point(x, y):
            self.lid_highlighted = True
        else:
            self.lid_highlighted = False

    def on_mouse_drag(self, x, y, dx, dy, buttons, modifiers):
        if self.can_active:
            self.can_sprite.x = x
            self.can_sprite.y = y
            #self.can_rect.centerx = x
            #self.can_rect.centery = y
            #self.can_sprite.set_position(self.can_rect.x, self.can_rect.y)

            dist = math.sqrt(abs(dx*dx + dy*dy))
            self.can_sprite.rotation = dx / 10.0 * 45

            if dist > 10:
                self.fallen = True
                self.can_active = False
                if dx > 0:
                    self.can_sprite.rotation = 90
                else:
                    self.can_sprite.rotation = -90

                events.Fire('CanTipped')

                if not self.opened:
                    self.opened = True
                    self.can_sprite.image = self.image_opened
                    self.lid_rect.bottomleft = self.can_rect.bottomleft
                    self.lid_rect.x += dx * 5
                    self.lid_rect.y += dy * 5

            for leaf in self.candidateLeaves:
                if self.collides(leaf.x, leaf.y):
                    leaf.die()

        elif self.lid_active:
            self.lid_rect.center = (x, y)

    def On_LeafSweptOff(self, leaf):
        self.candidateLeaves[leaf] = 1

    def On_LeafDeath(self, leaf):
        if leaf in self.candidateLeaves:
            del self.candidateLeaves[leaf]
Beispiel #44
0
 def __init__(self, pos, **kwargs):
   shape = Rect.createAtOrigin(96, 72)
   
   BasicUnit.__init__(self, pos, shape, name='GOLEM', **kwargs)
   
   self.rangedWeapon = BasicRangedAttack(self, 'boulder', size=(26,26))
Beispiel #45
0
 def generateNeighborDict(self, time):
   """Generate dict of neighbors. A neighbor is any object
   within the bounding box of an objects trajectory during time.
   Objects must be able to collide to be considered neighbors"""
   
   #first, calculate bounding box for each object
   
   boundDict = {}
   
   for i in range(len(self.objectList)):      
     
     p1 = self.objectList[i].pos
     p2 = self.objectList[i].getPosInTime(time)
     
     shape = self.objectList[i].shape
     
     #Get bounding boxes at the 2 positions
     box1 = shape.getBoundingBox().translate(p1)
     box2 = shape.getBoundingBox().translate(p2)
     
     #generate the union between them and store it
     bbox = Rect.union(box1, box2)
     
     boundDict[i] = bbox
               
   d = {}
   
   #TODO: improve, this is O(n^2) for testing
   #TODO: is this only necessary for objects that can stop each other?
   
   for i in range(len(self.objectList)):
     iObj = self.objectList[i]
     iRect = boundDict[i]
     #Check nearby tiles
     tl =  [int(floor(iRect.x1/32)), int(floor(iRect.y1/32))] #top left tile indices
     br = [int(ceil(iRect.x2/32)), int(ceil(iRect.y2/32))] #bottom right tile indices
     for x in range(tl[0], br[0]+1):
       for y in range(tl[1], br[1]+1):
         jObj = self.tileGrid[x][y]
         
         #Following Code copied from below
         
         #this is only applicable for objects which can create
         # collision events
         if not CollisionFilter.canCollide(iObj,jObj):
           continue
         #iRect = boundDict[i]
         jRect = jObj.shape.getBoundingBox().translate(jObj.pos)
         
         if Rect.touches(iRect, jRect):
           if iObj in d:            
             d[iObj].add(jObj)
           else:
             d[iObj] = set([jObj])          
           
           if jObj in d:
             d[jObj].add(iObj)
           else:
             d[jObj] = set([iObj])
       #End of copied code
         
         
     #Check other objects    
     for j in range(i+1, len(self.objectList)):
       
       #iObj = self.objectList[i]
       jObj = self.objectList[j]
       
       #this is only applicable for objects which can create
       # collision events
       if not CollisionFilter.canCollide(iObj,jObj):
         continue
       
       #iRect = boundDict[i]
       jRect = boundDict[j]
       
       if Rect.touches(iRect, jRect):
         
         if iObj in d:            
           d[iObj].add(jObj)
         else:
           d[iObj] = set([jObj])          
         
         if jObj in d:
           d[jObj].add(iObj)
         else:
           d[jObj] = set([iObj])
           
   return d
Beispiel #46
0
    def _drawKeys(self, dc):
        blackPen = wx.Pen('black')
        whiteBrush = wx.Brush('white')
        font = wx.Font(10, wx.FONTFAMILY_SWISS, wx.FONTSTYLE_NORMAL,
                       wx.FONTWEIGHT_NORMAL, False, 'Arial Rounded MT Bold')
        dc.SetFont(font)
        scale = 1

        if self._displayMode == DISPLAY_MODE_DYNAMIC_RESIZE:
            displayRect = self._getDisplayRect()
            print "displayRect: %s" % displayRect
            #           dc.SetMapMode(wx.MM_TEXT)
            dc.SetMapMode(wx.MM_METRIC)
            contentRect = Rect(dc.DeviceToLogicalX(displayRect.x),
                               dc.DeviceToLogicalY(displayRect.y),
                               dc.DeviceToLogicalXRel(displayRect.width),
                               dc.DeviceToLogicalYRel(displayRect.height))
            print "contentRect: %s" % contentRect
            scale = self._getScale(contentRect)
            #           dc.SetPen(wx.Pen('black', 1*scale))
            dc.SetMapMode(wx.MM_TEXT)

        for displayKey in self._displayKeys.values():
            #           if self._isKeySelected(displayKey.handle):
            #               if self.FindFocus() == self:
            #                   # TODO: Generalize this magic number from system
            #                   #       settings.  Currently is Mac selection blue.
            #                   dc.SetPen(wx.Pen('#3e75d6', 2))
            #               else:
            #                   dc.SetPen(wx.Pen('dark grey', 2))
            #               dc.SetBrush(wx.Brush('light grey'))
            #           else:
            #               dc.SetPen(blackPen)
            #               dc.SetBrush(whiteBrush)
            label_rect = deepcopy(displayKey.scaled)
            key_rect = deepcopy(displayKey.scaled)

            # make any necessary adjustments
            if self._displayMode == DISPLAY_MODE_DYNAMIC_RESIZE:
                key_rect = key_rect * scale

            # draw key rectangle
            dc.DrawRoundedRectangleRect(key_rect.Get(), -.075)

            # draw label
            if False:
                label_rect.Deflate(5, 2)
                label = self._getLabel(displayKey)
                if label:
                    dc.SetUserScale(scale, scale)
                    (width, height) = dc.GetTextExtent(label)
                    if width > label_rect.width:
                        # TODO: better wrapping
                        #                   extents = dc.GetPartialTextExtents(label)
                        label = fill(label, 5)
                    dc.DrawLabel(label, label_rect.Get(),
                                 wx.ALIGN_LEFT | wx.ALIGN_BOTTOM)
                    if self._isKeySelected(displayKey.handle):
                        dc.SetPen(blackPen)
                        dc.SetBrush(whiteBrush)
                    dc.SetUserScale(1, 1)
Beispiel #47
0
 def _render_rect(self):
     self._rect = Rect(
         tuple(self.pos),
         (self._image.get_size()[0] / 16, self._image.get_size()[1] / 16))
Beispiel #48
0
def gen_sweep_plane(src_Hs, src_frames):

    max_poly = None  # the bound of the blended image
    bldIm = None  # the blended plane image
    cost_info = None  # An array structure to collect pixel colors of
                      # blended frames
    nframes = len(src_frames)
    o = np.array([[0], [0], [1]])  # origin = zero

    # Get max polygon
    for k in range(nframes):
        cpoly = Rect(Point(0, 0),
                       Point(src_frames[k].shape[1],
                       src_frames[k].shape[0])).get_trans_regpoly(src_Hs[k], 10)
        if(k == 0):
            max_poly = cpoly
        else:
            max_poly = max_poly | cpoly
        #end if
    #end for

    (xmin, xmax, ymin, ymax) = max_poly.boundingBox(0)
    max_rec = Rect(Point(xmin, ymin), Point(xmax, ymax))
    #print "Max: " , max_rec, "W: ", max_rec.width(), " H: ", max_rec.height()

    #alocate costs and count matrixes
    cost_info = np.zeros([int(max_rec.height()),
                        int(max_rec.width()),
                        nframes, 3], dtype=np.int)
    counts = np.zeros([int(max_rec.height()),
                        int(max_rec.width())], dtype=np.int)

    bldIm = cv.CreateMat(int(np.round(max_rec.height())),
                        int(np.round(max_rec.width())), cv.CV_32FC3)
    cv.Zero(bldIm)

    for k in range(nframes):
        cur_H = src_Hs[k]
        cur_o = np.dot(cur_H, o)
        #  translate the warped frame to origin from topleft corner
        disp = np.array([[1, 0, (0 - cur_o[0, 0]) / cur_o[2, 0]],
                        [0, 1, (0 - cur_o[1, 0]) / cur_o[2, 0]],
                        [0, 0, 1]])
        o_H = np.dot(disp, cur_H)
        tpoly = Rect(Point(0, 0),
                       Point(src_frames[k].shape[1],
                             src_frames[k].shape[0])).get_trans_poly(cur_H)
        cpoly = Rect(Point(0, 0),
                       Point(src_frames[k].shape[1],
                       src_frames[k].shape[0])).get_trans_regpoly(cur_H, 10)
        (xmin, xmax, ymin, ymax) = cpoly.boundingBox(0)
        frec = Rect(Point(xmin, ymin), Point(xmax, ymax))

        mask = gen_mask(frec, tpoly)

        #print "Rec: ", frec, "W: ", frec.width(), " H: ", frec.height()

        if k == 0:
            fwarp = cv2.warpPerspective(src_frames[k], o_H,
                            (int(frec.width()), int(frec.height())))
            # get blended image
            blend_views(bldIm, fwarp, mask,
                            frec, max_rec)
            # determine costs
            collect_costs_info(cost_info, counts, fwarp, mask,
                                frec, max_rec, k)
        else:
            fwarp = cv2.warpPerspective(src_frames[k], o_H,
                            (int(frec.width()), int(frec.height())))

            # get blended image
            blend_views(bldIm, fwarp, mask,
                            frec, max_rec)
            # determine costs
            collect_costs_info(cost_info, counts, fwarp, mask,
                                frec, max_rec, k)
        #end if
    #end for

    bldIm = np.asarray(bldIm)

    # Scale blended image to 8U
    bldIm8U = scaleTo8U(bldIm, counts)

    ## Measure Cost
    costs = None
    costs = calculate_costs(cost_info, counts)

    ##return blended image and costs
    return (bldIm8U, costs, max_rec)
Beispiel #49
0
 def get_body_rect(self):
   dy = settings.player_body_adjustment if self.default_angle == 0 else -settings.player_body_adjustment
   return Rect(self.pos[0], self.pos[1] + dy, settings.player_body_width, settings.player_body_height, self.angle)
Beispiel #50
0
  def get_stick_head(self):
    stick_ball_offset = pygame.Vector2(settings.ball_radius, 0)
    offset_rotated = stick_ball_offset.rotate(-self.angle)

    ball_pos = self.get_ball_pos()
    return Rect(ball_pos[0] + offset_rotated[0], ball_pos[1] + offset_rotated[1], settings.stick_head_width, settings.stick_head_height, self.angle)
Beispiel #51
0
 def client_area(self) -> Rect:
     return Rect(self._area.x + 1, self._area.y + 1, self._area.w - 2, self._area.h - 2)
Beispiel #52
0
 def __init__(self, pos, **kwargs):
   shape = Rect.createAtOrigin(32, 28)
   
   BasicUnit.__init__(self, pos, shape, name='MAGE', **kwargs)
   
   self.rangedWeapon = BasicRangedAttack(self, 'fireball')
Beispiel #53
0
def gen_sweep_plane(src_Hs, src_frames):

    max_poly = None  # the bound of the blended image
    bldIm = None  # the blended plane image
    cost_info = None  # An array structure to collect pixel colors of
    # blended frames
    nframes = len(src_frames)
    o = np.array([[0], [0], [1]])  # origin = zero

    # Get max polygon
    for k in range(nframes):
        cpoly = Rect(Point(0, 0),
                     Point(src_frames[k].shape[1],
                           src_frames[k].shape[0])).get_trans_regpoly(
                               src_Hs[k], 10)
        if (k == 0):
            max_poly = cpoly
        else:
            max_poly = max_poly | cpoly
        #end if
    #end for

    (xmin, xmax, ymin, ymax) = max_poly.boundingBox(0)
    max_rec = Rect(Point(xmin, ymin), Point(xmax, ymax))
    #print "Max: " , max_rec, "W: ", max_rec.width(), " H: ", max_rec.height()

    #alocate costs and count matrixes
    cost_info = np.zeros(
        [int(max_rec.height()),
         int(max_rec.width()), nframes, 3],
        dtype=np.int)
    counts = np.zeros(
        [int(max_rec.height()), int(max_rec.width())], dtype=np.int)

    bldIm = cv.CreateMat(int(np.round(max_rec.height())),
                         int(np.round(max_rec.width())), cv.CV_32FC3)
    cv.Zero(bldIm)

    for k in range(nframes):
        cur_H = src_Hs[k]
        cur_o = np.dot(cur_H, o)
        #  translate the warped frame to origin from topleft corner
        disp = np.array([[1, 0, (0 - cur_o[0, 0]) / cur_o[2, 0]],
                         [0, 1, (0 - cur_o[1, 0]) / cur_o[2, 0]], [0, 0, 1]])
        o_H = np.dot(disp, cur_H)
        tpoly = Rect(Point(0, 0),
                     Point(src_frames[k].shape[1],
                           src_frames[k].shape[0])).get_trans_poly(cur_H)
        cpoly = Rect(Point(0, 0),
                     Point(src_frames[k].shape[1],
                           src_frames[k].shape[0])).get_trans_regpoly(
                               cur_H, 10)
        (xmin, xmax, ymin, ymax) = cpoly.boundingBox(0)
        frec = Rect(Point(xmin, ymin), Point(xmax, ymax))

        mask = gen_mask(frec, tpoly)

        #print "Rec: ", frec, "W: ", frec.width(), " H: ", frec.height()

        if k == 0:
            fwarp = cv2.warpPerspective(
                src_frames[k], o_H, (int(frec.width()), int(frec.height())))
            # get blended image
            blend_views(bldIm, fwarp, mask, frec, max_rec)
            # determine costs
            collect_costs_info(cost_info, counts, fwarp, mask, frec, max_rec,
                               k)
        else:
            fwarp = cv2.warpPerspective(
                src_frames[k], o_H, (int(frec.width()), int(frec.height())))

            # get blended image
            blend_views(bldIm, fwarp, mask, frec, max_rec)
            # determine costs
            collect_costs_info(cost_info, counts, fwarp, mask, frec, max_rec,
                               k)
        #end if
    #end for

    bldIm = np.asarray(bldIm)

    # Scale blended image to 8U
    bldIm8U = scaleTo8U(bldIm, counts)

    ## Measure Cost
    costs = None
    costs = calculate_costs(cost_info, counts)

    ##return blended image and costs
    return (bldIm8U, costs, max_rec)
Beispiel #54
0
 def __init__(self, pos, **kwargs):
   shape = Rect.createAtOrigin(32, 26)
   
   BasicUnit.__init__(self, pos, shape, name='THIEF', **kwargs)
   
   self.rangedWeapon = BasicRangedAttack(self, 'knife', size=(12,12))
Beispiel #55
0
  def generateCollisionList(self, time):
    """Generate a dictionary of collisions between object
    that are allowed to generate collision events
    TODO: FINISH DOC HERE
    
    only considers collisions that happen <= time"""
    
    #d = {}
    l = []
    
    #TODO: improve, this is O(n^2) for testing
    
    for i in range(len(self.objectList)):
      
      objI = self.objectList[i]
      
      
      #create bounding box of trajectory and test for collision with appropriate tiles
      p1 = objI.pos
      p2 = objI.getPosInTime(time)     
      shape = self.objectList[i].shape      
      #Get bounding boxes at the 2 positions
      box1 = shape.getBoundingBox().translate(p1)
      box2 = shape.getBoundingBox().translate(p2)     
      #generate the union between them and store it
      bbox = Rect.union(box1, box2)
      
      tl =  [int(floor(bbox.x1/32)), int(floor(bbox.y1/32))] #top left tile indices
      br = [int(ceil(bbox.x2/32)), int(ceil(bbox.y2/32))] #bottom right tile indices
      #print tl[0], br[0]
      for x in range(tl[0], br[0]+1):
        for y in range(tl[1], br[1]+1):
          objJ = self.tileGrid[x][y]
          #the following is copied from below
          if not CollisionFilter.canCollide(objI, objJ):
            continue
          #Note, the shapes are at the origin, so we have to translate them
          # to the objects current position
          s1 = objI.shape.translate(objI.getPos())
          s1vel = objI.vel
          
          s2 = objJ.shape.translate(objJ.getPos())
          s2vel = objJ.vel
  
          #TODO: this will always return none!!!
          colInfo = getCollisionInfo(s1,s1vel,s2,s2vel)
                  
          if colInfo is not None:          
            
            #only consider events <= time
            colTime, objIStops, objJStops = colInfo         
            
            if colTime <= time:
              #print colInfo
              
              #if objI not in d:
              #  d[objI] = set([()])
              
              l.append((colTime, objI, objIStops,objJ,objJStops))
        ####end of copied code
      
      #check collision with other objects      
      for j in range(i+1, len(self.objectList)):
        
        #objI = self.objectList[i]
        objJ = self.objectList[j]
        
        
        #If the objects can't collide, don't even bother 
        # comparing them
        if not CollisionFilter.canCollide(objI, objJ):
          continue
        
        #Note, the shapes are at the origin, so we have to translate them
        # to the objects current position
        s1 = objI.shape.translate(objI.getPos())
        s1vel = objI.vel
        
        s2 = objJ.shape.translate(objJ.getPos())
        s2vel = objJ.vel

        #TODO: this will always return none!!!
        colInfo = getCollisionInfo(s1,s1vel,s2,s2vel)
                
        if colInfo is not None:          
          
          #only consider events <= time
          colTime, objIStops, objJStops = colInfo         
          
          if colTime <= time:
            #print colInfo
            
            #if objI not in d:
            #  d[objI] = set([()])
            
            l.append((colTime, objI, objIStops,objJ,objJStops))

    return l   
Beispiel #56
0
 def __init__(self, pos, **kwargs):
   shape = Rect.createAtOrigin(30, 26)
   
   BasicUnit.__init__(self, pos, shape, name='SKELETON', **kwargs)
   
   self.rangedWeapon = BasicRangedAttack(self, 'bone', size=(14,14))
Beispiel #57
0
 def __init__(self, pos, **kwargs):
   shape = Rect.createAtOrigin(20, 20)
   
   BasicUnit.__init__(self, pos, shape, name='ELF', **kwargs)
   
   self.rangedWeapon = BasicRangedAttack(self, 'rock',size=(12,12))
Beispiel #58
0
 def __init__(self, pos, **kwargs):
   shape = Rect.createAtOrigin(32, 32)
   
   BasicUnit.__init__(self, pos, shape, name='ORC', **kwargs)
   
   self.rangedWeapon = KnifeThrower(self)
Beispiel #59
0
 def get_rect(self):
     return Rect(self.x, self.y, settings.goalie_width,
                 settings.goalie_height)
Beispiel #60
0
 def helper(name):
     room = Rect(2, 2, 10, 10)
     return get_monster(0, 0, game_map, room, name, [])[0]