Java Tetris Game Download

0 views
Skip to first unread message

Roy Dassow

unread,
Aug 5, 2024, 9:56:49 AM8/5/24
to rsasarprocon
Im making Tetris in java for fun... I pretty much had everything working... but later found out that when I wanted to change the dimensions so it was square ([10 row][10 col] matrix, but instead a [12 row][10 col] matrix), that I started getting Index Out of Bound exceptions... see here: Java Tetris - weird row clearing issue

EDIT----------I've tried implementing both ValarDohaeris and Svend Hansen's suggestions... Now the block is moving right when I press down, up when I press left, and down when I press right...


... it seems like the x,y problem takes place here too because you trying to control y (vertical) coordinates but (in real) you control x (horizontal) coordinates only :S It is still because of the row,col instead of a classic Java (col,row or y,x) [][] array index positions.


The Tetris game is one of the most popular computer games ever created.The original game was designed and programmed by a Russian programmerAlexey Pajitnov in 1985. Since then, Tetris is available on almostevery computer platform in lots of variations.Even my mobile phone has a modified version of the Tetris game.Tetris is called a falling block puzzle game. In this game, we have sevendifferent shapes called tetrominoes.S-shape, Z-shape, T-shape, L-shape, Line-shape, MirroredL-shape and a Square-shape.Each of these shapes is formed with four squares.The shapes are falling down the board.The object of the Tetris game is to move and rotate the shapes, so thatthey fit as much as possible. If we manage to form a row, the row isdestroyed and we score. We play the tetris game until we top out.


The tetrominoes are drawn using the Swing painting API. We use thejava.util.Timer to create a game cycle. The shapes move on asquare by square basis (not pixel by pixel). Mathematically the board in thegame is a simple list of numbers.The game starts immediately after it is launched. We can pause the game bypressing the p key. The space key will drop the Tetris piece immediately tothe bottom. The d key will drop the piece one line down. (It can be used tospeed up the falling a bit.) The game goes at constant speed, no accelerationis implemented. The score is the number of lines that we have removed.


The Shape class provides information about a Tetris piece.protected enum Tetrominoe NoShape, ZShape, SShape, LineShape, TShape, SquareShape, LShape, MirroredLShapeThe Tetrominoe enum holds seven Tetris shape names and theempty shape called NoShape.coords = new int[4][2];setShape(Tetrominoe.NoShape);The coords array holds the actual coordinates of a Tetris piece.


Some important variables are initialized. The isFallingFinisheddetermines if the Tetris shape has finished falling and we then need to createa new shape. The isStarted is used to check if the gamehas started. Likewise, the isPaused is used to check if the gameis paused. The numLinesRemoved counts the number of lines that wehave removed so far. The curX and curY determine theactual position of the falling Tetris shape.private int squareWidth() return (int) getSize().getWidth() / BOARD_WIDTH;private int squareHeight() return (int) getSize().getHeight() / BOARD_HEIGHT;These lines determine the width and height of a single Tetrominoe square.private Tetrominoe shapeAt(int x, int y) return board[(y * BOARD_WIDTH) + x];We determine the shape at the given coordinates. The shapes are stored inthe board array.


Every Tetris piece has four squares. Each of the squares is drawn with thedrawSquare() method. Tetris pieces have different colours.The left and top sides of a square are drawn with a brighter color. Similarly,the bottom and right sides are drawn with darker colours. This is to simulatea 3D edge.private class GameCycle implements ActionListener @Override public void actionPerformed(ActionEvent e) doGameCycle(); In the GameCycle, we call the doGameCycle() method,creating a game cycle.private void doGameCycle() update(); repaint();The game is divided into game cycles. Each cycle udpates the gameand redraws the board.


One of the most common computer games ever created is the Tetris game. Nowadays we can play this game on mobile too. The game was designed, as well as created by Alexey Pajitnov in 1985. He was a Russian Programmer. A lot of different variation has come to this game has come in the market. However, in this tutorial, we will be creating a basic Tetris game.


Tetris game is known as a block puzzle falling game. In a Tetris game, we have a total of seven different shapes known as Tetrominoes. Those seven Tetrominoes are Line-shape, Z-shape, S-shape, L-shape, T-shape, Square-shape, and a Mirrored L-shape. All the mentioned shapes are composed of only four squares. The shapes will fall down the board. The aim of a player playing the Tetris game is to rotate and move shapes so that they get fit as much as they can. If a complete row is formed, that row is destroyed, and the score is incremented. Until we top out, the Tetris game is played.


The Window.java file contains the main method. Therefore, it is the file we need compile. The file contains the code that invokes the constructor of the classes mentioned in the other files. Thus, compiling the Window.java file compiles the other files too. For running the game, use the command java Window. A few snapshots of the game is mentioned below.


About two years ago, when I was in grade 9, I decided to make a tetris clone in Java. One or two months later, I had a fully working and playable tetris, complete with background and sound effects and scoring and graphical effects when a line is cleared.


Run the AI against a half height, 1010 grid. Using 10 columns is *very* important, as survival strategies change with less or more columns. The 8 column simulation is giving you bunk data for an actual game But since you seem to be trying to tune the AI for survival, 10 rows instead of 20 involves uses the same strategies, but just ends orders of magnitude faster.


As to your tournament function, are you running each candidate several times and testing the -averages- against each other? If not a bad mino run, early or late, would make a perfectly strong candidate appear weak, again making your runs meaningless. When writing a Tetris AI myself I found I needed about 60 runs of each candidate before the average lines cleared became somewhat stable.


You should strongly consider changing the selection. Keep the best candidate to prevent losing any effective values. Consider moving away from tournament selection and just do the random crossover you have already. If you are converging at a local minimum, then not enough variation is being created. Your tournament is a major contributor to that. Also, implement a mutation to zero out parameters, as their actual presence may inhibit the most effective strategy. Rethink the fitness function. If bad runs will result, then either use a static seed or use a probabilistic score, like average score or macimum score over 10 runs. Finally, try more than just 10 generations. I have optimized simple functions that took 100,000 generations to reach a high level of fitness. Good luck. Machine learning is very exciting.


the ai is doing this, because it gets rewarded bigtime when it is clearing multiple lines at once. when building thightly stacked columns with a single hole on top of each other, and the effect of a tetris block with a high score on nr of direct neighbours. ( read vertical column of 4 blocks)


An ideia is to assume that a feature is either positive or negative, so you can take a random between 0 and 1, narrowing the search space. Another ideia is to fix a sequence of n random games, and let each agent play the whole sequence, taking the average of cleared rows as fitness!


Okay I get it now! So there are really two scoring formulas. One is the regular in game score, 40 points for a single line, etc. I missed that part. This score determines how good is the other scoring formula which was used to determine the moves. I had a Eureka moment.


Java version repo: -first

Haskell version repo: -first

- master branch - single-threaded version

- recursive-handle-tetris-commands - version with channels and the cycle is started using recursive function

- chan branch - version with channels and the cycle is initiated using fold


An article -games-in-scala

- describes control sequences that allow to print in any arbitrary location on the screen, rather than in line-by-line manner

- describes how to read arrow button press events


decided to implement in haskell, wrote some preliminary code that reads arrow button presses from console, didn't know how to write tetris in functional style, came across a comment about fs2, been reading about iteratee, postponed tetris, lost preliminary code.


there is a channel (concurrent queue)

a timer sends a "tick" command to the channel

a recursive keys2commands function translates read symbols into commands, which it then sends to channel

some function reads commands from the channel and passes them to the handleTetrisCommand function which reacts to them

handleTetrisCommand receives game state and a command as an input, shows an arena and returns the next state of a game


There's a tradition to print Hello World to the console when beginning learning a language. Let's call printing Hello World to the console a first level of interactivity. A next level is when a program gets an input from a user and prints the result to the console. Sounds similar to the way functions work.


One of the merits of a functional style is said to be the fact that functions don't produce side effects. Side effects have the potential to over-complicate the code, making it resemble a bowl of spagetti (it is called spagetti-code), and unwanted side effects are errors, bugs. When we use functions, we don't have side effects, so from the beginning we eliminate the possibility of introducing an unwanted side effect into the code.


Are we going to write some UI or a server, or maybe an operation system kernel? It would be too far of a jump on a learning curve, which seems to be pretty steep in haskell's case. We got to flatten the learning curve.

3a8082e126
Reply all
Reply to author
Forward
0 new messages