Michaels Checkers Game

<< Don and Nick's Violin Hero | OldProjectsTrailIndex | Justin and Xavier's Tennis Game >>

Checkers.


Fr Chris Notes:

Wow! This works great! I presume you want to have it so if you select a piece you can touch it again to deselect a piece, right? the selectedChecker is actually a copy of the Selected Checker itself, and I dont think it should live in the CheckerGame class. I think that is information that should be in the Checker class. The Applet has the MouseListener, so it can look at which Checker was clicked upon, and if it is selected already, cause it to be deselected, and if it is not selected, mark it as selected.

  class Checker

 ///stuff

  boolean selected=false;

  public boolean isSelected() {
        return selected;
  }
  public void select(){
      selected=true;
  }
  publice void deselect(){
       selected=false;
 }

class CheckerGame
  //stuff
  Checker checker = board.FindChecker(simpleLoc);
  if (checker.isSelected) checker.deselect(); 
  else checker.select();


Of cousrse this is a design change.... I would omit the CHeckerBoardBG and have the Checkerboard call a draw method in the Checker class that would draw it self on a blue or white or black location since the CHecker knows if it is selected, and can there could be a Location method that could return when it shold be a white or a black background... but you may not wish to reorganize the game at this point....

Checker.java

import java.awt.Color;
import java.awt.Graphics;


public class Checker {
	private Location pos; // absolute top-left
	private int team;

	private boolean dead;
	private boolean king; 

	public static final int RED = 0;
	public static final int BLACK = 1;
	public static int size = 40; // radius

	public Checker()
	{
		pos = new Location(0, 0);
		king = false;
		dead = false;
		team = RED;
	}
	public Checker(int x, int y, int initteam)
	{
		pos = new Location(x, y);
		dead = false;
		king = false;
		team = initteam;
	}

	public int getTeam()
	{
		return team;
	}

	public void SetLocation(Location loc)
	{
		pos = loc;
	}

	public Location GetLocation()
	{
		return pos;
	}

	public void SetPosition(int x, int y)
	{
		pos.Set(x, y);
	}

	public int[] GetPosition()
	{
		return pos.Get();
	}

	public int GetX()
	{
		return pos.GetX();
	}

	public int GetY()
	{
		return pos.GetY();
	}

	public void paint(Graphics g)
	{
		if (team == BLACK)
			g.setColor(Color.black);
		else if (team == RED)
			g.setColor(Color.red);
        g.fillOval(GetX()*size, GetY()*size, size, size);
	}

	public Location getLocation()
	{
		return pos;
	}

	public boolean canMoveTo(CheckerBoard board, Location loc)
	{
		if (loc.equals(getLocation())) // we can't move to our own location
			return false;

		if (board.FindChecker(loc) != null) //we can't move to any occupied location
			return false;

		if ((loc.GetX() - getLocation().GetX())%2 == 0)
			return false;

		if (loc.GetY() == getLocation().GetY())
			return false;

		if(team == RED && loc.GetY() < getLocation().GetY() && !king) // normal red checkers only move down
			return false;

		if (team == BLACK && loc.GetY() > getLocation().GetY() && !king ) // normal black cehcekrs only move up
			return false;


		return true;
	}

	private boolean canJumpTo(CheckerBoard board, Location loc)
	{
		Location current = getLocation();
		Location between = new Location((loc.GetX()+current.GetX())/2, (loc.GetY()+current.GetY())/2);

		Checker checker = board.FindChecker(between);
		if (checker != null && checker.getTeam() != getTeam())
		{
			return true;
		}
		return false;
	}

	public int lengthTo(Location loc)
	{
		return Math.abs(getLocation().GetY() - loc.GetY());
	}

	//Generic move
	public boolean tryMove(CheckerBoard board, Location loc)
	{
		if (lengthTo(loc) == 2 && canJumpTo(board, loc))
		{
			Location current = getLocation();
			Location between = new Location((loc.GetX()+current.GetX())/2, (loc.GetY()+current.GetY())/2);

			Checker checker = board.FindChecker(between);
			if (checker != null && checker.getTeam() != getTeam())
			{
				board.checkers.remove(checker);
				SetLocation(loc);
				return true;
			}
		}

		if (canMoveTo(board, loc))
		{
			SetLocation(loc);
			return true;
		}
		return false;
	}
}

CheckerBG.java

import java.awt.Color;
import java.awt.Graphics;

public class CheckerBG {
	private int colorState;
	private Location pos; // absolute top-left
	private int oldColorState;

	private boolean highlighted = false;

	public static int size = Checker.size;

	public static final int GREY = 0;
	public static final int WHITE = 1;

	public CheckerBG(int x, int y, int initColor)
	{
		pos = new Location(x, y);
		colorState = initColor;
	}

	public Location getLocation()
	{
		return pos;
	}

	public void SetHighlighted(boolean highlight)
	{
		highlighted = highlight;
	}

	public void SetColor(int color)
	{
		colorState = color;
	}

	public void paint(Graphics g)
	{
		if (highlighted)
			g.setColor(Color.cyan);
		else if (colorState == GREY)
			g.setColor(Color.GRAY);
		else if (colorState == WHITE)
			g.setColor(Color.WHITE);

		g.fillRect(pos.GetX()*size, pos.GetY()*size, Checker.size, Checker.size);
	}
}

CheckerBoard.java

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

public class CheckerBoard {
	ArrayList<Checker> checkers;
	ArrayList<CheckerBG> backgrounds;
	private int[] bounds; // 8x8? 10x10? what?

	private int turn = 1;

	private static int margin = 5;

	public CheckerBoard(int xb, int yb)
	{
		bounds = new int[2];
		bounds[0] = xb;
		bounds[1] = yb;

		int offset = 0;

		checkers = new ArrayList<Checker>();
		backgrounds = new ArrayList<CheckerBG>();
		for(int i = 0; i < bounds[0]; i++)
		{
			for(int j = 0; j < bounds[1]; j++)
			{
				if ((i%2)==0)
				{
					offset = j%2;
					if(j <= 2)
					{
						AddChecker(new Checker(i+offset, j, Checker.RED));
					}

					if(j >= (bounds[1]-3))
					{
						AddChecker(new Checker(i+offset, j, Checker.BLACK));
					}
				}
				if( ((i%2 == 1) && (j%2 == 0)) || ((i%2 == 0) && (j%2 == 1)) )
					AddCheckerBG(new CheckerBG(i, j, CheckerBG.WHITE));
				else
					AddCheckerBG(new CheckerBG(i, j, CheckerBG.GREY));
			}
		}
	}

	public int getTurn()
	{
		return turn;
	}

	public void addTurn()
	{
		turn++;
	}

	public void AddChecker(Checker checker)
	{
		checkers.add(checker);
	}

	public void AddCheckerBG(CheckerBG bg)
	{
		backgrounds.add(bg);
	}

	public void ResetHighlights()
	{
		for (int i = 0; i < backgrounds.size(); i++)
		{
			backgrounds.get(i).SetHighlighted( false );
		}
	}

	public void paint(Graphics g)
	{
		for ( CheckerBG bg : backgrounds )
		{
			bg.paint(g);
		}
		for ( Checker c : checkers )
		{
			c.paint(g);
		}
	}
	public Checker FindChecker(Location loc) //takes simple (not screen) coordinates
	{
		for(int i = 0; i<checkers.size();i++)
		{
			if (checkers.get(i).getLocation().equals(loc))
			{
				return checkers.get(i);
			}
		}

		return null;
	}

	public CheckerBG FindBG(Location loc) //takes simple (not screen) coordinates
	{
		for(int i = 0; i<backgrounds.size();i++)
		{
			if (backgrounds.get(i).getLocation().equals(loc))
			{
				return backgrounds.get(i);
			}
		}

		return null;
	}
	public Location ScreenPosToLocation(int x, int y)
	{
		int squareSize = Checker.size;

		return new Location(x/squareSize, y/squareSize);
	}

	public int GetWinner()
	{
		boolean red = false, black = false;
		for(int i = 0; i < checkers.size(); i++)
		{
			Checker checker = checkers.get(i);
			int team = checker.getTeam();

			if (team == Checker.RED)
				red = true;
			else if (team == Checker.BLACK)
				black = true;

			if (red && black)
				return -1;
		}
		if (red && !black)
			return Checker.RED;
		else if (!red && black)
			return Checker.BLACK;

		return -1;
	}
}

CheckerGame.java

/**
 *  CheckerGame.
 * 
 * @author Michael Vu - Class of 09
 * @version May 19, 2009
 * 
 * - Total modification of the TicTacToeGame
 * - Missing some features of American Checkers
 */
import javax.*;
import java.awt.event.*; 
import java.applet.Applet;
import java.awt.*;

public class CheckerGame extends Applet
    implements MouseListener
{  
        CheckerBoard board;
        int appletWidth;
        int appletHeight;
        int x1, x2, y1, y2, cell;
        boolean gameOver;
        Image virtualMem;
        Graphics gBuffer;

        Checker selectedChecker = null;

    /**
     * MOUSE LISTENER IS AN INTERFACE so it requires
     * all these methods, even if you do nothing:
     */

    public void mouseEntered(MouseEvent e) {}
    public void mouseExited(MouseEvent e) {}
    public void mousePressed(MouseEvent e) {}
    public void mouseReleased(MouseEvent e) {}
    public void mouseClicked(MouseEvent e) 
    {
    	board.ResetHighlights();

    	int x = e.getX();
    	int y = e.getY();

    	Location simpleLoc = board.ScreenPosToLocation(x, y);

    	int team = board.getTurn()%2;
    	if (selectedChecker != null)
    	{
    		if (selectedChecker.tryMove(board, simpleLoc));
    		{
    			board.addTurn();
    		}
    		selectChecker(null);
    	}
    	else
    	{
        	Checker checker = board.FindChecker(simpleLoc);
        	if (checker != null)
        	{
        		if (team != checker.getTeam())
        			return;

            	CheckerBG bg = board.FindBG(simpleLoc);
            	if (bg != null)
            		bg.SetHighlighted(true);

            	selectChecker(checker);
        	}
        	else
        	{
        		selectChecker(null);
        	}
    	}



        repaint();

    }
    /**
     * Init
     */
    public void init()
    {
        board=new CheckerBoard(8, 8); //8x8
        gameOver=false;

        appletWidth = getWidth();
        appletHeight = getHeight(); 
        x1=appletWidth/3;
        x2=x1+appletWidth/3;
        y1=appletHeight/3;
        y2=y1+appletHeight/3;
        cell=x1/2;
        virtualMem = createImage(appletWidth,appletHeight);
        gBuffer = virtualMem.getGraphics();
        gBuffer.setColor(Color.white);
        gBuffer.fillRect(0,0,appletWidth,appletHeight);
        addMouseListener(this); 

    }

    public void selectChecker(Checker selected)
    {
    	selectedChecker = selected;
    }

    private String gameStatus()
    {
        String m;
        if (board.getTurn()%2 == 1) m="Black's Turn"; else m="Red's Turn";

        int winner = board.GetWinner();
        if (winner == Checker.RED)
        {
        	gameOver=true;
        	m="Red Wins";
        }
        else if (winner == Checker.BLACK)
        {
        	gameOver = true;
        	m="Black Wins";
        }
        return m;
    }

    public int getTurn(CheckerBoard board)
    {
    	return board.getTurn();
    }
    public void paint(Graphics g)
    {
        gBuffer.setColor(Color.white);
        gBuffer.fillRect(0,0,appletWidth,appletHeight);
        gBuffer.setColor(Color.black);
        gBuffer.drawString(gameStatus(), 20,appletHeight-20);

        board.paint(gBuffer);

        g.drawImage(virtualMem,0,0,this);
    }
    public void update(Graphics g)
	{
		paint(g); //get rid of flicker with this method
	}
}

Location.java

public class Location {
	private int[] pos;

	public Location(int x, int y)
	{
		pos = new int[2];
		pos[0] = x;
		pos[1] = y;
	}

	public boolean equals(Location loc)
	{
		if( (GetX() == loc.GetX()) && (GetY() == loc.GetY()) )
		{
			return true;
		}
		return false;

	}
	public void Set(int[] loc)
	{
		pos = loc;
	}

	public void Set(int x, int y)
	{
		pos[0] = x;
		pos[1] = y;
	}

	public int[] Get()
	{
		return pos;
	}
	public int GetX()
	{
		return pos[0];
	}
	public int GetY()
	{
		return pos[1];
	}
}