Designing an application utilizing event-driven programming

Assignment Help JAVA Programming
Reference no: EM13987943

Learning objectives

• Designing an application utilizing event-driven programming.
• The Model-View-Controller design pattern.

Background information

We are going to create our own implementation of the game "circle the dot". A version for android, on which this description is based, can be foundhere. A version for iOS can be foundhere. This game is simple: a blue dot is trying to "escape" the board (that is, exit from the board), while the player attempts the prevent that by selecting gray dots, turning them into orange dots that the blue dot cannot cross. Figure figure1shows two examples of the initial game configuration screen 1.

2293_Game-circle the dot.png

Figure 1: Two examples of the initial configuration of the game.

The player wins when the blue dot is encircled by orange dots (Figurefigure2). As can be seen on Figurefigure1, initially, some of the dots are already orange (this is a random selection, as we will explain later). The initial location of the blue dot is also randomly selected, but toward the center of the board. If the board has an even number of rows/columns, then the blue dots is randomly located on one of the central four dots, while if the number of rows/columns is odd, it is randomly located on one of the central nine dots (Figurefigure3). At each step the blue dot will move to one of the six neighboring dots (Figurefigure4).

1The UI is based on "Puzzler" by Apple.

33_Game-circle the dot1.png

Figure 2: The player won: the blue dot is circled by orange dots.

Model-View-Controller

Model-View-Controller (MVC) is a very common design pattern, and you will easily find lots of information about it on-line (e.g.wikipedia,apple,microsoftto name a few). The general idea is to separate the roles of your classes into three categories:

• The Model: these are the objects of that store the current state of your system.

• The View (or views): these are the objects that are representing the model to the user (the UI). The representation reflects the current state of the model. You can have several views displayed at the same time, though in our case, we will have just one.

• The Controller: these are the objects that provide the logic of the system, how its state evolves overtime based on its interaction with the "outside" (typically, interactions with the user).

One of the great advantages of MVC is the clear separation it provides between different concerns: the model only focuses on capturing the current state, and doesn't worry about how this is displayed nor how it evolves. The view's only job is to provide an accurate representation of the current state of the model, and to provide the means to handle user inputs, and pass these inputs on to the controller if needed. The controller is the "brain" of the application, and doesn't need to worry about state representation or user interface.

In addition to the separation, MVC also provides a logical collaboration-schema between the three components (Figurefigure5). In our case, it works as follows:

1. When something happens on the view (in our case, when the user selects a gray dot to turn it orange), the controller is informed (message 1 of Figurefigure5).

2. The controller processes the information and updates the model accordingly (message 2 of Figurefigure5).

3. Once the information is processed and the model is updated, the controller informs the view (or views) that it should refresh itself (message 3 of Figurefigure5).

4. Finally, each view re-read the model to reflect the current state accurately (message 4 of Figurefigure5).

The model:

The first step is to build the model of the game. This will be done via the class GameModel and the helper class Point. Our unique instance of the class GameModel will have to store the current state of the game. This includes

126_Game-circle the dot2.png

Figure 3: Initial location of the blue dot: on an even board (left), the position is randomly selected among the four central dots. On an odd board (right), it is randomly selected among the nine central locations.

• The definition of three possible status of a dot. Each dot has one of the following status
-AVAILABLE : this dot is not the blue dot, and it hasn't been selected,
-SELECTED : this dot is not the blue dot, but it has been selected,
-DOT : this dot is the blue dot.
• The current location of the blue dot
• The current status of every dot on the board
• The number of steps taken by the player so far
• The size of the board.

It also provides the necessary setters and getters, so the the controller and the view can check the status of any dot, and the controller can change the status of a dot or move the blue dot. Finally, it provides a way to initialize the game, placing the blue dot randomly as explained earlier, and preselecting some of the other dots with a set probability. In our case, we are going to use 10% as the probability that a dot that isn't the blue dot is initially selected.

A detailed description of the classes can be found here:
• GameModel Documentation
• GameModel.java
• Point Documentation
• Point.java

The view

We then need to build the UI of the game. This will be done with two main classes. The first class is GameView, which extends JFrame. It is the main window of the application. Mostly, it shows two buttons at the bottom, to reset and to quit the game, and it includes an instance of the second class, BoardView.

The class BoardView, which extendsJPanel, contains the board. The board is made of a series of dots, n lines and n columns of them (where n is the size of the board). To implement the dots, we will use the class DotButton which extends the

716_Game-circle the dot3.png

Figure 4: The blue dot moves one dot at a time, in one of the six dots that surrounds it.

1549_Collaboration between the Model.png

Figure 5: The collaboration between the Model, the View and the Controller.

classJButton. DotButton is based onPuzzler by Apple. You can review the code of the program "Puzzler" seen in lab 4 to help you with the class DotButton.

The main difficulty of the UI is the presentation of the board. If the board was a normal square, as shown in Figurefigure7, it you be really easy to layout the DotButton instances on the Panel. For example, aGridLayoutof size (n, n) would have worked. But the actual board of the game is not a perfect square. Instead, each line is shifted left or right when compared to the previous line (see Figurefigure7). There is no immediate way of creating such a Layout easily.

We are going to use the following two steps approach: we will put each row of DotButton instances on its own instance of a JPanel class, on which aFlowLayoutmanager will be used. If you look at the documentation ofJPanel, you will see that it is possible to add a border to the panel. Since the icons used by the DotButton instances are squares of size 40 pixels, the ideas is to add a border of size 20 at the correct location to obtain the desired result. The set of JPanels can then be added on the BoardView JPanel using for example an appropriate GridLayout manager.

Note that although instances of both GameView and BoardView classes have buttons, these instances are not the listeners for the events generated by these buttons. This is handled by the controller.

A detailed description of the classes can be found here:
• GameView Documentation
• GameView.java
• BoardView Documentation
• BoardView.java
• DotButton Documentation
• DotButton.java

124_Collaboration between the Model1.png

Figure 6: A perfectly square board.

• A zip file containing the icons. Taken fromPuzzler by Apple.

The Controller

Finally, we have to implement the controller, via the class GameController. The constructor of the class receives as parameter the size of the board. The instance of the model and the view are created in this constructor.

The instance of the class GameController is the one managing the events generated by the interaction of the player with the game. It should thus provide the corresponding methods, and implement the logic of the game. During the game, after the player selects a new dot, the controller must decide what to do next. There are three cases to cover: the player won the game, the player lost the game, or else the blue dot must move to one of its neighboring dots to attempt to avoid encirclement.

In the first two cases, the controller must inform the player of the result, and in case of victory, must also provide the number of steps it took the player to win the game (Figurefigure8). In order to achieve this, the controller can use the class method showOptionDialog of the classJOptionPane.

If the game is to continue, the controller must implement a strategy for an efficient selection of the next move for the blue dot. We suggest two strategies: one easy one to get the application going, and an efficient one.

• The easy strategy is to simply move the blue dot randomly to an available neighboring dot. This will allow you to get a first version of the game working. This is not the "real" solution, though, so if this is the only strategy you implement, you will not get full marks.

• The better strategy is to find the shortest path possible for the blue dot to exit the board, without going through a blocked dot (an orange dot). This is detailed below.

Breadth-First Search

To find the shortest path, we are going to implement a breadth-first search for a path from the current location of the blue dot to the border of the board. As we will soon see in class, such a breadth-first search is guarantied to find the shortest paths first. As we will also see, using a Queue is a one of the easy ways to do a breadth-first search.

To implement our queue, we will use an instance of the classLinkedList. To add an object to our queue, we will use the method addLast, and to remove an object from the queue, we will use the method removeFirst.

Here is a sketch of a breadth-first search algorithm using a queue. It starts from the position start and looks for the shortest path to one of the positions in the list targets. It has a list of position called blocked which are positions that cannot be used along the path. The list blocked contains initially the positions that must be avoided. During the search, we also use "blocked" to avoid building paths that cross each-other. In the pseudo-code below, we say that a position is "neighboring" another one if we can go from the first position to the second in a single move.

863_Collaboration between the Model2.png

Figure 7: The actual disposition of the board.

Breadth-First-Search(start, targets, blocked) create a empty queue. add the path ‘‘{start}'' to the end of the queue.

While the queue is not empty Do

Remove the path q from the head of the queue. Let c be the last position of that path

For all positions p neighboring c If p is not in blocked Then

If p is in targets then return the path ‘‘q + {p}''

Else

add the path ‘‘q + {p}'' to the end of the queue add p into blocked

End If End If

End For End While

// The queue is empty and we have not returned a path. The targets
// are not reachable from position start. return FAIL
The instance of the class GameController is created by the class CircleTheDot, which contains the main. A runtime parameter can be passed on to the main, to specify the size of the board (at least 4). If a valid size is not passed, a default size of 9 is used.
A detailed description of the classes can be found here:
• GameController Documentation
• GameController.java
• CircleTheDot Documentation
• CircleTheDot.java

916_Collaboration between the Model3.png

Figure 8: Winning and losing the game.

Bonus

The pseudo code for the breadth-first search is deterministic. A smart player will always be able to anticipate the next move of the blue dot. Try to modify your game so that the blue dot next move is chosen randomly between all the possible shortest path (that is, the choice is still always the shortest path, but if there are more than one choice, and the one that is taken is chosen randomly).

Rules and regulation

Follow all the directives available on theassignment directives web page, and submit your assignment through the on-line submission systemBlackboard Learn.

You must preferably do the assignment in teams of two, but you can also do the assignment individually. Pay attention to the directives and answer all the following questions.

You must use the provided template classes.

Reference no: EM13987943

Questions Cloud

Choosing between two bonds in which to invest their cash : Leigh Delight Candy, Inc. is choosing between two bonds in which to invest their cash. One is being offered from Hershey's and will mature in 10 years and pay. $30 each quarter. The other alternative is a Mars' bond that will mature in 20 years and p..
Role of gestalt principles in perceptual organization : In 200 to 300 words, describe the role of Gestalt principles in perceptual organization. Explain how these principles help us organize our world
Calculate usher sports shops cash flow from operations : In 2015, Usher Sports Shop had cash flows from investing activities of –$4,534,000 and cash flows from financing activities of –$5,965,000. The balance in the firm’s cash account was $1,632,000 at the beginning of 2015 and $1,776,000 at the end of th..
Calculate the securitys default risk premium : A particular security’s equilibrium rate of return is 9 percent. For all securities, the inflation risk premium is 3.80 percent and the real risk-free rate is 2.8 percent. The security’s liquidity risk premium is 0.35 percent and maturity risk premiu..
Designing an application utilizing event-driven programming : Designing an application utilizing event-driven programming - the Model-View-Controller design pattern - You can review the code of the program "Puzzler" seen in lab 4 to help you with the class DotButton.
What is the value of the lump sum : What is the lump sum deposited today at 8% compounded qrtly for 10 years, will yeild the same amount if $4000 deposit with 6% interest end of 6 months compound simi annual, 10 years. What is the value of the lump sum?
Finding the changing interest rates over time : Give two alternatives. Be sure you explain how the alternatives work so that even a government regulator could understand it. As part of your answer be sure to discuss the two risks that bond holders are exposed to because of changing interest rat..
What is the one-year treasury security rate : Suppose we observe the three-year Treasury security rate (1R3) to be 5.3 percent, the expected one-year rate next year—E(2r1)—to be 5.8 percent, and the expected one-year rate the following year—E(3r1)—to be 6.2 percent. If the unbiased expectations ..
Total of ten consecutive cash flows : Suppose you deposit $529 five years from today and each year thereafter deposit $529 for a total of ten consecutive cash flows (CF's); i.e. ten consecutive annual CF's beginning five years (t = 5) from today. Calculate the present value today (t = 0)..

Reviews

Write a Review

JAVA Programming Questions & Answers

  Write a client code that creates two objects

Write a Java program that (1) Defines a base/super class A, a subclass B (inherits from A), and a subclass C (inherits from B).

  Add event handling to the button find out the value the

make a windows program in java that has a labeled text field for the price of a meal. there are different discounts for

  Once getting into student information menu

Once getting into student information menu, you should be able to see a full list of students' information (first name, last name, SSN, DOB, year and major).

  Write a on the popularity of java

Write a 4-5-page research-oriented paper in APA format that focuses on the "Popularity of Java". The paper must cite at least 5 references, not including the textbook or the Bible.

  Program that allows the user to enter an unknown number

Writer a program that allows the user to enter an unknown number of characters, stores those characters in a data structure (a vector) and then prints the values to the screen.

  Program buttons that implements a window with three button

Proper coding conventions required the first letter of the class start with a capital letter and the first letter of each additional word start with a capital letter

  Implement a class called reversewords

Implement a class called ReverseWords that uses a stack to output a set of elements input by the user in reverse order.

  Demonstrates conditions under which the compareto() method

Write an application that demonstrates conditions under which the compareTo() method retrun a positive number, a negative number, and a zero when used to compare two Strings, Save the file as CompareStringValues.java. Lab Assignment

  Program translates a number into the closest letter grade

Write a Java program that translates a number into the closest letter grade. For example, the number 2.8 (which might have been the average of several grades) would be converted to B-

  Algorithm into a java program

Based on the feedback received for Question 3 in Assignment 1, transform your algorithm into a JAVA program. Your code should contain appropriate validations and must focus on code optimization.

  Write and run a java program

Write and run a Java program which allows the user to input two doubles and outputs the greater of the two?

  Reverse the array, and find the largest element

find the max block of an array by splitting it into three parts: left, middle, right. And then reverse the array, and find the largest element.

Free Assignment Quote

Assured A++ Grade

Get guaranteed satisfaction & time on delivery in every assignment order you paid with us! We ensure premium quality solution document along with free turntin report!

All rights reserved! Copyrights ©2019-2020 ExpertsMind IT Educational Pvt Ltd