JavaRush /Java Blog /Random EN /2048 in JAVA
timurnav
Level 21

2048 in JAVA

Published in the Random EN group
In the meantime, I decided to write a couple of games, I started with “ Tic Tac Toe ”, but got stuck on it a little while studying multiplayer, while I was studying I came across the idea that I could make a game to play alone. The most vivid memory is 2048, the logic in it is quite simple. Following tradition, I decided to start writing it for the console. I made it a little simpler than the original:
  1. the number is added only to the outer row opposite the direction of the shift, i.e. moved up to the bottom row, a number was added;
  2. only 2 are added, in the original sometimes 4 are also added, I decided not to bother;
  3. in a console game, input and output are made (you won’t believe it!) through the console, so the output should be in the form of an improvised table, which I already have experience with :) the input was initially planned in numbers, but then I remembered the big tasks and adapted the KeyboardObserver, minus - the niggle occurs at the slightest manipulation with the mouse, i.e. launched the application, and then only use the down-up-right-left arrows. I honestly promised myself to figure out the issue, but I don’t know when yet, so here is the product of midnight poking at the keyboard.
According to the logic of the program itself, there is nothing to explain, in the main method we track the buttons and, depending on the last one, set the required one Direction, then go to Moves, and execute the desired method. The “necessary method” first moves all occupied cells in the desired direction, if there is room to move, then checks for matches in columns/rows, if it finds matches, then sums and moves the rest of the column/row. Then it draws the field again and so on in an endless loop until you lose, or until the cat runs across the mouse button. I tried to make comments in the code so that later it would be clear to everyone (including me). Link to the archive with the game 2048 Console Edition Extras. info, it’s more pleasing to the eye to play not in the idea, but in the Windows console. To do this, go to folder 2048 in the downloaded archive and launch a batch file with the logical name RUN. but here again you only need to press the arrow keys, otherwise the application closes without asking. PS here you just need to screw the database, then you can take care of the front, I’ll do it in the near future. I’ll also probably write a PPS for Android, but this is still a very distant future, which, as you know, is better not to think about it :)
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION