Nibbles
In this part of the QtJambi programming tutorial, we will create a Nibbles game clone.Nibbles is an older classic video game. It was first created in late 70s. Later it was brought to PCs. In this game the player controls 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.
Development
The size of each of the joints of a snake is 10px. The snake is controlled with the cursor keys. Initially, the snake has three joints. The game starts immediately. When the game is finished, we display "Game Over" message in the center of the window.Board.java
package com.zetcode;First we will define some globals used in our game.
import com.trolltech.qt.core.QBasicTimer;
import com.trolltech.qt.core.QPoint;
import com.trolltech.qt.core.QTimerEvent;
import com.trolltech.qt.core.Qt;
import com.trolltech.qt.gui.QColor;
import com.trolltech.qt.gui.QFont;
import com.trolltech.qt.gui.QFontMetrics;
import com.trolltech.qt.gui.QFrame;
import com.trolltech.qt.gui.QImage;
import com.trolltech.qt.gui.QKeyEvent;
import com.trolltech.qt.gui.QPaintEvent;
import com.trolltech.qt.gui.QPainter;
public class Board extends QFrame {
private final int WIDTH = 300;
private final int HEIGHT = 300;
private final int DOT_SIZE = 10;
private final int ALL_DOTS = 900;
private final int RAND_POS = 29;
private final int DELAY = 140;
private int x[] = new int[ALL_DOTS];
private int y[] = new int[ALL_DOTS];
private int dots;
private int apple_x;
private int apple_y;
private boolean left = false;
private boolean right = true;
private boolean up = false;
private boolean down = false;
private boolean inGame = true;
private QBasicTimer timer;
private QImage ball;
private QImage apple;
private QImage head;
public Board() {
setStyleSheet("QWidget { background-color: black }");
setFocusPolicy(Qt.FocusPolicy.StrongFocus);
ball = new QImage("dot.png");
apple = new QImage("apple.png");
head = new QImage("head.png");
initGame();
}
private void initGame() {
dots = 3;
for (int z = 0; z < dots; z++) {
x[z] = 50 - z*10;
y[z] = 50;
}
locateApple();
timer = new QBasicTimer();
timer.start(DELAY, this);
}
@Override
public void paintEvent(QPaintEvent event) {
super.paintEvent(event);
QPainter painter = new QPainter();
painter.begin(this);
if (inGame) {
drawObjects(painter);
} else {
gameOver(painter);
}
painter.end();
}
private void drawObjects(QPainter painter) {
painter.drawImage(apple_x, apple_y, apple);
for (int z = 0; z < dots; z++) {
if (z == 0)
painter.drawImage(x[z], y[z], head);
else painter.drawImage(x[z], y[z], ball);
}
}
private void gameOver(QPainter painter) {
String msg = "Game Over";
QFont small = new QFont("Helvetica", 12,
QFont.Weight.Bold.value());
QFontMetrics metr = new QFontMetrics(small);
int textWidth = metr.width(msg);
int h = height();
int w = width();
painter.setPen(QColor.white);
painter.setFont(small);
painter.translate(new QPoint(w/2, h/2));
painter.drawText(-textWidth/2, 0, msg);
}
private void checkApple() {
if ((x[0] == apple_x) && (y[0] == apple_y)) {
dots++;
locateApple();
}
}
private void move() {
for (int z = dots; z > 0; z--) {
x[z] = x[(z - 1)];
y[z] = y[(z - 1)];
}
if (left) {
x[0] -= DOT_SIZE;
}
if (right) {
x[0] += DOT_SIZE;
}
if (up) {
y[0] -= DOT_SIZE;
}
if (down) {
y[0] += DOT_SIZE;
}
}
private void checkCollision() {
for (int z = dots; z > 0; z--) {
if ((z > 4) && (x[0] == x[z]) && (y[0] == y[z])) {
inGame = false;
}
}
if (y[0] > HEIGHT) {
inGame = false;
}
if (y[0] < 0) {
inGame = false;
}
if (x[0] > WIDTH) {
inGame = false;
}
if (x[0] < 0) {
inGame = false;
}
}
private void locateApple() {
int r = (int) (Math.random() * RAND_POS);
apple_x = ((r * DOT_SIZE));
r = (int) (Math.random() * RAND_POS);
apple_y = ((r * DOT_SIZE));
}
@Override
protected void timerEvent(QTimerEvent event) {
if (inGame) {
checkApple();
checkCollision();
move();
} else {
timer.stop();
}
repaint();
}
@Override
public void keyPressEvent(QKeyEvent event)
{
int key = event.key();
if (key == Qt.Key.Key_Left.value() && !right) {
left = true;
up = false;
down = false;
}
if ((key == Qt.Key.Key_Right.value()) && !left) {
right = true;
up = false;
down = false;
}
if ((key == Qt.Key.Key_Up.value()) && !down) {
up = true;
right = false;
left = false;
}
if ((key == Qt.Key.Key_Down.value()) && !up) {
down = true;
right = false;
left = false;
}
}
}
The WIDTH and 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. The RAND_POS constant is used to calculate a random position of an apple. The DELAY constant determines the speed of the game.
private int x[] = new int[ALL_DOTS];These two arrays store x, y coordinates of all possible joints of a snake.
private int y[] = new int[ALL_DOTS];
The initGame() method initializes variables, loads images and starts a timeout function.
if (inGame) {Inside the paintEvent() method, we check the inGame variable. If it is true, we draw our objects. The apple and the snake joints. Otherwise we display "Game over" text.
drawObjects(painter);
} else {
gameOver(painter);
}
private void drawObjects(QPainter painter) {The drawObjects() method draws the apple and the joints of the snake. The first joint of a snake is its head, which is represented by a red circle.
painter.drawImage(apple_x, apple_y, apple);
for (int z = 0; z < dots; z++) {
if (z == 0)
painter.drawImage(x[z], y[z], head);
else painter.drawImage(x[z], y[z], ball);
}
}
private void checkApple() {The checkApple() method checks, if the snake has hit the apple object. If so, we add another snake joint and call the locateApple() method, which randomly places a new apple object.
if ((x[0] == apple_x) && (y[0] == apple_y)) {
dots++;
locateApple();
}
}
In the move() method we have the key algorithm of the game. To understand it, look at how the snake is moving. You control the head of the snake. You 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.
for (int z = dots; z > 0; z--) {This code moves the joints up the chain.
x[z] = x[(z - 1)];
y[z] = y[(z - 1)];
}
if (left) {Move the head to the left.
x[0] -= DOT_SIZE;
}
In the checkCollision() method, we determine if the snake has hit itself or one of the walls.
for (int z = dots; z > 0; z--) {Finish the game, if the snake hits one of its joints with the head.
if ((z > 4) && (x[0] == x[z]) && (y[0] == y[z])) {
inGame = false;
}
}
if (y[0] > HEIGHT) {Finish the game, if the snake hits the bottom of the Board.
inGame = false;
}
The locateApple() method locates an apple randomly on the board.
int r = (int) (Math.random() * RAND_POS);We get a random number from 0 to RAND_POS - 1.
apple_x = ((r * DOT_SIZE));These line set the x, y coordinates of the apple object.
...
apple_y = ((r * DOT_SIZE));
if (inGame) {Every 140 ms, the timerEvent() method is called. If we are in the game, we call three methods, that build the logic of the game. Otherwise we stop the timer.
checkApple();
checkCollision();
move();
} else {
timer.stop();
}
In the onKeyPressEvent() method of the Board class, we determine the keys that were pressed.
if (key == Qt.Key.Key_Left.value() && !right) {If we hit the left cursor key, we set left variable to true. This variable is used in the move()method to change coordinates of the snake object. Notice also, that when the snake is heading to the right, we cannot turn immediately to the left.
left = true;
up = false;
down = false;
}
Nibbles.java
package com.zetcode;In this class, we set up the Nibbles game.
import com.trolltech.qt.gui.QApplication;
import com.trolltech.qt.gui.QMainWindow;
/**
* ZetCode QtJambi tutorial
*
* In this program, we create
* a Nibbles game clone.
*
* @author jan bodnar
* website zetcode.com
* last modified April 2009
*/
public class Nibbles extends QMainWindow {
public Nibbles() {
setWindowTitle("Nibbles");
resize(310, 310);
setCentralWidget(new Board());
move(300, 300);
show();
}
public static void main(String[] args) {
QApplication.initialize(args);
new Nibbles();
QApplication.exec();
}
}
Figure: Nibbles
This was the Nibbles computer game programmed with the QtJambi library.
No comments:
Post a Comment