You are on page 1of 3

import java.util.

*;

public class MyGame {

public static void main(String[] args) {

Scanner input = new Scanner(System.in); //get user input


Random rand = new Random(); //generate random numbers

// set up the game


int size = rand.nextInt(10) + 1; //room size from 1 to 10
int ax = rand.nextInt(size);
int ay = rand.nextInt(size);

int ex = rand.nextInt(size);
int ey = rand.nextInt(size);

int gx = rand.nextInt(size);
int gy = rand.nextInt(size);

int hx = rand.nextInt(size);
int hy = rand.nextInt(size);

int stepsLeft = 10; //player gets 10 steps

// print the board


printBoard(size, ax, ay, ex, ey, gx, gy, hx, hy);

// main game loop


while(stepsLeft > 0) {

// get player input


System.out.print("Enter direction (N, S, E, W) and steps: ");
String moves = input.nextLine();

// split input
String[] parts = moves.split(" ");

// check input
if(parts.length != 2) {
System.out.println("Invalid input");
continue;
}

String dir = parts[0];


int numSteps = Integer.parseInt(parts[1]);

if(numSteps < 1 || numSteps > 2) {


System.out.println("Steps must be 1 or 2");
continue;
}

// process input
if(dir.equals("N")) {
ay -= numSteps;
}
else if(dir.equals("S")) {
ay += numSteps;
}
else if(dir.equals("E")) {
ax += numSteps;
}
else if(dir.equals("W")) {
ax -= numSteps;
}
else {
System.out.println("Invalid direction");
continue;
}

// move enemy randomly


ex += rand.nextInt(3) - 1;
ey += rand.nextInt(3) - 1;

// keep enemy in bounds


if(ex < 0) ex = 0;
if(ex >= size) ex = size-1;
if(ey < 0) ey = 0;
if(ey >= size) ey = size-1;

// use up steps
stepsLeft--;

// check winning and losing


if(ax == ex && ay == ey) {
System.out.println("You were caught! Game over");
break;
}
if(ax == gx && ay == gy) {
System.out.println("You found gold! You win!");
break;
}
if(ax == hx && ay == hy) {
System.out.println("You escaped! You win!");
break;
}

// print updated board


printBoard(size, ax, ay, ex, ey, gx, gy, hx, hy);

System.out.println("Steps left: " + stepsLeft);


}

System.out.println("Out of steps! Game over");

// prints the game board


private static void printBoard(int size, int ax, int ay, int ex, int ey, int
gx, int gy, int hx, int hy) {

for(int y = 0; y < size; y++) {


for(int x = 0; x < size; x++) {
if(x == ax && y == ay) System.out.print("A");
else if(x == ex && y == ey) System.out.print("E");
else if(x == gx && y == gy) System.out.print("G");
else if(x == hx && y == hy) System.out.print("H");
else System.out.print(".");
}
System.out.println();
}

You might also like