Share
Explore

Java Reflection Game

Creating a fun and interactive game to demonstrate the power of Java's Introspection and Reflection API can be quite engaging.
Let's design a simple console-based game where players discover hidden features of objects using reflection.

### Game Concept: "The Mysterious Mansion"

**Objective**: Players explore a mysterious mansion, inspecting various objects in rooms to discover hidden features and unlock secrets.
**Gameplay**:
- The mansion has several rooms, each containing different objects. - Players can inspect objects to reveal hidden fields and methods. - Some methods, when invoked, reveal secrets, give clues, or unlock new rooms.
### Implementation:
#### 1. Base Classes for the Game
**GameObject**: Represents any object in the game.
```java public class GameObject { private String description;
public GameObject(String description) { this.description = description; }
public String getDescription() { return description; } } ```
**Room**: Represents a room in the mansion.
```java import java.util.ArrayList; import java.util.List;
public class Room { private String name; private List<GameObject> objects;
public Room(String name) { this.name = name; this.objects = new ArrayList<>(); }
public void addObject(GameObject object) { objects.add(object); }
public List<GameObject> getObjects() { return objects; }
public String getName() { return name; } } ```
#### 2. Specific Game Objects
We create some specific objects with hidden methods and fields.
```java public class Mirror extends GameObject { private String secretMessage = "The key is in the vase!";
public Mirror() { super("An ancient mirror with mysterious carvings."); }
private void revealSecret() { System.out.println(secretMessage); } } ```
#### 3. Main Game Logic
The `Game` class handles the game setup and the main game loop.
```java import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.Scanner;
public class Game { private Room currentRoom; private Scanner scanner;
public Game() { setupGame(); scanner = new Scanner(System.in); }
private void setupGame() { // Create rooms and objects Room hall = new Room("Grand Hall"); Mirror mirror = new Mirror(); hall.addObject(mirror);
// More rooms and objects...
currentRoom = hall; // Starting room }
public void start() { System.out.println("Welcome to the Mysterious Mansion!");
while (true) { System.out.println("You are in the " + currentRoom.getName()); System.out.println("What do you want to inspect?");
for (int i = 0; i < currentRoom.getObjects().size(); i++) { GameObject obj = currentRoom.getObjects().get(i); System.out.println((i + 1) + ": " + obj.getDescription()); }
int choice = scanner.nextInt(); if (choice > 0 && choice <= currentRoom.getObjects().size()) { inspectObject(currentRoom.getObjects().get(choice - 1)); } else { System.out.println("Invalid choice. Try again."); } } }
private void inspectObject(GameObject object) { Class<?> cls = object.getClass();
System.out.println("Inspecting: " + object.getDescription()); Field[] fields = cls.getDeclaredFields(); for (Field field : fields) { field.setAccessible(true); try { System.out.println("Field: " + field.getName() + ", Value: " + field.get(object)); } catch (IllegalAccessException e) { System.out.println("Could not access field: " + field.getName()); } }
Method[] methods = cls.getDeclaredMethods(); for (Method method : methods) { method.setAccessible(true); if (method.getParameterCount() == 0) { try { System.out.println("Invoking method: " + method.getName()); method.invoke(object); } catch (Exception e) { System.out.println("Could not invoke method: " + method.getName()); } } } }
public static void main(String[] args) { Game game = new Game(); game.start(); } } ```
### Gameplay Experience:
- Players run the game and find themselves in a room in the mansion. - They choose an object to inspect. - The game reveals the fields and invokes the methods of the chosen object using reflection. - Hidden messages or actions are triggered, leading to further exploration.
This game is a simple demonstration of Java's Introspection and Reflection API. It can be extended with more rooms, objects, and complex interactions. The core idea is to use reflection to dynamically discover and interact with the properties of game objects, making the game an exploratory adventure into the capabilities of Java Reflection.

Exercise B: Let’s Extend the Haunted Mansion by adding a Dying Room with a Haunted Vase:

Game Enhancements:

Dying Room: A new room called "Dying Room" with a Haunted Vase.
Haunted Vase: A new HauntedVase class with a secret and a method to lift its curse.
Room Navigation: Players can now move between the "Grand Hall" and the "Dying Room".
Gameplay: Players use reflection to discover and interact with objects, now with an added element of navigating between rooms and solving the mystery of the Haunted Vase.
This extension adds more depth to the game, encouraging exploration and interaction with the mansion's mysterious artifacts using Java's Reflection API.
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.List;

public class Game {
private Room currentRoom;
private Scanner scanner;

public static void main(String[] args) {
Game game = new Game();
game.start();
}

public Game() {
setupGame();
scanner = new Scanner(System.in);
}

private void setupGame() {
// Create rooms and objects
Room hall = new Room("Grand Hall");
Room dyingRoom = new Room("Dying Room");

Mirror mirror = new Mirror();
HauntedVase hauntedVase = new HauntedVase();

hall.addObject(mirror);
dyingRoom.addObject(hauntedVase);

// Link rooms - for simplicity, let's just go back and forth
hall.setAdjacentRoom(dyingRoom);
dyingRoom.setAdjacentRoom(hall);

currentRoom = hall; // Starting room
}

public void start() {
System.out.println("Welcome to the Mysterious Mansion!");

boolean playing = true;
while (playing) {
System.out.println("\nYou are in the " + currentRoom.getName());
System.out.println("Objects in the room:");
List<GameObject> objects = currentRoom.getObjects();
for (int i = 0; i < objects.size(); i++) {
System.out.println((i + 1) + ": " + objects.get(i).getDescription());
}

System.out.println((objects.size() + 1) + ": Move to the adjacent room");
System.out.println((objects.size() + 2) + ": Exit game");

System.out.print("Enter your choice: ");
int choice = scanner.nextInt();

if (choice > 0 && choice <= objects.size()) {
inspectObject(objects.get(choice - 1));
} else if (choice == objects.size() + 1) {
currentRoom = currentRoom.getAdjacentRoom();
} else if (choice == objects.size() + 2) {
playing = false;
System.out.println("Exiting Mysterious Mansion. Goodbye!");
} else {
System.out.println("Invalid choice. Try again.");
}
}
}

private void inspectObject(GameObject object) {
Class<?> cls = object.getClass();

System.out.println("Inspecting: " + object.getDescription());
Field[] fields = cls.getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
try {
System.out.println("Field: " + field.getName() + ", Value: " + field.get(object));
} catch (IllegalAccessException e) {
System.out.println("Could not access field: " + field.getName());
}
}

Method[] methods = cls.getDeclaredMethods();
for (Method method : methods) {
method.setAccessible(true);
if (method.getParameterCount() == 0) {
try {
System.out.println("Invoking method: " + method.getName());
method.invoke(object);
} catch (Exception e) {
System.out.println("Could not invoke method: " + method.getName());
}
}
}
}

class Room {
private String name;
private List<GameObject> objects;
private Room adjacentRoom; // Added for room navigation

public Room(String name) {
this.name = name;
this.objects = new ArrayList<>();
}

public void addObject(GameObject object) {
objects.add(object);
}

public List<GameObject> getObjects() {
return objects;
}

public String getName() {
return name;
}

public void setAdjacentRoom(Room room) {
this.adjacentRoom = room;
}

public Room getAdjacentRoom() {
return adjacentRoom;
}
}

class GameObject {
private String description;

public GameObject(String description) {
this.description = description;
}

public String getDescription() {
return description;
}
}

class Mirror extends GameObject {
private String secretMessage = "The key is in the vase!";

public Mirror() {
super("An ancient mirror with mysterious carvings.");
}

private void revealSecret() {
System.out.println(secretMessage);
Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
CtrlP
) instead.