Stone Game

<< Slider Puzzle | FinalProjectsTrailIndex | TileGridApplet >>

Stone.gif

Stone.java

import java.awt.Color;

import info.gridworld.actor.Actor;


public class Stone extends Actor {

	public Stone() {
		setColor(Color.WHITE);
	}
	public Stone(Color c) {
		setColor(c);
	}

}

StoneGame.java

Here I put the burden of counting stones in the Game class rather than the the Stone class. While this will spot the maximum number in a row, it does not check for the end of the game nor who the winner is. Can you find a way to use setMessage to identify the winner, or else to announce that it is a tie game?

import java.awt.Color;
import java.util.ArrayList;

import info.gridworld.actor.Actor;
import info.gridworld.actor.ActorWorld;
import info.gridworld.grid.BoundedGrid;
import info.gridworld.grid.Grid;
import info.gridworld.grid.Location;


public class StoneGame extends ActorWorld {
	private int turn;
	private BoundedGrid gr;
	public StoneGame() {
		gr=new BoundedGrid(4,4);
		this.setGrid(gr);
	    System.setProperty("info.gridworld.gui.selection", "hide");
		System.setProperty("info.gridworld.gui.frametitle", "Stone Game");
		System.setProperty("info.gridworld.gui.tooltips", "hide");

	    turn =0;
	    setMessage("Try to get 4 in a row\n Yellow's Move");

	}
	public boolean locationClicked(Location loc){
		if (gr.get(loc)==null){
			Color c=Color.YELLOW;
			setMessage("Try to get 4 in a row\n Green's Move");
			turn++;
			if (turn%2==0) {
				c=Color.GREEN;
				setMessage("Try to get 4 in a row\n Yellow's Move");
			}
			Stone s = new Stone(c);
			s.putSelfInGrid(gr, loc);
			setMessage(getMessage()+" Max in a row: "+getLargestInARow());
		}
		return true;
	}
	public static void main(String[] args)
	{
        StoneGame game=new StoneGame();
        game.show();
	}
	public int numberInARow(Actor a, int dir){
		int result = 1;
		ArrayList<Location> locs=new ArrayList<Location>();
		Location next=a.getLocation();
		//Follow the direction until the edge of the grid
		//Or no actor there
		while (gr.isValid(next)&& gr.get(next)!=null){
			locs.add(next);
			next=next.getAdjacentLocation(dir);
		}

		//Find the colors until nothing there
		Color firstColor=a.getColor();
		Color nextColor=firstColor;
		int i=1;
		while (i<locs.size()&& firstColor.equals(nextColor)){
			Actor s=(Actor) gr.get(locs.get(i));
			nextColor = s.getColor();
			if (firstColor.equals(nextColor))
				result++;
			i++;
		}
		return result;
	}
	public int getLargestInARow(){
		int max=0;
		ArrayList<Location> stones=gr.getOccupiedLocations();
		//inspect each stone's max run
		for (int i=0; i<stones.size();i++){
			Actor s=(Actor) gr.get(stones.get(i));
			int stoneMax=0;
			for(int dir=0;dir<180;dir+=45){
				int n=numberInARow(s, dir);
				if (n>stoneMax)
					stoneMax=n;
			}
			if (stoneMax>max)
				max=stoneMax;
		}
		return max;
	}

}