⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 world.java

📁 SIMULATION FOURMILIERE -3D-ISOMETRIQUE
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
        int x = p.getX();
        int y = p.getY();
        if (tab[y][x].isObstacle())
            return false;
        /* If the current tile is an antHill, we could have many insects waiting for the tile
         * become free before appearing. Si if there is already an insect, we don't put the new
         * at this place. We do nothing. This new insect will apear on the map at his first move. 
         */
        if (tab[y][x].getInsect() == null) {
            tab[y][x].setInsect(insect);
            
            // We inform the model that there is an insect here
            updateModel(x, y, true);
        }
        return true;
    }
    
    
    /**
     * Move an insect to a tile to another
     * @param insect    insect to move
     * @param dest      point to fix the insect
     * @return true if the insect has moved (eg. if the destination is not an obstacle)
     */
    public boolean moveInsect(Insect insect, WorldPoint dest) {
        if (!isCrossable(dest) )
            return false;
        int x = insect.getPos().getX();
        int y = insect.getPos().getY();

        /* There is a possibility that more than one insect is on the current tile : 
         * if it is an antHill, and if new ants are waiting to appear. So before removing
         * the insect of the old tile, we check if it is the good one !
         */
        Insect test = tab[y][x].getInsect();
        if (test != null && test.equals(insect))
            tab[y][x].setInsect(null);
        tab[dest.getY()][dest.getX()].setInsect(insect);
        // We inform the grid that the 2 tiles have changed
        updateModel(x, y, false);
        updateModel(dest.getX(), dest.getY(), false);
        return true;
    }
    
    
    /**
     * Remove an insect from the floor
     * @param insect    insect to dereference
     */
    public void removeInsect(Insect insect) {
        WorldPoint curPos = insect.getPos();
        int x = curPos.getX();
        int y = curPos.getY();
        /* There is a possibility that more than one insect is on the current tile : 
         * if it is an antHill, and if new ants are waiting to appear. So before removing
         * the insect, we check if it is the good one !
         */
        Insect test = tab[y][x].getInsect();
        if (test != null && test.equals(insect)) {
            tab[curPos.getY()][curPos.getX()].setInsect(null);
            updateModel(x, y, false);
        }
    }
    
    
    /**
     * Return the list of the teams (the first is the one we play with)
     * @return the list of the teams
     */
    public List<Team> getTeams() {
        return tabTeam;
    }
    
    
    /**
     * Erase all the teams presents.
     */
    public void clearTeams() {
        tabTeam.clear();
    }
    
    
    /**
     * Update the elements presents in a specific tile
     * BE CAREFUL : this will store the result in a DoubleBuffered image. So changes 
     *              won't be visible until we call the refresh() method.
     * >> If you want an immediate change, use updateModelDirect()
     * @param x         the X coord of the tile to refresh
     * @param y         the Y coord of the tile to refresh
     * @param isDirect  if false, the change is store in a double buffered picture, 
     *                  and will be displayed only by a refresh() call
     * @see #refresh()
     */
    public void updateModel(int x, int y, boolean isDirect) {
        // Background
        EnumSet<Values> elems = EnumSet.noneOf(Values.class);
        elems.addAll(tab[y][x].getPictures());

        // Got an insect here ?
        Insect insect = tab[y][x].getInsect();  // Got insect here ?
        if (insect != null)
            elems.addAll(insect.getPictures());
        // Got a selection point here ?
        if (selectedPoint != null && selectedPoint.equals(getPoint(x, y)))
            elems.add(Values.select);
        
        // We update the graphic
        if (! isDirect)
            model.setDeffered(x, y, elems);
        else
            model.setDirect(x, y, elems);
    }
    

    /**
     * Update all the tiles'pictures of the game
     * @see #refresh()
     */
    public void updateAllModel() {
        for (int y = 0; y < sizeY; ++y)
            for (int x = 0; x < sizeX; ++x)
                updateModel(x, y, true);
        refresh();
    }
    
    
    /**
     * Force the GridPane to redraw everything
     */
    public void refresh() {
        model.swap();
    }
    
    
    /**
     * Return the PathFinding object, that permits to search for fastests paths
     * @return the PathFinding
     */
    public PathFinding getPathFinding() {
        return path;
    }
    

    /**
     * Save the current game in a file.
     * The method compresses the datas
     * @param file  file where we save
     */
    public void saveGame(String file) throws BadWorldFormatException  {
        try {
            ObjectOutputStream out = new ObjectOutputStream(new GZIPOutputStream(new FileOutputStream(file)));
            // Compress Serialize of the current object
            out.writeObject(new Integer(sizeX));
            out.writeObject(new Integer(sizeY));
            out.writeObject(tab);
            out.writeObject(tabTeam);
            out.writeObject(tabFood);
            out.flush(); // flush the memory
            out.close(); // close the stream
        } catch (Exception e) {
            throw new BadWorldFormatException(e.getMessage()); 
        }
    }


    /**
     * Load the current game elements from a file.
     * The method uncompresses the datas
     * @param file  file loaded
    */
    @SuppressWarnings("unchecked")
    /* We KNOW what we are doing. And we KNOW that the
        result will be good !!! The only error could be when a third-person create a level with
        wrong objects in it. But then it generates an exception !!
    */
    public void loadGame(String file) throws BadWorldFormatException {
        /* We store the file content in temporary objects. This way, if a file is corrupted,
        * we don't corrupt our real variables !!! */
        Integer tmpSizeX;
        Integer tmpSizeY;
        Floor[][] tmpTab;
        ArrayList<Team> tmpTabTeam;
        ArrayList<WorldPoint> tmpTabFood;
        // We unserialize, uncompress the file and store its content
        try {
            ObjectInputStream in = new ObjectInputStream(new GZIPInputStream(new FileInputStream(file)));
            tmpSizeX = (Integer)in.readObject();
            tmpSizeY = (Integer)in.readObject();
            tmpTab = (Floor[][])in.readObject();
            tmpTabTeam = (ArrayList<Team>)in.readObject();
            tmpTabFood = (ArrayList<WorldPoint>) in.readObject();
            in.close(); // close the stream
        } catch (Exception e) {
            throw new BadWorldFormatException(e.getMessage()); 
        }
        // And if everything goes right, we store the result in the good variables
        sizeX = tmpSizeX;
        sizeY = tmpSizeY;
        tab = tmpTab;
        tabTeam = tmpTabTeam;
        tabFood = tmpTabFood;
        path = new PathFinding(this);
        @SuppressWarnings("unchecked") 
        Set<Values>[] array = (Set<Values>[]) new Set<?>[sizeX * sizeY]; 
        model = new DefaultGridModel<Values>(sizeY, sizeX, Arrays.asList(array));
        //model = new DefaultGridModel<Values>(sizeY, sizeX, Arrays.asList(new Set[sizeX * sizeY]));
    }

    
    /**
     * Save the current level in ascii mode
     * Here are the possible elements :
     *   - 'space' for empty blocks (grass)
     *   - '#' for walls
     *   - 'o' for food
     *   - '1' for the player's antHill
     *   - '2' for other antHills
     * @param file  file where we save
     */
    public void saveLevel(String file) throws BadWorldFormatException  {
        try {
            // We open the file
            BufferedWriter out = new BufferedWriter(new FileWriter(file));
            
            // We write the current dimensions
            String sX = Integer.toString(sizeX);
            String sY = Integer.toString(sizeY);
            out.write(sX); out.newLine();
            out.write(sY); out.newLine();
            
            // We write a representation of all the tiles
            for (int y=0; y < sizeY; ++y) {
                for (int x=0; x < sizeX; ++x) {
                    Floor f = tab[y][x];
                    Values foreType = f.getType();
                    StorableWorldElem c = null;
                    switch (f.getBackgroundType()) {
                    case grass :
                    	c = StorableWorldElem.GRASS;
                    	if (foreType != null)
	                    	switch (foreType) {
	                    	case food: 			c = StorableWorldElem.GRASS_FOOD; break;
	                    	case rock: 			c = StorableWorldElem.GRASS_ROCK; break;
	                    	case antHill: 		c = StorableWorldElem.GRASS_ANTHILL; break;
	                    	case antHill_enemy: c = StorableWorldElem.GRASS_ANTHILL_EN; break;
	                    	}
                    	break;
                    case desert:
                    	c = StorableWorldElem.DESERT;
                    	if (foreType != null)
	                    	switch (foreType) {
	                    	case food: 			c = StorableWorldElem.DESERT_FOOD; break;
	                    	case rock: 			c = StorableWorldElem.DESERT_ROCK; break;
	                    	case antHill: 		c = StorableWorldElem.DESERT_ANTHILL; break;
	                    	case antHill_enemy: c = StorableWorldElem.DESERT_ANTHILL_EN; break;
	                    	}
                    	break;
                    case water:
                    	c = StorableWorldElem.WATER;
                    }                    
                    out.write(StorableWorldElem.getCharValue(c));
                }
                out.newLine();
            }
            // And we close
            out.flush();
            out.close();
        } catch (Exception e) {
        	e.printStackTrace();
        	throw new BadWorldFormatException(e.getMessage()); 
        }
    }
    

    /**
     * Load a level from a file. This file is an ascii one, with a special character for element
     * For a list of acceptable characters to write, see the SaveLevel function 
     * Verifications of what number of what element is allowed are not made here !!
     * This function takes the elements ant put them in the ground. That's all.
     * @param file the file we want to load
     * @see #saveLevel(String)
     */
    public void loadLevel(String file) throws BadWorldFormatException {
        /* We store the file content in temporary objects. This way, if a file is corrupted,
        * we don't corrupt our real variables !!! */
    	Integer tmpSizeX;
        Integer tmpSizeY;
        Floor[][] tmpTab;
        ArrayList<Team> tmpTabTeam = new ArrayList<Team>();
        ArrayList<WorldPoint> tmpTabFood = new ArrayList<WorldPoint>();
        int nbAntHill = 0;
        int nbAntHillOpp = 0;
        
        // We try to get the file
        try {
            BufferedReader in = new BufferedReader(new FileReader(file));
            tmpSizeX = Integer.parseInt(in.readLine());
            tmpSizeY = Integer.parseInt(in.readLine());
            tmpTab = new Floor[tmpSizeY][tmpSizeX];
            for (int y = 0; y < tmpSizeY; ++y) {
                // Before using a ling, we check if she is OK
                String line = in.readLine();
                if (line == null)
                    throw new BadWorldFormatException("Not enough colums found");
                if (line.length() != tmpSizeX)
                    throw new BadWorldFormatException("Bad number of tiles for line " + y);
                // If the size is good, we convert all the characters in Floor elements
                for (int x = 0; x < tmpSizeX; ++x) {
                    Values valBack = Values.grass;
                    Values valFore = null;
                    StorableWorldElem c = StorableWorldElem.getValueChar(line.charAt(x));
                    switch (c) {
	                    case GRASS_FOOD			: valFore = Values.food; break;
	                    case GRASS_ROCK			: valFore = Values.rock; break;
	                    case GRASS_ANTHILL		: valFore = Values.antHill; nbAntHill++; break;
	                    case GRASS_ANTHILL_EN	: valFore = Values.antHill_enemy; nbAntHillOpp++; break;
	                    case DESERT				: valBack = Values.desert; break;
	                    case DESERT_FOOD		: valBack = Values.desert; valFore = Values.food; break;
	                    case DESERT_ROCK		: valBack = Values.desert; valFore = Values.rock; break;
	                    case DESERT_ANTHILL		: valBack = Values.desert; valFore = Values.antHill; nbAntHill++; break;
	                    case DESERT_ANTHILL_EN	: valBack = Values.desert; valFore = Values.antHill_enemy; break;
	                    case WATER				: valBack = Values.water;
                    }
                    tmpTab[y][x] = new Floor(valFore, valBack,x, y);
                }
            }
            in.close(); // close the stream
        } catch (Exception e) {
            throw new BadWorldFormatException(e.getMessage());
        }
        // And if everything goes right, we store the result in the good variables
        sizeX = tmpSizeX;
        sizeY = tmpSizeY;
        tab = tmpTab;
        tabTeam = tmpTabTeam;
        tabFood = tmpTabFood;
        path = new PathFinding(this);
        WorldBlur.blurMap(tab);
        //model = new DefaultGridModel<Values>(sizeY, sizeX, Arrays.asList(new Set[sizeX * sizeY]));
        @SuppressWarnings("unchecked") 
        Set<Values>[] array = (Set<Values>[]) new Set<?>[sizeX * sizeY]; 
        model = new DefaultGridModel<Values>(sizeY, sizeX, Arrays.asList(array));

    }
    
    
    /**
     * Give all the positions of the food in the map
     * @return the List of food
     */
    public List<WorldPoint> getFood() {
        return tabFood;
    }
    
    
    /**
     * Give the point of the current tile
     * @param x the x coord
     * @param y the y coord
     * @return the point of this position, else null of the position is not available
     */
    public WorldPoint getPoint(int x, int y) {
        return isPositionAvailable(x,y)
            ? tab[y][x].getPoint()
            : null;
    }
    
      
    /**
     * Give the weight of the tile. This represents the difficulty we will have
     * to cross this tile
     * @return the weight
     */
    public int getWeight(final int x, final int y) {
    	return tab[y][x].getWeight();
    }
    
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -