Java Craps Applet GUI Trouble - java

I'm having a difficult time understanding where and when to repaint() in my Craps game. I understand that after every instance of an event, like when Start Game or Roll Dice is selected, I need to put repaint(). However when I change the string output from "" to "You've Won!!" in each case and then reprint, the app does not recognize it. I have scanned the site for possible remedies, but cannot find anything like what I'm trying to do, as I'm using .gif's for the dice images and am writing an applet, thus I cannot just sysout in a main method. Any and all criticism is of course welcome, I can handle the heat..
What I have so far:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.*;
import java.util.Random;
public class Craps extends JApplet implements ActionListener {
Random gen = new Random();
// constant variables for game status
final int WON = 0, loss = 1, CONTINUE = 2;
// other variables used
boolean firstRoll = true; // true if first roll of dice
int diceSum = 1; // sum of the dice
int aPoint = 1; // point if no win/loss on first roll
int stillGame = CONTINUE; // game not over yet
int dice1 = gen.nextInt(6) + 1;
int dice2 = gen.nextInt(6) + 1;
int diceSec, dice2Sec;
int Horizon = gen.nextInt(260) + 25;
int secHorizon = gen.nextInt(260) + 25;
int Vertical = gen.nextInt(150) + 40;
int SecVerto = gen.nextInt(150) + 40;
Image[] dice = new Image[6];
int Low = 35, High = 335;
int Up = 50, Down = 250;
int wins = 0;
String s1 = "";
// GUI
JButton rollButton, startButton;
public void init() {
Button rollButton = new Button("Roll Dice");
Button startButton = new Button("Start Game");
setSize(400, 400);
setLayout(null);
for (int i = 0; i < 6; i++) {
dice[i] = getImage(getCodeBase(), "dice" + (i + 1) + ".gif");
}
// create button to start the game
startButton.setBounds(40, 300, 100, 20);
add(startButton);
startButton.addActionListener(this);
startButton.setEnabled(true);
// create button to roll dice
rollButton.setBounds(230, 300, 100, 20);
add(rollButton);
rollButton.addActionListener(this);
rollButton.setEnabled(true);
} // end of init
public void paint(Graphics g) {
super.paint(g);
// draw craps table
g.setColor(Color.red);
g.fillRect(1, 1, 400, 400);
// draw playing field
g.setColor(Color.green);
g.fillRoundRect(25, 40, 310, 210, 75, 75);
// paint the images of the dice
g.drawImage(dice[dice1 - 1], Horizon, Vertical, 32, 32, this);
g.drawImage(dice[dice2 - 1], secHorizon, SecVerto, 32, 32, this);
g.setColor(Color.black);
g.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 22));
g.drawString(s1, 33, 280);
}
public void actionPerformed(ActionEvent e) {
// first roll of dice
Horizon = gen.nextInt(260) + 25;
secHorizon = gen.nextInt(260) + 25;
Vertical = gen.nextInt(150) + 40;
SecVerto = gen.nextInt(150) + 40;
if (e.getSource() == rollButton) {
// while (stillGame == CONTINUE) {
if (firstRoll) {
diceSum = diceRoller(); // roll dice
// repaint();
switch (diceSum) {
// user victory on first roll
case 7:
case 11:
stillGame = WON;
s1 = "You Win";
wins++;
break;
// user loss on first roll
case 2:
case 3:
case 12:
stillGame = loss;
s1 = "You Lose";
break;
default:
stillGame = CONTINUE;
aPoint = diceSum;
firstRoll = false;
s1 = "The Point is " + aPoint + "";
break;
} // end switch
// end if (firstRoll) statement
repaint();
}
else {
diceSum = diceRoller(); // roll dice
// determine game status
if (diceSum == aPoint) // win by making point
s1 = "You Win!!";
else if (diceSum == 7) // lose by rolling seven
s1 = "Suck It";
}
// end while loop
} // end if structure body
// subsequent roll of dice
else {
diceSum = diceRoller(); // roll dice
// determine game status
if (diceSum == aPoint) { // win by making point
s1 = "You Win!!";
stillGame = WON;
} else if (diceSum == 7) { // lose by rolling seven
s1 = "You've Lost";
stillGame = loss;
}
}// end else structure
if (e.getSource() == startButton) {
s1 = "";
}
repaint();
}
// roll dice, calculate sum and display results
public int diceRoller() {
int sum;
dice1 = gen.nextInt(6) + 1; // pick random dice values
dice2 = gen.nextInt(6) + 1;
sum = dice1 + dice2; // sum die values
return sum; // return the sum of dice
} // end method rollDice
} // end

Seems your problem in next: in init() method you declare local variables:
Button rollButton = new Button("Roll Dice");
Button startButton = new Button("Start Game");
and add ActionListener to them, but in your actionPerformed(ActionEvent e) method you compare source with null :
e.getSource() == rollButton
e.getSource() == startButton
here : rollButton == null and startButton == null, because of that, your if statement never execute, only else statement.
Declare your buttons in init() method like next:
rollButton = new JButton("Roll Dice");
startButton = new JButton("Start Game");
I think it helps you.
Also read about variables in java.

Related

How to prevent my KeyEvent from repainting both objects?

I am working on a simple game which requires 1 player (the square) and some enemies that spawn randomly inside the play-area. I am running into an issue currently, because when I run my program, pressing any arrow key will repaint not only the player's new location, but it will also re-spawn all the enemies into the new locations.
I have gone through my code a few times and I am still stumped as to why this is happening. Any help would be greatly appreciated.
P.S. I am not a very experienced programmer, so some of this code may not be as efficient as possible and some things may be incorrect; feel free to point out any errors besides the issue at hand. Thanks!
Main Class
public class Eat {
public static void main(String[] args) {
// Creating the main frame
JFrame main = new JFrame("Eat 'Em All - Version 1.0.2");
main.setSize(497, 599);
main.setLocationRelativeTo(null);
main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
main.setResizable(false);
// Colours and borders
Border areaBorder = new LineBorder(Color.LIGHT_GRAY, 3);
// Creating main JPanel
JPanel area = new JPanel();
area.setLayout(new BoxLayout(area, BoxLayout.PAGE_AXIS));
area.setBackground(Color.WHITE);
main.setContentPane(area);
// Creating the drawing/image/player
DrawPlayer player = new DrawPlayer();
player.setPreferredSize(new Dimension(497, 539));
player.setOpaque(false);
// Enemies
DrawEnemy enemy = new DrawEnemy();
enemy.setPreferredSize(new Dimension(497, 539));
enemy.setBackground(Color.WHITE);
// Creating the control panel for buttons, etc
JPanel control = new JPanel();
control.setPreferredSize(new Dimension(497, 60));
control.setLayout(new GridLayout(1, 2, 0, 0));
control.setBorder(areaBorder);
JLabel welcome = new JLabel(" Welcome to Eat 'Em All |--| Press 'Start'");
JButton start = new JButton("Start");
// Adding it all to the frame
main.add(enemy);
enemy.add(player);
control.add(welcome);
control.add(start);
area.add(control);
// Adding keylistener and making button false
player.addKeyListener(player);
player.setFocusable(true);
start.setFocusable(false);
enemy.setFocusable(false);
// Bring frame to front and visible
main.toFront();
main.setVisible(true);
System.out.println(player.getWidth() / 2);
System.out.println(player.getHeight() / 2);
}
}
Drawing Player Class
public class DrawPlayer extends JPanel implements KeyListener {
long xPosition = 0;
long yPosition = 0;
public void paintComponent(Graphics g) {
super.paintComponent(g);
// Making loop to get points and move it
// Center of area is x: 245 y: 255
int xPoints[] = {235, 255, 255, 235, 235, 255};
int yPoints[] = {265, 265, 245, 245, 265, 245};
for (int i = 0; i < xPoints.length; i++) {
xPoints[i] += xPosition;
yPoints[i] += yPosition;
}
g.setColor(Color.BLUE);
g.drawPolygon(xPoints, yPoints, xPoints.length);
}
public void keyPressed(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_DOWN:
if (yPosition == 245) {
yPosition -= 5;
} else {
yPosition += 5;
}
break;
case KeyEvent.VK_UP:
if (yPosition == -245) {
yPosition += 5;
} else {
yPosition -= 5;
}
break;
case KeyEvent.VK_LEFT:
if (xPosition == -235) {
xPosition += 5;
} else {
xPosition -= 5;
}
break;
case KeyEvent.VK_RIGHT:
if (xPosition == 235) {
xPosition -= 5;
} else {
xPosition += 5;
}
break;
}
repaint();
}
public void keyReleased(KeyEvent e) {
}
public void keyTyped(KeyEvent e) {
}
}
Drawing Enemies Class
public class DrawEnemy extends JPanel {
public void paintComponent(Graphics f) {
super.paintComponent(f);
for (int i = 0; i < 10; i++ ){
f.setColor(Color.RED);
f.drawOval((int)(Math.random() * ((440 - 0) + 0) + 0), (int)(Math.random() * ((500 - 0) + 0) + 0), 50, 50);
}
}
}
Your have a problem here:
public void paintComponent(Graphics f) {
super.paintComponent(f);
for (int i = 0; i < 10; i++ ){
f.setColor(Color.RED);
f.drawOval((int)(Math.random() * ((440 - 0) + 0) + 0), (int)(Math.random() * ((500 - 0) + 0) + 0), 50, 50);
}
}
You've got program logic inside of a painting method, something you should never do, since you never have full control over when or even if a painting method will be called. The solution, get the randomization out of the paintComponent method and into its own separate method, one that you call if and only if you want to randomize the enemies, and not every time you repaint.
Other issues:
Separate your program logic from your GUI.
For instance you should have a non-GUI Enemy class, one that has fields for its own position, its size, its movement, perhaps a move() method, perhaps a collision(Player p) method.
You should have only one JPanel that does drawing and this should be its only job.
Again, you don't tie movement of anything to the painting method.
You would want a game loop of some sort, perhaps a Swing Timer. This will generate regularly spaced ticks that will prod Enemies and Players to move.
Get rid of KeyListener code and favor Key Bindings. The latter is much less kludgy when it comes to component focus. Do check the tutorial for this.

Rock, paper, scissors game Java applet

I'm having problems with my java applet. I've made a Rock paper scissors game and i have 2 problems which I can't solve:
1. how to load the applet without the rock image on the left (players choice)
2. the score for player and computer does not reduce by 1 for every lost game
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class RockScissorsPaper extends Applet implements ActionListener
{
private Button rockButton;
private Button scissorsButton;
private Button paperButton;
private String buttonPressed = "";
private int computerValue = -1;
private int myValue;
private int playerScore = 10;
private int computerScore = 10;
private int drawScore = 0;
private Image imgRock;
private Image imgScissors;
private Image imgPaper;
public void init()
{
rockButton = new Button("Rock");
scissorsButton = new Button("Scissors");
paperButton = new Button("Paper");
add(rockButton);
add(scissorsButton);
add(paperButton);
rockButton.addActionListener(this);
scissorsButton.addActionListener(this);
paperButton.addActionListener(this);
imgRock = getImage(getCodeBase(), "rock.jpg");
imgScissors = getImage(getCodeBase(), "scissors.jpg");
imgPaper = getImage(getCodeBase(), "paper.jpg");
}
public void actionPerformed(ActionEvent event)
{
buttonPressed = ((Button)event.getSource()).getLabel();
computerValue = randomNumber012();
translator(buttonPressed);
repaint();
}
public void paint(Graphics g)
{
super.paint(g);
rockButton.setLocation(20,260);
rockButton.setSize(70,35);
paperButton.setLocation(210, 260);
paperButton.setSize(70, 35);
scissorsButton.setLocation(380, 260);
scissorsButton.setSize(90, 35);
choice(g);
g.drawString("Player's Wins: " + playerScore, 10, 20);
g.drawString("Computer's Wins: " + computerScore, 180, 20);
g.drawString("Draws: " + drawScore, 400, 20);
g.drawString("Your Choice: " + buttonPressed, 20, 60);
g.drawString("Computer's Pick: ", 350, 60);
winner(g, computerValue, myValue);
}
int randomNumber012()
{
return (int)(Math.random()*3);
}
public void translator(String s)
{
if(s.equals("Rock"))
{
myValue = 0;
}
else if(s.equals("Scissors"))
{
myValue = 1;
}
else if(s.equals("Paper"))
{
myValue = 2;
}
}
public void choice(Graphics g)
{
if(myValue == 0)
{
g.drawImage(imgRock, 20, 100, 100, 60, this);
}
else if(myValue == 1)
{
g.drawImage(imgScissors, 20, 100, 100, 60, this);
}
else if(myValue == 2)
{
g.drawImage(imgPaper, 20, 100, 100, 60, this);
}
if(computerValue == 0)
{
g.drawString("Computer's Pick: Rock", 350, 60);
g.drawImage(imgRock, 350, 100, 100, 60, this);
}
else if(computerValue == 1)
{
g.drawString("Computer's Pick: Scissors", 350, 60);
g.drawImage(imgScissors, 350, 100, 100, 60, this);
}
else if(computerValue == 2)
{
g.drawString("Computer's Pick: Paper", 350, 60);
g.drawImage(imgPaper, 350, 100, 100, 60, this);
}
}
public void winner(Graphics g, int cv, int mv)
{
if(cv == -1)
{
g.drawString("", 200, 100);
}
else if(cv == mv)
{
g.drawString("Draw", 200, 250);
drawScore = drawScore + 1;
}
else if(cv == 0 && mv == 1 || cv == 2 && mv == 0 || cv == 1 && mv == 2)
{
g.drawString("Computer Wins", 200, 250);
playerScore = playerScore - 1;
}
else
{
g.drawString("You Win!", 200, 250);
computerScore = computerScore - 1;
}
if (playerScore == 0)
{
System.out.println("You lost!");
playerScore = 10;
computerScore = 10;
drawScore = 0;
}
else if(computerScore == 0)
{
System.out.println("You won!");
playerScore = 10;
computerScore = 10;
drawScore = 0;
}
}
}
how to load the applet without the rock image on the left (players choice)
You need to have a fourth case for your myValue variable, when the player has not made a choice yet. Right now you only have three potential values, and the default is 0, which is why you see a rock image before you make a choice.
the score for player and computer does not reduce by 1 for every lost game
You're using ints where you should be using enums and booleans, which is making your code harder to understand. I'd highly recommend refactoring your code to use enums and booleans instead of ints.
Also, you're always calling every method from the paint() method. Don't do that. Instead, only call the functions that check for a winner when the player actually makes a choice, presumably from a button click.
Finally, you're also calling setLocation() inside your paint() method, which is a bad idea. You should only call setLocation() once, or better yet, use a layout manager.

Java Poker Game - Change diamonds and hearts to red

I am working on a poker game in Java.
I would like to know how to make the diamond and heart symbol red instead of white filled, since I cannot find it in the unicode list.
Any help is appreciated.
EDIT: I would like to know how to paint the symbols to red.
This is my code so far:
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class PokerHand extends Frame implements ActionListener {
Button b = new Button("Click for new hand");
boolean dealt[] = new boolean[52];
String[] playercard = new String[10];
String[] playersuit = new String[10];
Random r = new Random();
int drawn;
public static void main(String args[]) {
PokerHand ph = new PokerHand();
ph.doIt();
}
public void doIt() {
int ct;
for (ct = 0; ct <= 9; ++ct) { // first loop that you learned tonight
playercard[ct] = " ";
playersuit[ct] = " ";
} // ends for loop
b.addActionListener(this);
this.setLayout(new FlowLayout());
this.add(b);
this.setSize(500, 500);
this.setVisible(true);
}// ends doIt method
public void paint(Graphics g) {
g.setFont(new Font(null, 1, 30));
g.drawString("Me", 400, 100);
g.drawString(playercard[0], 30, 100);
g.drawString(playersuit[0], 60, 100);
g.drawString(playercard[1], 90, 100);
g.drawString(playersuit[1], 120, 100);
g.drawString(playercard[2], 150, 100);
g.drawString(playersuit[2], 180, 100);
g.drawString(playercard[3], 210, 100);
g.drawString(playersuit[3], 240, 100);
g.drawString(playercard[4], 270, 100);
g.drawString(playersuit[4], 300, 100);
g.drawString("You", 400, 200);
g.drawString(playercard[5], 30, 200);
g.drawString(playersuit[5], 60, 200);
g.drawString(playercard[6], 90, 200);
g.drawString(playersuit[6], 120, 200);
g.drawString(playercard[7], 150, 200);
g.drawString(playersuit[7], 180, 200);
g.drawString(playercard[8], 210, 200);
g.drawString(playersuit[8], 240, 200);
g.drawString(playercard[9], 270, 200);
g.drawString(playersuit[9], 300, 200);
}
public void actionPerformed(ActionEvent ae) {
int ct;
ct = 0;
int card;
int suit;
// we draw 10 cards here
while (ct < 10) { // a while loop in practice
drawn = r.nextInt(52);
if (dealt[drawn] != true) { // if in practice
card = drawn % 13 + 1;
suit = drawn / 13;
dealt[drawn] = true;
playercard[ct] = String.valueOf(card);
if (card == 1) {
playercard[ct] = "A";
}
if (card == 11) {
playercard[ct] = "J";
}
if (card == 12) {
playercard[ct] = "Q";
}
if (card == 13) {
playercard[ct] = "K";
}
if (suit == 0) {
playersuit[ct] = "\u2660";
}
if (suit == 1) {
playersuit[ct] = "\u2661"; //change to red heart
}
if (suit == 2) {
playersuit[ct] = "\u2662"; //change to red diamond
}
if (suit == 3) {
playersuit[ct] = "\u2663";
}
ct = ct + 1;
} // ends if
}// ends while
repaint();
for (int x = 0; x <= 51; ++x)
dealt[x] = false;
}// ends method
}// ends the class
If your Unicode font has the hearts, clubs, diamonds and spades symbols, then all you need to do to draw them in the color of your choice is the same as drawing any other character in the color of your choice: simply use setColor.
Now you should start from the "filled" version of spades, hearts, diamonds and clubs, they are:
- spade: \u2660
- heart: \u2665 (use 2665 instead of 2661)
- diamonds: \u2666 (use 2666 instead of 2662)
- clubs: \u2663b
Then you simply do:
g.setColor(Color.RED);
g.drawString("\u2665");
And then you change the color, say, back to black to draw text and back to red/black for suits (or red, black, blue and green if you want to use a "four-color deck").
This is (FINALLY) working for me! Ultimately the unicode doesn't change for the suits themselves, it's the \uFE0F that makes it "pop" and give it the color.
public enum Suit {
SPADES("\u2660\uFE0F"), HEARTS("\u2665\uFE0F"), DIAMONDS("\u2666\uFE0F"), CLUBS("\u2663\uFE0F");
private final String icon;
Suit(String icon) {
this.icon = icon;
}
public String getIcon() {
return icon;
}
}

Hangman Graphics

I'm having trouble getting the graphics to show up with my hangman program.
This is the code for my engine class:
public static void main(String[] args)
{
//hangman viewer stuff
//////////////////////////////////////////////////////////////
JFrame frame = new JFrame();
frame.setSize(200,375); //invoked the method setSize on the implicit parameter frame
frame.setTitle("Hangman");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
HangmanComponent g = new HangmanComponent();
frame.add(g);
frame.setVisible(true);
///////////////////////////////////////////////////////////////
String wordd = JOptionPane.showInputDialog("Type in a word.");
int length = wordd.length();
String blank = "_ ";
String word2 = new String("");
int guesscount = 10;
ArrayList<String>answers=new ArrayList<String>(); //creates reference to empty structure that will contain references
char blanks[]=new char[wordd.length()]; //creates an array with the same number of terms as the length of the word
for (int i=0; i<length; i++)//fills the array with blanks corresponding to the length of the word
{
blanks[i] = '_';
}
HangmanComponent y = new HangmanComponent();
while (true)
{
String letter = JOptionPane.showInputDialog("Guess a letter! You have "+guesscount+" guesses."+"\n"+answers+"\n"+Arrays.toString(blanks).replace(",", " ").replace("[","").replace("]","")); //Prints a space
char letterchar = letter.charAt(0); //converts string letter to char letterchar
int idx = 0;
boolean found = false;
answers.add(letter); //adds the string to the arraylist answers
while (idx >= 0 && idx < length) //idx is greater than or equal to 0 but less than the length of the word
{
//System.out.println("idx = " + idx);
idx = wordd.indexOf(letter, idx); //idx is the index of "letter" in "wordd" and finds all instances of the letter
//System.out.println("idx = " + idx + ", guesscount = " + guesscount);
if (idx != -1) //if idx is not -1 (the letter exists in the word)
{
found = true;
blanks[idx] = letterchar; //sets the term in the array equal to the letter
idx += 1; //idx=idx+1
}
else
{
guesscount=guesscount-1;
y.nextStage();
y.printStage();
frame.add(y);
frame.setVisible(true);
break;
}
}
if (found)
{
JOptionPane.showMessageDialog(null, Arrays.toString(blanks).replace(",", " ").replace("[","").replace("]","")+"\n"+"You found a letter!"+"\n"+answers);
}
else
{
JOptionPane.showMessageDialog(null, Arrays.toString(blanks).replace(",", " ").replace("[","").replace("]","")+"\n"+"That letter is not in the word! Guess again!"+"\n"+answers);
if (guesscount == 0)
{
JOptionPane.showMessageDialog(null, "Sorry, you're all out of guesses. The answer was '"+wordd+".' Thanks for playing!");
break;
}
}
char [] lettersArray = wordd.toCharArray(); //converts word to array of chars
if (Arrays.equals(blanks, lettersArray))//compares array of blanks to array of letters
{
JOptionPane.showMessageDialog(null, "You guessed the word! Thanks for playing!");
break;
}
}
}
and this is the code for my HangmanComponent class (with the graphics)
int stage=0;
public void nextStage()
{
stage++;
}
public void printStage()
{
System.out.println("Your stage number is:"+stage);
}
public void paintComponent(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
g2.setStroke(new BasicStroke(5,BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL));
g2.setColor(Color.BLACK);
g.drawLine(50, 30, 50, 10);
g.drawLine(50, 10, 130, 10);
g.drawLine(130, 10, 130, 300);
g.drawLine(20, 300, 150, 300);
if (stage==1)
{
//draws the head
g2.setStroke(new BasicStroke(3,BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL));
Ellipse2D.Double head = new Ellipse2D.Double(25, 30, 50, 50);
g2.draw(head);
}
else if (stage==2)
{
//draws the body
g.drawLine(50, 80, 50, 180);
}
else if (stage==3)
{
//draws the left arm
g.drawLine(10, 150, 50, 100);
}
else if (stage==4)
{
//draws the right arm
g.drawLine(50, 100, 90, 150);
}
else if (stage==5)
{
//draws the left leg
g.drawLine(30, 250, 50, 180);
}
else if (stage==6)
{
//draws the right leg
g.drawLine(50, 180, 70, 250);
}
else if (stage==7)
{
//draws the left eye
Ellipse2D.Double lefteye = new Ellipse2D.Double(40, 50, 1, 1);
g2.draw(lefteye);
g2.fill(lefteye);
}
else if (stage==8)
{
//draws the right eye
Ellipse2D.Double righteye = new Ellipse2D.Double(58, 50, 1, 1);
g2.draw(righteye);
g2.fill(righteye);
}
else if (stage==9)
{
//draws the mouth
Arc2D.Double mouth = new Arc2D.Double(40.00, 50.00, 20.00, 20.00, 180.00, 190.00, Arc2D.OPEN);
g2.draw(mouth);
}
}
Right now, the hangman program runs perfectly fine, but the graphic is only added the first time the user inputs a wrong letter. How do I get the graphics to be inputted for every time a wrong letter is inputted?

getting my ovals to stack up on each column [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
issue with my main method in my connect4 game
Hi,
on my connect4 game, whenever i click on any square it places the oval on that specific square, how do i get it so that it places the oval on the lowest square in that column so that it can stack up?
package Game;
import java.util.ArrayList;
public class ConnectFourBoard {
// This constant is used to indicate the width and height, in cells,
// of the board. Since we want an 8x8 board, we'll set it to 8.
private static final int WIDTH = 8;
private static final int HEIGHT = 8;
private ConnectFourCell[][] currentPlayer;
// The current state the Othello board is defined with these two
// fields: a two-dimensional array holding the state of each cell,
// and a boolean value indicating whether it's the black player's
// turn (true) or the white player's turn (false).
private ConnectFourCell[][] cells;
private boolean isBlueTurn;
// Since the board is a model and it needs to notify views of changes,
// it will employ the standard "listener" mechanism of tracking a list
// of listeners and firing "events" (by calling methods on those
// listeners) when things change.
private ArrayList<ConnectFourListener> listeners;
public ConnectFourBoard()
{
// Arrays, in Java, are objects, which means that variables of
// array types (like cells, which has type OthelloCell[][]) are
// really references that say where an array lives. By default,
// references point to null. So we'll need to create an actual
// two-dimensional array for "cells" to point to.
cells = new ConnectFourCell[WIDTH][HEIGHT];
listeners = new ArrayList<ConnectFourListener>();
reset();
isBlueTurn = true;
}
public void reset(){
for (int i = 0; i<WIDTH ; i++){
for (int j = 0; j<HEIGHT; j++){
cells[i][j] = ConnectFourCell.NONE;
}
}
isBlueTurn = true;
}
public void addConnectFourListener(ConnectFourListener listener)
{
listeners.add(listener);
}
public void removeConnectFourListener(ConnectFourListener listener)
{
if (listeners.contains(listener))
{
listeners.remove(listener);
}
}
// These are fairly standard "fire event" methods that we've been building
// all quarter, one corresponding to each method in the listener interface.
private void fireBoardChanged()
{
for (ConnectFourListener listener : listeners)
{
listener.boardChanged();
}
}
private void fireGameOver()
{
for (ConnectFourListener listener : listeners)
{
listener.gameOver();
}
}
// isBlackTurn() returns true if it's the black player's turn, and false
// if it's the white player's turn.
public boolean isBlueTurn()
{
return isBlueTurn;
}
public int getWidth()
{
return WIDTH;
}
public int getHeight(){
return HEIGHT;
}
// getBlackScore() calculates the score for the black player.
public int getBlackScore()
{
return getScore(ConnectFourCell.BLUE);
}
// getWhiteScore() calculates the score for the white player.
public int getWhiteScore()
{
return getScore(ConnectFourCell.RED);
}
// getScore() runs through all the cells on the board and counts the
// number of cells that have a particular value (e.g., BLACK or WHITE).
// This method uses the naive approach of counting them each time
// it's called; it might be better to keep track of this score as we
// go, updating it as tiles are added and flipped.
private int getScore(ConnectFourCell cellValue)
{
int score = 0;
for (int i = 0; i < WIDTH; i++)
{
for (int j = 0; j < HEIGHT; j++)
{
if (cells[i][j] == cellValue)
{
score++;
}
}
}
return score;
}
// getWhiteScore() calculates the score for the white player.
public int getRedScore()
{
return getScore(ConnectFourCell.RED);
}
public int getBlueScore() {
// TODO Auto-generated method stub
return getScore(ConnectFourCell.BLUE);
}
public ConnectFourCell getCell(int x, int y)
{
if (!isValidCell(x, y))
{
throw new IllegalArgumentException(
"(" + x + ", " + y + ") is not a valid cell");
}
return cells[x][y];
}
/**
* The drop method.
*
* Drop a checker into the specified HEIGHT,
* and return the WIDTH that the checker lands on.
*/
int drop(int HEIGHT) {
if (hasWon()) {
return -1;
}
for ( ; WIDTH<6 && HEIGHT != 0; WIDTH++) { };
if (WIDTH==6) {
// if the WIDTH is 6, it went through all 6 WIDTHs
// of the cells, and couldn't find an empty one.
// Therefore, return false to indicate that this
// drop operation failed.
return -1;
}
// fill the WIDTH of that HEIGHT with a checker.
cells[HEIGHT][WIDTH] = currentPlayer[HEIGHT][WIDTH];
// alternate the players
//currentPlayer = (currentPlayer%2)+1;
return WIDTH;
}
/**
* The toString method
*
* Returns a String representation of this
* Connect Four (TM) game.
*/
public String toString() {
String returnString = "";
for (int WIDTH=5; WIDTH>=0; WIDTH--) {
for (int HEIGHT=0; HEIGHT<7; HEIGHT++) {
returnString = returnString + cells[HEIGHT][WIDTH];
}
returnString = returnString + "\n";
}
return returnString;
}
/**
* The hasWon method.
*
* This method returns true if one of the
* players has won the game.
*/
public boolean hasWon()
{
// First, we'll establish who the current player and the opponent is.
//ConnectFourCell
ConnectFourCell myColor =
isBlueTurn() ? ConnectFourCell.BLUE : ConnectFourCell.RED;
ConnectFourCell otherColor =
isBlueTurn() ? ConnectFourCell.RED : ConnectFourCell.BLUE;
return true;
}
public void validMove( ){
}
public void makeAMove(int x, int y){
//System.out.println(x+" "+y);
// cells[x][y] = ConnectFourCell.BLUE;
//Check who's turn it is. Set to that color.
ConnectFourCell myColor = null;
if ( isBlueTurn == true){
myColor = myColor.BLUE;
}
else {
myColor = myColor.RED;
}
cells[x][y] = myColor;
//Check if it's a valid move. If there is a piece there. can't
// Look at the column. play piece in the highest available slot
//Check if there are 4 in a row.
for (int WIDTH=0; WIDTH<6; WIDTH++) {
for (int HEIGHT=0; HEIGHT<4; HEIGHT++) {
if (!(cells[HEIGHT][WIDTH] == ConnectFourCell.NONE) &&
cells[HEIGHT][WIDTH] == cells[HEIGHT+1][WIDTH] &&
cells[HEIGHT][WIDTH] == cells[HEIGHT+2][WIDTH] &&
cells[HEIGHT][WIDTH] == cells[HEIGHT+3][WIDTH]) {
}
}
}
// check for a vertical win
for (int WIDTH=0; WIDTH<3; WIDTH++) {
for (int HEIGHT=0; HEIGHT<7; HEIGHT++) {
if (!(cells[HEIGHT][WIDTH] == ConnectFourCell.NONE) &&
cells[HEIGHT][WIDTH] == cells[HEIGHT][WIDTH+1] &&
cells[HEIGHT][WIDTH] == cells[HEIGHT][WIDTH+2] &&
cells[HEIGHT][WIDTH] == cells[HEIGHT][WIDTH+3]) {
}
}
}
// check for a diagonal win (positive slope)
for (int WIDTH=0; WIDTH<3; WIDTH++) {
for (int HEIGHT=0; HEIGHT<4; HEIGHT++) {
if (!(cells[HEIGHT][WIDTH] == ConnectFourCell.NONE) &&
cells[HEIGHT][WIDTH] == cells[HEIGHT+1][WIDTH+1] &&
cells[HEIGHT][WIDTH] == cells[HEIGHT+2][WIDTH+2] &&
cells[HEIGHT][WIDTH] == cells[HEIGHT+3][WIDTH+3]) {
}
}
}
// check for a diagonal win (negative slope)
for (int WIDTH=3; WIDTH<6; WIDTH++) {
for (int HEIGHT=0; HEIGHT<4; HEIGHT++) {
if (!(cells[HEIGHT][WIDTH] == ConnectFourCell.NONE) &&
cells[HEIGHT][WIDTH] == cells[HEIGHT+1][WIDTH-1] &&
cells[HEIGHT][WIDTH] == cells[HEIGHT+2][WIDTH-2] &&
cells[HEIGHT][WIDTH] == cells[HEIGHT+3][WIDTH-3]) {
}
}
}
fireBoardChanged();
isBlueTurn = !isBlueTurn;
}
private boolean isValidCell(int x, int y)
{
return x >= 0 && x < WIDTH
&& x>= 0 && x<HEIGHT
&& y >= 0 && y < WIDTH
&& y>= 0 && y<HEIGHT;
}
}
package UI;
import java.awt.*;
import javax.swing.*;
import UI.ConnectFourBoardPanel;
import Game.ConnectFourBoard;
import Game.ConnectFourListener;
public class ConnectFourFrame extends JFrame implements ConnectFourListener {
// Variables
private ConnectFourBoard board;
private JLabel scoreLabel;
private ConnectFourBoardPanel boardPanel;
private JLabel statusLabel;
public ConnectFourFrame()
{
// The frame builds its own model.
board = new ConnectFourBoard();
// We want the frame to receive notifications from the board as its
// state changes.
System.out.println(this);
board.addConnectFourListener(this);
setTitle("Informatics 45 Spring 2011: ConnectFour Game");
setSize(700, 700);
setResizable(true);
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
getContentPane().setBackground(Color.BLACK);
buildUI();
refreshUI();
}
private void buildUI()
{
GridBagLayout layout = new GridBagLayout();
getContentPane().setLayout(layout);
Font labelFont = new Font("SansSerif", Font.BOLD, 18);
scoreLabel = new JLabel();
scoreLabel.setForeground(Color.WHITE);
scoreLabel.setFont(labelFont);
layout.setConstraints(
scoreLabel,
new GridBagConstraints(
0, 0, 1, 1, 1.0, 0.0,
GridBagConstraints.CENTER,
GridBagConstraints.NONE,
new Insets(10, 10, 10, 10), 0, 0));
getContentPane().add(scoreLabel);
boardPanel = new ConnectFourBoardPanel(board);
layout.setConstraints(
boardPanel,
new GridBagConstraints(
0, 1, 1, 1, 1.0, 1.0,
GridBagConstraints.CENTER,
GridBagConstraints.BOTH,
new Insets(10, 10, 10, 10), 0, 0));
getContentPane().add(boardPanel);
statusLabel = new JLabel();
statusLabel.setForeground(Color.WHITE);
statusLabel.setFont(labelFont);
layout.setConstraints(
statusLabel,
new GridBagConstraints(
0, 2, 1, 1, 1.0, 0.0,
GridBagConstraints.CENTER,
GridBagConstraints.NONE,
new Insets(10, 10, 10, 10), 0, 0));
getContentPane().add(statusLabel);
}
private void refreshUI()
{
// Refreshing the UI means to change the text in each of the
// two labels (the score and the status) and also to ask the
// board to repaint itself.
scoreLabel.setText(
"Blue: " + board.getBlueScore() +
" Red: " + board.getRedScore());
if ( board.isBlueTurn() == false){
statusLabel.setText("Blue's Turn: ");
}
if ( board.isBlueTurn() == true){
statusLabel.setText("Red's Turn: ");
}
boardPanel.repaint();
}
// These are the ConnectFourBoardListener event-handling methods.
public void boardChanged()
{
// When the board changes, we'll refresh the entire UI. (There
// are times when this approach is too inefficient, but it will
// work fine for our relatively simple UI.)
refreshUI();
}
public void gameOver()
{
// When the game is over, we'll pop up a message box showing the final
// score, then, after the user dismisses the message box, dispose of
// this window and end the program.
JOptionPane.showMessageDialog(
this,
"Game over!\nFinal score: " + scoreLabel.getText(),
"Game Over",
JOptionPane.INFORMATION_MESSAGE);
dispose();
}
}
Welcome to StackOverflow. You're question is fine - but pasting your whole program, in general, is a bad idea. You should describe your program, and include the snippet where you calculate how the ovals are filled in.
Having said that, here's a crack at the answer :
- You want to look at the tile thats currently selected, and if the tile underneath it is occupied, fill in that cell. If its not occupied, set the current tile to the underneath tile, and repeat. You want to do this until you get to the bottom row.
The answer above doesn't incude checking if the selected tile is already occupied, but I'm sure you can easily figure that out.

Categories

Resources