Cara Mudah Membuat Game Untuk Android. Cara membuat aplikasi android dengan eclipse cukup sederhana. Agan harus lihat dulu web agan versi mobile.
In this part of the Java 2D games tutorial, we create a Java Snake game clone. Source code and images can be found at the author's Github Java-Snake-Game repository.
Snake
Snake is an older classic video game. It was first created in late 70s. Later it was brought to PCs. In this game the playercontrols a snake. The objective is to eat as many apples as possible. Each time the snake eats an apple its body grows. The snake must avoid the walls and its own body. This game is sometimes called Nibbles.
Development of Java Sname game
The size of each of the joints of a snake is 10 px. The snake is controlled with the cursor keys. Initially, the snake has three joints. If the game is finished, the 'Game Over' message is displayed in the middle of the board.
Board.java
First we will define the constants used in our game.
The
B_WIDTH
and B_HEIGHT
constants determine the size of the board. The DOT_SIZE
is the size of the apple and the dot of the snake. The ALL_DOTS
constant defines the maximum number of possible dots on the board (900 = (300*300)/(10*10)). The RAND_POS
constant is used to calculate a random position for an apple. The DELAY
constant determines the speed of the game.These two arrays store the x and y coordinates of all joints of a snake.
In the
loadImages()
method we get the images for the game.The ImageIcon
class is used for displaying PNG images.In the
initGame()
method we create the snake, randomly locatean apple on the board, and start the timer.If the apple collides with the head, we increase the number of joints of the snake.We call the
locateApple()
method which randomly positions a new apple object.In the
move()
method we have the key algorithm of the game. To understand it, look at how the snake is moving. We control the head of the snake. We can change its direction with the cursor keys. The rest of the joints move one position up the chain. The second joint moves where the first was, the third joint where the second was etc. This code moves the joints up the chain.
This line moves the head to the left.
In the
checkCollision()
method, we determine if the snake has hit itself or one of the walls. If the snake hits one of its joints with its head the game is over.
The game is finished if the snake hits the bottom of the board.
This is the main class.
The
setResizable()
method affects the insets of the JFrame
container on some platforms. Therefore, it is important to call it before the pack()
method. Otherwise, the collision of the snake's head with the right and bottom borders might not work correctly.This was the Snake game in Java.