Java: Wie kann man das Programm nochmals durchlaufen lassen?
Man soll bei cash das Geld eingeben und wenn man genug Geld hat, soll alles nochmal durchlaufen werden (bei while ( isRunning )). Wie kann man das am besten lösen, ohne das eine Fehlermeldung kommt? Sorry für den langen Code :D
PS: Die Mitte des Codes ist relativ unwichtig.
//S. 244-245
public class Snake {
public static void main(String[] args) {
boolean isRunning = true;
boolean ok = true;
while ( isRunning ) {
if ( ok )
System.out.println("Cash einwerfen:");
ok = false;
int cash = new java.util.Scanner( System.in ).nextInt();
java.awt.Point playerPosition = new java.awt.Point( 10, 9 );
java.awt.Point snakePosition = new java.awt.Point( 39, 0 );
java.awt.Point goldPosition = new java.awt.Point( 6, 6 );
java.awt.Point doorPosition = new java.awt.Point( 0, 5 );
java.awt.Point gold2Position = new java.awt.Point( 20, 8 );
boolean rich = false;
boolean rich2 = false;
while ( true ) {
for ( int y = 0; y < 10; y++ ) {
for ( int x = 0; x < 40; x++) {
java.awt.Point p = new java.awt.Point( x, y );
if ( playerPosition.equals ( p ) )
System.out.print('&');
else if ( snakePosition.equals( p ) )
System.out.print('S');
else if ( goldPosition.equals( p ) )
System.out.print('$');
else if ( gold2Position.equals( p ) )
System.out.print('$'); //Wichtig: print statt println
else if ( doorPosition.equals( p ) )
System.out.print('#');
else System.out.print('.');
}
System.out.println();
}
//Textausgaben
if ( rich && rich2 && playerPosition.equals( doorPosition ) ) {
System.out.println("Gewonnen!");
break;
}
if ( playerPosition.equals( snakePosition ) ) {
System.out.println("Game Over!");
break;
}
if ( playerPosition.equals ( goldPosition ) ) {
rich = true;
goldPosition.setLocation( -1, -1 );
}
if ( playerPosition.equals ( gold2Position ) ) {
rich2 = true;
gold2Position.setLocation( -1, -1 );
goldPosition.setLocation( -1, -1 );
}
switch ( new java.util.Scanner ( System.in ).next() ) {
case "w" : playerPosition.y = Math.max( 0, playerPosition.y - 1); break;
case "s" : playerPosition.y = Math.min( 9, playerPosition.y + 1); break;
case "a" : playerPosition.x = Math.max( 0, playerPosition.x - 1); break;
case "d" : playerPosition.x = Math.min( 39, playerPosition.x + 1); break;
case "wa": playerPosition.y = Math.max( 0, playerPosition.y - 1);
playerPosition.y = Math.max( 0, playerPosition.x - 1 ); break;
case "wd": playerPosition.y = Math.max( 0, playerPosition.y - 1);
playerPosition.x = Math.min( 39, playerPosition.x + 1); break;
case "sa": playerPosition.y = Math.min( 9, playerPosition.y + 1);
playerPosition.x = Math.max( 0, playerPosition.x - 1); break;
case "sd": playerPosition.y = Math.min( 9, playerPosition.y + 1);
playerPosition.x = Math.min( 39, playerPosition.x + 1); break;
}
PC,
programmieren,
Java,
snake