Exemplo n.º 1
0
    def endCapture(self):
        if (self.mBrushBehavior != BrushBehavior.Capture):
            return
        self.mBrushBehavior = BrushBehavior.Free
        tileLayer = self.currentTileLayer()
        # Intersect with the layer and translate to layer coordinates
        captured = self.capturedArea()
        captured &= QRect(tileLayer.x(), tileLayer.y(),
                          tileLayer.width(), tileLayer.height())
        if (captured.isValid()):
            captured.translate(-tileLayer.x(), -tileLayer.y())
            map = tileLayer.map()
            capture = tileLayer.copy(captured)
            
            stamp = Map(map.orientation(),
                             capture.width(),
                             capture.height(),
                             map.tileWidth(),
                             map.tileHeight())
            # Add tileset references to map
            for tileset in capture.usedTilesets():
                stamp.addTileset(tileset)

            stamp.addLayer(capture)

            self.stampCaptured.emit(TileStamp(stamp))
        else:
            self.updatePreview()
Exemplo n.º 2
0
    def get_next_location_details(self, direction, x, y):
        """
        params:
        current user's direction (relative to north 0~360d), current x & y pos
        return:
        distance to next loc, direction to next loc (relative to user) & next loc's node
        """
        nextLocNode = self.get_next_location(x, y)
        if self.nextLoc and self.nextLoc['nodeName'] in self.reachedLoc:
            self.prevLoc = self.nextLoc
        self.nextLoc = nextLocNode
        dist = Map.get_distance(nextLocNode["x"], x, nextLocNode["y"], y)

        northAt = Map.get_north_at(self.building, self.level)
        userDir = direction + northAt  # relative to map
        userDir = userDir % 360
        movingDir = Map.get_direction(x, nextLocNode["x"],
                                      y, nextLocNode["y"])  # relative to map
        relativeDir = movingDir - userDir
        # if relativeDir > 0, it's at user's rhs, else lhs
        if relativeDir > 180:
            relativeDir -= 360
        if relativeDir < -180:
            relativeDir += 360

        return relativeDir, dist, nextLocNode
Exemplo n.º 3
0
	def build(self):
		#create window
		root = Widget()
		root.size = Window.size
		root.center = Window.center

		#create map
		Map.tileSet = TileFactory
		board = Map(size=(504,504))
		root.add_widget(board.getDisplayRoot())

		#add starting tile
		tile_fact = TileFactory()
		for i in range(1):
			btn = tile_fact.newTile(board)
			board.addPiece(btn,(i*126,i*126))

		#create players
		CurrentTile.map = board
		CurrentTile.tile_size = TileFactory.size

		playerTile = CurrentTile()
	
		newTile = tile_fact.newTile(board)
		root.add_widget(playerTile)

		playerTile.resetTile(newTile)

		return root
Exemplo n.º 4
0
class Game(object):

    def __init__(self):
        pygame.init()
        self.window = pygame.display.set_mode((640, 480))
        self.player = Player(x=100, y=100, width=640, height=480)
        self.plupp = Plupp(window_width=640, window_height=480)
        self.clock = pygame.time.Clock()
        self.map = Map()

        while True:
            CollisionHandler.handle_plupp_collisions(player=self.player, plupp=self.plupp)
            CollisionHandler.handle_player_collisions(player=self.player, map=self.map)

            EventHandler.handle_events(player=self.player, plupp=self.plupp)
            self.clock.tick(15)
            self.update()
            self.draw()

    def update(self):
        self.player.update()

    def draw(self):
        self.window.fill((0, 0, 255))
        self.player.draw(self.window)
        self.plupp.draw(self.window)
        self.map.draw(self.window)
        pygame.display.flip()
Exemplo n.º 5
0
class GameState:
    def __init__(self):
        self.controller = Controller(self)
        
        self.side = PlayerSide(self)
        self.map = Map(self)
        self.gui = GameStateGUI(self)
    
    def handleEvents(self,events):
        self.controller.handleEvents(events)
    
    def tick(self):
        self.map.tick()
        self.side.tick()
    
    def blit(self,screen):
        screen.fill((0,0,0))
        self.map.blit(screen)
        self.side.blit(screen)
        
        self.gui.blit(screen)
        
        if self.controller.action[0] == PLACEOBJECT:
            screen.blit(R.IMAGES[R.buildings[self.controller.action[1]]["image"]],(pygame.mouse.get_pos()[0]/20*20+self.map.offset[0]%20,
                                                                                   pygame.mouse.get_pos()[1]/20*20+self.map.offset[1]%20))
Exemplo n.º 6
0
def test():
    the_map = Map()
    tic = time.clock()
    the_map.discretize_map()
    print time.clock() - tic
    #obstacle = Polygon([(40,15), (45,15), (45,20), (40,20)], safety_region_length=4.0)
    #the_map.add_obstacles([obstacle])

    tend = 10
    dT = 1
    h  = 0.05
    N  = int(tend/h)  + 1
    N2 = int(tend/dT) + 1

    x0 = np.array([10, 10, 0.0, 3.0, 0, 0])
    xg = np.array([50, 50, 0])

    myDynWnd = DynamicWindow(dT, N2)

    v = Vessel(x0, xg, h, dT, N, [myDynWnd], is_main_vessel=True, vesseltype='viknes')
    v.current_goal = np.array([50, 50])

    world = World([v], the_map)

    myDynWnd.the_world = world
    
    world.update_world(0,0)

    fig = plt.figure()
    ax  = fig.add_subplot(111, aspect='equal', autoscale_on=False,
                          xlim=(-10, 160), ylim=(-10, 160))
    
    world.visualize(ax, 0, 0)
    
    plt.show()
Exemplo n.º 7
0
    def update_pos_by_dist_and_dir(self, distance, direction):
        """
        params:
        distance - distance went through
        direction - angles relative to the west (clockwise)
        """
        dirRelativeNorth = Map.get_direction_relative_north(self.building, self.level, direction)
        northAt = Map.get_north_at(self.building, self.level)
        userDir = dirRelativeNorth + northAt  # relative to map
        userDir = userDir % 360
        if not self.nextLoc:
            self.nextLoc = self.get_next_location(self.pos[0], self.pos[1])
        movingDir = Map.get_direction(self.pos[0], self.nextLoc["x"],
                                      self.pos[1], self.nextLoc["y"])  # relative to map
        relativeDir = movingDir - userDir
        # if relativeDir > 0, it's at user's rhs, else lhs
        if relativeDir > 180:
            relativeDir -= 360
        if relativeDir < -180:
            relativeDir += 360
        (x, y, newDir) = Map.get_direction_details(self.building, self.level, distance, direction + relativeDir)

        vec1X = self.pos[0] - float(self.nextLoc["x"])
        vec1Y = self.pos[1] - float(self.nextLoc["y"])
        vec2X = self.pos[0] + x - float(self.nextLoc["x"])
        vec2Y = self.pos[1] + y - float(self.nextLoc["y"])
        isSameDirection = (vec1X * vec2X + vec1Y * vec2Y > 0)
        isReachNextLoc = self.is_reach_node(self.nextLoc, self.pos[0] + x, self.pos[1] + y)
        isWentPass = not isSameDirection and not isReachNextLoc
        if isWentPass:
            self.reachedLoc.append(self.nextLoc["nodeName"])
        self.update_pos(x, y)
Exemplo n.º 8
0
def testParticleFilter():
    print 'Testing the ParticleFilter class ...'

    # Read map
    map = Map()
    map.readMap('../data/map/wean.dat')

    # basic tests
    filter = ParticleFilter()
    filter.initParticles(map)

    X = [Particle(0,0,0, 0.1), Particle(0,0,0, 0.1), Particle(0,0,0, 0.1)]
  
    print 'X after resampling', filter._resample(X)

    # test for update function
    pos = filter._update((5.0, 6.0, 0.0), (1, 2, 0.0), (2, 2, 0.0))
    print pos # this should print something close to (6, 6, 0)

    '''
    ind = weighted_choice([0.4, 0, 0])
    if ind != 0:
        print 'FAILED weighted_choice test.'

    ind = weighted_choice([0.4, .6, 0.2])
    print 'ind = ', ind
    '''

    return
Exemplo n.º 9
0
 def test_all_trips_3(self):
     map = Map(1, 2, 3)
     map.append(1, 3, 1)
     map.append(3, 1, 1)
     accept_func = lambda step, distance: True
     trim_func   = lambda step, distance: step > 5
     self.assertEqual(map.all_trips(1, 3, accept_func, trim_func), 3)
class TestMainSimulation(unittest.TestCase):
    def setUp(self):
        self.map=Map('data/londontubes.txt')
        self.map.initialise_map()
    def test_create_random_target_stations_returns_correct_number(self):
        self.target_stations=main.create_random_target_stations(self.map, 800)
        self.assertEquals(800, len(self.target_stations))
Exemplo n.º 11
0
def new_map():
    map = Map(join(MAIN_PATH, 'templates', 'Seoul_districts.svg'))
    if request.method == 'POST':
        req_dict = json.loads(request.data)
        print(req_dict)
        map.change_color(req_dict)
        return redirect('/map')
Exemplo n.º 12
0
def do_upload_from_app():
  picture = request.forms.get('picture')
  lat = request.forms.get('latitude')
  lng = request.forms.get('longitude')

  raw = decodestring(picture)
  now = datetime.now()
  date_filename = now.strftime("%Y%m%d-%H%M%S") + '.jpg'
  print date_filename
  grid_db = connection['grid_files']
  fs = gridfs.GridFS(grid_db)
  fs.put(raw, filename=date_filename)
  # Insert the filename and other data in the pictures db
  hack_db = connection['hackathon']
  hack_db.pictures.insert_one(
      {'filename': date_filename,
       'datetime': now,
       'latitude': lat,
       'longitude': lng,
       'disaster': 0}
  )
  m = Map(hack_db)
  map_id = m.get_map_id(now, [float(lng), float(lat)])
  hack_db.pictures.update_one({"filename": date_filename}, {"$set": {"disaster": map_id}})
  # Get the image back out
  image = fs.get_last_version(filename=date_filename)
  bottle.response.content_type = 'image/jpeg'
  return image
Exemplo n.º 13
0
def enter():
    global timer, player, map, Player_missile, FirstEnemys, SecondEnemys, enemy_missile, enemy_explosion, bomb, bomb_explosion, item, boss, boss_missile
    global angle, ui
    global score
    score = Score()
    timer = Timer()
    player = Player()
    player.kind = 2
    map = Map()
    map.kind = 2

    ui = UI()
    bomb = []
    FirstEnemys = []
    SecondEnemys = []
    Player_missile = []
    enemy_missile = []
    enemy_explosion = []
    bomb_explosion = []
    item = []
    boss = []
    boss_missile = [Boss_missile(10,10 ) for i in range(72)]
    for member in boss_missile:
        angle += 10
        if angle >360 :
            member.y +=400
        member.angle = angle
Exemplo n.º 14
0
class Game:
    def __init__(self, config_filename):
        data = json.load(open(config_filename, 'r'))

        # init map
        self.map = Map(data)

        # init player
        self.player = Player(data['player'])

    def get_current_location_name(self):
        return self.map.get_current_location_name()

    def get_action(self):
        return self.get_action_dic().keys()

    def get_action_dic(self):
        return self.map.get_current_action()

    def play_action(self, action):
        action_dic = self.get_action_dic()
        action_dic[action](self.player)

    def get_player(self):
        return self.player

    def get_status(self):
        status = self.player.get_status()
        status['current_location'] = self.get_current_location_name()
        return status
Exemplo n.º 15
0
 def read(self, fileName):
     uncompressed = QByteArray()
     # Read data
     f = QFile(fileName)
     if (f.open(QIODevice.ReadOnly)) :
         compressed = f.readAll()
         f.close()
         uncompressed, length = decompress(compressed, 48 * 48)
     
     # Check the data
     if (uncompressed.count() != 48 * 48) :
         self.mError = self.tr("This is not a valid Droidcraft map file!")
         return None
     
     uncompressed = uncompressed.data()
     # Build 48 x 48 map
     # Create a Map -> Create a Tileset -> Add Tileset to map
     # -> Create a TileLayer -> Fill layer -> Add TileLayer to Map
     map = Map(Map.Orientation.Orthogonal, 48, 48, 32, 32)
     mapTileset = Tileset.create("tileset", 32, 32)
     mapTileset.loadFromImage(QImage(":/tileset.png"), "tileset.png")
     map.addTileset(mapTileset)
     # Fill layer
     mapLayer =  TileLayer("map", 0, 0, 48, 48)
     # Load
     for i in range(0, 48 * 48):
         tileFile = int(uncompressed[i])&0xff
         y = int(i / 48)
         x = i - (48 * y)
         tile = mapTileset.tileAt(tileFile)
         mapLayer.setCell(x, y, Cell(tile))
     
     map.addLayer(mapLayer)
     return map
Exemplo n.º 16
0
def load_binary(sender, instance, **kwargs):
    if not instance.stage_data:
        file = instance.stage_file
        print instance._get_upload_path(file.name)
        map = Map(file.read(), True)
        instance.title = map.get_name()
        instance.stage_data = map.dump_to_json()
        print instance.stage_data
Exemplo n.º 17
0
	def test_existing_map(self):
		db = MongoClient().geo_example
		db.drop_collection('disasters')
		db.disasters.create_index([("loc", GEOSPHERE)])
		result = db.disasters.insert_many([{"loc": { 'type': "Point", 'coordinates': [ -73, 40 ] }, "name": "blah1.44", "start_datetime": datetime.now()}])		
		print result.inserted_ids
		m = Map(db)
		m.get_map_id(datetime.now(), [0, 0])
Exemplo n.º 18
0
class PyAction:
    def __init__(self, type=1):
        pygame.init()
        screen = pygame.display.set_mode(SCR_RECT.size)
        pygame.display.set_caption("ROCKMAN WORLD 5")
        
        # load images
        Block.images = split_image(load_image("plute_map.png"), 16, 16, 16)
        Block.image = Block.images[0] #初期化

        # music
#        pygame.mixer.music.load("data/mars.nsf")
#        pygame.mixer.music.play(-1) 
        
        # loading map
        self.map = Map("data/plute.map")
        
        # main loop
        clock = pygame.time.Clock()
        while True:
            clock.tick(60)
            self.update()
            self.draw(screen)
            pygame.display.update()
            self.key_handler()

    def update(self):
        self.map.update()
    
    def draw(self, screen):
        self.map.draw()
        
        # draw part of map by offset
        offsetx, offsety = self.map.calc_offset()
        
        # 端ではスクロールしない
        if offsetx < 0:
            offsetx = 0
        elif offsetx > self.map.width - SCR_RECT.width:
            offsetx = self.map.width - SCR_RECT.width
        
        if offsety < 0:
            offsety = 0
        elif offsety > self.map.height - SCR_RECT.height:
            offsety = self.map.height - SCR_RECT.height
        
        # マップの一部を画面に描画
        screen.blit(self.map.surface, (0,0), (offsetx, offsety, SCR_RECT.width, SCR_RECT.height))
    
    def key_handler(self):
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == KEYDOWN and event.key == K_ESCAPE:
                pygame.quit()
                sys.exit()
Exemplo n.º 19
0
def enter():
    global map,pica,enemy1,dino
    open_canvas(800,400)
    game_framework.reset_time()
    map = Map()
    pica = Pica()
    map.set_center_object(pica)
    pica.set_background(map)
    enemy1 = Enemy()
Exemplo n.º 20
0
class WorldScreen(Screen):
    """The main game screen with a world to wander around."""

    def __init__(self, map_name):
        Screen.__init__(self)
        self.load_screen = LoadScreen()
        self.load_screen.draw()
        self.camera = pygame.Rect((0,0), CAMERA_SIZE)
        self.map = Map(map_name)
        self.party = PartyManager(self)
        self.npcs = NPCManager(self)
        self.gui = StatsWindow(self.party.sprites)
        self.party.add("hero")
        self.npcs.add("npc")
        self.dialog_text = "Sample dialog text."
        self.map.scroll(self.camera, self.party.chars['hero'])

    def add_sprites(self):
        self.chars = pygame.sprite.Group([
            self.party.sprites ])
        self.all_sprites = pygame.sprite.OrderedUpdates([
            self.map.layers['terrain'],
            self.chars,
            self.map.layers['foreground'],
            self.gui ])

        self.layers = pygame.sprite.LayeredDirty()
        for sprite in self.all_sprites:
            self.layers.add(sprite)
        # critical line to make the npc appear!
        # only took 50 mins to find this!    
        self.layers.add(self.npcs.sprites)

    def draw(self):
        """Draws the sprites to the screen and updates the window."""

        self.layers.update()
        rects = self.layers.draw(self.window)
        pygame.display.update(rects)

        if random.random() < 0.01:
            sounds.sounds.FEAR.play()            

        if random.random() < 0.003:
            sounds.sounds.BABY.play()            


    def destroy(self):
        """Destroy the current screen."""

        for sprite in self.all_sprites:
            sprite.kill()

        self.map = None
        self.party = None
        self.gui = None
Exemplo n.º 21
0
    def test_map_with_obstaces(self):
        map = Map(10,10)
        map.set_obstacles([
            P(2,2),
            P(5,5),
            P(5,6)
        ])

        self.assertTrue(map.is_free(P(0,0)))
        self.assertFalse(map.is_free(P(2,2)))
Exemplo n.º 22
0
    def render(screen, width, height, gamestate, selected_id, host, port):
        raycaster = Raycaster(gamestate["players"], gamestate["walls"])
        raycaster.update()
        map_size = raycaster.get_map_size() + 1.0

        if selected_id == 0:
            for player in gamestate["players"]:
                Game.render_vision(raycaster, player, screen, width, height, map_size, len(gamestate["players"]))
        elif selected_id > 0 and selected_id - 1 < len(gamestate["players"]):
            Game.render_vision(raycaster, gamestate["players"][selected_id - 1], screen, width, height, map_size,
                               len(gamestate["players"]))

        Map.render(gamestate["walls"], screen, width, height, map_size)
        for p in gamestate["players"]:
            Player.render(p, raycaster, screen, width, height, map_size)
        for projectile in gamestate["projectiles"]:
            Projectile.render(projectile, screen, width, height, map_size)
        for p in gamestate["players"]:
            Player.render_font(p, screen, width, height, map_size)


        myfont = pygame.font.SysFont("Arial", 22)
        label = myfont.render("Ticks remaining: " + str(gamestate["remaining_ticks"]), 1, (255, 255, 255))
        s = pygame.Surface((label.get_width() + 20, label.get_height() + 20), pygame.SRCALPHA)  # per-pixel alpha
        s.fill((45, 45, 45, 200))
        screen.blit(s, (width // 2 - label.get_width() // 2 - 10, 0))
        screen.blit(label, (width // 2 - label.get_width() // 2, 10))

        myfont = pygame.font.SysFont("Arial", 16)
        label = myfont.render("test", 1, (255, 255, 255))
        line_height = label.get_height()
        myfont = pygame.font.SysFont("Arial", 32)
        label = myfont.render("Ranking-----", 1, (255, 255, 255))
        line_width = label.get_width()
        s = pygame.Surface((line_width + 20, line_height * (len(gamestate["ranking"]) + 2) + 40), pygame.SRCALPHA)  # per-pixel alpha
        s.fill((45, 45, 45, 200))
        screen.blit(s, (0, 0))

        myfont = pygame.font.SysFont("Arial", 32)
        label = myfont.render("Ranking", 1, (255, 255, 255))
        screen.blit(label, (10, 10))
        myfont = pygame.font.SysFont("Arial", 16)
        i = 2
        sorted_x = sorted(gamestate["ranking"].items(), key=operator.itemgetter(1), reverse=True)
        for key, value in sorted_x:
            label = myfont.render(key + ": " + str(value), 1, (255, 255, 255))
            screen.blit(label, (10, 10 + label.get_height() * 1.1 * i))
            i += 1

        myfont = pygame.font.SysFont("Arial", 32)
        label = myfont.render(host + ":" + str(port), 1, (255, 255, 0))
        s = pygame.Surface((label.get_width() + 20, label.get_height() + 20), pygame.SRCALPHA)  # per-pixel alpha
        s.fill((45, 45, 45, 200))
        screen.blit(s, (width // 2 - label.get_width() // 2 - 10, height - label.get_height() - 20))
        screen.blit(label, (width // 2 - label.get_width() // 2, height - label.get_height() - 10))
Exemplo n.º 23
0
def input(graph):
    node_list = set()
    edge_list = []
    for i in graph:
        node_list.add(i[0])
        node_list.add(i[1])
        edge_list.append([i[0], i[1], int(i[2:])])
    map = Map(*node_list)
    for i in edge_list:
        map.append(*i)
    return map
Exemplo n.º 24
0
 def get(self):
   try:
     name = re.sub("/get/", "", self.request.path)
     key = db.Key(name)
     map = Map()
     map = map.get(key)
     result = urllib.urlencode([('result', str(map.text)),
                                ('key', str(map.key()))])
   except Exception, error:
     message = 'Could not find map: ' + str(error)
     result = urllib.urlencode([('error', message)])
Exemplo n.º 25
0
def editMap():
    global mapEditor, ctrlLayer, mapLayer
    mapfile = "./map/%s"%(editMapPanel.listBox.selectedtext())
    ctrlLayer = mapEditor
    mapEditor.mapfile = mapfile
    mapLayer = Map(mapwidth,mapheight)
    mapEditor.map = mapLayer
    mapLayer.read(mapfile)
    loader = Loader()
    loader.load(images["loadmap"],screen,mapLayer.load,\
        [images["bar"].subsurface(0,0,barlength,barheight),(barx,bary)])
    ctrlLayer.minimap = mapLayer.minimap
Exemplo n.º 26
0
 def test_sum_distance(self):
     map = Map(1, 2, 3)
     map.append(1, 2, 1)
     map.append(2, 3, 2)
     map.append(3, 1, 4)
     self.assertEqual(map.sum_distance(1, 2), 1)
     self.assertEqual(map.sum_distance(1, 2, 3), 3)
     self.assertEqual(map.sum_distance(1, 2, 3, 1), 7)
     self.assertEqual(map.sum_distance(2, 1), 'NO SUCH ROUTE')
Exemplo n.º 27
0
Arquivo: world.py Projeto: m64/PEG
 def loadMap(self, map_name, filename):
     """Loads a map and stores it under the given name in the maps list.
        @type map_name: String
        @param map_name: The name of the map to load
        @type filename: String
        @param filename: File which contains the map to be loaded
        @return: None"""
     if not map_name in self.maps:
         map = Map(self.engine, self.data)
         self.maps[map_name] = map
         map.load(filename)
     else:
         self.setActiveMap(map_name)
Exemplo n.º 28
0
    def loadMap(self, mapname, filename):
        """Loads a map an stores it under the given name in the maps list.
        """
        map = Map(self.engine, self.data)
        
        """Need to set active map before we load it because the map 
        loader uses call backs that expect to find an active map. 
        This needs to be reworked.
        """
        self.maps[mapname] = map
        self.setActiveMap(mapname)

        map.load(filename)
Exemplo n.º 29
0
def main():

    print "Loading ", MAPFILE
    m = Map(MAPFILE)

    print "Loading Path library"
    p = Path()

    #Find list of peaks to start searching from
    print "Finding peaks..."
    peaks = p.find_peaks(m)

    print "Searching for best ski slope..."
    maxDict = dict.fromkeys(["startPoint","totalDrop","pathLen","dropTuple","dirTuple"], None)
    
    #Find peak with greatest path
    for pt in peaks:
        
        #Get list of drops, list of directions
        tempDropTuple, tempDirTuple = p.find_longest_path( m, pt )
        
        tempTotalDrop = sum(tempDropTuple) #Calc total drop from list
        tempPathLength = len(tempDirTuple) + 1 #Calc length of path

        #Debugging
        #print "------"
        #print "pathLen="+str(tempPathLength)
        #print "totalDrop="+str(tempTotalDrop)
        #print "startPt="+str(pt)
        #print "startHeight="+str(m.get_height(pt))
        #print "dropTuple="+str(tempDropTuple)
        #print "dirTuple="+str(tempDirTuple)
        #print "path="+str(m.get_path(pt, tempDirTuple))

        #If a new maximum is found, update record
        if maxDict["pathLen"] <= tempPathLength and maxDict["totalDrop"] < tempTotalDrop:
            maxDict["startPoint"] = pt
            maxDict["totalDrop"] = tempTotalDrop
            maxDict["pathLen"] = len(tempDirTuple) + 1
            maxDict["dropTuple"] = tempDropTuple
            maxDict["dirTuple"] = tempDirTuple
        
    print "Done.\n"
    maxDict["path"] = m.get_path( maxDict["startPoint"], maxDict["dirTuple"] )

    #Print results
    print 'Results:'
    for key in maxDict:
        print key, ':', maxDict[key]
    
    return
Exemplo n.º 30
0
class Area:
    # Area object
    def __init__(self):
        self.name = ""
        self.map = Map()

    def parsing(self, value):
        if "name" in value:
            self.name = value["name"]
        if "map" in value:
            self.map.parsing(value["map"])

    def __str__(self):
        return "Name : %s ; Map : %s" % (self.name, self.map)
Exemplo n.º 31
0
 def __init__(self):
     self.car_storage = {}
     self.map = Map()
Exemplo n.º 32
0
class GameScreen(Screen):

    def __init__(self):
        self.subscreen = GameSubScreen.START_MENU
        self.map = Map(MAP_FOLDER + CONFIG.CURRENT_LEVEL + '.tcm')  # Stores the current map
        self.player = Player(len(self.map.layers[4].tiles[0]), 32)
        self.bot = Bot(len(self.map.layers[4].tiles[0]) + 32, 32)
        self.in_game_menu_bg = None

        # In game menu elements
        button_margin = 50
        self.in_game_resume_button = Button(96, CONFIG.WINDOW_HEIGHT - 96 - 3 * button_margin, label='RESUME')
        self.in_game_save_button = Button(96, CONFIG.WINDOW_HEIGHT - 96 - 2 * button_margin, label='SAVE GAME')
        self.in_game_exit_button = Button(96, CONFIG.WINDOW_HEIGHT - 96 - button_margin, label='EXIT')

        if CONFIG.SAVE_GAME != '':
            load_save_game(self)
            CONFIG.SAVE_GAME = ''

    def display_start_menu(self, screen):
        self.subscreen = GameSubScreen.GAME
        return Screens.GAME

    def display_in_game_menu(self, screen):
        screen.blit(self.in_game_menu_bg, (0, 0))
        self.in_game_resume_button.display(screen)
        self.in_game_save_button.display(screen)
        self.in_game_exit_button.display(screen)

        if self.in_game_exit_button.state == ButtonState.RELEASED:
            return Screens.MAIN_MENU
        elif self.in_game_resume_button.state == ButtonState.RELEASED:
            self.subscreen = GameSubScreen.GAME
            return Screens.GAME
        elif self.in_game_save_button.state == ButtonState.RELEASED:
            save_game(self)
            return Screens.GAME
        return Screens.GAME

    def display_game(self, screen):
        self.map.draw(screen, self.player, 0, 5)
        self.bot.display(screen, self.map, self.player)
        self.player.display(screen, self.map)
        self.map.draw(screen, self.player, 5, 8)

        if pygame.key.get_pressed()[pygame.locals.K_ESCAPE]:

            # Save game screenshot as a background
            pygame.image.save(screen, IMAGE_FOLDER + 'screenshot.png')
            self.in_game_menu_bg = pygame.image.load(IMAGE_FOLDER + 'screenshot.png')
            self.in_game_menu_bg.set_alpha(150)

            self.subscreen = GameSubScreen.IN_GAME_MENU
            return Screens.GAME
        return Screens.GAME

    def display(self, screen):
        if self.subscreen == GameSubScreen.GAME:
            return self.display_game(screen)
        elif self.subscreen == GameSubScreen.START_MENU:
            return self.display_start_menu(screen)
        else:
            return self.display_in_game_menu(screen)
        return Screens.GAME
Exemplo n.º 33
0
class Core:
    def __init__(self):
        user_dir = "%s%s.kismon%s" % (os.path.expanduser("~"), os.sep, os.sep)
        if not os.path.isdir(user_dir):
            print("Creating Kismon user directory %s" % user_dir)
            os.mkdir(user_dir)
        config_file = "%skismon.conf" % user_dir
        self.config_handler = Config(config_file)
        self.config_handler.read()
        self.config = self.config_handler.config

        self.sources = {}
        self.crypt_cache = {}
        self.networks = Networks(self.config)
        self.client_threads = {}
        self.init_client_threads()
        self.tracks = Tracks("%stracks.json" % user_dir)
        self.tracks.load()

        if "--disable-map" in sys.argv:
            self.map_error = "--disable-map used"
        else:
            self.map_error = check_osmgpsmap()

        if self.map_error is not None:
            self.map_error = "%s\nMap disabled" % self.map_error
            print(self.map_error, "\n")

        self.init_map()

        self.main_window = MainWindow(self.config, self.client_start,
                                      self.client_stop, self.map,
                                      self.networks, self.sources, self.tracks,
                                      self.client_threads)
        self.main_window.log_list.add("Kismon", "started")
        if self.map_error is not None:
            self.main_window.log_list.add("Kismon", self.map_error)

        self.networks_file = "%snetworks.json" % user_dir
        if os.path.isfile(self.networks_file):
            try:
                self.networks.load(self.networks_file)
            except:
                error = sys.exc_info()[1]
                print(error)
                dialog_message = "Could not read the networks file '%s':\n%s\n\nDo you want to continue?" % (
                    self.networks_file, error)
                dialog = Gtk.MessageDialog(self.main_window.gtkwin,
                                           Gtk.DialogFlags.DESTROY_WITH_PARENT,
                                           Gtk.MessageType.ERROR,
                                           Gtk.ButtonsType.YES_NO,
                                           dialog_message)

                def dialog_response(dialog, response_id):
                    self.dialog_response = response_id

                dialog.connect("response", dialog_response)
                dialog.run()
                dialog.destroy()
                if self.dialog_response == -9:
                    print("exit")
                    self.clients_stop()
                    self.main_window.gtkwin = None
                    return
        self.networks.set_autosave(self.config["networks"]["autosave"],
                                   self.networks_file,
                                   self.main_window.log_list.add)

        if self.map is not None:
            self.networks.notify_add_list["map"] = self.add_network_to_map
            self.networks.notify_remove_list["map"] = self.map.remove_marker
            GLib.timeout_add(100, self.map.set_last_from_config)

        self.main_window.network_list.crypt_cache = self.crypt_cache

        GLib.timeout_add(500, self.queues_handler)
        GLib.timeout_add(300, self.queues_handler_networks)
        GLib.idle_add(self.networks.apply_filters)

    def init_map(self):
        if self.map_error is not None:
            self.map = None
        else:
            try:
                from .map import Map
            except SystemError:
                from map import Map
            user_agent = 'kismon/%s' % utils.get_version()
            self.map = Map(self.config["map"], user_agent=user_agent)
            self.map.set_last_from_config()

    def init_client_thread(self, server_id):
        server = self.config["kismet"]["servers"][server_id]
        self.client_threads[server_id] = ClientThread(server)
        self.client_threads[server_id].client.set_capabilities(
            ('status', 'source', 'info', 'gps', 'bssid', 'bssidsrc', 'ssid'))
        if "--create-kismet-dump" in sys.argv:
            self.client_threads[server_id].client.enable_dump()

    def init_client_threads(self):
        server_id = 0
        for server in self.config["kismet"]["servers"]:
            self.init_client_thread(server_id)
            server_id += 1

    def client_start(self, server_id):
        if server_id in self.client_threads and self.client_threads[
                server_id].is_running:
            self.client_stop(server_id)
        self.sources[server_id] = {}
        self.init_client_thread(server_id)
        if "--load-kismet-dump" in sys.argv:
            self.client_threads[server_id].client.load_dump(sys.argv[2])
        self.client_threads[server_id].start()

    def client_stop(self, server_id):
        if self.client_threads[server_id].client.connecting:
            # kill connecting sockets, don't wait for the timeout
            try:
                self.client_threads[server_id].client.s.shutdown(
                    socket.SHUT_RDWR)
            except OSError:
                pass
        self.client_threads[server_id].stop()

    def clients_stop(self):
        for server_id in self.client_threads:
            self.client_stop(server_id)
        return True

    def queue_handler(self, server_id):
        server_name = self.config['kismet']['servers'][server_id]
        if self.main_window.gtkwin is None:
            return False

        thread = self.client_threads[server_id]
        if len(thread.client.error) > 0:
            for error in thread.client.error:
                self.main_window.log_list.add(server_name, error)
            thread.client.error = []
            self.main_window.server_tabs[server_id].server_switch.set_active(
                False)
            page_num = self.main_window.notebook.page_num(
                self.main_window.log_list.widget)
            self.main_window.notebook.set_current_page(page_num)

        #gps
        gps = None
        fix = None
        gps_queue = thread.get_queue("gps")
        while True:
            try:
                data = gps_queue.pop()
                if gps is None:
                    gps = data
                if data["fix"] > 1:
                    fix = (data["lat"], data["lon"])
                    if self.config['tracks']['store'] == True:
                        self.tracks.add_point_to_track(server_name,
                                                       data['lat'],
                                                       data['lon'],
                                                       data['alt'])
                    break
            except IndexError:
                break
        if gps is not None:
            self.main_window.server_tabs[server_id].update_gps_table(gps)
            if fix is not None and self.map is not None:
                server = "server%s" % (server_id + 1)
                if server_id == 0:
                    self.map.set_position(fix[0], fix[1])
                else:
                    self.map.add_marker(server, server, fix[0], fix[1])
                self.map.add_track(fix[0], fix[1], server_id)

        #status
        for data in thread.get_queue("status"):
            self.main_window.log_list.add(server_name, data["text"])

        #info
        info_queue = thread.get_queue("info")
        try:
            data = info_queue.pop()
            self.main_window.server_tabs[server_id].update_info_table(data)
        except IndexError:
            pass

        #source
        update = False
        for data in thread.get_queue("source"):
            uuid = data["uuid"]
            if uuid == "00000000-0000-0000-0000-000000000000":
                continue
            self.sources[server_id][uuid] = data

            update = True
        if update is True:
            self.main_window.server_tabs[server_id].update_sources_table(
                self.sources[server_id])

    def queues_handler(self):
        for server_id in self.client_threads:
            self.queue_handler(server_id)
        return True

    def queue_handler_networks(self, server_id):
        thread = self.client_threads[server_id]

        #ssid
        for data in thread.get_queue("ssid"):
            self.networks.add_ssid_data(data)

        #bssid
        bssids = {}
        for data in thread.get_queue("bssid"):
            mac = data["bssid"]
            self.networks.add_bssid_data(data, server_id)
            if mac in self.main_window.signal_graphs and "signal_dbm" not in thread.client.capabilities[
                    "bssidsrc"]:
                self.main_window.signal_graphs[mac].add_value(
                    None, None, data["signal_dbm"], server_id)

            bssids[mac] = True

        #bssidsrc
        for data in thread.get_queue("bssidsrc"):
            if "signal_dbm" not in data or data["uuid"] not in self.sources[
                    server_id]:
                continue

            mac = data["bssid"]
            if mac in self.main_window.signal_graphs:
                self.main_window.signal_graphs[mac].add_value(
                    self.sources[server_id][data["uuid"]], data,
                    data["signal_dbm"], server_id)

        if len(self.networks.notify_add_queue) > 0:
            self.networks.start_queue()
            if len(self.networks.notify_add_queue) > 500:
                self.networks.disable_refresh()
                self.main_window.networks_queue_progress()

        self.main_window.update_statusbar()

    def queues_handler_networks(self):
        for server_id in self.client_threads:
            self.queue_handler_networks(server_id)
        return True

    def quit(self):
        self.clients_stop()

        if self.map is not None:
            lat = self.map.osm.get_property("latitude")
            lon = self.map.osm.get_property("longitude")
            self.config["map"]["last_position"] = "%.6f/%.6f" % (lat, lon)

        while None in self.config['kismet']['servers']:
            self.config['kismet']['servers'].remove(None)
        self.config_handler.write()
        self.networks.save(self.networks_file, force=True)
        if self.config['tracks']['store'] == True:
            self.tracks.save()

    def add_network_to_map(self, mac):
        network = self.networks.get_network(mac)

        try:
            crypt = self.crypt_cache[network["cryptset"]]
        except KeyError:
            crypt = decode_cryptset(network["cryptset"], True)
            self.crypt_cache[network["cryptset"]] = crypt

        if "AES_CCM" in crypt or "AES_OCB" in crypt:
            color = "red"
        elif "WPA" in crypt:
            color = "orange"
        elif "WEP" in crypt:
            color = "yellow"
        else:
            color = "green"

        self.map.add_marker(mac, color, network["lat"], network["lon"])
Exemplo n.º 34
0
from mip import *
from map import Map
from util import vehicles, num_vehicles
import time
import matplotlib.pyplot as plt
import pandas as pd

time_1 = time.perf_counter()

map_1 = Map("Result_1.json")
distances = map_1.distances
points = map_1.points
origin_id = map_1.origin_id

# Declare model
m = Model(sense=MINIMIZE, solver_name=CBC)
m.max_gap = 0.1

path = {}
for dist_key in distances:
    for vehicle in vehicles:
        path[dist_key[0], dist_key[1], vehicle] = m.add_var(var_type=BINARY)

# max_path = m.add_var(var_type=CONTINUOUS)
avg_distance = m.add_var(var_type=CONTINUOUS)
vehicle_distance = {}
for vehicle in vehicles:
    vehicle_distance[vehicle] = m.add_var(var_type=CONTINUOUS)

all_points = points.copy()
all_points.append(origin_id)
Exemplo n.º 35
0
                        "--showlaneids",
                        action="store_const",
                        const=True,
                        help="Show all lane ids in map")
    parser.add_argument("-l",
                        "--laneid",
                        nargs='+',
                        help="Show specific lane id(s) in map")
    parser.add_argument("--loc",
                        action="store",
                        type=str,
                        required=False,
                        help="Specify the localization pb file in txt format")

    args = parser.parse_args()

    map = Map()
    map.load(args.map)
    lane_ids = args.laneid
    if lane_ids is None:
        lane_ids = []
    map.draw_lanes(plt, args.showlaneids, lane_ids)

    if args.loc is not None:
        localization = Localization()
        localization.load(args.loc)
        localization.plot_vehicle(plt)

    plt.axis('equal')
    plt.show()
Exemplo n.º 36
0
class GUI(QtWidgets.QMainWindow):
    
    def __init__(self, parent = None):
        QtWidgets.QMainWindow.__init__(self, parent)
        
        # hold the set of keys we're pressing
        self.keys_pressed = set()

        # use a timer to get refresh
        self.timer = QBasicTimer()
        self.timer.start(3, self)
        
        self.setCentralWidget(QtWidgets.QWidget()) # QMainWindown must have a centralWidget to be able to add layouts
        self.horizontal = QtWidgets.QHBoxLayout() # Horizontal main layout
        
        self.centralWidget().setLayout(self.horizontal)
        '''
        Sets up the window.
        '''
        self.setGeometry(300, 300, 900, 1000)
        self.setWindowTitle('Tasohyppely')
        self.showFullScreen()

        # Add a scene for drawing 2d objects
        self.scene = QtWidgets.QGraphicsScene()
        self.scene.setSceneRect(0, 0, 800, 800)

        # Add a view for showing the scene
        self.view = QtWidgets.QGraphicsView(self.scene, self)
        self.view.adjustSize()
        self.view.show()
        self.horizontal.addWidget(self.view)
        self.graph = SquareGraphs()
        self.graphSquares = self.graph.create_square_graphs()
        self.map = Map()
        
        for i in range(self.map.get_height()):
            for j in range(self.map.get_width()):
                self.scene.addItem(self.graphSquares[i][j])
                
        self.player = Player()
        self.player.setPos(53, 700)
        self.scene.addItem(self.player)
        self.enemy_container = Enemy_container()
        self.enemy = Enemy()
        self.enemy.setPos(200, 500)
        self.scene.addItem(self.enemy)
        self.enemy_container.add_enemy(self.enemy)
        self.enemy2 = Enemy()
        self.enemy2.setPos(650, 300)
        self.scene.addItem(self.enemy2)
        self.enemy_container.add_enemy(self.enemy2)
        self.enemy3 = Enemy()
        self.enemy3.setPos(150,200)
        self.scene.addItem(self.enemy3)
        self.enemy_container.add_enemy(self.enemy3)
        self.enemies = self.enemy_container.get_enemies()
        self.text = QLabel()
        self.text.setText("You Won!")
        a = QFont("Arial", 40, QFont.Bold)
        self.text.setFont(a)
        
        self.text1 = QLabel(self.centralWidget())
        self.text1.setText("You Lost!")
        a = QFont("Arial", 40, QFont.Bold)
        self.text1.setFont(a)
        self.draw_loss = 250
        self.a = 0
    
            
        
    def get_graphSquares(self):
        return self.graphSquares
        
    def keyPressEvent(self, event):
        self.keys_pressed.add(event.key())

    def keyReleaseEvent(self, event):
        self.keys_pressed.remove(event.key())

    def timerEvent(self, event):
        
        self.game_update()
        if self.player.has_won():
            
            self.horizontal.addWidget(self.text)
            self.draw_won = 1

            
            
        if self.player.get_draw_won() == 1:
            
            self.horizontal.removeWidget(self.text)
            self.text.deleteLater()
            self.text = None
            self.player.add_draw_won()
            self.reset_won()
            
        self.player.check_if_coll_enemy(self.enemies)
        if self.player.has_lost():
            self.a = 1
            self.horizontal.addWidget(self.text1)
        if self.a == 1 and self.draw_loss > 1:
            self.draw_loss -= 1
            
            
        if self.draw_loss == 1:
            self.horizontal.removeWidget(self.text1)
            self.text1.deleteLater()
            self.text1 = None
            self.player.add_draw_loss()
            self.reset_loss()
            self.a = 0
            self.draw_loss = 250
            
            
        
    
            
        self.enemy.enemy_update()
        self.enemy2.enemy_update()
        self.enemy3.enemy_update()
        self.update()
    
    def reset_won(self):
        self.text = QLabel()
        self.text.setText("You Won!")
        a = QFont("Arial", 35, QFont.Bold)
        self.text.setFont(a)
        
    def reset_loss(self):
        self.text1 = QLabel()
        self.text1.setText("You Lost!")
        a = QFont("Arial", 35, QFont.Bold)
        self.text1.setFont(a)
        
    
    def game_update(self):
        self.player.game_update(self.keys_pressed)
Exemplo n.º 37
0
class GUI:
    # Initialization function
    # The actual initialization
    def __init__(self, host, console, hal):
        t = threading.Thread(target=self.run_server)

        self.payload = {
            'robot_coord': '',
            'robot_contorno': '',
            'text_buffer': '',
            'laser': '',
            'sonar_sensor': '',
            'pos_vertices': '',
            'laser_global': '',
            'EnableMapping': ''
        }
        # self.map_message = {
        #     'EnableMapping': ''
        # }
        self.server = None
        self.client = None

        self.host = host

        self.acknowledge = False
        self.acknowledge_lock = threading.Lock()

        # Take the console object to set the same websocket and client
        self.console = console
        self.hal = hal
        t.start()

        pose3d_object = ListenerPose3d("/robot0/odom")
        laser_object = ListenerLaser("/robot0/laser_1")
        self.map = Map(laser_object, pose3d_object)

    # Explicit initialization function
    # Class method, so user can call it without instantiation
    @classmethod
    def initGUI(cls, host, console):
        # self.payload = {'image': '', 'shape': []}
        new_instance = cls(host, console)
        return new_instance

    # Function to get the client
    # Called when a new client is received
    def get_client(self, client, server):
        self.client = client
        self.console.set_websocket(self.server, self.client)

    # Function to get value of Acknowledge
    def get_acknowledge(self):
        self.acknowledge_lock.acquire()
        acknowledge = self.acknowledge
        self.acknowledge_lock.release()

        return acknowledge

    # Function to set value of Acknowledge
    def set_acknowledge(self, value):
        self.acknowledge_lock.acquire()
        self.acknowledge = value
        self.acknowledge_lock.release()

    # Update the gui
    def update_gui(self):
        # Payload Map Message
        self.payload["robot_coord"], self.payload[
            "robot_contorno"] = self.map.setRobotValues()
        # Payload the Sonar and Laser data
        self.payload["pos_vertices"], self.payload[
            "sonar_sensor"] = self.map.setSonarValues()
        self.payload["laser"], self.payload[
            "laser_global"] = self.map.setLaserValues()
        # Payload Console Messages
        message_buffer = self.console.get_text_to_be_displayed()
        self.payload["text_buffer"] = str(message_buffer)

        message = "#gui" + json.dumps(self.payload)
        self.server.send_message(self.client, message)

    # Function to read the message from websocket
    # Gets called when there is an incoming message from the client
    def get_message(self, client, server, message):
        # Acknowledge Message for GUI Thread
        if (message[:4] == "#ack"):
            self.set_acknowledge(True)

# Message for Console
        elif (message[:4] == "#con"):
            self.console.prompt(message)

    # Activate the server
    def run_server(self):
        self.server = WebsocketServer(port=2303, host=self.host)
        self.server.set_fn_new_client(self.get_client)
        self.server.set_fn_message_received(self.get_message)
        self.server.run_forever()

    # Function to reset
    def reset_gui(self):
        self.map.reset()
Exemplo n.º 38
0
 def setUp(self):
     self.map = Map(10, 10, 0)
     self.robot = Robot(self.map)
Exemplo n.º 39
0
# author: 0aqz0
# date: 2018/11/20
"""
A* path planning implementation with python
"""
import math
from collections import deque
import matplotlib.pyplot as plt
import time
from map import Map

NEED_DRAW = False
map = Map()
grid_size = 10  # grid resolution
robot_size = 1  # robot size
obstacle_x = []  # coordinate x of obstacles
obstacle_y = []  # coordinate y of obstacles
motions = [
    [1, 0, 1],  # right          cost: 1
    [0, 1, 1],  # up             cost: 1
    [-1, 0, 1],  # left           cost: 1
    [0, -1, 1],  # down           cost: 1
    # [-1,-1,math.sqrt(2)],   # left and down  cost: 2^0.5
    # [-1,1,math.sqrt(2)],    # left and up    cost: 2^0.5
    # [1,-1,math.sqrt(2)],    # right and down cost: 2^0.5
    # [1,1,math.sqrt(2)],     # right and up   cost: 2^0.5
]


class Point:
    """
Exemplo n.º 40
0
def start_game():
    INVENTORY.add('potion')
    INVENTORY.add('potion')
    INVENTORY.add('dragon blood')

    HOOK['NED'] = Character('nel1',(0,0),'NEL',1)
    
    player = Character('nod1',(0,0),'NOD',1)
    player.map_mode()
    player.do(MoveCharacter())
    player.do(CheckForBattle())


    MAPS['inside_house_nod'] = Map('inside_house_nod')
    MAPS['village'] = Map('village')
    MAPS['village2'] = Map('village2')
    MAPS['village3'] = Map('village3')

    MAPS['inside_house_gen_1'] = Map('inside_house_gen_1')
    MAPS['inside_house_gen_2'] = Map('inside_house_gen_2')
    MAPS['inside_house_gen_3'] = Map('inside_house_gen_3')
    MAPS['inside_house_gen_4'] = Map('inside_house_gen_4')
    MAPS['inside_ceremony_hall'] = Map('inside_ceremony_hall')
    MAPS['grassland'] = Map('grassland')
    MAPS['forest'] = Map('forest')
    MAPS['falaise'] = Map('falaise')


    MAPS['inside_house_nod'].spawnPlayer(player, (7,9))
    MAPS['inside_house_nod'].displayDialog('Intro')

    cocos.director.director.window.push_handlers(KEYBOARD)
Exemplo n.º 41
0
class Game:
    """Adding pygame mixer, which needs to be tweaked
    in order to avoid lag"""
    def __init__(self):
        pygame.mixer.pre_init(44100, -16, 2, 1024)
        pygame.init()
        pygame.mixer.set_num_channels(16)
        self.screen = pygame.display.set_mode(
            [WIDTH, HEIGHT])  # pygame.FULLSCREEN | pygame.DOUBLEBUF
        pygame.display.set_caption(TITLE)
        self.clock = pygame.time.Clock()
        self.load_data()

    def load_data(self):
        """Adding music & fx"""
        root_folder = path.dirname(__file__)
        img_folder = path.join(root_folder, "data", "img")
        music_folder = path.join(root_folder, "data", "music")
        fx_folder = path.join(root_folder, "data", "fx")

        sprites = Spritesheet(path.join(img_folder, "spritesheet_x2.png"))

        # IMAGES

        self.item_images = {}
        for item_name in ITEMS:
            sprite_at = ITEMS[item_name]['SPRITE_AT']
            self.item_images[item_name] = sprites.image_at(
                sprite_at[0], sprite_at[1], TILESIZE, 2, KEY_COLOR)

        self.player_img = sprites.image_at(PLAYER_SPRITE_AT[0],
                                           PLAYER_SPRITE_AT[1], TILESIZE, 2,
                                           KEY_COLOR)

        self.bee_img = sprites.image_at(BEE_SPRITE_AT[0], BEE_SPRITE_AT[1],
                                        TILESIZE, 2, KEY_COLOR)

        self.bee_nest_img = sprites.image_at(BEE_NEST_SPRITE_AT[0],
                                             BEE_NEST_SPRITE_AT[1], TILESIZE,
                                             2, KEY_COLOR)

        self.top_wall_img = sprites.image_at(TOP_WALL_SPRITE_AT[0],
                                             TOP_WALL_SPRITE_AT[1], TILESIZE,
                                             2, KEY_COLOR)

        self.front_wall_img = sprites.image_at(FRONT_WALL_SPRITE_AT[0],
                                               FRONT_WALL_SPRITE_AT[1],
                                               TILESIZE, 2, KEY_COLOR)

        # SOUND
        # Using arrays to add some variance
        pygame.mixer.music.load(path.join(music_folder, BG_MUSIC))
        self.basic_gun_fx = []
        for fx in BASIC_GUN_FX:
            pewpew = pygame.mixer.Sound(path.join(fx_folder, fx))
            pewpew.set_volume(0.1)
            self.basic_gun_fx.append(pewpew)
        self.critter_death_fx = []
        for fx in CRITTER_DEAD_FX:
            self.critter_death_fx.append(
                pygame.mixer.Sound(path.join(fx_folder, fx)))
        self.item_fx = {}
        for fx in ITEMS:
            self.item_fx[fx] = pygame.mixer.Sound(
                path.join(fx_folder, ITEMS[fx]['FX']))

    def reset(self):
        self.all_sprites = pygame.sprite.Group()
        self.walls = pygame.sprite.Group()
        self.mobs = pygame.sprite.Group()
        self.bullets = pygame.sprite.Group()
        self.nests = pygame.sprite.Group()
        self.items = pygame.sprite.Group()

        self.current_map = Map()
        self.current_map.load_from_file("bigMap.txt")
        # self.current_map.create_cave_cellular_automata(self, 50, 50)
        # self.current_map.create_cave_diggers(self, 50, 50)

        self.current_map.create_sprites_from_data(self)

        self.player = Player(self, self.current_map.entry_point[0],
                             self.current_map.entry_point[1], self.all_sprites,
                             self.player_img, PLAYER_SPEED, PLAYER_HEALTH)

        HealthPack(self, self.player.pos.x + TILESIZE,
                   self.player.pos.y + TILESIZE)

        SpeedUp(self, self.player.pos.x - TILESIZE,
                self.player.pos.y - TILESIZE)

        self.camera = Camera(self.current_map.pixel_width,
                             self.current_map.pixel_height)

    def run(self):
        """Start playing music!"""
        self.playing = True
        # pygame.mixer.music.play(loops=-1)
        while self.playing:
            self.dt = self.clock.tick(FPS)
            self.events()
            self.update()
            self.draw()

    def quit(self):
        pygame.quit()
        sys.exit()

    def update(self):
        self.all_sprites.update()
        self.camera.update(self.player)

        # bullets hitting nests
        hits = pygame.sprite.groupcollide(self.nests, self.bullets, False,
                                          True)
        for nest, bullets in hits.items():
            nest.hit(bullets[0].damage)

        # bullets hitting mobs
        hits = pygame.sprite.groupcollide(self.mobs, self.bullets, False, True)
        for mob, bullets in hits.items():
            mob.hit(bullets[0].damage)

        # mobs hitting player
        hits = pygame.sprite.spritecollide(self.player, self.mobs, False,
                                           False)
        for mob in hits:
            mob.attack(self.player)

        # mobs hitting mobs
        hits = pygame.sprite.groupcollide(self.mobs, self.mobs, False, False)
        for mobA, mobB in hits.items():
            mobA.push(mobB[0])

        # player hitting items
        hits = pygame.sprite.spritecollide(self.player, self.items, False,
                                           False)
        for item in hits:
            item.picked_by(self.player)

    def draw(self):
        pygame.display.set_caption("{:.2f}".format(self.clock.get_fps()))
        self.screen.fill(DARKGREY)
        for sprite in self.all_sprites:
            if isinstance(sprite, Mob) and sprite != self.player:
                sprite.draw_health()

            self.screen.blit(sprite.image, self.camera.apply_to_sprite(sprite))

            # pygame.draw.rect(self.screen, YELLOW,
            #                self.camera.apply_to_sprite(sprite))

        self.draw_player_health(self.screen, 10, 10,
                                self.player.health / PLAYER_HEALTH)
        pygame.display.flip()

    def draw_player_health(self, surface, x, y, health):
        if health < 0:
            health = 0
        BAR_LENTH = 100
        BAR_HEIGHT = 20
        fill = health * BAR_LENTH
        outline = pygame.Rect(x, y, BAR_LENTH, BAR_HEIGHT)
        fill_rect = pygame.Rect(x, y, fill, BAR_HEIGHT)
        if health > 0.6:
            col = GREEN
        elif health > 0.3:
            col = YELLOW
        else:
            col = RED
        pygame.draw.rect(surface, col, fill_rect)
        pygame.draw.rect(surface, WHITE, outline, 2)

    def events(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                self.quit()

    def show_start_screen(self):
        pass
class Monitor:
    def __init__(self):
        self.data_collector = DataCollector()
        self.new_location = DataCollector()

    def collect_default_data(self):
        self.data_collector.filter_radius()

    def relocate(self, location=None, coordinates=None, radius: int = 250):
        if location is not None:
            geolocator = Nominatim(user_agent="team_1_earthquake_detector")
            location_latitude = geolocator.geocode(location).latitude
            location_longitude = geolocator.geocode(location).longitude
            location_coordinates = (location_latitude, location_longitude)
            return self.new_location.filter_radius(location_coordinates,
                                                   radius)

        if coordinates is not None:
            return self.new_location.filter_radius(coordinates, radius)

    def build_map(self, location=None, coordinates=None, radius=None):
        self.map = Map()

        if location is None and coordinates is None:
            self.map.set_up_map()
            self.collect_default_data()
            earthquake_overlay = EarthquakeOverlay(
                self.data_collector.earthquake_data_clean)
            earthquake_overlay.apply_circle_markers(self.map.map)
            earthquake_overlay.apply_magnitude_markers(self.map.map)
            earthquake_overlay.apply_connective_lines(self.map.map)
            earthquake_overlay.apply_heatmap(self.map.map)
            tectonic_overlay = TectonicOverlay()
            tectonic_overlay.apply_overlay(self.map.map)
            tectonic_overlay.add_to_layer_control(self.map.map)
            return self.map

        if location is not None or coordinates is not None:
            self.map.set_up_map(location=coordinates)
            self.relocate(location=location,
                          coordinates=coordinates,
                          radius=radius)
            earthquake_overlay = EarthquakeOverlay(
                self.new_location.earthquake_data_clean)
            earthquake_overlay.apply_circle_markers(self.map.map)
            earthquake_overlay.apply_magnitude_markers(self.map.map)
            earthquake_overlay.apply_connective_lines(self.map.map,
                                                      coordinates)
            earthquake_overlay.apply_heatmap(self.map.map)
            tectonic_overlay = TectonicOverlay()
            tectonic_overlay.apply_overlay(self.map.map)
            tectonic_overlay.add_to_layer_control(self.map.map)
            return self.map

    def perform_earthquake_analytics(self, location=None, radius=None):
        self.data_collector.prep_data()
        self.data_collector.filter_radius()
        earthquake_analytics = EarthquakeAnalytics(
            self.data_collector.earthquake_data,
            self.data_collector.earthquake_data_clean)

        total_filtered = earthquake_analytics.get_total_filtered_earthquakes(
            location=location, radius=radius)
        minor_filtered = earthquake_analytics.get_filtered_minor_earthquakes(
            location=location, radius=radius)
        moderate_filtered = earthquake_analytics.get_filtered_moderate_earthquakes(
            location=location, radius=radius)
        strong_filtered = earthquake_analytics.get_filtered_strong_earthquakes(
            location=location, radius=radius)
        closest_filtered = earthquake_analytics.get_closest_filtered_earthquake(
            location=location)
        place_of_closest_filtered = earthquake_analytics.get_place_of_closest_filtered_earthquake(
            location=location)
        strongest_filtered = earthquake_analytics.get_strongest_filtered_earthquake(
            location=location, radius=radius)
        total_worldwide = earthquake_analytics.get_total_earthquakes_worldwide(
        )
        minor_worldwide = earthquake_analytics.get_minor_earthquakes_worldwide(
        )
        moderate_worldwide = earthquake_analytics.get_moderate_earthquakes_worldwide(
        )
        strong_worldwide = earthquake_analytics.get_strong_earthquakes_worldwide(
        )
        strongest_worldwide = earthquake_analytics.get_strongest_earthquake_worldwide(
        )
        place_of_strongest_worldwide = earthquake_analytics.get_place_of_strongest_earthquake_worldwide(
        )

        return total_filtered, minor_filtered, moderate_filtered, strong_filtered, closest_filtered, place_of_closest_filtered,\
               strongest_filtered, total_worldwide, minor_worldwide, moderate_worldwide, strong_worldwide, strongest_worldwide, \
               place_of_strongest_worldwide
Exemplo n.º 43
0
class Game:
    def __init__(self):

        self.map = Map()
        self.menu = Menu(self.map.window)
        self.messageBoard = MessageBoard(self.map.window,
                                         graphics.Point(300, 400),
                                         graphics.Point(500, 500))
        self.turn_indicator = MessageBoard(self.map.window,
                                           graphics.Point(200, 450),
                                           graphics.Point(300, 500))
        self.event_box = MessageBoard(self.map.window, graphics.Point(300, 0),
                                      graphics.Point(500, 100))

        self.nations = []
        self.regions = []

        self.load_nations()

        self.map.regions = self.regions
        self.selectedNation = None

        self.player_nation = self.nations[0]
        self.player_turn = True

        print(self.nations[0])

    def load_nations(self):
        f = open("map_maker/nation_geometry.txt")

        rows = f.readlines()

        for row in rows:
            tempNation = json.loads(row)
            points = []
            for i in tempNation['points']:
                points.append(
                    geometry.Point(tempNation['points'][i]['x'],
                                   tempNation['points'][i]['y']))
            nation = Nation(tempNation['name'], tempNation['color'], 1000)
            region = Region(points)
            region.shape.color = nation.color
            region.name = nation.name
            nation.regions = [region]
            self.nations.append(nation)
            self.regions.append(region)

    def draw(self):
        self.map.draw()
        self.menu.draw()
        self.messageBoard.draw()
        self.turn_indicator.draw()

    def run(self):
        playing = True
        while playing:
            self.draw()
            self.player_turn_action()
            self.draw()
            self.random_event(self.player_nation)

            for nation in self.nations:
                if nation != self.player_nation and nation.soldiers != 0:
                    self.ai_turn(nation)

            first = None
            playing = False
            for nation in self.nations:
                if nation.soldiers > 0 and first is None:
                    first = nation
                elif nation.soldiers > 0:
                    playing = True

            if self.player_nation.soldiers == 0:
                playing = False

            self.player_turn = True

    def player_turn_action(self):
        attack_move = True
        recruit_move = True
        self.menu.attackButton.visible = True
        self.menu.recruitButton.visible = True

        while self.player_turn:
            self.turn_indicator.new_message(self.player_nation.name)
            self.turn_indicator.change_color(self.player_nation.color)
            clickedPoint = self.map.window.getMouse()

            clicked = self.what_was_clicked(clickedPoint)

            if clicked is None:
                self.draw()
            elif clicked[0] == 'nation' and self.selectedNation != clicked[1]:
                self.selectedNation = clicked[1]
                self.menu.loadNation(clicked[1],
                                     self.selectedNation == self.player_nation)
            elif clicked[
                    0] == 'attack' and self.selectedNation == self.player_nation:
                self.menu.attackButton.clicked = True
                self.menu.draw()
                attackingClick = self.map.window.getMouse()

                defender = self.what_was_clicked(attackingClick)
                if defender is not None and defender[
                        0] == 'nation' and defender[1] != self.selectedNation:
                    result = self.battle(defender[1], self.selectedNation)

                    self.messageBoard.new_message(result)
                    attack_move = False
                    self.menu.attackButton.visible = False
                    self.menu.draw()

                self.menu.attackButton.clicked = False
            elif clicked[
                    0] == 'recruit' and self.selectedNation == self.player_nation:
                clicked[1].clicked = True
                self.menu.draw()
                self.recruit(self.selectedNation,
                             int(self.menu.recruit_amount.getText()))
                clicked[1].clicked = False
                recruit_move = False
                self.menu.recruitButton.visible = False
                self.menu.draw()

            self.player_turn = recruit_move or attack_move

    def ai_turn(self, nation):
        self.turn_indicator.new_message(nation.name)
        self.turn_indicator.change_color(nation.color)
        target = None
        while target is None:
            target = self.nations[random.randint(0, len(self.nations) - 1)]
            if target == nation or target.soldiers == 0:
                target = None
        self.recruit(nation, random.randint(0, int(nation.money * 10)))
        sleep(1)
        self.messageBoard.new_message(self.battle(target, nation))

        self.random_event(nation)
        self.draw()

    def random_event(self, nation):
        sleep(1)
        event = self.events(random.randint(1, 3))
        event(nation, self.event_box)
        self.draw()
        self.map.window.getMouse()
        self.event_box.undraw()

    def events(self, index):
        switcher = {
            1: self.soldierEvent,
            2: self.moneyEvent,
            3: self.loseEvent
        }
        return switcher.get(index)

    def soldierEvent(self, nation, event_box: MessageBoard):
        nation.soldiers = nation.soldiers + 500
        event_box.new_message(nation.name + " gained 500 soldiers!")

    def moneyEvent(self, nation, event_box: MessageBoard):
        nation.money = nation.money + 100
        event_box.new_message(nation.name + " gained 100 gp!")

    def loseEvent(self, nation, event_box: MessageBoard):
        print("you lose")
        event_box.new_message("That f*****g sucks.")

    def what_was_clicked(self, point: graphics.Point):
        if 0 < point.getX() < 50 and 400 < point.getY() < 425:
            return 'attack', self.menu.attackButton

        if self.menu.recruitButton.rect.getP1().getX() < point.getX(
        ) < self.menu.recruitButton.rect.getP2(
        ).getX() and self.menu.recruitButton.rect.getP1().getY() < point.getY(
        ) < self.menu.recruitButton.rect.getP2().getY():
            return 'recruit', self.menu.recruitButton

        for nation in self.nations:
            for region in nation.regions:
                if region.shape.polygon.contains(
                        geometry.Point(point.x, point.y)):
                    return 'nation', nation

    def recruit(self, nation: Nation, amount):
        if amount / 10 <= nation.money:
            nation.soldiers = nation.soldiers + amount
            nation.money = nation.money - (amount / 10)
            self.messageBoard.new_message(nation.name + " has recruited " +
                                          str(amount) + " Soldiers")
        else:
            self.messageBoard.new_message("Not Enough Money!")
        self.draw()

    def battle(self, defender: Nation, attacker: Nation):
        battleInfo = ""

        battleInfo = battleInfo + attacker.name + " has attacked " + defender.name + "!\n"

        battle = Battle(attacker, defender)

        battleInfo = battleInfo + defender.name + " lost " + str(
            battle.outcome[1]) + " soldiers\n"
        battleInfo = battleInfo + attacker.name + " lost " + str(
            battle.outcome[0]) + " soldiers\n"

        return battleInfo
Exemplo n.º 44
0
            # Assign dynamic border cells to waypoints
            wp.dynamic_border_cells = bound_cells_sm

        return np.array(ub_hor), np.array(lb_hor), border_cells_hor_sm


if __name__ == '__main__':

    # Select Track | 'Real_Track' or 'Sim_Track'
    path = 'Sim_Track'

    if path == 'Sim_Track':

        # Load map file
        map = Map(file_path='maps/sim_map.png',
                  origin=[-1, -2],
                  resolution=0.005)

        # Specify waypoints
        wp_x = [
            -0.75, -0.25, -0.25, 0.25, 0.25, 1.25, 1.25, 0.75, 0.75, 1.25,
            1.25, -0.75, -0.75, -0.25
        ]
        wp_y = [
            -1.5, -1.5, -0.5, -0.5, -1.5, -1.5, -1, -1, -0.5, -0.5, 0, 0, -1.5,
            -1.5
        ]

        # Specify path resolution
        path_resolution = 0.05  # m / wp
Exemplo n.º 45
0
    def __init__(self, parent = None):
        QtWidgets.QMainWindow.__init__(self, parent)
        
        # hold the set of keys we're pressing
        self.keys_pressed = set()

        # use a timer to get refresh
        self.timer = QBasicTimer()
        self.timer.start(3, self)
        
        self.setCentralWidget(QtWidgets.QWidget()) # QMainWindown must have a centralWidget to be able to add layouts
        self.horizontal = QtWidgets.QHBoxLayout() # Horizontal main layout
        
        self.centralWidget().setLayout(self.horizontal)
        '''
        Sets up the window.
        '''
        self.setGeometry(300, 300, 900, 1000)
        self.setWindowTitle('Tasohyppely')
        self.showFullScreen()

        # Add a scene for drawing 2d objects
        self.scene = QtWidgets.QGraphicsScene()
        self.scene.setSceneRect(0, 0, 800, 800)

        # Add a view for showing the scene
        self.view = QtWidgets.QGraphicsView(self.scene, self)
        self.view.adjustSize()
        self.view.show()
        self.horizontal.addWidget(self.view)
        self.graph = SquareGraphs()
        self.graphSquares = self.graph.create_square_graphs()
        self.map = Map()
        
        for i in range(self.map.get_height()):
            for j in range(self.map.get_width()):
                self.scene.addItem(self.graphSquares[i][j])
                
        self.player = Player()
        self.player.setPos(53, 700)
        self.scene.addItem(self.player)
        self.enemy_container = Enemy_container()
        self.enemy = Enemy()
        self.enemy.setPos(200, 500)
        self.scene.addItem(self.enemy)
        self.enemy_container.add_enemy(self.enemy)
        self.enemy2 = Enemy()
        self.enemy2.setPos(650, 300)
        self.scene.addItem(self.enemy2)
        self.enemy_container.add_enemy(self.enemy2)
        self.enemy3 = Enemy()
        self.enemy3.setPos(150,200)
        self.scene.addItem(self.enemy3)
        self.enemy_container.add_enemy(self.enemy3)
        self.enemies = self.enemy_container.get_enemies()
        self.text = QLabel()
        self.text.setText("You Won!")
        a = QFont("Arial", 40, QFont.Bold)
        self.text.setFont(a)
        
        self.text1 = QLabel(self.centralWidget())
        self.text1.setText("You Lost!")
        a = QFont("Arial", 40, QFont.Bold)
        self.text1.setFont(a)
        self.draw_loss = 250
        self.a = 0
Exemplo n.º 46
0
def runGame():
    pygame.mixer.music.load("resource/sound/BGM01.at3.mp3")
    pygame.mixer.music.set_volume(0.3)
    pygame.mixer.music.play(-1, 0.0)

    map = Map(MAIN_WIDTH // BASIC_UNIT, MAIN_HEIGHT // BASIC_UNIT, BLOCK_MIN,
              BLOCK_MAX, INIT_TIME_ADD_CAR, INIT_NUM_ADD_CAR, TIME_CROSS,
              TIME_CAR)
    option = 0
    bias_w, bias_h = BIAS_WIDTH_BASIC, BIAS_HEIGHT_BASIC
    bias_time_last = time.time()
    bias_direct = None
    while True:
        #检测退出事件
        checkForQuit()

        map.update()

        key_d = checkForKeyDown()
        key_u = checkForKeyUp()
        for i, k in enumerate(
            [K_0, K_1, K_2, K_3, K_4, K_5, K_6, K_7, K_8, K_9]):
            if key_d == k:
                option = i

        if key_d == K_LEFT:
            bias_direct = "E"
        elif key_d == K_UP:
            bias_direct = "S"
        elif key_d == K_RIGHT:
            bias_direct = "W"
        elif key_d == K_DOWN:
            bias_direct = "N"

        if bias_direct == "E":
            if time.time(
            ) - bias_time_last > BIAS_TIME and bias_w >= BIAS_WIDTH_MIN + BASIC_UNIT:
                bias_w -= BASIC_UNIT
                bias_time_last = time.time()
            if key_u == K_LEFT:
                bias_direct = None
        elif bias_direct == "S":
            if time.time(
            ) - bias_time_last > BIAS_TIME and bias_h >= BIAS_HEIGHT_MIN + BASIC_UNIT:
                bias_h -= BASIC_UNIT
                bias_time_last = time.time()
            if key_u == K_UP:
                bias_direct = None
        elif bias_direct == "W":
            if time.time(
            ) - bias_time_last > BIAS_TIME and bias_w <= BIAS_WIDTH_MAX - BASIC_UNIT:
                bias_w += BASIC_UNIT
                bias_time_last = time.time()
            if key_u == K_RIGHT:
                bias_direct = None
        elif bias_direct == "N":
            if time.time(
            ) - bias_time_last > BIAS_TIME and bias_h <= BIAS_HEIGHT_MAX - BASIC_UNIT:
                bias_h += BASIC_UNIT
                bias_time_last = time.time()
            if key_u == K_DOWN:
                bias_direct = None
        #print("BIAS: ", bias_direct, bias_w, bias_h)

        map.setTimeAddCar(OPTION_ADD_CAR[option][0] * BASIC_TIME_ADD_CAR)
        map.setNumAddCar(OPTION_ADD_CAR[option][1] * BASIC_NUM_ADD_CAR)

        num_start, num_move, num_cross, num_end, avg_distance, avg_time, avg_speed = map.count(
        )

        #绘图步骤 --------
        drawBackground()
        drawMap(map, option, bias_w, bias_h)
        drawMessage(num_start, num_move, num_cross, num_end, avg_distance,
                    avg_time, avg_speed, OPTION_ADD_CAR[option][0],
                    OPTION_ADD_CAR[option][1])

        pygame.display.update()
        #clearKeyEvent()
        fps_lock.tick(FPS)
    return score
Exemplo n.º 47
0
class Game:
    def __init__(self):
        self.UIDcounter = 0
        self.players = []
        self.maxPlayers = 6
        self.closed = False
        self.cycle = 0
        self.started = False
        self.map = Map(self)
        Message.game = self
        self.story = ""
        self.orders = []
        self.masterPlayer = None
        self.entities = []
        self.races = []

    def onLoad(self):
        Message.game = self

    def initGame(self):
        self.map.initTiles(-4, 4, -4, 4)

        defaultMasterPassword = "******"
        master = Player(self,
                        None,
                        defaultMasterPassword,
                        "",
                        "",
                        "",
                        uber=True)
        self.masterPlayer = master

    def getPlayer(self, secret):
        if self.masterPlayer.secret == secret:
            return self.masterPlayer
        for player in self.players:
            if player.secret == secret:
                return player
        return None

    def getPlayerByUID(self, UID):
        for player in self.players:
            if player.UID == UID:
                return player
        return None

    def addOrder(self, order):
        order.setDelayed()
        self.orders.append(order)
        player.addOrder(order)

    def sendMessage(self, sender, receiverUID, content):
        mask = str(sender)
        message = Message(mask, content, receiverUID)
        self.getEntity(receiverUID).message(message)
        return 0

    def sendGameMessage(self, receiverUID, content):
        mask = "Game"
        message = Message(mask, content, receiverUID)
        self.getEntity(receiverUID).message(message)

    def addStory(self, line):
        if not line in self.story:  # SO that multiple things being created can just have the same story, which is only added once- duplication of story should never be done deliberately.
            line = "[%s] %s" % (time.ctime(), line
                                )  # Add time stamp to beginning
            self.story += line + "\n"

    def vote(self, player, value):
        if not self.started: return

        self.votes[player] = value
        if sum(self.votes.values()) >= len(self.players):
            self.advanceCycle()

    def resetVotes(self):
        self.votes = {
            player: False
            for player in self.players if not player.uber
        }

    def initCycle(self):
        self.resetVotes()
        for entity in self.map.entities:
            entity.preCycle()
        for player in self.players:
            player.initCycle()
        for entity in self.map.entities:
            entity.initCycle()
        # Not sure if order will matter- since player.initCycle has already been called, players no longer remember their orders, even if the game does
        for order in self.orders:
            player, order = order
            id = [-1]
            order = order[:-1]
            response = player.interpret(order, id=id)
            formattedString = "The order %s has produced result code %s" % (
                str(order), response)
            self.sendGameMessage(player.UID, formattedString)
        self.orders = []
        self.save()

    def save(self):
        loader.save(self)

    def startGame(self):
        print "\n----------------------------STARTING GAME----------------------------\n"
        self.closed = True
        self.started = True
        self.initCycle()
        for i in xrange(len(self.players)):
            self.players[i].gameIndex = i

    def advanceCycle(self):
        # Maybe rename this function to _advanceCycle, and make an adavanceCycle function to spin this function off as a thread- so as not to block server-client thread.
        self.cycle += 1
        print "\n----------------------------CYCLE %s----------------------------\n" % (
            self.cycle, )
        self.initCycle()

    def addPlayer(self, player):
        if self.closed:
            raise Exception()
        self.players.append(player)
        if len(self.players) == self.maxPlayers:
            self.closed = True

    def generateUID(
        self, thing
    ):  # TODO: change so that it takes the object being assigned a UID, then appends it to a list, so it doesn't need to use a class property
        temp = self.UIDcounter
        self.UIDcounter += 1
        self.entities.append(thing)
        return temp

    def getEntity(self, UID):
        for entity in self.entities:
            if entity.UID == UID:
                return entity
        return None

    def load(self):
        pass

    def fight(self, entity1, entity2):
        if entity1.parent != entity2.parent:
            return 1
        strength1 = sum([
            thing._fightStrength()
            for thing in self.map.getLocationArray(entity1)
        ])
        strength2 = sum([
            thing._fightStrength()
            for thing in self.map.getLocationArray(entity2)
        ])
        value1 = sum([random.randint(1, strength1) for _ in xrange(2)]) - 1
        value2 = sum([random.randint(1, strength2) for _ in xrange(2)]) - 1
        entity1.hurt(value2)
        entity2.hurt(value1)

        return 0
Exemplo n.º 48
0
class Options(state_engine.GameState):
    """
    The class for the options state.
    """
    def __init__(self):
        """
        @rtype: None
        """
        state_engine.GameState.__init__(self)
        self.current_select = 0
        self.all_opts = {
            "CHARACTER": ["mario", "luigi", "toad", "peach"],
            "DIFFICULTY": ["none", "easy", "normal", "difficult", "expert"],
            "NUMBER_OF_PLAYER": [1, 2],
            "LAYER0": ["layer0/0.png", "layer0/1.png"],
            "LAYER1": ["layer1/0.png", "layer1/1.png"]
        }
        self.current_opts = load_options()
        for elem in self.current_opts.keys():
            self.current_opts[elem] = self.all_opts[elem].index(
                self.current_opts[elem])
        self.available_opts = list(self.all_opts)
        self.available_opts.sort()
        self.options_map = Map(None, None)

    def write_opts(self):
        dict_opts = {}
        for k in self.all_opts:
            dict_opts[k] = self.all_opts[k][self.current_opts[k]]
        with open("options_file.data", "wb") as f:
            pickle.dump(dict_opts, f, pickle.HIGHEST_PROTOCOL)

    def get_event(self, event):
        """
        Do something according to the last event that happened.
        @param event: the last event that occurred.
        @type event: pygame.event
        @rtype: None
        """
        if event.type == pg.KEYDOWN:
            if event.key == pg.K_ESCAPE:
                self.next_state = "MAIN_MENU"
                self.write_opts()
                self.persist["MAP"] = self.options_map
                self.done = True
            elif event.key == pg.K_UP:
                self.current_select = (self.current_select - 1) % len(
                    self.available_opts)
            elif event.key == pg.K_DOWN:
                self.current_select = (self.current_select + 1) % len(
                    self.available_opts)
            elif event.key == pg.K_RIGHT:
                self.current_opts[self.available_opts[self.current_select]] = \
                    (self.current_opts[self.available_opts[self.current_select]] + 1) % \
                    len(self.all_opts[self.available_opts[self.current_select]])
            elif event.key == pg.K_LEFT:
                self.current_opts[self.available_opts[self.current_select]] = \
                    (self.current_opts[self.available_opts[self.current_select]] - 1) % \
                    len(self.all_opts[self.available_opts[self.current_select]])

    def update(self):
        """
        Update the state.
        @rtype: None
        """
        self.options_map.update(5)

    def startup(self, persistent):
        """
        Called when a state resumes being active.
        @param persistent: a dict passed from state to state
        @type persistent: dict{}
        @rtype: None
        """
        self.persist = persistent
        if "MAP" in self.persist:
            self.options_map = self.persist["MAP"]

    def draw(self, surface):
        """
        Draw everything to the screen.
        @param surface: The surface that will be displayed.
        @type surface: pygame.Surface
        @rtype: None
        """
        width, height = surface.get_size()

        self.options_map.display(surface)

        for i, k in enumerate(self.available_opts):
            if i == self.current_select:
                text_color = (255, 0, 0)
            else:
                text_color = 0, 0, 0
            text = self.font.render(
                k + " " + str(self.all_opts[k][self.current_opts[k]]), 1,
                text_color)
            width_text, height_text = text.get_size()
            surface.blit(text, ((width - width_text) / 2,
                                (height - height_text) / 2 + (2 * i) * 24))
Exemplo n.º 49
0
class Scene(ScrollableLayer):
    anchor = (0, 0)
    is_event_handler = True
    walls = []
    labels = []
    #collision = cm.CollisionManagerBruteForce()
    #palitraCollision = cm.CollisionManagerBruteForce()

    focusX = 1500
    focusY = 500

    currentBlock = CurrentBlockDescriptor()

    appendMode = 1

    buttonsTextHelp = "q-pallet, 1 - background, 2 - unmovable background, 3 - indestructible object, 4 - object, t - increase type"

    viewPoint = (0, 0)
    windowWidth = 2000
    windowHeight = 800

    def __init__(self, keyboard, scroller):
        super().__init__()
        self.set_view(0, 0, self.windowWidth, self.windowHeight, 0, 0)
        self.palitra = Palitra()
        self.map = Map()
        self.add(self.map, z=2)
        self.add(self.palitra, z=3)

        self.keyboard = keyboard
        self.scroller = scroller
        # self.buttonsProvider = ButtonsProvider()
        # self.objectProvider = ObjectProvider(self.keyboard, self.collision, self.palitraCollision)
        #
        # self.helperLayer = cocos.layer.Layer()
        # self.buttonsInfo = Label(self.buttonsTextHelp, font_name='Helvetica', font_size=12, anchor_x='left',  anchor_y='top')
        # self.text = Label("Some text", font_name='Helvetica', font_size=12, anchor_x='left',  anchor_y='bottom')
        # self.helperLayer.add(self.text)
        # self.helperLayer.add(self.buttonsInfo)
        # self.add(self.helperLayer, z=5)
        #
        # self.palitra = cocos.layer.Layer()
        # self.palitraObject = []
        # self.add(self.palitra, z=2)

    def setMenuLayer(self, menu_layer):
        self.menu_layer = menu_layer
        self.menu_layer.visible = False

    def checkButtons(self, dt):
        x_direction = self.keyboard[key.LEFT] - self.keyboard[key.RIGHT]
        y_direction = self.keyboard[key.DOWN] - self.keyboard[key.UP]
        print(self.keyboard[key.DOWN], self.keyboard[key.UP])
        x, y = self.position

        if self.keyboard[key.Q]:
            self.palitra.visible = 1 - self.palitra.visible
            sleep(0.2)

        if self.keyboard[key.E]:
            self.menu_layer.visible = 1 - self.menu_layer.visible
            sleep(0.2)

        if x_direction:
            x += x_direction * 20

        if y_direction:
            y += y_direction * 20

        if x_direction or y_direction:
            self.set_view(0, 0, self.windowWidth, self.windowHeight, x, y)
            self.palitra.updatePosition(self.windowWidth, self.windowHeight,
                                        self.position)

        if self.keyboard[key.SPACE]:
            self.set_view(0, 0, self.windowWidth, self.windowHeight, 0, 0)
            self.palitra.updatePosition(self.windowWidth, self.windowHeight,
                                        self.position)

    def on_mouse_drag(self, x, y, dx, dy, buttons, modifiers):
        x, y = self.getCoordByViewPoint(x, y)
        leftClick = buttons == 1
        rightClick = buttons == 4

        if not self.palitra.visible:
            if leftClick and self.currentBlock:
                self.map.addBrick(x, y, self.currentBlock)
            if rightClick: self.map.removeBrick(x, y)

    def on_mouse_press(self, x, y, buttons, modifiers):
        if self.palitra.visible:
            self.currentBlock = self.palitra.click(x, y)

        x, y = self.getCoordByViewPoint(x, y)
        leftClick = buttons == 1
        rightClick = buttons == 4

        if not self.palitra.visible:
            if leftClick and self.currentBlock:
                self.map.addBrick(x, y, self.currentBlock)
            if rightClick: self.map.removeBrick(x, y)

        sleep(0.01)

        #self.updateInfo(str(x) + ',' + str(y))

    def resize(self, width, height):
        self.viewPoint = (width // 2, height // 2)
        self.windowWidth = width
        self.windowHeight = height
        self.palitra.resizeMap(width, height, self.viewPoint)

        #self.buttonsInfo.position = (0, self.currentHeight)
        #self.setLayersPosition()
        #self.resizeMap()

    def getCoordByViewPoint(self, x, y):
        view_x, view_y = self.viewPoint
        pos_x, pos_y = self.position
        x = (x - view_x) - (pos_x - view_x)
        y = (y - view_y) - (pos_y - view_y)
        return (x, y)
Exemplo n.º 50
0
    def search(self, city, params, low, high):
        reqo = Req()
        mapo = Map()

        self.g = reqo.initialSearch(city, low, high)

        nHouses = json.loads(self.g.text)['total_records']
        temp = [House(0, 0, 0) for i in range(nHouses)]

        nParams = len(params)

        paramlist = [x for x in params if x is not None]

        nParams = len(paramlist)

        for i in range(0, nHouses):
            lat = json.loads(self.g.text)['results'][i]['lat']
            lng = json.loads(self.g.text)['results'][i]['long']
            mlsid = json.loads(self.g.text)['results'][i]['mls_id']

            temp[i] = House(mlsid, lat, lng)

            if (nParams >= 1):
                temp[i].setWTime(
                    mapo.getDistanceTime((lat, lng),
                                         mapo.getGeoCode(paramlist[0])))
            if (nParams >= 2):
                temp[i].setETime(
                    mapo.getDistanceTime((lat, lng),
                                         mapo.getGeoCode(paramlist[1])))
            if (nParams >= 3):
                temp[i].set1Time(
                    mapo.getDistanceTime((lat, lng),
                                         mapo.getGeoCode(paramlist[2])))
            if (nParams >= 4):
                temp[i].set2Time(
                    mapo.getDistanceTime((lat, lng),
                                         mapo.getGeoCode(paramlist[3])))
            if (nParams >= 5):
                temp[i].set3Time(
                    mapo.getDistanceTime((lat, lng),
                                         mapo.getGeoCode(paramlist[4])))
        print("\n")

        return temp
Exemplo n.º 51
0
class Room:
    def __init__(self, map_width, map_height, players_amount, room_id, logger):
        self.id = room_id  # TODO: Hash?
        self.log = logger
        self.map = Map(map_width, map_height, logger)
        self.players_amount = players_amount
        self.players = [
            Player(local_id, *self.calc_start_pos(local_id))
            for local_id in range(players_amount)
        ]
        self.initial_update()  # Update map with initial players position

        self._turn_owner = 0
        self.steps_left = 3

        self.log.write(
            f'Room with {len(self.players)} players and ID:{self.id} created')

    def __str__(self):
        return ROOM_INFO.format(self.id, len(self.players),
                                self.get_turn_owner(), self.steps_left)

    def turn(self, player_id, direction):
        self.log.write(
            f'Player {player_id} with ID{player_id} turns {direction}')
        if not DIRECTIONS.get(direction):  # Necessary?&
            err = f'Wrong direction: {direction}; Possible directions: {DIRECTIONS.keys()}'
            self.log.error(err)
            raise ValueError(err)

        self.log.write(
            f'Direction {direction} is valid; Turn owner {self.get_turn_owner()}; Your ID: {player_id}'
        )
        if self.get_turn_owner() != player_id:
            err = f'You are player {player_id}; Player {self.get_turn_owner()} should turn now'
            self.log.error(err)
            return False, err

        player, position_delta = self.players[player_id], DIRECTIONS[direction]
        self.log.write(f'Checks passed, player {player} stepping {direction}')

        status, cell_content = self.map.step(player, position_delta)

        self.log.write(
            f'Player stands on cell' if status else f'Failed to stand on cell')

        return status, self.get_turn_owner(change=True)

    def get_turn_owner(
        self,
        change=False
    ):  # Change when turning, don't change when comparing to player's id
        if change:  # Maybe change every second (third ?) call
            if self.steps_left:  # Steps amount decreased if != 0
                self.steps_left -= 1

            if not self.steps_left:  # else?
                self.steps_left = STEPS_PER_TURN
                if self._turn_owner < len(
                        self.players
                ):  # If last player's step - new round, zero player's turn
                    self._turn_owner += 1
                else:
                    self._turn_owner = 0
        return self._turn_owner

    def calc_start_pos(self, id):
        # Place players
        return self.map.width // self.players_amount * id, self.map.height // self.players_amount * id

    def initial_update(self):
        self.log.write(f'Initial players positioning')
        for player in self.players:
            x, y = player.x, player.y

            self.log.write(
                f'Player {player} with ID{player.id} now stands on (X:Y): ({x}:{y})'
            )
            self.map.cells[x][y] = str(player)

    def get_map(self):
        return self.map.get()
Exemplo n.º 52
0
def bot_routine(user_id: int, game_id: int, token: str) -> None:
    """mod: this function is main function of the module."""
    current_map = Map()
    path_finder = PathFinder()
    start_position = None
    next_move = None
    turbo_flag = False
    current_state_response = None
    game_status_flag = True

    def send_current_state_request() -> None:
        """mod: this function sends REST API request."""
        global api_gateway_urls, get_current_state_method
        nonlocal user_id, game_id, token, current_state_response
        current_state_response = requests.get(
            api_gateway_urls + get_current_state_method,
            params={'GameId': game_id})
        current_state_response.raise_for_status()

    def send_post_move_request() -> None:
        global api_gateway_urls, post_move_method
        """mod: this function sends REST API request."""
        nonlocal start_position, next_move, turbo_flag, user_id, game_id, token
        direction = None
        if next_move.row_index > start_position.row_index:
            direction = 'UP'
        elif next_move.row_index < start_position.row_index:
            direction = 'DOWN'
        elif next_move.column_index > start_position.column_index:
            direction = 'RIGHT'
        elif next_move.column_index < start_position.column_index:
            direction = 'LEFT'
        response = requests.post(
                api_gateway_urls + post_move_method,
                json={'Direction': direction, 'UserID': user_id, 'TurboFlag': turbo_flag})
        response.raise_for_status()

    def send_unregister_user_request() -> None:
        """mod: this function sends REST API request."""
        global api_gateway_urls, unregister_user_method
        nonlocal token
        response = requests.delete(api_gateway_urls + unregister_user_method,
                                   params={"token": token})
        response.raise_for_status()

    def parse_current_state_response() -> None:
        """mod: this function parses REST API response."""
        nonlocal current_state_response, current_map, path_finder, start_position, game_status_flag, user_id
        game_state = json.loads(current_state_response.form.get('data'))

        time_to_update = 0
        current_map.map_scheme['height'] = game_state['map']['height']
        current_map.map_scheme['width'] = game_state['map']['width']
        current_map.obstacles_positions = game_state['map']['obstacles']
        current_map.bots_positions = game_state['map']['power-ups']
        current_map.traces_positions = game_state['map']['tracers']
        path_finder.tron_map = current_map

        players_positions = list()
        for player in game_state['players']:
            if player['id'] == user_id:
                start_position = player['headPosition']
                path_finder.start_position = start_position
                path_finder.turbos_number = player['turboAmount']
                time_to_update = player["timeToUpdate"]
            else:
                players_positions.append(player['headPosition'])
        current_map.players_positions = players_positions
        if not time_to_update:
            game_status_flag = False
        elif time_to_update < 1:
            path_finder.algorithm = 'Random'
        elif time_to_update < 2:
            path_finder.algorithm = 'Survival'
        else:
            path_finder.algorithm = 'A*'

    while True:
        try:
            send_current_state_request()
            parse_current_state_response()
            if not game_status_flag:
                send_unregister_user_request()
                return
            try:
                next_move, turbo_flag = path_finder.get_direction()
                send_post_move_request()
            except NoSolution:
                continue
        except requests.exceptions.HTTPError as http_err:
            print(f'HTTP error occurred: {http_err}')
            return
Exemplo n.º 53
0
        pygame.display.update()


if __name__ == '__main__':
    os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (5, 25)

    colors = {
        "GRAY": (110, 110, 110),
        "DARK_GRAY": (50, 50, 50),
        "YELLOW": (255, 255, 0),
        "BLUE": (0, 0, 255),
        "RED": (255, 0, 0)
    }

    pygame.init()

    win_dim = (900, 600)
    window = pygame.display.set_mode(win_dim)
    pygame.display.set_caption("SIMULATION VER2")

    objectNumber = 0

    map_loc = {
        "top_left": (win_dim[0] // 2 - 300, win_dim[1] // 2 - 250),
        "bottom_right": (win_dim[0] // 2 + 50, win_dim[0] // 2 + 50)
    }
    map = Map(window, map_loc["top_left"], colors["GRAY"], colors["RED"], 30,
              colors["YELLOW"], colors["BLUE"])

    main()
Exemplo n.º 54
0
from map import Map
new_map = Map(radius=0.177, clearance=0.25)
import math
import numpy as np

class Node():

    def __init__(self, parent=None, position=None):
        self.parent = parent
        self.position = position

        self.f = 0
        self.g = 0
        self.h = 0

def astar(start, goal, step_size):
    "Return list of tuples for path"

    start_node = Node(None, start)
    goal_node = Node(None, goal)

    #initialize frontier and closed list
    Frontier = []
    closed_list = []

    Frontier.append(start_node)
    
    while(len(Frontier) > 0):
        # print(len(Frontier))
        current_node = Frontier[0]
        current_index = 0
    'xmax': 30,
    'ymin': -30,
    'ymax': 30
  }

  # d_sigma = 0.1 # Controls the spread of the particles
  # yaw_sigma = 0.2 / 0.025  # deviation for yaw, devide by 0.025 since the time duration is 0.025.
  linear_deviation = 0.4
  yaw_deviation = 0.1

  # Initalize robot position
  initial_pos = np.array([0,0,0]) # x, y, theta
  robot_pos = RobotPos(initial_pos, numParticles=num_particles, particle_threshold= 0.5 * num_particles)
  
  # Initialize map;
  map = Map(config)
  title = "Displaying robot at the 0 epoch."
  map.plot(robot_pos, robot_trajectory = None, title = title, save_fig = False)


  # Preprocess IMU and Encoder measurements;
  encoder_counts = data['encoder_counts'][:, 300:] # Skipping the first 300 hundred measurements;
  encoder_timestamp = data['encoder_stamps'][300:]

  imu_yaw_velocity = data['imu_angular_velocity'][2, :]
  imu_timestamps = data['imu_stamps']

  filtered_imu_yaw_velocity = low_pass_imu(imu_yaw_velocity)

  # Transform the lidar data to the body frame;
  lidar_timestamps = data['lidar_stamps']
Exemplo n.º 56
0
def main():
    args = parse_arguments()
    map = Map(args.map_folder)
    mapper = Mapper(map)
    raw_coords = list(map.getCoordinatesToDraw())
    coords = []
    for row, col in raw_coords:
        if row % 4 != 0 or col % 2 != 0:
            continue
        coords.append(gridToCoords(row, col))
    coords.sort()

    time_last_message = time.perf_counter()
    last_available_tiles = set()
    for coord in coords:
        finished_tiles = mapper.get_available_tiles()
        if coord in finished_tiles:
            continue
        time_current = time.perf_counter()
        if time_current - time_last_message > 1.0:
            print(
                f"{100.0 * mapper.get_cnt() / len(coords):.2f}% done, added tiles: {finished_tiles - last_available_tiles}"
            )
            last_available_tiles = finished_tiles.copy()
            time_last_message = time_current
        mapper.stupidMakeTiles(*coord)
    """
    step = 0
    for row, col in coords:
        step += 1
        print("[{}%]".format(100.0 * step / len(coords)))
        if row % 4 != 0 or col % 2 != 0:
            continue
        path = os.path.join("data", "5", "{}".format(row / 4 ))
        if not os.path.exists(path):
            os.makedirs(path)
        dummyMakeTile(row, col).save(os.path.join(path, "{}.png".format(col / 2)))
    """

    # zoom 4 ---> 0

    to_join = raw_coords

    for zoom in range(4, -1, -1):
        new_join = set()
        for row, col in to_join:
            if zoom == 4:
                if row % 4 != 0 or col % 2 != 0:
                    continue
                row //= 4
                col //= 2
            if row % 2 == 1:
                row -= 1
            if col % 2 == 1:
                col -= 1
            new_join.add((row, col))
        to_join = new_join

        for row, col in to_join:
            # print("join {} {}".format(row, col))
            R = row // 2
            C = col // 2
            path = os.path.join("data", str(zoom), str(R))
            if not os.path.exists(path):
                os.makedirs(path)
            canvas = Image.new("RGBA", (BLOCK_SIZE, BLOCK_SIZE))
            for dx in range(0, 2):
                for dz in range(0, 2):
                    try:
                        tile = Image.open(
                            os.path.join(
                                "data",
                                str(zoom + 1),
                                str(row + dx),
                                "%d.png" % (col + dz),
                            )).convert("RGBA")
                    except IOError:
                        tile = Image.new("RGBA", (BLOCK_SIZE, BLOCK_SIZE))
                    tile = tile.resize((BLOCK_SIZE // 2, BLOCK_SIZE // 2))
                    canvas.paste(tile,
                                 (dz * BLOCK_SIZE // 2, dx * BLOCK_SIZE // 2),
                                 tile)
            canvas.save(os.path.join(path, "%d.png" % C))
Exemplo n.º 57
0
class MCL:
    def __init__(self, num_particles=100):
        self.measurement_sigma = 1
        self.movement_sigma = 1
        self.delta = 2  # distortion coeff
        self.num_particles = num_particles

        self.particles = []
        for _ in range(num_particles):
            self.particles.append(Particle())

        self.pose = Particle()
        self.map = Map()
        self.reset()

    def measurement_model(self, current_sonar_reading, location):
        expected_sonar_reading = self.map.expected_sonar_reading(location)
        prob = gaussian(current_sonar_reading, expected_sonar_reading,
                        self.measurement_sigma)
        return prob

    def motion_model(self, movement_distance):
        return random.normalvariate(movement_distance, self.movement_sigma)

    def measurement_update(self, current_sonar_reading):
        for particle in self.particles:
            particle.belief = self.measurement_model(current_sonar_reading,
                                                     particle.location)
        self.resample()

    def motion_update(self, movement_distance):
        for particle in self.particles:
            particle.location += int(self.motion_model(movement_distance))
            if particle.location > self.map.length:
                particle.location = self.map.length
            # elif particle.location < 0:
            #     particle.location = 0

    '''
        Calculate and return the average location and belief as the position estimation
    '''

    def calculatePose(self):
        location = 0
        belief = 0
        for particle in self.particles:
            location += particle.location * particle.belief
            belief += particle.belief
        self.pose.location = int(location / self.num_particles)
        self.pose.belief = belief / self.num_particles

    def resample(self):
        resampled = []
        sum_belief = 0
        for particle in self.particles:
            sum_belief += particle.belief

        avg_belief = sum_belief / self.num_particles
        for particle in self.particles:
            if particle.belief > avg_belief:  # if it deserves, generate a clone with random distortion
                temp = particle
                temp.location += int(self.delta *
                                     random.random())  # distortion
                if temp.location > self.map.length:
                    temp.location = self.map.length
                resampled.append(temp)

        for i in range(self.num_particles):
            if i < len(resampled):  # copy the resampled ones
                self.particles[i] = resampled[i]
            else:  # fill the list with random particles
                temp = Particle()
                self.particles[i] = self.reset_individual(temp)

    '''
        Reset all particles with random locations and same belief
    '''

    def reset(self):
        for particle in self.particles:
            particle = self.reset_individual(particle)

    def reset_individual(self, particle):
        particle.location = random.randrange(self.map.length)
        particle.belief = 1 / self.num_particles
        return particle
Exemplo n.º 58
0
                for enemy in enemies:
                    if contact(shot, enemy):
                        enemy.set_damage(shot.get_damage())
                for player in players:
                    if contact(shot, player):
                        player.set_damage(shot.get_damage())
                create_impact(shot.get_position(), shot.get_direction())
                shots.remove(shot)
            # Caso 3: El disparo ha alcanzao su maxima distancia
            else:
                shots.remove(shot)

        if len(enemies) == 0:
            end_menu(True)
            game_over = True

        elif len(players) == 0:
            end_menu(False)
            game_over = True

        pygame.display.update()


pygame.init()
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGTH))
clock = pygame.time.Clock()
map = Map()
map.generate_soldiers(players)
map.generate_enemies(enemies)
map_surface = map.get_map_surface()
run_game()
Exemplo n.º 59
0
        screen.blit(object.image, object.pos)


def drawEnemy(enemyList):
    for enemy in enemyList:
        enemy.move()


#SETUP
pygame.init()
screen = pygame.display.set_mode([384, 384])
tileSet = [
    pygame.image.load('..\\Art\\Grass.png').convert(),
    pygame.image.load('..\\Art\\Dirt.png').convert()
]
map = Map(12, 12, 32, tileSet)
setupMap(map)

player = GameObject(
    pygame.image.load('..\\Art\\WhiteBoon.png').convert(), (playerX, playerY))
enemy = Enemy(1, getMovePath())

gameObjects.append(player)
gameObjects.append(enemy)

pygame.display.set_caption("Boons")

#loadBackground('..\\Art\\RedBoon.png',32, 384,384)

#Game Settings
clockRate = pygame.time.Clock()
Exemplo n.º 60
0
from player import Player
from map import Map
map = Map(15, 15)
map.loop()