I am trying to write the game 2048 in java, right now I only make one row to understand how it works. Using HashMap and using Collection.shuffle method to get the random Point position. When I run my code, it places the random number in a random spot, but I also got the syntax error, "Exception in thread "main" java.lang.NullPointerException" and it shows the problems are in my Model class my getValue(int row, int column) notificationToView() What is the error referring to? How can I fix it?
import java.util.Random;
import java.awt.Point;
import java.util.Collections;
import java.util.HashMap;
import java.util.ArrayList;
public class Model {
View _view;
private HashMap<Point, Integer> _map;
public Model(){
_map = new HashMap<Point, Integer>();
for(int i = 0; i < 4; i++)
_map.put(new Point(0,i), -1);
}
/**
* Assigns randomly generated int values to the
* variables of the model.
*/
public void notificationToView() {
_map.put(getRandomPoint(), getRandom2OR4());
_view.updateView();
}
public int getRandom2OR4(){
Random r = new Random();
if(r.nextInt() % 5 == 0 )
return 4;
else
return 2;
}
public Point getRandomPoint(){
ArrayList<Point> unoccupied = new ArrayList<Point>();
for (int i = 0; i < 4; i++)
{
if(_map.get(new Point(0,i)) == -1)
unoccupied.add(new Point(0,i));
}
Collections.shuffle(unoccupied);
Point random = unoccupied.get(0);
return random;
}
public int getValue( int row, int column) {
return _map.get(new Point(row, column));
}
/**
* Method that associates the a view as an observer
* of the model. Being an observer implies receiving
* notifications when the data in the model changes.
*/
public void addObserver(View view) {
_view = view;
}
}
public class View implements Runnable {
private JFrame _frame;
private JPanel _panel;
private Model _model;
private ArrayList<JButton> _list;
public View(Model m){
_model = m;
}
/**
* This method updates the view based on the current
* values stored in the data model.
*/
public void updateView() {
for(int i = 0; i < 4; i++){
if(_model.getValue(0,i) != -1)
_list.get(i).setText("" + _model.getValue(0, i));
else
_list.get(i).setText("");
}
}
@Override
public void run() {
_list = new ArrayList<JButton>();
_frame = new JFrame("Lab7");
_panel = new JPanel();
// create 4 buttons
for(int i = 0; i < 4; i++){
JButton buttons = new JButton();
_list.add(buttons);
_panel.add(_list.get(i));
_list.get(i).setFont(new Font("Georgia", Font.PLAIN,40));
_list.get(i).addKeyListener(new MyKeyEvent(_model));
}