- GUI
- Windows API tutorial
- Introduction to Windows API
- Windows API main functions
- System functions in Windows API
- Strings in Windows API
- Date & time in Windows API
- A window in Windows API
- First steps in UI
- Windows API menus
- Windows API dialogs
- Windows API controls I
- Windows API controls II
- Windows API controls III
- Advanced controls in Windows API
- Custom controls in Windows API
- The GDI in Windows API
- PyQt4 tutorial
- PyQt5 tutorial
- Qt4 tutorial
- Introduction to Qt4 toolkit
- Qt4 utility classes
- Strings in Qt4
- Date and time in Qt4
- Working with files and directories in Qt4
- First programs in Qt4
- Menus and toolbars in Qt4
- Layout management in Qt4
- Events and signals in Qt4
- Qt4 Widgets
- Qt4 Widgets II
- Painting in Qt4
- Custom widget in Qt4
- The Breakout game in Qt4
- Qt5 tutorial
- Introduction to Qt5 toolkit
- Strings in Qt5
- Date and time in Qt5
- Containers in Qt5
- Working with files and directories in Qt5
- First programs in Qt5
- Menus and toolbars in Qt5
- Layout management in Qt5
- Events and signals in Qt5
- Qt5 Widgets
- Qt5 Widgets II
- Painting in Qt5
- Custom widget in Qt5
- Snake in Qt5
- The Breakout game in Qt5
- PySide tutorial
- Tkinter tutorial
- Tcl/Tk tutorial
- Qt Quick tutorial
- Java Swing tutorial
- JavaFX tutorial
- Java SWT tutorial
- wxWidgets tutorial
- Introduction to wxWidgets
- wxWidgets helper classes
- First programs in wxWidgets
- Menus and toolbars in wxWidgets
- Layout management in wxWidgets
- Events in wxWidgets
- Dialogs in wxWidgets
- wxWidgets widgets
- wxWidgets widgets II
- Drag and Drop in wxWidgets
- Device Contexts in wxWidgets
- Custom widgets in wxWidgets
- The Tetris game in wxWidgets
- wxPython tutorial
- Introduction to wxPython
- First Steps
- Menus and toolbars
- Layout management in wxPython
- Events in wxPython
- wxPython dialogs
- Widgets
- Advanced widgets in wxPython
- Drag and drop in wxPython
- Internationalisation
- Application skeletons in wxPython
- The GDI
- Mapping modes
- Creating custom widgets
- Tips and Tricks
- wxPython Gripts
- The Tetris game in wxPython
- C# Winforms Mono tutorial
- Java Gnome tutorial
- Introduction to Java Gnome
- First steps in Java Gnome
- Layout management in Java Gnome
- Layout management II in Java Gnome
- Menus in Java Gnome
- Toolbars in Java Gnome
- Events in Java Gnome
- Widgets in Java Gnome
- Widgets II in Java Gnome
- Advanced widgets in Java Gnome
- Dialogs in Java Gnome
- Pango in Java Gnome
- Drawing with Cairo in Java Gnome
- Drawing with Cairo II
- Nibbles in Java Gnome
- QtJambi tutorial
- GTK+ tutorial
- Ruby GTK tutorial
- GTK# tutorial
- Visual Basic GTK# tutorial
- PyGTK tutorial
- Introduction to PyGTK
- First steps in PyGTK
- Layout management in PyGTK
- Menus in PyGTK
- Toolbars in PyGTK
- Signals & events in PyGTK
- Widgets in PyGTK
- Widgets II in PyGTK
- Advanced widgets in PyGTK
- Dialogs in PyGTK
- Pango
- Pango II
- Drawing with Cairo in PyGTK
- Drawing with Cairo II
- Snake game in PyGTK
- Custom widget in PyGTK
- PHP GTK tutorial
- C# Qyoto tutorial
- Ruby Qt tutorial
- Visual Basic Qyoto tutorial
- Mono IronPython Winforms tutorial
- Introduction
- First steps in IronPython Mono Winforms
- Layout management
- Menus and toolbars
- Basic Controls in Mono Winforms
- Basic Controls II in Mono Winforms
- Advanced Controls in Mono Winforms
- Dialogs
- Drag & drop in Mono Winforms
- Painting
- Painting II in IronPython Mono Winforms
- Snake in IronPython Mono Winforms
- The Tetris game in IronPython Mono Winforms
- FreeBASIC GTK tutorial
- Jython Swing tutorial
- JRuby Swing tutorial
- Visual Basic Winforms tutorial
- JavaScript GTK tutorial
- Ruby HTTPClient tutorial
- Ruby Faraday tutorial
- Ruby Net::HTTP tutorial
- Java 2D games tutorial
- Java 2D tutorial
- Cairo graphics tutorial
- PyCairo tutorial
- HTML5 canvas tutorial
- Python tutorial
- Python language
- Interactive Python
- Python lexical structure
- Python data types
- Strings in Python
- Python lists
- Python dictionaries
- Python operators
- Keywords in Python
- Functions in Python
- Files in Python
- Object-oriented programming in Python
- Modules
- Packages in Python
- Exceptions in Python
- Iterators and Generators
- Introspection in Python
- Ruby tutorial
- PHP tutorial
- Visual Basic tutorial
- Visual Basic
- Visual Basic lexical structure
- Basics
- Visual Basic data types
- Strings in Visual Basic
- Operators
- Flow control
- Visual Basic arrays
- Procedures & functions in Visual Basic
- Organizing code in Visual Basic
- Object-oriented programming
- Object-oriented programming II in Visual Basic
- Collections in Visual Basic
- Input & output
- Tcl tutorial
- C# tutorial
- Java tutorial
- AWK tutorial
- Jetty tutorial
- Tomcat Derby tutorial
- Jtwig tutorial
- Android tutorial
- Introduction to Android development
- First Android application
- Android Button widgets
- Android Intents
- Layout management in Android
- Android Spinner widget
- SeekBar widget
- Android ProgressBar widget
- Android ListView widget
- Android Pickers
- Android menus
- Dialogs
- Drawing in Android
- Java EE 5 tutorials
- Introduction
- Installing Java
- Installing NetBeans 6
- Java Application Servers
- Resin CGIServlet
- JavaServer Pages, (JSPs)
- Implicit objects in JSPs
- Shopping cart
- JSP & MySQL Database
- Java Servlets
- Sending email in a Servlet
- Creating a captcha in a Servlet
- DataSource & DriverManager
- Java Beans
- Custom JSP tags
- Object relational mapping with iBATIS
- Jsoup tutorial
- MySQL tutorial
- MySQL quick tutorial
- MySQL storage engines
- MySQL data types
- Creating, altering and dropping tables in MySQL
- MySQL expressions
- Inserting, updating, and deleting data in MySQL
- The SELECT statement in MySQL
- MySQL subqueries
- MySQL constraints
- Exporting and importing data in MySQL
- Joining tables in MySQL
- MySQL functions
- Views in MySQL
- Transactions in MySQL
- MySQL stored routines
- MySQL Python tutorial
- MySQL Perl tutorial
- MySQL C API programming tutorial
- MySQL Visual Basic tutorial
- MySQL PHP tutorial
- MySQL Java tutorial
- MySQL Ruby tutorial
- MySQL C# tutorial
- SQLite tutorial
- SQLite C tutorial
- SQLite PHP tutorial
- SQLite Python tutorial
- SQLite Perl tutorial
- SQLite Ruby tutorial
- SQLite C# tutorial
- SQLite Visual Basic tutorial
- PostgreSQL C tutorial
- PostgreSQL Python tutorial
- PostgreSQL Ruby tutorial
- PostgreSQL PHP tutorial
- PostgreSQL Java tutorial
- Apache Derby tutorial
- SQLAlchemy tutorial
- MongoDB PHP tutorial
- MongoDB Java tutorial
- MongoDB JavaScript tutorial
- MongoDB Ruby tutorial
- Spring JdbcTemplate tutorial
- JDBI tutorial
Sokoban
In this part of the Java 2D games tutorial, we will create a Java Sokoban game clone.
Sokoban
Sokoban is another classic computer game. It was created in 1980 by Hiroyuki Imabayashi. Sokoban means a warehouse keeper in Japanese. The player pushes boxes around a maze. The objective is to place all boxes in designated locations.
Development
We control the sokoban object with cursor keys. We can also press the R key to restart the level. When all bags are placed on the destination areas, the game is finished. We draw "Completed" string in the left upper corner of the window.
Board.java
package sokoban; import java.awt.Color; import java.awt.Graphics; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.util.ArrayList; import javax.swing.JPanel; public class Board extends JPanel { private final int OFFSET = 30; private final int SPACE = 20; private final int LEFT_COLLISION = 1; private final int RIGHT_COLLISION = 2; private final int TOP_COLLISION = 3; private final int BOTTOM_COLLISION = 4; private ArrayList walls = new ArrayList(); private ArrayList baggs = new ArrayList(); private ArrayList areas = new ArrayList(); private Player soko; private int w = 0; private int h = 0; private boolean completed = false; private String level = " ######\n" + " ## #\n" + " ##$ #\n" + " #### $##\n" + " ## $ $ #\n" + "#### # ## # ######\n" + "## # ## ##### ..#\n" + "## $ $ ..#\n" + "###### ### #@## ..#\n" + " ## #########\n" + " ########\n"; public Board() { addKeyListener(new TAdapter()); setFocusable(true); initWorld(); } public int getBoardWidth() { return this.w; } public int getBoardHeight() { return this.h; } public final void initWorld() { int x = OFFSET; int y = OFFSET; Wall wall; Baggage b; Area a; for (int i = 0; i < level.length(); i++) { char item = level.charAt(i); if (item == '\n') { y += SPACE; if (this.w < x) { this.w = x; } x = OFFSET; } else if (item == '#') { wall = new Wall(x, y); walls.add(wall); x += SPACE; } else if (item == '$') { b = new Baggage(x, y); baggs.add(b); x += SPACE; } else if (item == '.') { a = new Area(x, y); areas.add(a); x += SPACE; } else if (item == '@') { soko = new Player(x, y); x += SPACE; } else if (item == ' ') { x += SPACE; } h = y; } } public void buildWorld(Graphics g) { g.setColor(new Color(250, 240, 170)); g.fillRect(0, 0, this.getWidth(), this.getHeight()); ArrayList world = new ArrayList(); world.addAll(walls); world.addAll(areas); world.addAll(baggs); world.add(soko); for (int i = 0; i < world.size(); i++) { Actor item = (Actor) world.get(i); if ((item instanceof Player) || (item instanceof Baggage)) { g.drawImage(item.getImage(), item.x() + 2, item.y() + 2, this); } else { g.drawImage(item.getImage(), item.x(), item.y(), this); } if (completed) { g.setColor(new Color(0, 0, 0)); g.drawString("Completed", 25, 20); } } } @Override public void paint(Graphics g) { super.paint(g); buildWorld(g); } class TAdapter extends KeyAdapter { @Override public void keyPressed(KeyEvent e) { if (completed) { return; } int key = e.getKeyCode(); if (key == KeyEvent.VK_LEFT) { if (checkWallCollision(soko, LEFT_COLLISION)) { return; } if (checkBagCollision(LEFT_COLLISION)) { return; } soko.move(-SPACE, 0); } else if (key == KeyEvent.VK_RIGHT) { if (checkWallCollision(soko, RIGHT_COLLISION)) { return; } if (checkBagCollision(RIGHT_COLLISION)) { return; } soko.move(SPACE, 0); } else if (key == KeyEvent.VK_UP) { if (checkWallCollision(soko, TOP_COLLISION)) { return; } if (checkBagCollision(TOP_COLLISION)) { return; } soko.move(0, -SPACE); } else if (key == KeyEvent.VK_DOWN) { if (checkWallCollision(soko, BOTTOM_COLLISION)) { return; } if (checkBagCollision(BOTTOM_COLLISION)) { return; } soko.move(0, SPACE); } else if (key == KeyEvent.VK_R) { restartLevel(); } repaint(); } } private boolean checkWallCollision(Actor actor, int type) { if (type == LEFT_COLLISION) { for (int i = 0; i < walls.size(); i++) { Wall wall = (Wall) walls.get(i); if (actor.isLeftCollision(wall)) { return true; } } return false; } else if (type == RIGHT_COLLISION) { for (int i = 0; i < walls.size(); i++) { Wall wall = (Wall) walls.get(i); if (actor.isRightCollision(wall)) { return true; } } return false; } else if (type == TOP_COLLISION) { for (int i = 0; i < walls.size(); i++) { Wall wall = (Wall) walls.get(i); if (actor.isTopCollision(wall)) { return true; } } return false; } else if (type == BOTTOM_COLLISION) { for (int i = 0; i < walls.size(); i++) { Wall wall = (Wall) walls.get(i); if (actor.isBottomCollision(wall)) { return true; } } return false; } return false; } private boolean checkBagCollision(int type) { if (type == LEFT_COLLISION) { for (int i = 0; i < baggs.size(); i++) { Baggage bag = (Baggage) baggs.get(i); if (soko.isLeftCollision(bag)) { for (int j=0; j < baggs.size(); j++) { Baggage item = (Baggage) baggs.get(j); if (!bag.equals(item)) { if (bag.isLeftCollision(item)) { return true; } } if (checkWallCollision(bag, LEFT_COLLISION)) { return true; } } bag.move(-SPACE, 0); isCompleted(); } } return false; } else if (type == RIGHT_COLLISION) { for (int i = 0; i < baggs.size(); i++) { Baggage bag = (Baggage) baggs.get(i); if (soko.isRightCollision(bag)) { for (int j=0; j < baggs.size(); j++) { Baggage item = (Baggage) baggs.get(j); if (!bag.equals(item)) { if (bag.isRightCollision(item)) { return true; } } if (checkWallCollision(bag, RIGHT_COLLISION)) { return true; } } bag.move(SPACE, 0); isCompleted(); } } return false; } else if (type == TOP_COLLISION) { for (int i = 0; i < baggs.size(); i++) { Baggage bag = (Baggage) baggs.get(i); if (soko.isTopCollision(bag)) { for (int j = 0; j < baggs.size(); j++) { Baggage item = (Baggage) baggs.get(j); if (!bag.equals(item)) { if (bag.isTopCollision(item)) { return true; } } if (checkWallCollision(bag, TOP_COLLISION)) { return true; } } bag.move(0, -SPACE); isCompleted(); } } return false; } else if (type == BOTTOM_COLLISION) { for (int i = 0; i < baggs.size(); i++) { Baggage bag = (Baggage) baggs.get(i); if (soko.isBottomCollision(bag)) { for (int j = 0; j < baggs.size(); j++) { Baggage item = (Baggage) baggs.get(j); if (!bag.equals(item)) { if (bag.isBottomCollision(item)) { return true; } } if (checkWallCollision(bag, BOTTOM_COLLISION)) { return true; } } bag.move(0, SPACE); isCompleted(); } } } return false; } public void isCompleted() { int num = baggs.size(); int compl = 0; for (int i = 0; i < num; i++) { Baggage bag = (Baggage) baggs.get(i); for (int j = 0; j < num; j++) { Area area = (Area) areas.get(j); if (bag.x() == area.x() && bag.y() == area.y()) { compl += 1; } } } if (compl == num) { completed = true; repaint(); } } public void restartLevel() { areas.clear(); baggs.clear(); walls.clear(); initWorld(); if (completed) { completed = false; } } }
The game is simplified. It only provides the very basic functionality. The code is than easier to understand. The game has one level.
private final int OFFSET = 30; private final int SPACE = 20; private final int LEFT_COLLISION = 1; private final int RIGHT_COLLISION = 2; private final int TOP_COLLISION = 3; private final int BOTTOM_COLLISION = 4;
The wall image size is 20x20px. This reflects the SPACE
constant. The OFFSET
is the distance between the borders of the window and the game world. There are four types of collisions. Each one is represented by a numerical constant.
private ArrayList walls = new ArrayList(); private ArrayList baggs = new ArrayList(); private ArrayList areas = new ArrayList();
The walls, baggs and areas are special containers, which will hold all the walls, baggs and areas of the game.
private String level = " ######\n" + " ## #\n" + " ##$ #\n" + " #### $##\n" + " ## $ $ #\n" + "#### # ## # ######\n" + "## # ## ##### ..#\n" + "## $ $ ..#\n" + "###### ### #@## ..#\n" + " ## #########\n" + " ########\n";
This is the level of the game. Except for the space, there are five characters. The hash (#) stands for a wall. The dollar ($) represents the box to move. The dot (.) character represents the place where we must move the box. The at character (@) is the sokoban. And finally the new line character (\n) starts a new row of the world.
public final void initWorld() { int x = OFFSET; int y = OFFSET; ...
The initWorld()
method initiates the game world. It goes through the level string and fills the above mentioned lists.
} else if (item == '$') { b = new Baggage(x, y); baggs.add(b); x += SPACE;
In case of the dollar character, we create a Baggage
object. The object is appended to the baggs list. The x
variable is increased accordingly.
public void buildWorld(Graphics g) { ...
The buildWorld()
method draws the game world on the window.
ArrayList world = new ArrayList(); world.addAll(walls); world.addAll(areas); world.addAll(baggs); world.add(soko);
We create a world list which includes all objects of the game.
for (int i = 0; i < world.size(); i++) { Actor item = (Actor) world.get(i); if ((item instanceof Player) || (item instanceof Baggage)) { g.drawImage(item.getImage(), item.x() + 2, item.y() + 2, this); } else { g.drawImage(item.getImage(), item.x(), item.y(), this); } ...
We iterate through the world container and draw the objects. The player and the baggage images are a bit smaller. We add 2px to their coordinates to center them.
if (completed) { g.setColor(new Color(0, 0, 0)); g.drawString("Completed", 25, 20); }
If the level is completed, we draw "Completed" in the upper left corner of the window.
if (key == KeyEvent.VK_LEFT) { if (checkWallCollision(soko, LEFT_COLLISION)) { return; } if (checkBagCollision(LEFT_COLLISION)) { return; } soko.move(-SPACE, 0); ...
Inside the keyPressed()
method, we check what keys were pressed. We control the sokoban object with the cursor keys. If we press the left cursor key, we check if the sokoban collides with a wall or with a baggage. If it does not, we move the sokoban to the left.
} else if (key == KeyEvent.VK_R) { restartLevel(); }
We restart the level if we press the R key.
if (type == LEFT_COLLISION) { for (int i = 0; i < walls.size(); i++) { Wall wall = (Wall) walls.get(i); if (actor.isLeftCollision(wall)) { return true; } } return false; ...
The checkWallCollision()
method was created to ensure that the sokoban or a baggage do not pass the wall. There are four types of collisions. The above lines check for the left collision.
private boolean checkBagCollision(int type) { }
The checkBagCollision()
is a bit more involved. A baggage can collide with a wall, with a sokoban object or with another baggage. The baggage can be moved only if it collides with a sokoban and does not collide with another baggage or a wall. When the baggage is moved, it is time to check if the level is completed by calling the isCompleted()
method.
for (int i = 0; i < num; i++) { Baggage bag = (Baggage) baggs.get(i); for (int j = 0; j < num; j++) { Area area = (Area) areas.get(j); if (bag.x() == area.x() && bag.y() == area.y()) { compl += 1; } } }
The isCompleted()
method checks if the level is completed. We get the number of bags. We compare the x, y coordinates of all the bags and the destination areas.
if (compl == num) { completed = true; repaint(); }
The game is finished, when the completed variable equals the number of bags in the game.
public void restartLevel() { areas.clear(); baggs.clear(); walls.clear(); initWorld(); if (completed) { completed = false; } }
If we do some bad move, we can restart the level. We delete all objects from the important lists and initiate the world again. The completed variable is set to false.
Actor.java
package sokoban; import java.awt.Image; public class Actor { private final int SPACE = 20; private int x; private int y; private Image image; public Actor(int x, int y) { this.x = x; this.y = y; } public Image getImage() { return this.image; } public void setImage(Image img) { image = img; } public int x() { return this.x; } public int y() { return this.y; } public void setX(int x) { this.x = x; } public void setY(int y) { this.y = y; } public boolean isLeftCollision(Actor actor) { if (((this.x() - SPACE) == actor.x()) && (this.y() == actor.y())) { return true; } else { return false; } } public boolean isRightCollision(Actor actor) { if (((this.x() + SPACE) == actor.x()) && (this.y() == actor.y())) { return true; } else { return false; } } public boolean isTopCollision(Actor actor) { if (((this.y() - SPACE) == actor.y()) && (this.x() == actor.x())) { return true; } else { return false; } } public boolean isBottomCollision(Actor actor) { if (((this.y() + SPACE) == actor.y()) && (this.x() == actor.x())) { return true; } else { return false; } } }
This is the Actor
class. The class is a base class for other actors in the game. It encapsulates the basic functionality of an object in the Sokoban game.
public boolean isLeftCollision(Actor actor) { if (((this.x() - SPACE) == actor.x()) && (this.y() == actor.y())) { return true; } else { return false; } }
This method checks if the actor collides with another actor (wall, baggage, sokoban) to the left.
Wall.java
package sokoban; import java.awt.Image; import java.net.URL; import javax.swing.ImageIcon; public class Wall extends Actor { private Image image; public Wall(int x, int y) { super(x, y); URL loc = this.getClass().getResource("wall.png"); ImageIcon iia = new ImageIcon(loc); image = iia.getImage(); this.setImage(image); } }
This is the Wall class. It inherits from the Actor
class. Upon construction, it loads a wall image from the filesystem.
Player.java
package sokoban; import java.awt.Image; import java.net.URL; import javax.swing.ImageIcon; public class Player extends Actor { public Player(int x, int y) { super(x, y); URL loc = this.getClass().getResource("sokoban.png"); ImageIcon iia = new ImageIcon(loc); Image image = iia.getImage(); this.setImage(image); } public void move(int x, int y) { int nx = this.x() + x; int ny = this.y() + y; this.setX(nx); this.setY(ny); } }
This is the Player
class. It is the class to create the sokoban object.
public void move(int x, int y) { int nx = this.x() + x; int ny = this.y() + y; this.setX(nx); this.setY(ny); }
This class has a move()
method, which moves the object inside the world.
Baggage.java
package sokoban; import java.awt.Image; import java.net.URL; import javax.swing.ImageIcon; public class Baggage extends Actor { public Baggage(int x, int y) { super(x, y); URL loc = this.getClass().getResource("baggage.png"); ImageIcon iia = new ImageIcon(loc); Image image = iia.getImage(); this.setImage(image); } public void move(int x, int y) { int nx = this.x() + x; int ny = this.y() + y; this.setX(nx); this.setY(ny); } }
This is the class for the Baggage
object. This object is movable, so it has the move()
method also.
Area.java
package sokoban; import java.awt.Image; import java.net.URL; import javax.swing.ImageIcon; public class Area extends Actor { public Area(int x, int y) { super(x, y); URL loc = this.getClass().getResource("area.png"); ImageIcon iia = new ImageIcon(loc); Image image = iia.getImage(); this.setImage(image); } }
This is the Area
class. It is the object, on which we try to place the baggages.
Sokoban.java
package sokoban; import javax.swing.JFrame; public final class Sokoban extends JFrame { private final int OFFSET = 30; public Sokoban() { InitUI(); } public void InitUI() { Board board = new Board(); add(board); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(board.getBoardWidth() + OFFSET, board.getBoardHeight() + 2*OFFSET); setLocationRelativeTo(null); setTitle("Sokoban"); } public static void main(String[] args) { Sokoban sokoban = new Sokoban(); sokoban.setVisible(true); } }
This is the main class.

This was the Sokoban game.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论