Bird Hop
Typer | Posted on | |
/*
@startuml
class Bird {
- position: int
- facingRight: boolean
- static final int LIMIT
+ Bird()
+ hop(): void
+ turn(): void
+ toString(): String
}
class BirdHop {
+ main(args: String[]): void
}
BirdHop --> Bird : "Creates & Controls"
Bird --> java.util.Scanner : "Uses for random start"
@enduml
*/
import java.util.Scanner;
class Bird {
private int position;
private boolean facingRight;
private static final int LIMIT = 10;
public Bird() {
this.position = 0;
this.facingRight = true;
}
public void hop() {
if (facingRight && position < LIMIT) {
position++;
System.out.println("The bird hopped!");
} else if (!facingRight && position > -LIMIT) {
position--;
System.out.println("The bird hopped!");
} else {
System.out.println("The bird cannot move further in this direction! Please turn around.");
}
}
public void turn() {
facingRight = !facingRight;
System.out.println("The bird turned.");
}
@Override
public String toString() {
String status = "Position: " + position + ", facing: " + (facingRight ? "Right -->" : "Left <--");
return status;
}
}
public class BirdHop {
public static void main(String[] args) {
try (Scanner scan = new Scanner(System.in)) {
Bird bird = new Bird();
String command;
System.out.println("----- Welcome to the Bird Simulation -----");
System.out.println("Commands: O (Output), H (Hop), T (Turn), E (Exit)");
while (true) {
System.out.println("Please enter a letter (O/H/T/E) to play: ");
command = scan.nextLine().trim().toUpperCase();
switch (command) {
case "O" ->
System.out.println(bird);
case "H" -> {
bird.hop();
}
case "T" -> {
bird.turn();
}
case "E" -> {
System.out.println("Game ended. Goodbye!");
return;
}
default -> {
System.out.println("Invalid command.");
}
}
}
}
}
}