fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. private static final Random RANDOM = new Random();
  11. public static void main(String[] args) {
  12. Player p = new Player();
  13. NPC other = new NPC();
  14.  
  15. for (int turn = 0; turn < 10; turn++) {
  16. System.out.printf("turn %d%n", turn);
  17. for (LevelCrawler current : new LevelCrawler[]{p, other}) {
  18. move(current);
  19. }
  20. }
  21. }
  22.  
  23. private static void move(LevelCrawler crawler) {
  24. GameObject go = RANDOM.nextBoolean() ? new Chest() : new NPC();
  25. go.accept(crawler);
  26. }
  27. }
  28.  
  29. interface LevelCrawler {
  30. void handle(Chest c);
  31.  
  32. void handle(NPC npc);
  33. }
  34.  
  35. class Player implements LevelCrawler {
  36. public void handle(Chest c) {
  37. System.out.println("opening a chest");
  38. }
  39.  
  40. public void handle(NPC npc) {
  41. System.out.println("meeting NPC");
  42. }
  43. }
  44.  
  45. abstract class GameObject {
  46. abstract void accept(LevelCrawler p);
  47. }
  48.  
  49. class Chest extends GameObject {
  50. @Override
  51. void accept(LevelCrawler p) {
  52. p.handle(this);
  53. }
  54. }
  55.  
  56. class NPC extends GameObject implements LevelCrawler {
  57. @Override
  58. void accept(LevelCrawler p) {
  59. p.handle(this);
  60. }
  61.  
  62. @Override
  63. public void handle(Chest c) {
  64. System.out.println("chests are for the players, leaving it alone");
  65. }
  66.  
  67. @Override
  68. public void handle(NPC npc) {
  69. System.out.println("forming group with other npc");
  70. }
  71. }
Success #stdin #stdout 0.1s 34216KB
stdin
Standard input is empty
stdout
turn 0
meeting NPC
chests are for the players, leaving it alone
turn 1
meeting NPC
forming group with other npc
turn 2
meeting NPC
forming group with other npc
turn 3
opening a chest
chests are for the players, leaving it alone
turn 4
meeting NPC
chests are for the players, leaving it alone
turn 5
opening a chest
chests are for the players, leaving it alone
turn 6
opening a chest
forming group with other npc
turn 7
meeting NPC
chests are for the players, leaving it alone
turn 8
opening a chest
chests are for the players, leaving it alone
turn 9
opening a chest
chests are for the players, leaving it alone