# Score-Algorythmus



## dicestacking (15. Jun 2010)

ich bin grad dabei space invaders zu programmieren, aber nicht irgendwie, sondern so richtig altmodisch, also eigentlich ein Klon^^. und weil bei den alten space invaders(400*300) die pixeln richtig schirch waren, habe ich mal die zahlen für den score - pixelig und grün auf schwarzem hintergrund - mit gimp nebeneinander auf einer gif-datei gespeichert.

ich habe eine methode, mit der ich den score berechne und an die klasse "Score", die von sprite erbt weitergebe, um sie anschliessend auszugeben.

wie von euch warscheinlich erwarted funzt es nicht^^. der dreck will einfach nicht ich such schon seit 4 stunden fehler -.-

dieser algorythmus mag vom aufbau her komisch ausschauen, aber ich gebe den score unabhängig von ihrer grösse vom rechten bildschirmrand ausgehend aus.

die variable score habe ich nur zum test der zahl 123 zugewiesen.

```
private void computeAndCreateScore(int addscore)
    {
        score = 123;
        score += addscore;

        int x = 390;
        int y = 11;

        String strScore = Long.toString(score);
        for(int i = strScore.length()-1;i>=0; i--)
        {
            Score sco = new Score(ziffern, x, y, 10, this);
            switch(strScore.charAt(i))
            {
                case '0': sco.setLoop(0, 0); break;
                case '1': sco.setLoop(1, 1); break;
                case '2': sco.setLoop(2, 2); break;
                case '3': sco.setLoop(3, 3); break;
                case '4': sco.setLoop(4, 4); break;
                case '5': sco.setLoop(5, 5); break;
                case '6': sco.setLoop(6, 6); break;
                case '7': sco.setLoop(7, 7); break;
                case '8': sco.setLoop(8, 8); break;
                case '9': sco.setLoop(9, 9);
            }
            x -= 10;
        }
    }
```

es wäre sehr nett, wenn jemand einen fehler ect. finden würde.

danke im voraus

mfg Dice


----------



## Meldanor (15. Jun 2010)

Was funktioniert genau nicht? 
und wie sehen die Funktionen Score.SetLoop(int i , int j ) aus?


----------



## dicestacking (16. Jun 2010)

also... mein programm ist gleich aufgabaut wie das programm aus quaxli's tut.

also das problem ist das, dass sich die zahlen nicht ausgeben lassen.

die methode private void computeAndCreateScore(int addscore){...} ist in meiner hauptklasse, dem GamePanel.

die methode setLoop(int from, int to){...} ist in der klasse Score, die von Sprite erbt.
ich habe jedoch in der klasse Score noch nichts besonderes definiert, deswegen poste ich dann einfach mal die klasse sprite...

EDIT: Andere sprites wie etwa mein raumschiff lassen sich schon ausgeben.

setLoop():

```
public void setLoop(int from, int to)
    {
        loop_from = from;
        loop_to = to;
        currentpic = from;
    }
```

Sprite:

```
import java.awt.Graphics;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;

public abstract class Sprite extends Rectangle2D.Double implements Drawable, Movable
{
    long delay;
    long animation = 0;
    GamePanel parent;
    BufferedImage[] pics;
    int currentpic = 0;
    protected double dx;
    protected double dy;
    int loop_from;
    int loop_to;
    boolean remove = false;

    public Sprite(BufferedImage[] i, double x, double y, long delay, GamePanel p)
    {
        pics = i;
        this.x = x;
        this.y = y;
        this.delay = delay;
        this.width = pics[0].getWidth();
        this.height = pics[0].getHeight();
        parent = p;
        loop_from = 0;
        loop_to = pics.length - 1;
    }
    public void drawObjects(Graphics g)
    {
        g.drawImage(pics[currentpic], (int) x, (int) y, null);
    }
    public void doLogic(long delta)
    {
        animation += (delta / 1000000);
        if (animation > delay)
        {
            animation = 0;
            computeAnimation();
        }
    }
    public void move(long delta)
    {
        if (dx != 0)
        {
            x += dx * (delta / 1e9);
        }
        if (dy != 0)
        {
            y += dy * (delta / 1e9);
        }
    }
    private void computeAnimation()
    {
        currentpic++;

        if(currentpic > loop_to)  currentpic = loop_from;
    }

    public abstract boolean collidedWith(Sprite s);

    public void setLoop(int from, int to)
    {
        loop_from = from;
        loop_to = to;
        currentpic = from;
    }
    public void setVerticalSpeed(double d)
    {
        dy = d;
    }
    public void setHorizontalSpeed(double d)
    {
        dx = d;
    }
    public double getVerticalSpeed()
    {
        return dy;
    }
    public double getHorizontalSpeed()
    {
        return dx;
    }
    public void setX(double i)
    {
        x = i;
    }
    public void setY(double i)
    {
        y = i;
    }
    public boolean checkOpaqueColorCollisions(Sprite s)
    {
        Rectangle2D.Double cut = (Double) this.createIntersection(s);

        if ((cut.width < 1) || (cut.height < 1))
        {
            return false;
        }

        // Rechtecke in Bezug auf die jeweiligen Images
        Rectangle2D.Double sub_me = getSubRec(this, cut);
        Rectangle2D.Double sub_him = getSubRec(s, cut);

        BufferedImage img_me = pics[currentpic].getSubimage((int) sub_me.x, (int) sub_me.y,
                (int) sub_me.width, (int) sub_me.height);
        BufferedImage img_him = s.pics[s.currentpic].getSubimage((int) sub_him.x, (int) sub_him.y,
                (int) sub_him.width, (int) sub_him.height);

        for (int i = 0; i < img_me.getWidth(); i++)
        {
            for (int n = 0; n < img_him.getHeight(); n++)
            {
                int rgb1 = img_me.getRGB(i, n);
                int rgb2 = img_him.getRGB(i, n);

                if (isOpaque(rgb1) && isOpaque(rgb2))
                {
                    return true;
                }
            }
        }
        return false;
    }
    protected Rectangle2D.Double getSubRec(Rectangle2D.Double source, Rectangle2D.Double part)
    {
        //Rechtecke erzeugen
        Rectangle2D.Double sub = new Rectangle2D.Double();

        //get X - compared to the Rectangle
        if (source.x > part.x)
        {
            sub.x = 0;
        }
        else
        {
            sub.x = part.x - source.x;
        }

        if (source.y > part.y)
        {
            sub.y = 0;
        }
        else
        {
            sub.y = part.y - source.y;
        }

        sub.width = part.width;
        sub.height = part.height;

        return sub;
    }
    protected boolean isOpaque(int rgb)
    {
        int alpha = (rgb >> 24) & 0xff;
        //red   = (rgb >> 16) & 0xff;
        //green = (rgb >>  8) & 0xff;
        //blue  = (rgb ) & 0xff;

        if (alpha == 0)
        {
            return false;
        }
        
        return true;
    }
}
```

GamePanel:

```
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import java.util.Vector;
import javax.imageio.ImageIO;
import javax.swing.*;

public class GamePanel extends JPanel implements Runnable, KeyListener, ActionListener
{
    private static final long serialVersionUID = 1L;
    boolean game_running = true;
    boolean started = false;
    boolean once = false;

    long delta = 0;
    long last = 0;
    long fps = 0;
    long gameover = 0;
    long score = 0;

    SpaceShuttle space;
    Vector<Sprite> actors;

    boolean left = false;
    boolean right = false;
    boolean spacebar = false;
    int speed = 200;

    Timer timer;
    BufferedImage background;
    BufferedImage[] ziffern;

    //SoundLib slib;
    
    public static void main(String[] args) 
    {
        new GamePanel(492, 385);
    }
    public GamePanel(int w, int h) 
    {
        this.setPreferredSize(new Dimension(w, h));
        this.setMaximumSize(new Dimension(w,h));
        this.setBackground(Color.black);
        JFrame frame = new JFrame("SpaceInvaders");
        frame.setLocation(100, 100);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.addKeyListener(this);
        frame.add(this);
        frame.pack();
        frame.setVisible(true);
        doInitializations();
    }
    private void doInitializations() 
    {
        BufferedImage[] shuttle = loadPics("pics/shuttle.gif", 1);
        background = loadPics("pics/background.gif",1)[0];
        ziffern = loadPics("pics/ziffern.gif", 10);

        //slib = new SoundLib();
        //slib.loadSound("bumm", "sound/boom.wav");
        //slib.loadSound("rocket", "sound/rocket_start.wav");
        //slib.loadSound("heli", "sound/heli.wav");

        last = System.nanoTime();
        gameover = 0;

        actors = new Vector<Sprite>();
        space = new SpaceShuttle(shuttle,getWidth()/2-7,getHeight()-40,10,this);
        actors.add(space);

        if(isStarted())
        {
        //slib.loopSound("heli");
        }

        timer = new Timer(3000, this);
        timer.start();

        if (!once) 
        {
            once = true;
            Thread t = new Thread(this);
            t.start();
        }
        computeAndCreateScore(0);
    }
    public void run() 
    {
        while (game_running) 
        {
            computeDelta();

            if (isStarted()) 
            {
                checkKeys();
                doLogic();
                moveObjects();
            }

            repaint();

            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {}
        }
    }
    private void checkKeys()
    {
        if (right) space.setHorizontalSpeed( speed);
        if (left)  space.setHorizontalSpeed(-speed);
        if (!left && !right) space.setHorizontalSpeed(0);
    }
    private void doLogic() 
    {
        Vector<Sprite> trash = new Vector<Sprite>();

        for (Movable mov : actors) 
        {
            mov.doLogic(delta);
            Sprite check = (Sprite) mov;
            if (check.remove) trash.add(check);
        }
        for (int i = 0; i < actors.size(); i++) 
        {
            for (int n = i + 1; n < actors.size(); n++) 
            {
                Sprite s1 = actors.elementAt(i);
                Sprite s2 = actors.elementAt(n);

                s1.collidedWith(s2);
            }
        }

        if(trash.size() > 0)  for(Sprite s : trash)  actors.remove(s);

        if(gameover > 0)  if(System.currentTimeMillis() - gameover > 3000)  stopGame();
    }
    private void stopGame() 
    {
        timer.stop();
        //slib.stopLoopingSound();
        setStarted(false);
    }
    private void moveObjects() 
    {
        for(Movable mov : actors)  mov.move(delta);
    }

    @Override
    public void paintComponent(Graphics g) 
    {
        super.paintComponent(g);

        g.drawImage(background, 0, 0, this);

        g.setColor(Color.red);
        g.drawString("FPS: " + Long.toString(fps), 20, 10);

        if (!isStarted())  return;

        if(actors != null)  for(Drawable draw : actors)  draw.drawObjects(g);
    }
    private void computeDelta()
    {
        delta = System.nanoTime() - last;
        last = System.nanoTime();

        fps = ((long) 1e9) / delta;
    }
    private BufferedImage[] loadPics(String path, int pics)
    {
        BufferedImage[] anim = new BufferedImage[pics];
        BufferedImage source = null;

        URL pic_url = getClass().getClassLoader().getResource(path);

        try {
            source = ImageIO.read(pic_url);
        } catch (IOException e) {}

        for (int x = 0; x < pics; x++)
        {
            anim[x] = source.getSubimage(x * source.getWidth() / pics, 0,
                    source.getWidth() / pics, source.getHeight());
        }

        return anim;
    }
    public boolean isStarted()
    {
        return started;
    }
    public void setStarted(boolean started)
    {
        this.started = started;
    }
    public void keyPressed(KeyEvent e)
    {
        if(e.getKeyCode() == KeyEvent.VK_LEFT)  left = true;
        if(e.getKeyCode() == KeyEvent.VK_RIGHT)  right = true;
    }
    public void keyReleased(KeyEvent e)
    {
        if (e.getKeyCode() == KeyEvent.VK_LEFT)  left = false;
        if (e.getKeyCode() == KeyEvent.VK_RIGHT)  right = false;
            
        if (e.getKeyCode() == KeyEvent.VK_ENTER)
        {
            if (!isStarted())
            {
                score = 0;
                setStarted(true);
                doInitializations();
            }
        }

        if (e.getKeyCode() == KeyEvent.VK_ESCAPE)
        {
            if(isStarted())  stopGame();
            else
            {
                setStarted(false);
                System.exit(0);
            }
        }
    }
    public void keyTyped(KeyEvent e) 
    {
        if (e.getKeyCode() == KeyEvent.VK_SPACE) createRocket();
    }
    public void actionPerformed(ActionEvent e) 
    {

    }
    
@SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 400, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 300, Short.MAX_VALUE)
        );
    }// </editor-fold>                        

    private void createRocket()
    {

    }
    private void computeAndCreateScore(int addscore)
    {
        score = 123;
        score += addscore;

        int x = 390;
        int y = 11;

        String strScore = Long.toString(score);
        for(int i = strScore.length()-1;i>=0; i--)
        {
            Score sco = new Score(ziffern, x, y, 10, this);
            switch(strScore.charAt(i))
            {
                case '0': sco.setLoop(0, 0); break;
                case '1': sco.setLoop(1, 1); break;
                case '2': sco.setLoop(2, 2); break;
                case '3': sco.setLoop(3, 3); break;
                case '4': sco.setLoop(4, 4); break;
                case '5': sco.setLoop(5, 5); break;
                case '6': sco.setLoop(6, 6); break;
                case '7': sco.setLoop(7, 7); break;
                case '8': sco.setLoop(8, 8); break;
                case '9': sco.setLoop(9, 9);
            }
            x -= 10;
        }
    }
}
    // Variables declaration - do not modify                     
    // End of variables declaration
```


----------



## dicestacking (16. Jun 2010)

so, ich breche dieses Thema frühzeitig ab, weil ich immer nach der Instanzierung des Objektes Score muss ich immer darunter "actors.add(sco);" schreiben.

ENDLICH...:toll::toll::toll::toll::toll::toll:


----------

