Advertisement
iOS SDK

Build a Multiplayer Minesweeper Game: Server-Side Setup

by

This two-part mini-series will teach you how to create a multiplayer game called Minesweeper Flags. In this tutorial, you will learn how to implement the server side of the application, the database, and even the Web services. The next tutorial will teach you how to implement the user interface, web server communication, data parsing and interaction. Read on!


Minesweeper Flag

Minesweeper Flag is a multi-player board game that is played between two opponents. Commonly, either blue or red are assigned to each player. The board is composed by 256 equal squares, and each board has 51 mines placed in entirely random positions.

The goal of the game is to uncover all the squares in order to find 26 mines. Touching on the game board will reveal what is hidden underneath the chosen square: a bomb or a number. Every time a player touches on a square that contains a mine he/she is awarded with another move. Moreover, if a number is uncovered, that number represents the number of mines adjacent to the uncovered square.

At the beginning of the game the color of the player is automatically assigned and the board is completely covered. The player with the blue color always moves first.


Project Preview

Figure 5: Blue player
Preview of the Final Effect

System Model

In order to simplify the game and software requirements, a graphical model of all requirements is presented bellow. As you can see, the database, web services, and user interfaces are divided in several distinct layers in order to achieve software independence.

Figure 2: Layer Abstraction

Requirements

In order to complete the tutorial, the reader needs the following requirements:

  • MySQL
  • Netbeans with Web development packages
  • Xcode with iOS development kit.
  • Cocos2d for iOS

Layer Connection

The MySQL component can be seen as the core of the application since it will directly support the game persistence. It will store all data inherent to the Minesweeper Flag game, such as player moves, mine location, and scores.

The database of Minesweeper Flag is composing for only one tablet called games. The following image presents the database in a graphical way.

Figure 3: Entity Relationship Diagram

Database

  • The "games" table is the fundamental table since it preserves the core functions of the game. It contains the game and player identifier, the player turn, game matrix, and the uncovered matrix. The matrix field contains the mines location and their neighbors, while the uncovered matrix initially contains the 256 squares filled with a pre-determined 9 value. This field is very important, since it will be constantly used to check if a given square was already touched and its value. The 9 value means that this single square was not yet touched while the "*"" and "#"" character means that the blue or red player found a mine, correspondingly.

The Netbeans interface development environment is used to provide the web application and its direct web services. This tutorial is based on version 7.0.1 with the Bundled servers installed.


Step 1: Start a Java Web Application

Figure 4: Start a new Java Web Application



Click at File -> New Project


Step 2: Configure the Project Settings

Give a name to the project, its location and folder

Figure 5: Project Name

Step 3: Choose the Web Server Engine

Figure 6: Choose the Web server engine

In this tutorial, the authors used the Glassfish server with Java EE version 6 as a standard.


Step 4: Skip the Framework Option

Figure 7: Frameworks

Do not choose any framework, since we will not use any specification or feature of any of the presented frameworks.

At this point we have the Web server configured. The next step is to launch it in order to verify if everything is correctly configured.


Step 5: Run the Main Project

To run the main project you can click in the Run Main Project option, located at the Run menu or click in the green icon at the top toolbar. If everything is correct a Web page should appear with the message "Hello World!".

Figure 8: Run the Project

Now it is time to add the web services layer to the web server.


Step 6: Add a new RESTful Web Service

Figure 9: Add Web Service



Right click in the Project name and choose New -> Other. From the left menu options choose Web Services and from the right list RESTful Web Service from Patterns.


Step 8: Select a Pattern

Figure 10: Select a pattern

Choose the first option "Simple Root Reference".


Step 9: Web Service Configuration

Figure 11: Web Service name

Choose a resource package and define the Path for the root container of all services. Additionally, choose the MIME type. For this tutorial, the authors have selected the JSON data-interchange format.


Step 10: REST Resources Configurations

Figure 12: REST resources



Choose the last option "Create default Jersey REST servlet adaptor in web.xml".


Step 11: Add the Connection Methods

Additionally, two more methods were added in order to separate the data logic layer with the database layer; CreateConnection() and EndConnection(). The following snippets should be included in the MinesweeperService Java class.

Include this at the import section.

import java.sql.*;
import javax.jws.*;

Define the following class properties.

    private Connection conn = null;
    private Statement statement = null;
    private ResultSet resultSet = null;
    // The authors used the 8889 MySQL port at a localhost host.
    // Change it accordingly.
    private final String url = "jdbc:mysql://localhost:8889/";
    private final String dbName = "minesweeper";
    private final String driver = "com.mysql.jdbc.Driver";
    private final String userName = "root";
    private final String password = "root";

Copy and past the following web methods.

    private Boolean CreateConnection() {
        try {
            Class.forName(driver).newInstance();
            conn = DriverManager.getConnection(url + dbName, userName, password);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    private Boolean EndConnection() {
        try {
            if (resultSet != null)
                resultSet = null;
            if (statement != null)
                statement.close();
            if (conn != null)
                conn.close();
        } catch (Exception e) {
            return false;
        }

        return true;
    }

    @WebMethod(operationName = "authentication")
    public String authentication(@WebParam(name = "email") String email, @WebParam(name = "password") String pw) {
        CreateConnection();

        String query = "SELECT * FROM players WHERE Email='" + email + "' and Pass='" + pw + "';";
        try {
            statement = (Statement) conn.createStatement();
            resultSet = statement.executeQuery(query);

            if (resultSet.next()) {
                EndConnection();
                return "1";
            } else {
                EndConnection();
                return "0";
            }
        } catch (Exception ex) {
            EndConnection();
            return "0";
        }
    }
}

Step 12: Add the External MySQL JAR

As it is necessary to make a connection to the MySQL database, an external MySQL library is necessary. In order to add it to the project, right click in the project name and go to the Properties options. Then choose Libraries and click at Add JAR / folder.

Figure 13: Add the external MySQL .jar library

Step 13: Web Service Testing

Figure 14: Test the Web Service

Under the main project, click in the Web Services folder and with the second mouse button click in the MinesweeperService object and choose the Test RESTful Web Services option.


Step 14: Select Test File Target

Figure 15: Test files target

Leave the first option selected: "Locally Generated Test Client".

At this point, you should have a server side application that supports connecting with a database, communication with web servers, and the inherent web methods for game interaction.

All operations related to the game can be made using Step 12, although it is not user friendly to do so.


Next Time

In the second and final installment of this series, we will explain how to create a client-side, native iOS application that will connect with and consume the web server data. Stay tuned for part 2!

Related Posts
  • Code
    Android SDK
    Create a Music Player on Android: User Controls0d63m preview image@2x
    We are building a simple music player app for Android in this series. So far, we have presented a list of the songs on the device and allowed the user to make selections from it, starting playback using the MediaPlayer class in a Service class. In this final part of the series, we will let the user control playback, including skipping to the next and previous tracks, fast-forwarding, rewinding, playing, pausing, and seeking to particular points in the track. We will also display a notification during playback so that the user can jump back to the music player after using other apps.Read More…
  • Code
    Android SDK
    Create a Music Player on Android: Song Playback0d63m preview image@2x
    In this series, we are creating a music player on Android using the MediaPlayer and MediaController classes. In the first part, we created the app and prepared the user interface for playback. We presented the list of songs on the user device and specified a method to execute when the user makes a selection. In this part of the series, we will implement a Service class to execute music playback continuously, even when the user is not directly interacting with the application.Read More…
  • Computer Skills
    Electronics
    How to Use a Raspberry Pi as a Local Web ServerThumb
    In this tutorial I will show you how to set up a Raspberry Pi to be used as a Local Web Server with SSH and FTP functionality.Read More…
  • Code
    PHP
    Setting Up a Local Mirror for Composer Packages With SatisComposer retina preview
    Installing all your PHP libraries with Composer is a great way to save time. But larger projects automatically tested and run at each commit to your software version control (SVC) system will take a long time to install all the required packages from the Internet. You want to run your tests as soon as possible through your continuous integration (CI) system so that you have fast feedback and quick reactions on failure. In this tutorial we will set up a local mirror to proxy all your packages required in your project's composer.json file. This will make our CI work much faster, install the packages over the local network or even hosted on the same machine, and make sure we have the specific versions of the packages always available.Read More…
  • Code
    Android SDK
    Consuming Web Services with kSOAPEd4e2 preview image@2x
    In this tutorial, you'll learn how to consume web services using the popular kSOAP library in an Android application. kSOAP is a reputable library loved by developers who have the need to parse WSDL (Web Service Definition Language) and SOAP (Simple Object Access Protocol) messages.Read More…
  • Game Development
    Implementation
    How to Code a Self-Hosted PHP/SQL Leaderboard For Your GamePhp sql self hosted leaderboard 400px
    In this article, we're going to create our first MySQL leaderboard to host on a website or web server using simple PHP and some SQL. We'll then make a simple Unity example in C# using GUIText objects to add new scores to our leaderboard, display the top ten scores and display a user's score and rank.Read More…