# "Schiffe versenken"



## headgrowe (28. Nov 2009)

Ich habe eine frage zum dynamischen erstellten von buttons und wie ich wieder auf sie zugreifen kann....
(den text ändern kann .setText(); )
habs mit einem button[][] objekt probiert, doch das geht iwie nicht.
des weiteren auch, wie ich gif oder jpg grafiken in einen button einbauen kann bzw. wo ich diese im verzeichnis hinverschieben muss.

ich stelle das explizite codestück hier online und dann alle classen:


```
public class UIField extends JPanel implements ActionListener {
	private static final long serialVersionUID = 1L;

	public UIField() {
		setLayout(new GridLayout(0, 21));
		for(int i = 0; i<a.length;i++){
			newButton("~", i) {
		}
	}

	public void newButton(String text, int i) {
		JButton b = new JButton(text);
		String name = (i + 1) + "";
		b.setName(name);
		b.setToolTipText(name);
		b.addActionListener(this);
		b
				.setActionCommand(name);
		this.add(b);
	}

	public void actionPerformed(ActionEvent arg0) {
		arg0...		
	//buttontext verändern (setText("x");)
	}
}
```

THX


```
package Aufgabenstellung1und2;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Random;

import Grafics.UIFrame;

public class Battleships {
	public static final int MAX_SHIPS = 10;
	// 4 2er Schiffe. 3 3er Schiffe, 2 2erSchiffe....
	public static final int[] SHIP_TYPES_COUNT = { 4, 3, 2, 1 };
	public static final int MAX_HITS = SHIP_TYPES_COUNT[0] * 2
			+ SHIP_TYPES_COUNT[1] * 3 + SHIP_TYPES_COUNT[2] * 4
			+ SHIP_TYPES_COUNT[3] * 5;
	public static final int MIN_SHIP_LENGTH = 2;
	public static final int MAX_SHIP_LENGTH = 5;
	public static final int Field_SIZE = 20;

	private static int shots = 0;
	private static int hits = 0;

	private static Ship[] ships = new Ship[MAX_SHIPS];

	private static Random rand = new Random();

	private static Field[][] water = new Field[Field_SIZE][Field_SIZE];
	
	private static Battleships newBattle = new Battleships();
	
	// Field array mit feldern füllen
	public Battleships(){
		for (int height = 0; height < Field_SIZE; height++) {
			for (int width = 0; width < Field_SIZE; width++) {
				getWater()[height][width] = new Field(height, width);
			}
		}
		// schiffe generieren
		for (int i = 0; i < SHIP_TYPES_COUNT.length; i++) {
			for (int i2 = 0; i2 < SHIP_TYPES_COUNT[i]; i2++)
				placeShip((i + 2));
		}
		@SuppressWarnings("unused")
		UIFrame newWindow = new UIFrame();
	}

	private static void placeShip(int lenght) {
		int x = rand.nextInt(Field_SIZE);
		int y = rand.nextInt(Field_SIZE);
		boolean horiz = rand.nextInt(2) == 1 ? true : false;
		if (isPlaceable(x, y, lenght, horiz)) {
			Field[] deck = new Field[lenght];
			for (int i = 0; i < lenght; i++) {
				deck[i] = getWater()[x][y];
				if (horiz)
					x++;
				else
					y++;
			}
			ships[Ship.countShipPlaced++] = new Ship(deck);
		} else
			placeShip(lenght);
	}

	private static boolean isPlaceable(int x, int y, int length, boolean horiz) {
		for (int i = 0; i < length; i++) {
			if (y > (Field_SIZE - 1) || y < 0 || x > (Field_SIZE - 1) || y < 0)
				return false;
			else if (getWater()[x][y].getShip() != null)
				return false;
			if (horiz)
				x++;
			else
				y++;
		}
		return true;
	}
	
	//mit IO classe ersätzen...
	private static int getPosInt() {
		BufferedReader line = new BufferedReader(new InputStreamReader(
				System.in));
		try {
			String entry = line.readLine();

			// TestMethoden
			if (entry.equals("cheat"))
				cheat();
			if (entry.equals("autoshoot"))
				autoshoot();

			int number = Integer.parseInt(entry);
			if (number > 0 && number < 21) {
				return (number - 1);
			}
		} catch (NumberFormatException e) {
		} catch (IOException e) {
			e.printStackTrace();
		}
		System.out.print("Wrong entra. Try again. ");
		return getPosInt();
	}

	public static void main(String[] args) {
		System.out.println("\nGame Start!");
		printBattlefield();

		while (getHits() < MAX_HITS) {
			int x = getPosInt();
			int y = getPosInt();
			turn(x, y);
		}
		System.out.print("Fleet has sunk. The player needed " + getShots()
				+ " shots");
	}

	// spielzug
	public static void turn(int x, int y) {
		shoot(x, y);

		// Aufgabe 2
		printBattlefield();
		gameStatistc();
		System.out.println();
	}

	private static void shoot(int x, int y) {
		setShots(getShots() + 1);
		Field target = getWater()[x][y];
		if (target.isHit()) {
			if (target.getShip() == null)
				System.out.println("Already shot into the water at this place");
			else
				System.out.println("Already shot on the ship at this place");
		} else {
			target.setHit(true);
			if (target.getShip() == null)
				System.out.println("Hit water");
			else {
				setHits(getHits() + 1);
				if (target.getShip().isDestroyed())
					System.out.println("Ship with length "
							+ target.getShip().getLength() + " sunk");
				else
					System.out.println("Hit ship");
			}
		}
	}

	// Aufgabe 2
	private static void gameStatistc() {
		System.out.println("\nGame Statistc:");
		int[] typesSunk = new int[SHIP_TYPES_COUNT.length];
		for (int i = 0; i < ships.length; i++)
			typesSunk[ships[i].getLength()-2] += ships[i].isDestroyed() ? 1 : 0;
		for (int i = 0; i < typesSunk.length; i++)
			System.out.println("Ships with length "+(i+2)+" (" + SHIP_TYPES_COUNT[i]
					+ "): " + typesSunk[i] + " sunk, "
					+ (SHIP_TYPES_COUNT[i] - typesSunk[i]) + " remaining");
		System.out.println("Shots: " + getShots());
	}

	private static void printBattlefield() {
		// gibt buchstaben von A-T aus
		System.out.print("\t");
		for (int i = 65; i < getWater().length + 65; i++) {
			System.out.print((char) i);
		}
		int i = 0;
		for (Field[] items : getWater()) {
			System.out.print("\n" + ++i + "\t");
			for (Field item : items)
				if (!item.isHit())
					System.out.print("~");
				else {
					if (item.getShip() != null) {
						if (item.getShip().isDestroyed())
							System.out.print("X");
						else
							System.out.print("S");
					} else
						System.out.print("W");
				}
		}
	}

	// getter/setter Methoden

	public static void setWater(Field[][] water) {
		Battleships.water = water;
	}

	public static Field[][] getWater() {
		return water;
	}

	public static void setHits(int hits) {
		Battleships.hits = hits;
	}

	public static int getHits() {
		return hits;
	}

	public static void setShots(int shots) {
		Battleships.shots = shots;
	}

	public static int getShots() {
		return shots;
	}

	// testMethoden
	private static void autoshoot() {
		for (int x = 0; x < getWater().length; x++)
			for (int y = 0; y < getWater()[0].length; y++) {
				shoot(x, y);
				if (getHits() == MAX_HITS) {
					x = getWater().length;
					break;
				}
			}
	}

	private static void cheat() {
		for (Field[] items : getWater()) {
			for (Field item : items)
				if (item.getShip() == null)
					System.out.print("~");
				else
					System.out.print("S");
			System.out.println();
		}
	}

	public static void setNewBattle(Battleships newBattle) {
		Battleships.newBattle = newBattle;
	}

	public static Battleships getNewBattle() {
		return newBattle;
	}
}
```


```
package Aufgabenstellung1und2;

public class Field {
	private int x;
	private int y;

	private boolean hit = false;

	private Ship ship = null;

	public Field(int x, int y) {
		this.setX(x);
		this.setY(y);
	}

	// getter/setter - Methoden

	public void setHit(boolean hit) {
		this.hit = hit;
	}

	public boolean isHit() {
		return hit;
	}

	public void setShip(Ship ship) {
		this.ship = ship;
	}

	public Ship getShip() {
		return ship;
	}

	public void setX(int x) {
		this.x = x;
	}

	public int getX() {
		return x;
	}

	public void setY(int y) {
		this.y = y;
	}

	public int getY() {
		return y;
	}
}
```


```
package Aufgabenstellung1und2;

public class Ship {
	private Field[] deck;
	public static int countShipPlaced = 0;

	public Ship(Field[] deck) {
		this.deck = deck;
		for (Field item : deck)
			Battleships.getWater()[item.getX()][item.getY()].setShip(this);
	}

	public int getLength() {
		return deck.length;
	}

	public int countHits() {
		int count = 0;
		for (Field item : deck)
			if (item.isHit())
				count++;
		return count;
	}

	public boolean isDestroyed() {
		if (countHits() == getLength())
			return true;
		return false;
	}
}
```


```
package Grafics;

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;

import Aufgabenstellung1und2.Battleships;

public class UIField extends JPanel implements ActionListener {
	private static final long serialVersionUID = 1L;

	public UIField() {
		setLayout(new GridLayout(0, 21));
		add(new JLabel("  "));
		for (int i = 0; i < 20; i++) {
			add(new JLabel(" " + ( i + 1)));
		}
	}

	public void newButton(String text, int i, int i2) {
		JButton b = new JButton(text);
		String name = (i + 1) + " " + (i2 + 1);
		b.setName(name);
		b.setToolTipText(name);
		b.addActionListener(this);
		b
				.setActionCommand(name);
		this.add(b);
	}

	@Override
	public void actionPerformed(ActionEvent arg0) {
		String[] a = arg0.getActionCommand().split(" ");
		System.out.println(a[1]);
		System.out.println(a[0]);
		Battleships.turn(Integer.parseInt(a[0]) - 1,
				Integer.parseInt(a[1]) - 1);
		this.setVisible(false);	
		UIFrame.replaceUIFIeld();
		if (Battleships.getHits() >= Battleships.MAX_HITS)
			System.out.print("Fleet has sunk. The player needed " + Battleships.getShots()
					+ " shots");
	}
}
```


```
package Grafics;

import javax.swing.JFrame;
import javax.swing.JLabel;

import Aufgabenstellung1und2.Battleships;

public class UIFrame {

	private static JFrame window = new JFrame();
	
	public UIFrame() {
		getWindow().setLocation(200, 200);
		replaceUIFIeld();
		getWindow().setTitle("Battleship");
		getWindow().setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);		
		getWindow().setSize(1000, 700);		
		getWindow().setVisible(true);
	}

	public static void replaceUIFIeld() {
		UIField pane = new UIField();
		for (int i = 0; i < Battleships.getWater().length; i++) {
			pane.add(new JLabel(String.valueOf(i + 1)));
			for (int i2 = 0; i2 < Battleships.getWater()[0].length; i2++) {
				if (!Battleships.getWater()[i][i2].isHit())
					pane.newButton("~", i, i2);
				else {
					if (Battleships.getWater()[i][i2].getShip() != null)
						if (Battleships.getWater()[i][i2].getShip()
								.isDestroyed())
							pane.newButton("X", i, i2);
						else
							pane.newButton("S", i, i2);
					else
						pane.newButton("W", i, i2);
				}
			}
		}
		window.add(pane);
	}

	public static void setWindow(JFrame window) {
		UIFrame.window = window;
	}

	public static JFrame getWindow() {
		return window;
	}
}
```


----------



## javimka (28. Nov 2009)

headgrowe hat gesagt.:


> habs mit einem button[][] objekt probiert, doch das geht iwie nicht


Was genau hast du probiert und was geht nicht?

Ohne deinen 6 Klassen viel Beachtung gegeben zu haben, ein Image kannst du irgendwo deponieren, üblich sind Strukturen wie /ress/images/  (ress=Ressourcen) oder ähnlich. Das Bild lässt sich dann mit ImageIO laden und mit new JButton(new ImageIcon(image)) packst du es auf deinen Button.


----------



## Marco13 (28. Nov 2009)

Wenn ich das richtig überflogen habe, sollte man das mit der 2. Möglichkeit von http://www.java-forum.org/bilder-gui-damit-zusammenhaengt/49255-componenten-listener.html ganz gut lösen können.


----------



## headgrowe (28. Nov 2009)

@Marco13, das war der link den ich brauchte 
@javimka, thx wegen dem Image, werd ich gleich mal probieren


----------

