Advertisement
Guest User

Untitled

a guest
Sep 17th, 2018
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 11.44 KB | None | 0 0
  1. package me.James.commands.xpGains;
  2.  
  3. import com.vdurmont.emoji.EmojiParser;
  4. import me.James.modules.Modules;
  5. import me.James.userMess.UserMess;
  6. import org.javacord.api.DiscordApi;
  7. import org.javacord.api.entity.user.User;
  8. import org.javacord.api.event.message.reaction.ReactionAddEvent;
  9. import org.javacord.api.listener.message.MessageCreateListener;
  10. import org.javacord.api.listener.message.reaction.ReactionAddListener;
  11. import java.awt.*;
  12. import java.util.*;
  13. import java.util.List;
  14. import java.util.concurrent.CompletableFuture;
  15. import java.util.concurrent.Semaphore;
  16. import java.util.concurrent.TimeUnit;
  17.  
  18. public class ConnectFour implements Experienceable {
  19.     private final static int WINNING_XP = 25;
  20.     private final static ConnectFourPiece STARTING_USER_PIECE = ConnectFourPiece.BLUE;
  21.     private final static ConnectFourPiece SECOND_USER_PIECE = ConnectFourPiece.RED;
  22.     private long winningUser = 0;
  23.     private static ConnectFourPiece[][] canvas = new ConnectFourPiece[7][6];
  24.     private long startingUser;
  25.     private long secondUser = 0;
  26.     private Semaphore lock = new Semaphore(1);
  27.     private long currentUser;
  28.     private Modules mods;
  29.     private DiscordApi api;
  30.     public ConnectFour(DiscordApi api, UserMess mess) {
  31.         this.api = api;
  32.         this.mods = new Modules(api);
  33.         startingUser = mess.getMessageAuthor().getId();
  34.         currentUser = mess.getMessageAuthor().getId();
  35.         initializeBoard();
  36.         post(mess);
  37.         new ExperienceHandler(this);
  38.     }
  39.  
  40.     private void initializeBoard() {
  41.         ConnectFourPiece[][] canvas = new ConnectFourPiece[6][7];
  42.         for (int y = 0; y < 6; y++) {
  43.             for (int x = 0; x < 7; x++) {
  44.                 canvas[y][x] = ConnectFourPiece.EMPTY;
  45.             }
  46.         }
  47.     }
  48.  
  49.     private void post(UserMess mess) {
  50.         mess.sendMessage(mods.successEmbedGen("Should this be a :one: closed game, or :two: open game?", mess)).thenAccept(gameJoinState ->
  51.                 gameJoinState.addReactions(EmojiParser.parseToUnicode(":one:"), EmojiParser.parseToUnicode(":two:")).thenAccept(aVoid -> {
  52.                     gameJoinState.addReactionAddListener(event -> {
  53.                         if(event.getUser().getId() == startingUser){
  54.                             getSecondUser(event, mess)
  55.                                     .thenAccept(aVoid1 -> playLoop()).exceptionally(exception -> {
  56.                                         if(exception instanceof ForcefulGameEnd)
  57.                                             mess.sendMessage(mods.successEmbedGen("Canceling game!", mess))
  58.                                                     .thenAccept(gameEndMessage -> api
  59.                                                             .getThreadPool()
  60.                                                             .getScheduler()
  61.                                                             .schedule((Runnable) gameEndMessage::delete, 20, TimeUnit.SECONDS));
  62.                                         else if (exception instanceof InvalidGameStart){
  63.                                             mess.sendMessage(mods.successEmbedGen("Something went wrong getting a second user! Cancelling game!", mess))
  64.                                                     .thenAccept(gameEndMessage -> api
  65.                                                             .getThreadPool()
  66.                                                             .getScheduler()
  67.                                                             .schedule((Runnable) gameEndMessage::delete, 20, TimeUnit.SECONDS));
  68.                                         }
  69.                                         gameJoinState.getReactionAddListeners().forEach(reactionAddListener -> gameJoinState.removeListener(ReactionAddListener.class, reactionAddListener));
  70.                                         mess.sendMessage(exception.getMessage());
  71.                                         return null;
  72.                             });
  73.                         }
  74.                     });
  75.                 })
  76.         );
  77.     }
  78.     private void playLoop() {
  79.         List<Long> players = new LinkedList<>();
  80.         players.add(startingUser);
  81.         players.add(secondUser);
  82.         Iterator<Long> playerIterable = players.iterator();
  83.         while (playerIterable.hasNext()) try {
  84.             lock.acquire();
  85.             final long currentPlayer = playerIterable.next();
  86.             Point placed = playTurn(currentPlayer);
  87.             if (cheackForWin(placed, currentPlayer == startingUser ? ConnectFourPiece.RED : ConnectFourPiece.BLUE))
  88.                 endGame();
  89.         } catch (InterruptedException e) {
  90.             throw new InvalidGameStart();
  91.         }
  92.     }
  93.     private Point playTurn(long player) {
  94.         return new Point(2,2);
  95.     }
  96.     private void endGame() {
  97.  
  98.     }
  99.     private CompletableFuture<Void> getSecondUser(ReactionAddEvent event, UserMess mess) {
  100.         return CompletableFuture.supplyAsync(() -> {
  101.             if (event.getEmoji().asUnicodeEmoji().map(":one:"::equals).orElse(false)) {
  102.                 api.getCachedUserById(startingUser).ifPresent(user ->
  103.                         mess.sendMessage(mods.successEmbedGen("Mention someone to invite them to this game! You can always use `exit to quit to quit the game.", mess)).thenAccept(getSecondPlayerMessage ->
  104.                                 user.addMessageCreateListener(secondPlayerEvent -> {
  105.                                     if(secondPlayerEvent.getMessage().getContent().startsWith("`exit")) throw new InvalidGameStart();
  106.                                     if (!secondPlayerEvent.getMessage().getMentionedUsers().isEmpty()) {
  107.                                         mess.sendMessage(mods.successEmbedGen(
  108.                                                 String.format(
  109.                                                         "%s has invited you, %s, to a game of Connect Four, do you accept?",
  110.                                                         api.getCachedUserById(startingUser).map(User::getMentionTag).orElse("Error getting Name"),
  111.                                                         secondPlayerEvent.getMessage().getMentionedUsers().get(0).getMentionTag()
  112.                                                 ), mess)).thenAccept(secondPlayerInviteMessage ->
  113.                                                 secondPlayerInviteMessage.addReactions(EmojiParser.parseToUnicode(":check:"), EmojiParser.parseToUnicode(":xmark:")).thenAccept(secondPlayerAccept -> {
  114.                                                     secondPlayerInviteMessage.addReactionAddListener(secondPlayerAcceptReaction -> {
  115.                                                         if (secondPlayerAcceptReaction.getUser().getId() == secondPlayerEvent.getMessage().getMentionedUsers().get(0).getId() && secondPlayerAcceptReaction.getEmoji().asUnicodeEmoji().map(":check:"::equals).orElse(false)) {
  116.                                                             secondUser = secondPlayerAcceptReaction.getUser().getId();
  117.                                                             secondPlayerInviteMessage.getReactionAddListeners().forEach(reactionAddListener -> secondPlayerInviteMessage.removeListener(ReactionAddListener.class, reactionAddListener));
  118.                                                             return;
  119.                                                         } else if (secondPlayerAcceptReaction.getEmoji().asUnicodeEmoji().map(":xmark"::equals).orElse(false)) {
  120.                                                             secondPlayerInviteMessage.getReactionAddListeners().forEach(reactionAddListener -> secondPlayerInviteMessage.removeListener(ReactionAddListener.class, reactionAddListener));
  121.                                                             user.getMessageCreateListeners().forEach(messageCreateListener -> user.removeListener(MessageCreateListener.class, messageCreateListener));
  122.                                                             throw new ForcefulGameEnd();
  123.                                                         }
  124.                                                     });
  125.                                                 })
  126.                                         );
  127.                                     }
  128.                                 })
  129.                         ));
  130.             }
  131.             throw new InvalidGameStart();
  132.         });
  133.     }
  134.     private static String drawBoard() {
  135.         StringBuilder canvasStringRepresentation = new StringBuilder();
  136.         for(int y = 0; y < canvas.length; y++) {
  137.             for(int x = canvas[0].length - 1; x > 0; x--) {
  138.                 canvasStringRepresentation.append(String.format("%s ", canvas[x][y].getDiscordRepresentation()));
  139.             }
  140.             canvasStringRepresentation.append("\n");
  141.         }
  142.         return canvasStringRepresentation.toString();
  143.     }
  144.  
  145.     private static void updateBoard(int column, ConnectFourPiece currentPiece) {
  146.         for(int y = 0; y < canvas[0].length; y++){
  147.             if (!(canvas[y][column] == ConnectFourPiece.EMPTY)) {
  148.                 canvas[y][column] = currentPiece;
  149.                 break;
  150.             }
  151.         }
  152.     }
  153.     private boolean isNear(Point pos, Point pos1) {
  154.         return ((pos1.x + 1 == pos.x || pos1.x == pos.x || pos1.x - 1 == pos.x) &&
  155.                 (pos1.y + 1 == pos.y || pos1.y == pos.y || pos1.y - 1 == pos1.y) &&
  156.                 !((pos1.x + 1 == pos.x || pos1.x - 1 == pos.x) &&
  157.                         (pos1.y + 1 == pos.y || pos1.y - 1 == pos.y)));
  158.     }
  159.     private boolean patternSearcher(HashMap<Integer, Point> connectedHashMap) {
  160.         boolean won = false;
  161.         for (Map.Entry<Integer, Point> entry : connectedHashMap.entrySet()) {
  162.             Integer integer = entry.getKey();
  163.             Point point = entry.getValue();
  164.  
  165.         }
  166.         return won;
  167.     }
  168.     private boolean cheackForWin(final Point origin, final ConnectFourPiece piece) {
  169.         HashMap<Integer, Point> connectedHashMap = new HashMap<>();
  170.         for (int col = 0; col < canvas.length; col++) {
  171.             for (int row = 0; row < canvas[0].length; row++) {
  172.                 if (canvas[col][row].equals(piece) && isNear(origin, new Point(col, row))) {
  173.                     if (connectedHashMap.size() < 4)
  174.                         connectedHashMap.put(connectedHashMap.size() + 1, new Point(col, row));
  175.                     else return patternSearcher(connectedHashMap);
  176.                 }
  177.             }
  178.         }
  179.         return false;
  180.     }
  181.  
  182.     @Override
  183.     public Map.Entry<Long, Integer> gainXp() {
  184.         return new AbstractMap.SimpleImmutableEntry<>(winningUser, WINNING_XP);
  185.     }
  186.  
  187.     @Override
  188.     public String gameName() {
  189.         return "Connect Four";
  190.     }
  191.     enum ConnectFourPiece {
  192.         RED(EmojiParser.parseToUnicode(":red_circle:")),
  193.         BLUE(EmojiParser.parseToUnicode(":large_blue_circle:")),
  194.         EMPTY(EmojiParser.parseToUnicode(":black_circle:"));
  195.         private String discordRepresentation;
  196.         ConnectFourPiece(String discordRepresentation){
  197.             this.discordRepresentation = discordRepresentation;
  198.         }
  199.         public String getDiscordRepresentation() {
  200.             return discordRepresentation;
  201.         }
  202.     }
  203.     class ForcefulGameEnd extends RuntimeException {
  204.         ForcefulGameEnd() {
  205.             super("Starting user ended the game");
  206.         }
  207.     }
  208.     class InvalidGameStart extends RuntimeException {
  209.         InvalidGameStart() {
  210.             super("Something went wrong while finding the second user!");
  211.         }
  212.     }
  213. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement