Java项目:16款java游戏(java+swing)

源码获取:博客首页 "资源" 里下载!

功能简介:

16款Java小游戏

 

 

 

文件服务类:

public class Fileinput
{

    public Fileinput()
    {
        scanner = new Scanner(System.in);
    }

    public Fileinput(String s)
    {
        try
        {
            scanner = new Scanner(new File(s));
        }
        catch(Exception exception) { }
    }

    public String[] getParsedLine(String s)
    {
        return scanner.nextLine().split(s);
    }

    public int[] getParsedInts(String s)
    {
        String as[] = scanner.nextLine().split(s);
        int ai[] = new int[as.length];
        for(int i = 0; i < as.length; i++)
            ai[i] = Integer.parseInt(as[i]);

        return ai;
    }

    public String getLine()
    {
        return scanner.nextLine();
    }

    public int getInt()
    {
        String s = scanner.nextLine();
        Integer integer = new Integer(s);
        return integer.intValue();
    }

    public double getDouble()
    {
        String s = scanner.nextLine();
        Double double1 = new Double(s);
        return double1.doubleValue();
    }

    public boolean hasNext()
    {
        return scanner.hasNextLine();
    }

    private Scanner scanner;
}

菜单按钮:

public class BotoMenu extends AbstractComponent {

    // Estats del boto
    protected static final int NORMAL = 1;
    protected static final int MOUSE_CLICK = 2;
    protected static final int MOUSE_OVER = 3;
    // Imatge del boto sense mouse over
    protected Image imatgeNormal;
    // Imatge del boto amb mouse over
    protected Image imatgeMouseOver;
    // Imatge del boto quan es fa click
    protected Image mouseDownImage;
    // Imatge del text que ha de contenir el boto
    protected Image imageText;
    // Colors del boto per si no tenen imatge
    protected Color colorNormal = Color.white;
    protected Color colorMouserOver = Color.white;
    protected Color colorMouseClick = Color.white;
    // So del boto al mouse over
    protected Sound soOver;
    // So del boto al ser clicat
    protected Sound soClick;
    // Area que ocupa el boto
    protected Shape area;
    // Imatge actual del boto (la que es renderitzara)
    protected Image imatgeActual;
    // Color actual del boto
    protected Color colorActual;
    // Indica si hi ha mouse over
    protected boolean over;
    // Indica si s'ha clicat amb el ratoli
    protected boolean click;
    // Indica si no s'ha clicat
    protected boolean noClick;
    // Indica si el so s'ha acabat de reproduir
    protected boolean reproduit;
    // Indica si el boto ha de respondre a events
    protected boolean actiu;
    // Estat actual del boto
    protected int state = NORMAL;

    /**
     * Constructor amb 4 parametres
     * @param container joc
     * @param image imatge sense mouse over del boto
     * @param x posicio x del boto
     * @param y posicio y del boto
     */
    public BotoMenu(GUIContext container, Image image, int x, int y) {
        this(container, image, x, y, image.getWidth(), image.getHeight());
    }
    
    /**
     * Constructor amb 6 parametres
     * @param container joc
     * @param image imatge sense mouse over del boto
     * @param x posicio x del boto
     * @param y posicio y del boto
     * @param width amplada del boto
     * @param height alsada del boto
     */
    public BotoMenu(GUIContext container, Image image, int x, int y, int width,
            int height) {
        this(container, image, new Rectangle(x, y, width, height));
    }

    /**
     * Constructor amb 3 parametres
     * @param container joc
     * @param image imatge sense mouse over del boto
     * @param shape area que ocupa el boto
     */
    public BotoMenu(GUIContext container, Image image, Shape shape) {
        super(container);

        area = shape;
        imatgeNormal = image;
        imatgeActual = image;
        imatgeMouseOver = image;
        mouseDownImage = image;

        colorActual = colorNormal;

        state = NORMAL;
        Input input2 = container.getInput();
        over = area.contains(input2.getMouseX(), input2.getMouseY());
        click = input2.isMouseButtonDown(0);
        updateImage();
    }

    /**
     * Posiciona el boto a les coordenades indicades
     * @param x posicio x del boto
     * @param y posicio y del boto
     */
    public void setLocation(int x, int y) {
        if (area != null) {
            area.setX(x);
            area.setY(y);
        }
    }

    /**
     * Aquest metode s'usa per renderitzar o dibuixar en pantalla els elements que es vulguin
     * @param container
     * @param g
     */
    public void render(GUIContext container, Graphics g) {
        // Si ja te una imatge
        if (imatgeActual != null) {
            int xp = (int) (area.getX() + ((getWidth() - imatgeActual.getWidth()) / 2));
            int yp = (int) (area.getY() + ((getHeight() - imatgeActual.getHeight()) / 2));
            imatgeActual.draw(xp, yp, colorActual);
        } else {
            g.setColor(colorActual);
            g.fill(area);
        }
        // Si te imatge de text la dibuixem
        if (imageText != null) {
            int xp = (int) (area.getX() + ((getWidth() - imageText.getWidth()) / 2));
            int yp = (int) (area.getY() + ((getHeight() - imageText.getHeight()) / 2));

            imageText.draw(xp, yp, colorActual);
        }
        updateImage();
    }

    /**
     * Actualitza la imatge que s'ha de mostrar del boto segons l'estat en que es trobi
     */
    protected void updateImage() {
        // No mouse over
        if (!over) {
            imatgeActual = imatgeNormal;
            colorActual = colorNormal;
            state = NORMAL;
            noClick = false;
            reproduit = false;
        } else {
            // Mouse Over
            if (click) {
                // Clicat
                if ((state != MOUSE_CLICK) && (noClick)) {
                    if (soClick != null && actiu) {
                        soClick.play(1, (float)ManagerPerfil.getVolumEfectes() / 100);
                    }
                    imatgeActual = mouseDownImage;
                    colorActual = colorMouseClick;
                    state = MOUSE_CLICK;
                    notifyListeners();
                    noClick = false;
                }
            } else {
                // No clicat
                noClick = true;
                if (state != MOUSE_OVER) {
                    if (soOver != null) {
                        if (!reproduit && actiu) {
                            soOver.play(1, (float)ManagerPerfil.getVolumEfectes() / 100);
                            reproduit = true;
                        }
                    }
                    // Si esta actiu...
                    if (actiu) {
                        imatgeActual = imatgeMouseOver;
                        colorActual = colorMouserOver;
                        state = MOUSE_OVER;
                    }
                }
            }
        }
        click = false;
        state = NORMAL;
    }

    /**
     * Comprova si hi ha mouse over amb el boto
     * @param oldx
     * @param oldy
     * @param newx
     * @param newy
     */
    @Override
    public void mouseMoved(int oldx, int oldy, int newx, int newy) {
        over = area.contains(newx, newy);
    }

    /**
     * Comprova si s'ha clicat en el boto
     * @param button
     * @param mx
     * @param my
     */
    @Override
    public void mousePressed(int button, int mx, int my) {
        over = area.contains(mx, my);
        if (button == 0 && actiu) {
            click = true;
        }
    }

    /**
     * Comprova si s'ha produit un mouse released
     * @param button
     * @param mx
     * @param my
     */
    @Override
    public void mouseReleased(int button, int mx, int my) {
        over = area.contains(mx, my);
        if (button == 0) {
            click = false;
        }
    }

    // Getters i setters
    public int getX() {
        return (int) area.getX();
    }

    public int getY() {
        return (int) area.getY();
    }

    public void setNormalColor(Color color) {
        colorNormal = color;
    }

    public void setMouseOverColor(Color color) {
        colorMouserOver = color;
    }

    public void setMouseDownColor(Color color) {
        colorMouseClick = color;
    }

    public void setNormalImage(Image image) {
        imatgeNormal = image;
    }

    public void setMouseOverImage(Image image) {
        imatgeMouseOver = image;
    }

    public void setImageText(Image image) {
        imageText = image;
    }

    public void setMouseDownImage(Image image) {
        mouseDownImage = image;
    }

    public int getHeight() {
        return (int) (area.getMaxY() - area.getY());
    }

    public int getWidth() {
        return (int) (area.getMaxX() - area.getX());
    }

    public GUIContext getContainer() {
        return container;
    }

    public Image getImatgeActual() {
        return imatgeActual;
    }

    public void setActiu(boolean actiu) {
        this.actiu = actiu;
    }

    public boolean isActiu() {
        return this.actiu;
    }

    public void setMouseOverSound(Sound sound) {
        soOver = sound;
    }

    public void setMouseDownSound(Sound sound) {
        soClick = sound;
    }
}

菜单选择:

public class MenuSeleccio {

    // Contenidor del joc
    private GameContainer container;
    // Unitats que es mostraran per poder seleccionar
    private String unitatsAMostrar;
    // Informacio referent a cada unitat
    private String informacio;
    // Posicio X on es començara a col·locar el primer boto de tria d'unitat
    private int posXVariable;
    // Posicio Y on es començara a col·locar el primer boto de tria d'unitat
    private int posYVariable;
    // Posicio X del menu
    private int posX;
    // Posicio Y del menu
    private int posY;
    // Nombre de columnes que es volen mostrar en la tria d'unitats
    private int nColumnesMenu1 = 4;
    // Nombre de columnes que es volen mostrar en la tria d'unitats
    private int nColumnesMenu2 = 8;
    // Indica si hi ha hagut algun canvi
    private boolean canvi;
    // Indica si s'ha de mostrar informació del boto
    private boolean mostrarInformacio;
    // Indica si el menu esta actiu
    private boolean actiu;
    // ArrayList on es guarden els botons de seleccio d'unitats
    private ArrayList<BotoSeleccio> botonsSeleccio;
    // ArrayList que s'utilitza per borrar les unitats necessaries de l'arraylist anterior
    private ArrayList<BotoSeleccio> botonsSeleccio2;
    // ArrayList on es guarden els botons de unitats ja triades
    private ArrayList<BotoSeleccio> botonsTriats;
    // ArrayList que s'utilitza per borrar les unitats necessaries de l'arraylist anterior
    private ArrayList<BotoSeleccio> botonsTriats2;
    // ArrayList amb els labels per representar els enemics
    private ArrayList<LabelSeleccio> cartesEnemics;

    // Font per dibuixar text
    private Font font;

    /**
     * Constructor amb 3 parametres
     * @param container joc
     * @param x posicio x del menu
     * @param y posicio y del menu
     */
    public MenuSeleccio(GameContainer container, int x, int y) {
        this.container = container;
        posX = x;
        posY = y;
        posXVariable = posX + 40;
        posYVariable = posY + 220;
        botonsSeleccio = new ArrayList<BotoSeleccio>();
        botonsSeleccio2 = new ArrayList<BotoSeleccio>();
        botonsTriats = new ArrayList<BotoSeleccio>();
        botonsTriats2 = new ArrayList<BotoSeleccio>();
        cartesEnemics = new ArrayList<LabelSeleccio>();
        unitatsAMostrar = ManagerPerfil.getUnitatsDisponibles();
        
        font = ManagerRecursos.getFont("dejavuNormalFont");
        actiu = true;
        crearBotons();
        posicionarBotons();
        crearCartes();
    }

    /**
     * El motor s'encarrega de cridar aquest metode, aqui s'actualitzaran dades de variables o objectes
     * que s'estiguin usant en aquest estat
     * @param container
     * @param game
     * @param delta
     * @throws SlickException
     */
    public void update(GameContainer game, StateBasedGame state, int delta) {
        comprovarMoviments();
        if (canvi) {
            canvi = false;
            posicionarBotons();
        }
        int comptador = 0;
        for (BotoSeleccio b : botonsSeleccio) {
            if (b.isOver()) {
                informacio = b.getUnitat();
                mostrarInformacio = true;
            } else {
                comptador++;
            }
        }
        if (comptador == botonsSeleccio.size()) {
            informacio = "";
            mostrarInformacio = false;
        }
    }

    /**
     * Aquest metode s'usa per renderitzar o dibuixar en pantalla els elements que es vulguin
     * @param container
     * @param game
     * @param g
     * @throws SlickException
     */
    public void render(GameContainer game, StateBasedGame state, Graphics g) {
        for (BotoSeleccio b : botonsSeleccio) {
            b.render(container, g);
        }
        for (BotoSeleccio b : botonsTriats) {
            b.render(container, g);
        }
        if (actiu) {
            g.setFont(font);
            g.drawString("Wave: " + ManagerPerfil.getWave(), 745, 227);
        }
        for (LabelSeleccio ls : cartesEnemics) {
            ls.render(g);
        }
    }

    /**
     * Comprova si s'ha de canviar alguna unitat d'una zona a una altra
     * (Zona de seleccio a zona d'unitat ja triada i viceversa)
     */
    private void comprovarMoviments() {
        if (botonsTriats.size() < 8) {
            for (BotoSeleccio b : botonsSeleccio) {
                if (b.isNotaCanvi()) {
                    b.setNotaCanvi(false);
                    botonsSeleccio2.add(b);
                    botonsTriats.add(b);
                    canvi = true;
                }
            }
            botonsSeleccio.removeAll(botonsSeleccio2);
            botonsSeleccio2.clear();
        } else {
            for (BotoSeleccio b : botonsSeleccio) {
                if (b.isNotaCanvi()) {
                    b.setNotaCanvi(false);
                }
            }
        }
        for (BotoSeleccio b : botonsTriats) {
            if (b.isNotaCanvi()) {
                b.setNotaCanvi(false);
                botonsTriats2.add(b);
                botonsSeleccio.add(b);
                canvi = true;
            }
        }
        botonsTriats.removeAll(botonsTriats2);
        botonsTriats2.clear();

    }

    /**
     * Posiciona els botons a la posicio que els pertoca
     */
    private void posicionarBotons() {
        int columnes = 0;
        int files = 0;
        for (BotoSeleccio b : botonsSeleccio) {
            int posicioBotoX = (columnes * 90) + posXVariable;
            int posicioBotoY = (files * 110) + posYVariable;
            b.setLocation(posicioBotoX, posicioBotoY);
            if (columnes == nColumnesMenu1) {
                columnes = 0;
                files++;
            } else {
                columnes++;
            }
        }
        columnes = 0;
        files = 0;
        for (BotoSeleccio b : botonsTriats) {
            int posicioBotoX = (columnes * 90) + 40;
            int posicioBotoY = (files * 110) + 40;
            b.setLocation(posicioBotoX, posicioBotoY);
            if (columnes == nColumnesMenu2) {
                columnes = 0;
                files++;
            } else {
                columnes++;
            }
        }
    }

    /**
     * Posiciona les labels dels enemics
     */
    private void posicionaCartes() {
        int columnes = 0;
        int files = 0;
        for (LabelSeleccio ls : cartesEnemics) {
            int posicioBotoX = (columnes * 90) + 550;
            int posicioBotoY = (files * 110) + 270;
            ls.setLocation(posicioBotoX, posicioBotoY);
            if (columnes == 4) {
                columnes = 0;
                files++;
            } else {
                columnes++;
            }
        }
    }

    /**
     * Crea els botons necessaris
     */
    private void crearBotons() {
        String[] s = unitatsAMostrar.split("-");
        BotoSeleccio.setImatgeCarta(ManagerRecursos.getImage("botoCartaImage"));
        BotoSeleccio.setImatgeCartaOver(ManagerRecursos.getImage("botoCartaOverImage"));
        for (String text : s) {
            BotoSeleccio bs = new BotoSeleccio(container, ManagerRecursos.getImage("carta" + text + "Image"),
                    0, 0, text);
            bs.addListener();
           
            bs.setActiu(true);
            botonsSeleccio.add(bs);
        }
    }

    /**
     * Crea les labels dels enemics
     */
    private void crearCartes() {
        String[] enemicsImage = ManagerPerfil.getEnemicsWave().split("-");
        for (String z : enemicsImage) {
            LabelSeleccio ls = new LabelSeleccio(ManagerRecursos.getImage("botoCartaImage"),
                    ManagerRecursos.getImage("carta" + z + "Image"));
            cartesEnemics.add(ls);
        }
        posicionaCartes();
    }

    /**
     * Retorna les unitats que ha seleccionat el jugador per jugar la wave seguent
     * @return
     */
    public String agafarUnitats() {
        String seleccio = "";
        for (BotoSeleccio b : botonsTriats) {
            seleccio += b.getUnitat() + "-";
        }
        if (seleccio.length() > 1) {
            return seleccio.substring(0, seleccio.length() - 1);
        }
        return "";
    }

    /**
     * Comprova si s'ha seleccionat alguna unitat, sino s'ha seleccionat no deixa continuar
     * @return true si es comensa la partida
     */
    public boolean unitatsNoNull() {
        if (agafarUnitats().length() > 1) {
            return true;
        }
        return false;
    }

    /**
     * Realitza el desplasament dels botons quan comensa la partida
     * @param incrementY
     */
    public void moureBotons(int incrementY) {
        for (BotoSeleccio bs : botonsSeleccio) {
            bs.setLocation(bs.getX(), bs.getY() + incrementY);
        }
        for (BotoSeleccio bs : botonsTriats) {
            bs.setLocation(bs.getX(), bs.getY() + incrementY);
        }
        for (LabelSeleccio ls : cartesEnemics) {
            ls.setLocation(ls.getPosX(), ls.getPosY() + incrementY);
        }
    }

    /**
     * Desactiva els botons per a que no poguin ser clicats
     */
    public void silenciarBotons() {
        for (BotoSeleccio bs : botonsSeleccio) {
            bs.setActiu(false);
        }
        for (BotoSeleccio bs : botonsTriats) {
            bs.setActiu(false);
        }
        actiu = false;
    }
}

源码获取:博客首页 "资源" 里下载!

  • 5
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 8
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

qq1334611189

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值