IT rekvalifikace s garancí práce. Seniorní programátoři vydělávají až 160 000 Kč/měsíc a rekvalifikace je prvním krokem. Zjisti, jak na to!
Hledáme nové posily do ITnetwork týmu. Podívej se na volné pozice a přidej se do nejagilnější firmy na trhu - Více informací.
Avatar
Alex123
Člen
Avatar
Alex123:21.8.2019 19:46

package hra1;

import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Grap­hics2D;
import java.awt.Rectangle;
import java.awt.image­.BufferStrate­gy;
import static java.lang.Sys­tem.nanoTime;
import java.util.Arra­yList;
import hra1.Enemy;

public class RenderLayer extends Canvas implements Runnable {

private ArrayList<Enemy> f;
private static final long serialVersionUID = 1L;
private boolean isRunning;
private boolean isGameOver;
private float score;
private hrac hrac = new hrac(this);
private ArrayList<Entity> entities;

public RenderLayer(){
super();
this.f = new ArrayList<>();
this.entities = new ArrayList<>();
this.addMouse­MotionListener(this­.hrac);
this.isGameOver = false;
this.isRunning = false ;
this.score = 0 ;
this.setSize( new Dimension(800 , 600));

for (int a = 0; a < 5; a++){
this.entities­.add(new Enemy(this) {

}) ;

}

}

@Override
public void run() {

long lastTimeCycle = System.nanoTime();
long lastTimeOutput = System.curren­tTimeMillis();
double unprocesedTicks = 0;
double Nspertick = Math.pow(10 , 9) / 60;
int FPS = 0;
int Ticks = 0 ;

while (this.isRunning){
long nowTimeCycle = System.nanoTime();
unprocesedTicks += (nowTimeCycle - lastTimeCycle) / Nspertick ;
lastTimeCycle = nowTimeCycle;

while (unprocesedTicks >= 1){
Ticks++;
unprocesedTicks--;
this.update();

}
FPS++;
this.render();

if(System.curren­tTimeMillis() - lastTimeOutput > 1000){
lastTimeOutput += 1000;
System.out.prin­tln("Ticks: " + Ticks + "," + "Fps: " + FPS);
this.score += 0.5;
FPS = 0;
Ticks = 0;

}
}

}

public void start(){
this.isRunning = true;
Thread t = new Thread(this);
t.start();

}

private void render() {
BufferStrategy buffer = this.getBuffer­Strategy();
if(buffer == null){
this.createBuf­ferStrategy(3);
return;
}
Graphics g = buffer.getDraw­Graphics();
g.setColor(Co­lor.WHITE);
g.fillRect(0, 0, this.getWidth() , this.getHeight());

for (Entity e : this.entities){
e.render(g);
}

hrac.render(g);

g.setColor(Co­lor.BLUE);
g.drawString("Tvoje score: " + (int) this.score, 10, 10);

g.dispose();
buffer.show();
}

public void draw(Graphics2D g2){
g2.draw(getBou­nds());
}

private void update() {

for (Entity e : this.entities){
e.update();
}

hrac.update();

for (int i = 0; i < f.size(); i++) {
System.out.prin­tln("kolize2");
if (f.get(i) != null) {
Rectangle okrajeChytace = hrac.getBounds();
Rectangle okrajeCtverce = f.get(i).getBou­nds();
if (okrajeChytace­.intersects(o­krajeCtverce)) {
f.set(i, null);
System.out.prin­tln("kolize");

}}}}}


Zkusil jsem: Ahoj, potřeboval bych poradit s tím to kódem. :)

for (int i = 0; i < f.size(); i++) {
System.out.prin­tln("kolize2");
if (f.get(i) != null) {
Rectangle okrajeChytace = hrac.getBounds();
Rectangle okrajeCtverce = f.get(i).getBou­nds();
if (okrajeChytace­.intersects(o­krajeCtverce)) {
f.set(i, null);
System.out.prin­tln("kolize");

}}}}

Hlavně s touto částí.Je to pouze tato jedna třída, ostatní jsou v pohodě.
Takže jde tedy o to, že víše uvedený kód je na detekce kolizí (pomocí Rectangle).
Akorát že nefunguje, do konzole to nic nevypisuje, normálně se hra spustí, ale kolize nefungují. Zjistil sem, že kód nefunguje už od toho cyklu.Také jsem zkoušel využít třeba pole , LinkedList a teď ArrayList. Ale když to předělám třeba na pole ,... ,tak to prostě nefunguje stejně jako teď . Byl bych rád ,kdyby mi někdo pomohl to opravit a vysvětlil proč to nefungovalo. :) Děkuji za každý nápad.

Editováno 21.8.2019 19:47
 
Odpovědět
21.8.2019 19:46
Avatar
Odpovídá na Alex123
Matúš Olejník:22.8.2019 0:09

Ahoj v tom for cykle ideš od 0 po f.size() a nikde v tom kóde nevidím, že by si ten list niečím napĺňal, čiže f.size() vracia 0 a preto ten cyklus ani nezbehne. Skús najprv to opraviť :)

Nahoru Odpovědět
22.8.2019 0:09
/* I am not sure why this works but it fixes the problem */
Avatar
Alex
Člen
Avatar
Odpovídá na Matúš Olejník
Alex:22.8.2019 0:55

Ahoj, odpovědi si vážím. ☺ Já se omlouvám, protože jsem tam nevypisoval všechny třídy té hry . private ArrayList<Enemy> f; ... Ale Enemy je třída, ve které jsou uloženi protihráči, tak bych řekl ,že (f.size ())nulová nebude ,ale bude "náplňená" nepřáteli. ☺ Ale nevím to jistě

Editováno 22.8.2019 0:56
 
Nahoru Odpovědět
22.8.2019 0:55
Avatar
Odpovídá na Alex
Matúš Olejník:22.8.2019 5:48

ArrayList<Enemy> f; znamená že ten list očakáva že doňho budeš ukladať inštancie typu "Enemy". Dokým však nespravíš

f.add(new Enemy())

tak v ňom nič nebude.

V kóde čo si poslal, jediné čo s listom "f" robíš je, že ho inicializuješ

this.f = new ArrayList<>();

Keď si si nie si istý ako píšeš tak to do dvoch sekúnd vieš zistiť napr. tak že si pred tým cyklom vypíšeš f.size() alebo na ten riadok dáš breakpoint a môžeš si popozerať hocičo potrebuješ. Dokonca vnútri toho cyklu máš System.out.prin­tln("kolize2"); a ja typujem, že ani "kolize2" sa ti vôbec nevypisuje :)

Náznak toho čo popisuješ vidím pri práci s tým listom "entities". Ten aj inicializuješ a aj napĺňaš nepriateľmi v tomto cykle

for (int a = 0; a < 5; a++){
    this.entities.add(new Enemy(this) {
}) ;

(PS tie {} tam nemusia byť)
Po tomto ti entities.size() vráti 5.

Ak by si teda v tomto cykle

for (int i = 0; i < f.size(); i++) {
    System.out.println("kolize2");
    ...

namiesto f.size() dal entities.size() tak je šanca že skutočne pôjde od 0 po 4 vďaka tomu, že veľkosť listu entities bude 5. A samozrejme namiesto používania prázdneho listu "f" v ňom používaj tiež list"entities".

Nahoru Odpovědět
22.8.2019 5:48
/* I am not sure why this works but it fixes the problem */
Avatar
Alex
Člen
Avatar
Odpovídá na Matúš Olejník
Alex:22.8.2019 11:12

Ahoj, mockrát děkuji ☺já jsem na to úplně zapoměl. Já s programováním zrovna začínám, tak občas na něco takového zapomenu.

Editováno 22.8.2019 11:14
 
Nahoru Odpovědět
22.8.2019 11:12
Avatar
Alex123
Člen
Avatar
Alex123:22.8.2019 17:02

Ahoj, promiň, že otravuju. Opravil jsem to funguje to :) Ale než ta kolize nastane ,tak to trvá cca 5 vteřin než to vypíše "kolize" . Někdy se to vůbec nespustí, protože to zase přehnaně rychle vypíše "kolize". Nemáš nápad jak to opravit ,aby to bylo okamžité(jak narazí do enemy = kolize))
Posílám tu upravený celý kód. :D Děkuju:)

package hra1;

import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.image.BufferStrategy;
import static java.lang.System.nanoTime;
import java.util.ArrayList;
import java.awt.BorderLayout;
import java.util.LinkedList;
import javax.swing.JFrame;






public class RenderLayer extends Canvas implements Runnable {

    private ArrayList<Enemy> f;
    private static final long serialVersionUID = 1L;
    private boolean isRunning;
    private boolean isGameOver;
    private float score;
    private hrac hrac = new hrac(this);
    private ArrayList<Entity> entities;



    public RenderLayer(){
        super();
        this.f = new ArrayList<>();
       this.entities = new ArrayList<>();
        this.addMouseMotionListener(this.hrac);
        this.isGameOver = false;
        this.isRunning = false ;
        this.score = 0 ;
        this.setSize( new Dimension(800 , 600));



            for (int a = 0; a < 5; a++){
            this.entities.add(new Enemy(this)  {

            }) ;



}

            for (int x = 0; x < 5; x++){
            this.f.add(new Enemy(this)  {

            }) ;

    }}


    @Override
    public void run() {

       long lastTimeCycle =  System.nanoTime();
       long lastTimeOutput = System.currentTimeMillis();
       double unprocesedTicks = 0;
       double Nspertick = Math.pow(10 , 9) / 60;
       int FPS = 0;
       int Ticks = 0 ;


            while (this.isRunning){
                long nowTimeCycle = System.nanoTime();
                unprocesedTicks += (nowTimeCycle - lastTimeCycle) / Nspertick ;
                lastTimeCycle = nowTimeCycle;

                        while (unprocesedTicks >= 1){
                            Ticks++;
                            unprocesedTicks--;
                            this.update();



            }
            FPS++;
            this.render();


            if(System.currentTimeMillis() - lastTimeOutput > 1000){
                lastTimeOutput += 1000;
                System.out.println("Ticks: " + Ticks + "," + "Fps: " + FPS);
                this.score += 0.5;
                FPS = 0;
                Ticks = 0;

            }
            }


            }

     public void start(){
            this.isRunning = true;
            Thread t = new Thread(this);
            t.start();

            }


    private void render() {
        BufferStrategy buffer = this.getBufferStrategy();
        if(buffer == null){
            this.createBufferStrategy(3);
        return;
    }
        Graphics g = buffer.getDrawGraphics();
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, this.getWidth() , this.getHeight());



        for (Entity e : this.entities){
            e.render(g);
        }

        hrac.render(g);

        g.setColor(Color.BLUE);
        g.drawString("Tvoje score: " + (int) this.score, 15, 15);



        g.dispose();
        buffer.show();
    }




    private void update() {

        for (Entity e : this.entities){
            e.update();


        }



      hrac.update();



      for (int i = 0; i <  f.size(); i++) {
         if (f.get(i) != null) {
        Rectangle okrajeChytace = hrac.getBounds();
        Rectangle okrajeCtverce = f.get(i).getBoundsx();
            if (okrajeCtverce.intersects(okrajeChytace)) {
                 f.set(i, null);
                     System.out.println("Kolize");
                     this.isRunning = false ;
                     this.setVisible(isRunning);
                      }}}



    }}
package hra1;

import java.util.Random;

public class Vector {

    private int x;
    private int y;

    public static final int X_DIRECTION = 1;
    public static final int Y_DIRECTION = 2;


    public Vector (int x, int y){
        this.x = (x == 0 ? ++x : x);
        this.y = (y == 0 ? ++x : x);
    }


    public int getX(){
        return x;
    }

    public int getY(){
        return y;
    }

    public void changeDirection(int Direction){
        if (Direction == Vector.X_DIRECTION){
            this.x = -this.x;
        }
        else if (Direction == Vector.Y_DIRECTION){
            this.y = -this.y;
        }
    }

    public void newDirection(int Direction){
        Random random = new Random();
                if (Direction == Vector.X_DIRECTION){
                    int X = random.nextInt(5);
            this.x = this.x < 0 ? -X : X;
        }
        else if (Direction == Vector.Y_DIRECTION){
            int Y = random.nextInt(5);
            this.y = -this.y < 0 ? -Y : Y;
        }
    }

}
package hra1;

import java.awt.Color;
import java.awt.Graphics;
import java.util.Random;
import hra1.Vector;
import java.awt.Rectangle;
import java.awt.geom.Rectangle2D;



public class Enemy extends Entity {



     private Vector DirectionVector;


    public Enemy(RenderLayer l) {
        super(l);

        Random random = new Random();
        switch(random.nextInt(5)){
            case 0:
                this.color = Color.BLUE;
                break;
            case 1:
                this.color = Color.ORANGE;
                break;
            case 2:
                this.color = Color.BLACK;
                break;
            case 3:
                this.color = Color.YELLOW;
                break;
            case 4:
                this.color = Color.RED;
                break;
            case 5:
                this.color = Color.BLUE;
                break;
            case 6:
                this.color = Color.BLUE;
                break;
        }

        this.DirectionVector = new Vector(random.nextInt(5), random.nextInt(5));

        this.xpozice = random.nextInt(750);
        this.ypozice = random.nextInt(550);

        this.width = 50;
        this.height = 50;
    }


    @Override
    public void update() {
       this.xpozice += this.DirectionVector.getX();
       this.ypozice += this.DirectionVector.getY();




if (this.xpozice + this.width > 800){
           this.xpozice = 800 - this.width;
           this.DirectionVector.changeDirection(Vector.X_DIRECTION);
      }
       else if (this.xpozice < 0){
          this.xpozice = 0;
          this.DirectionVector.changeDirection(Vector.X_DIRECTION);
      }
       if (this.ypozice + this.height > 600){
           this.ypozice = 600 - this.height;
          this.DirectionVector.changeDirection(Vector.Y_DIRECTION);
       }
       else if (this.ypozice < 0){
          this.ypozice = 0;
          this.DirectionVector.changeDirection(Vector.Y_DIRECTION);
       }
    }




           @Override
    public void render(Graphics g) {
        g.setColor(this.color);
        g.fillRect(this.xpozice, this.ypozice, this.width, this.height);
    }

      public Rectangle getBounds() {
    return new Rectangle (xpozice,ypozice,50,50);
}

}
package hra1;

import java.awt.BorderLayout;

import javax.swing.JFrame;

public class Hra1 extends JFrame{
private static final long serialVersionUID = 1L;

    public static final String Game_Title = "1. Hra" ;

    public static void main(String[] args) {
       Hra1 hra = new Hra1();

        hra.init();
    }


    private void init() {

        RenderLayer layer = new RenderLayer();
        this.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
        this.setLayout(new BorderLayout() );
        this.add(layer);
        this.pack();
        this.setTitle(Hra1.Game_Title);
        this.setResizable(false);
        this.setVisible(true);
        layer.start();

    }
}
package hra1;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;






class hrac extends Entity implements MouseMotionListener {




    public hrac(RenderLayer l){
    super(l);
    this.color = Color.GREEN;
    this.width = this.height = 25;
    this.xpozice = 800 / 2 - this.width / 2;
    this.ypozice = 600 / 2 - this.height / 2;
    }





     @Override
    public void update() {
        if (this.xpozice + this.width > 800){
          this.xpozice = 800 - this.width;

      }
       else if (this.xpozice < 0){
          this.xpozice = 0;

      }
       if (this.ypozice + this.height > 600){
           this.ypozice = 600 - this.height;

       }
       else if (this.ypozice < 0){
          this.ypozice = 0;

       }








    }
    @Override
    public void render(Graphics g) {
       g.setColor(Color.GREEN);
       g.fillRect(this.xpozice, this.ypozice, this.width, this.height);
    }


    @Override
    public void mouseDragged(MouseEvent e) {
        this.mouseMoved(e);
    }

    @Override
    public void mouseMoved(MouseEvent e) {
       this.xpozice = e.getX() - this.width / 2;
       this.ypozice = e.getY() - this.height / 2;
    }

      public Rectangle getBounds() {
    return new Rectangle (xpozice,ypozice,25,25);
}





}
 
Nahoru Odpovědět
22.8.2019 17:02
Avatar
Odpovídá na Alex123
Matúš Olejník:23.8.2019 10:08

Pozri správu, toto bude chcieť viacej času :)

Nahoru Odpovědět
23.8.2019 10:08
/* I am not sure why this works but it fixes the problem */
Děláme co je v našich silách, aby byly zdejší diskuze co nejkvalitnější. Proto do nich také mohou přispívat pouze registrovaní členové. Pro zapojení do diskuze se přihlas. Pokud ještě nemáš účet, zaregistruj se, je to zdarma.

Zobrazeno 7 zpráv z 7.