I am a new to java programming and I am developing a simple a one player TICTACTOE game using swing. Thee are two classes. One main TICTACTOE class which uses an XOButtton class to set up buttons which can listen to click events. I begin by creating an object of this tictactoe class then use this object to call a method called initialCheckButton to find out if the buttons have been clicked 3 timess. If yes it calls another method to find out if the Xs or Os are consecutively displayed.If yes you win. I plan to develop this further but this is just a template. When the GUI dsiplays,clicking on buttons and display of successive Xs or Os does not display the message of the JoptionPane. Any help?
public class TicTacToe extends JFrame {
JPanel p = new JPanel();
boolean done = false;
XOButton buttons[] = new XOButton[9];
public static void main(String args[]) {
TicTacToe t = new TicTacToe();
t.initialCheckButton();
}
public TicTacToe() {
super("TicTacToe");
setSize(400, 400);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
p.setLayout(new GridLayout(3, 3));
for (int i = 0; i < 9; i++) {
buttons[i] = new XOButton();
p.add(buttons[i]);
}
add(p);
setVisible(true);
}
public void initialCheckButton() {
int sum = 0;
while (sum <= 3) {
for (int i = 0; i < 9; i++) {
if (buttons[i].checkButtonO() == 1) {
sum++;
}
if (buttons[i].checkButtonX() == 1) {
sum++;
}
}
}
checkButtonFinal();
}
public void checkButtonFinal() {
for (int i = 0; i < 9; i++)
for (int j = i + 3; j < 9; j++) {
for (int k = j + 3; k < 9; k++) {
if (buttons[i].checkButtonO() == buttons[j].checkButtonO() && buttons[k].checkButtonO() == 1)
JOptionPane.showMessageDialog(null, "Great, you won");
if (buttons[i].checkButtonX() == buttons[j].checkButtonX() && buttons[k].checkButtonX() == 1)
JOptionPane.showMessageDialog(null, "Great, you won");
}
}
for (int i = 0; i < 9; i += 3) {
if (buttons[i].checkButtonO() == buttons[i + 1].checkButtonO() && buttons[i + 2].checkButtonO() == 1)
JOptionPane.showMessageDialog(null, "Great, you won");
if (buttons[i].checkButtonX() == buttons[i + 1].checkButtonX() && buttons[i + 2].checkButtonX() == 1)
JOptionPane.showMessageDialog(null, "Great, you won");
}
for (int i = 0; i < 9; i += 2) {
for (int j = i + 2; j < 9; j += 2)
for (int k = j + 2; k < 9; k += 2) {
if (buttons[i].checkButtonO() == buttons[j].checkButtonO() && buttons[k].checkButtonO() == 1)
JOptionPane.showMessageDialog(null, "Great, you won");
if (buttons[i].checkButtonX() == buttons[j].checkButtonX() && buttons[k].checkButtonX() == 1)
JOptionPane.showMessageDialog(null, "Great, you won");
}
}
for (int i = 0; i < 9; i += 4) {
for (int j = i + 4; j < 9; j += 4)
for (int k = j + 4; k < 9; k += 4) {
if (buttons[i].checkButtonO() == buttons[j].checkButtonO() && buttons[k].checkButtonO() == 1)
JOptionPane.showMessageDialog(null, "Great, you won");
if (buttons[i].checkButtonX() == buttons[j].checkButtonX() && buttons[k].checkButtonX() == 1)
JOptionPane.showMessageDialog(null, "Great, you won");
}
}
}
public static class XOButton extends JButton implements ActionListener {
public int buttonClicked = 0;
public int buttonClickedX = 0;
public int buttonClickedO = 0;
ImageIcon X, O;
byte value = 0;
/*
* 0:nothing 1:X 2:O
*/
public XOButton() {
X = new ImageIcon(this.getClass().getResource("X.png"));
O = new ImageIcon(this.getClass().getResource("O.png"));
this.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
value++;
value %= 3;
switch (value) {
case 0:
setIcon(null);
buttonClicked = 0;
break;
case 1:
setIcon(X);
buttonClickedX = 1;
break;
case 2:
setIcon(O);
buttonClickedO = 1;
break;
}
}
public int checkButtonO() {
return buttonClickedO;
}
public int checkButtonX() {
return buttonClickedX;
}
}
}
The following is a refactored version of your code that includes some documented changes :
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class TicTacToe extends JFrame {
private static int ROW = 3, COLS = 3;
private final JPanel p;
private final XOButton buttons[];
//static counter, so it has the same value for all button instances
//used as a toggle between X and O
private static int counter = 0;
public static void main(String args[]) {
new TicTacToe();
}
public TicTacToe() {
super("TicTacToe");
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
buttons = new XOButton[ROW*COLS];
p = new JPanel();
p.setLayout(new GridLayout(3, 3));
initialize();
add(p);
pack();
setVisible(true);
}
private void initialize(){
for (int i = 0; i < 9; i++) {
buttons[i] = new XOButton();
p.add(buttons[i]);
}
}
//restart game
private void restart(){
p.removeAll();
initialize();
revalidate();
}
private void checkButtons() {
//many similar for loops are not easy to follow
//refactor into methods
XOButton[] winningButtons = checkRows();
if( winningButtons != null) {
won(winningButtons);
}
winningButtons = checkCols();
if( winningButtons != null) {
won(winningButtons);
}
winningButtons = checkDIagonals();
if( winningButtons != null) {
won(winningButtons);
}
}
//returns winning buttons, or null
private XOButton[] checkRows() {
for(int row = 0; row < buttons.length ; row +=3 ){
int totalX = buttons[row].buttonClickedX + buttons[row+1].buttonClickedX+ buttons[row+2].buttonClickedX ;
int totalO = buttons[row].buttonClickedO + buttons[row+1].buttonClickedO+ buttons[row+2].buttonClickedO ;
if(totalX >=3 || totalO >=3) return new XOButton[]{buttons[row], buttons[row+1], buttons[row+2]};
}
return null;
}
//returns winning buttons, or null
private XOButton[] checkCols() {
for(int col = 0; col < COLS ; col++ ){
System.out.println(col+"-"+(col+3)+"-"+(col+6));
int totalX = buttons[col].buttonClickedX + buttons[col+3].buttonClickedX+ buttons[col+6].buttonClickedX ;
int totalO = buttons[col].buttonClickedO + buttons[col+3].buttonClickedO+ buttons[col+6].buttonClickedO ;
if(totalX >=3 || totalO >=3) return new XOButton[]{buttons[col], buttons[col+3], buttons[col+6]};
}
return null;
}
//returns winning buttons, or null
private XOButton[] checkDIagonals() {
int totalX = buttons[0].buttonClickedX + buttons[4].buttonClickedX+ buttons[8].buttonClickedX ;
int totalO = buttons[0].buttonClickedO + buttons[4].buttonClickedO+ buttons[8].buttonClickedO ;
if(totalX >=3 || totalO >=3) return new XOButton[]{buttons[0], buttons[4], buttons[8]};
totalX = buttons[2].buttonClickedX + buttons[4].buttonClickedX+ buttons[6].buttonClickedX ;
totalO = buttons[2].buttonClickedO + buttons[4].buttonClickedO+ buttons[6].buttonClickedO ;
if(totalX >=3 || totalO >=3) return new XOButton[]{buttons[2], buttons[4], buttons[6]};
return null;
}
//invoked when there is a winner
private void won(XOButton[] winningButtons) {
for(XOButton button : winningButtons){
button.setBackground(Color.PINK);
}
JOptionPane.showMessageDialog(null, "Great, you won");
restart(); //start new game
}
class XOButton extends JButton implements ActionListener {
private int buttonClicked = 0, buttonClickedX = 0, buttonClickedO = 0;
String X, O; //avoid using unavailable images when posting
public XOButton() {
X = "X";
O = "O";
this.addActionListener(this);
setPreferredSize(new Dimension(40,40));
}
#Override
public void actionPerformed(ActionEvent e) {
if(buttonClicked > 0 ) return; //invoke only on first click
buttonClicked ++;
counter = (counter+1)%2; //changes from 1 to 0 and back to 1
switch (counter) {
case 0:
setText(X);
buttonClickedX = 1;
break;
case 1:
setText(O);
buttonClickedO = 1;
break;
}
checkButtons();//check buttons after every click
}
public int checkButtonO() {
return buttonClickedO;
}
public int checkButtonX() {
return buttonClickedX;
}
}
}
Related
I have this class called deepToe_2. Whenever I click on the shortcut key for run, eclipse runs another class called TicTacToe which I had previously ran.
I have tried making changes to run cofig but it still does not seem to work.
Here is my code :
package deepToe;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.*;
import javax.swing.*;
import deepToe.deepToe_2.buttonListener;
public class deepToe_2 extends JPanel {
JButton buttons[] = new JButton[9];
int alternate = 0;
String MotherBoard[] = {"","","","","","","","",""};
String board[];
public static void main(String[] args) {
JFrame window = new JFrame("Tic Tac Toe");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.getContentPane().add(new TicTacToe());
window.setBounds(300,200,300,300);
window.setVisible(true);
}
public deepToe_2()
{
setLayout(new GridLayout(3,3));
initializebuttons();
toss();
}
public void toss(){
Random ran = new Random();
int r = ran.nextInt(2);
if(r == 1){
JOptionPane.showMessageDialog(null, "deepToe goes First.");
alternate++;
deepToe();
}
else {
JOptionPane.showMessageDialog(null, "deepToe goes First.");
alternate++;
deepToe();
}
}
public void deepToe() {
if(alternate == 1) {
buttons[4].setText("O");
}else {
int moves[] = {-1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000};
for(int i = 0; i < 9; i++) {
board = MotherBoard;
if(board[i] == "") {
board[i] = "O";
moves[i] = evaluateBoard();
}
}
int high = -999, final_move = -1;
for(int j = 0; j < 9; j++) {
if(moves[j] > high){
high = moves[j];
final_move = j;
}
}
buttons[final_move].setText("O");
}
updateMotherBoard();
if(!(checkResults())) alternate++;
}
public int evaluateBoard() {
int x = 0;
if(canSomeoneWin("O") != -1) x += 2;
if(canSomeoneWin("X") != -1) x -= 2;
return x;
}
public void updateMotherBoard() {
for(int i = 0; i < 9; i++) {
MotherBoard[i] = buttons[i].getText();
}
}
public int canSomeoneWin(String c) {
int x = 0, y = 1, z = 2;
for(int j = 0; j < 3; j++){
if((board[y] == board[z])&&(board[y] == c)&&(board[x] == "")) return x;
if((board[x] == board[z])&&(board[x] == c)&&(board[y] == "")) return y;
if((board[x] == board[y])&&(board[x] == c)&&(board[z] == "")) return z;
x += 3;
y += 3;
z += 3;
}
x = 0; y = 3; z = 6;
for(int j = 0; j < 3; j++){
if((board[y] == board[z])&&(board[y] == c)&&(board[x] == "")) return x;
if((board[x] == board[z])&&(board[x] == c)&&(board[y] == "")) return y;
if((board[x] == board[y])&&(board[x] == c)&&(board[z] == "")) return z;
x++;
y++;
z++;
}
x = 0; y = 4; z = 8;
for(int j = 0; j < 2; j++){
if((board[y] == board[z])&&(board[y] == c)&&(board[x] == "")) return x;
if((board[x] == board[z])&&(board[x] == c)&&(board[y] == "")) return y;
if((board[x] == board[y])&&(board[x] == c)&&(board[z] == "")) return z;
x = 2; z = 6;
}
return -1;
}
public void initializebuttons()
{
for(int i = 0; i <= 8; i++)
{
buttons[i] = new JButton();
buttons[i].setText("");
buttons[i].addActionListener(new buttonListener());
add(buttons[i]);
}
buttons[5].setText("X");
}
public class buttonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
JButton buttonClicked = (JButton)e.getSource();
if((alternate%2 == 0)&&(buttonClicked.getText().equals(""))){
buttonClicked.setText("X");
updateMotherBoard();
if(!(checkResults())) {
alternate++;
deepToe();
}
}
}
}
public boolean checkResults(){
if(checkForWin())
{
if(alternate%2 == 0)
JOptionPane.showConfirmDialog(null, "Human wins. Great Job!!!");
else
JOptionPane.showConfirmDialog(null, "deepToe wins.");
return true;
}else{
if(checkForDraw()){
JOptionPane.showConfirmDialog(null, "Draw. Good game.");
return true;
}
}
return false;
}
public boolean checkForDraw() {
boolean yes = true;
for(int j = 0; j < 9; j++){
if(buttons[j].getText().equals("")) yes = false;
}
return yes;
}
public boolean checkForWin()
{
if( checkAdjacent(0,1) && checkAdjacent(1,2) ) //no need to put " == true" because the default check is for true
return true;
else if( checkAdjacent(3,4) && checkAdjacent(4,5) )
return true;
else if ( checkAdjacent(6,7) && checkAdjacent(7,8))
return true;
else if ( checkAdjacent(0,3) && checkAdjacent(3,6))
return true;
else if ( checkAdjacent(1,4) && checkAdjacent(4,7))
return true;
else if ( checkAdjacent(2,5) && checkAdjacent(5,8))
return true;
else if ( checkAdjacent(0,4) && checkAdjacent(4,8))
return true;
else if ( checkAdjacent(2,4) && checkAdjacent(4,6))
return true;
else
return false;
}
public boolean checkAdjacent(int a, int b)
{
if ( buttons[a].getText().equals(buttons[b].getText()) && !buttons[a].getText().equals("") )
return true;
else
return false;
}
}
It probably IS running this class, but you are inserting the wrong panel in your frame:
window.getContentPane().add(new TicTacToe());
it should be deepToe_2 like in
window.getContentPane().add(new deepToe_2());
since there is no other reference to that class in the poseted code.
Just to be sure change the frame's title:
JFrame window = new JFrame("Deep Toe 2"); // or so
I also would encourage you to (learn to) use the debugger, would b helpful to identify such problems...
Right click either in your class file or the class itself and click Run As -> Java Application
you need just to double click your class and then run the program from where ever you want. you can right click as suggested by kkflf or run it from shortcut key as you used to do.
Hope this will help.
I am programming a minesweeper game, and having a problem making the main method. I cant seem to get the text based game to output to the screen, allowing the user to interact with it. I have tried several ways, but none have worked.
public class Game {
private Board board;
boolean finish = false;
boolean win = false;
int turn = 0;
public void Jogo() {
board = new Board();
Play(board);
}
public void Play(Board board) {
do {
turn++;
System.out.println("Turn " + turn);
board.show();
finish = board.setPosition();
if (!finish) {
board.openNeighbors();
finish = board.win();
}
} while (!finish);
if (board.win()) {
System.out.println("Congratulations, you let the 10 fields with the mines in " + turn
+ " turns");
board.showMines();
} else {
System.out.println("Mine! You lost!");
board.showMines();
}
}
}
import java.util.Random;
import java.util.Scanner;
public class Board extends Game {
private int[][] mines;
private char[][] boardgame;
private int Line, Column;
Random random = new Random();
Scanner input = new Scanner(System.in);
public void Jogo() {
mines = new int[10][10];
boardgame = new char[10][10];
startMines();
randomMines();
fillTips();
startBoard();
}
public boolean win() {
int count = 0;
for (int line = 1; line < 9; line++)
for (int column = 1; column < 9; column++)
if (boardgame[line][column] == '_')
count++;
if (count == 10)
return true;
else
return false;
}
public void openNeighbors() {
for (int i = -1; i < 2; i++)
for (int j = -1; j < 2; j++)
if ((mines[Line + i][Column + j] != -1)
&& (Line != 0 && Line != 9 && Column != 0 && Column != 9))
boardgame[Line + i][Column + j] =
Character.forDigit(mines[Line + i][Column + j], 10);
}
public int getPosition(int Line, int Column) {
return mines[Line][Column];
}
public boolean setPosition() {
do {
System.out.print("\nLine: ");
Line = input.nextInt();
System.out.print("Column: ");
Column = input.nextInt();
if ((boardgame[Line][Column] != '_')
&& ((Line < 9 && Line > 0) && (Column < 9 && Column > 0)))
System.out.println("Field already shown");
if (Line < 1 || Line > 8 || Column < 1 || Column > 8)
System.out.println("Choose a number between 1 and 8");
} while ((Line < 1 || Line > 8 || Column < 1 || Column > 8)
|| (boardgame[Line][Column] != '_'));
if (getPosition(Line, Column) == -1)
return true;
else
return false;
}
public void show() {
System.out.println("\n Lines");
for (int Line = 8; Line > 0; Line--) {
System.out.print(" " + Line + " ");
for (int Column = 1; Column < 9; Column++) {
System.out.print(" " + boardgame[Line][Column]);
}
System.out.println();
}
System.out.println("\n 1 2 3 4 5 6 7 8");
System.out.println(" Columns");
}
public void fillTips() {
for (int line = 1; line < 9; line++)
for (int column = 1; column < 9; column++) {
for (int i = -1; i <= 1; i++)
for (int j = -1; j <= 1; j++)
if (mines[line][column] != -1)
if (mines[line + i][column + j] == -1)
mines[line][column]++;
}
}
public void showMines() {
for (int i = 1; i < 9; i++)
for (int j = 1; j < 9; j++)
if (mines[i][j] == -1)
boardgame[i][j] = '*';
show();
}
public void startBoard() {
for (int i = 1; i < mines.length; i++)
for (int j = 1; j < mines.length; j++)
boardgame[i][j] = '_';
}
public void startMines() {
for (int i = 0; i < mines.length; i++)
for (int j = 0; j < mines.length; j++)
mines[i][j] = 0;
}
public void randomMines() {
boolean raffled;
int Line, Column;
for (int i = 0; i < 10; i++) {
do {
Line = random.nextInt(8) + 1;
Column = random.nextInt(8) + 1;
if (mines[Line][Column] == -1)
raffled = true;
else
raffled = false;
} while (raffled);
mines[Line][Column] = -1;
}
}
}
public class MineSweeper extends Board {
public static void main(String[] args) {
Game game = new Game();
}
}
Main Class
package edu.bsu.cs121.mamurphy;
public class GameOfLifeMain {
public static void main(String[] args) {
{
new GameOfLifeGUI();
System.out.println();
}
}
}
Tester Class
package edu.bsu.cs121.mamurphy;
import java.awt.Color;
import java.awt.Graphics;
import java.io.File;
import java.util.Scanner;
import javax.swing.JPanel;
public class tester extends JPanel
{
final static int ROW = 25, COL = 75;
final static char DOT = '.';
static char[][] grid = new char[ROW + 2][COL + 2];
static char[][] nextgrid = new char[ROW + 2][COL + 2];
boolean sameFlag;
boolean blankFlag;
public static void init(char[][] grid, char[][] nextgrid) {
for (int row = 0; row <= ROW + 1; row++) {
for (int col = 0; col <= COL + 1; col++) {
grid[row][col] = DOT;
nextgrid[row][col] = DOT;
}
}
}
public static void pause() {
try {
Thread.currentThread();
Thread.sleep(1000L);
} catch (InterruptedException e) {
}
}
public void begin() {
init(grid, nextgrid);
read(grid);
repaint(); // calls paintComponent
pause();
while (sameFlag == true && blankFlag == false) {
nextGen(grid, nextgrid);
}
}
public static void read(char[][] grid) {
Scanner world = new Scanner(System.in);
System.out.println("Type the file name of the world you'd like to create.");
String fileName = world.nextLine();
{
try {
world = new Scanner(new File(fileName));
} catch (Exception ex) {
System.out.println("Please insert a valid file name.");
}
for (int row = 1; row <= ROW; row++) {
String s = world.next();
for (int col = 1; col <= COL; col++) {
grid[row][col] = s.charAt(col - 1);
}
}
}
}
public void print(Graphics g) {
int x, y;
y = 20;
for (int row = 1; row <= ROW; row++) {
x = 20;
for (int col = 1; col <= COL; col++) {
g.drawString("" + grid[row][col], x, y);
x = x + 7;
}
y = y + 15;
}
}
public static int neighbors(char[][] grid, int r, int c) {
// counts the # of closest neighbors that are X's
int count = 0;
for (int row = r - 1; row <= r + 1; row++) {
for (int col = c - 1; col <= c + 1; col++) {
if (grid[row][col] == 'X') {
count++;
}
}
}
if (grid[r][c] == 'X') {
count = count - 1;
}
return count;
}
public static void nextGen(char[][] grid, char[][] nextgrid) {
for (int row = 1; row <= ROW; row++) {
for (int col = 1; col <= COL; col++) {
if (grid[row][col] == 'X') {
int count = 0;
{
if (grid[row][col - 1] == 'X')
count = count + 1;
if (grid[row][col + 1] == 'X')
count = count + 1;
if (grid[row - 1][col] == 'X')
count = count + 1;
if (grid[row - 1][col - 1] == 'X')
count = count + 1;
if (grid[row - 1][col + 1] == 'X')
count = count + 1;
if (grid[row + 1][col - 1] == 'X')
count = count + 1;
if (grid[row + 1][col] == 'X')
count = count + 1;
if (grid[row + 1][col + 1] == 'X')
count = count + 1;
}
if (count == 2 || count == 3) {
nextgrid[row][col] = 'X';
} else
nextgrid[row][col] = DOT;
}
if (grid[row][col] == DOT) {
int count1 = 0;
{
if (grid[row][col - 1] == 'X')
count1 = count1 + 1;
if (grid[row][col + 1] == 'X')
count1 = count1 + 1;
if (grid[row - 1][col] == 'X')
count1 = count1 + 1;
if (grid[row - 1][col - 1] == 'X')
count1 = count1 + 1;
if (grid[row - 1][col + 1] == 'X')
count1 = count1 + 1;
if (grid[row + 1][col - 1] == 'X')
count1 = count1 + 1;
if (grid[row + 1][col] == 'X')
count1 = count1 + 1;
if (grid[row + 1][col + 1] == 'X')
count1 = count1 + 1;
}
if (count1 == 3)
nextgrid[row][col] = 'X';
}
}
}
}
public static void copy(char[][] grid, char[][] nextgrid) {
for (int i = 0; i < ROW + 1; i++) {
for (int j = 0; j < COL + 1; j++) {
grid[i][j] = nextgrid[i][j];
}
}
}
public static boolean isEmpty(char[][] grid, char[][] nextgrid) {
boolean blankFlag = true;
for (int i = 0; i < ROW + 1; i++) {
for (int j = 0; j < COL + 1; j++) {
if (grid[i][j] != DOT) {
blankFlag = false;
}
}
}
return blankFlag;
}
public static boolean isSame(char[][] grid, char[][] nextgrid) {
boolean sameFlag = false;
for (int i = 0; i < ROW + 1; i++) {
for (int j = 0; j < COL + 1; j++) {
if (grid[i][j] == nextgrid[i][j]) {
sameFlag = true;
break;
}
}
}
return sameFlag;
}
public void paintComponent(Graphics g) {
super.paintComponent(g);// erases panel Contents
g.setColor(Color.black);
if (sameFlag == false && blankFlag == false) {
print(g);
} else {
if (sameFlag == true) {
g.drawString("This worldis the same as the last one.", 10, 250);
}
if (blankFlag == true) {
g.drawString("Everyone died. Good job.", 10, 250);
}
}
}
}
GUI Class
package edu.bsu.cs121.mamurphy;
import javax.swing.*;
import java.awt.*;
//
public class GameOfLifeGUI extends JFrame {
public GameOfLifeGUI() {
super("Game of Life");
setSize(600, 445);
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(1, 2));
tester test1 = new tester();
test1.setBackground(Color.LIGHT_GRAY);
panel.add(test1);
setContentPane(panel);
setVisible(true);
Temp one = new Temp(test1);
one.start();
}
class Temp extends Thread {
tester anim;
public Temp(tester anim) {
this.anim = anim;
}
public void run()// for each instance of test begin will be executed
{
anim.begin();
}
}
}
Hi stackoverflow. I have been working on this game of life project for the last few days and I have hit one final wall in trying to finish it up. How do I make it proceed to the next generation?
I know for what I am required to do I need to ask the user if they wish to continue to the next generation or not. I know I need to use a scanner and then have a loop that checks to see what the user's input is, as well as a try catch to make sure the program doesn't crash if they type in anything that isn't what the program asks them to.
My only issue is that I do not know where to put this code at in my tester class (if that is actually where it needs to go).
Any help is greatly appreciated.
So I have been working on my final term project which is a Connect Four game. I ran into this issue where i believe my CheckWin logic should work, put is providing me with no output when i run the program. I have my CheckWin() being called in my actionPerformed and I am stuck as to what to do here. As a side note, is there any way to easily increase the size of text inside of a JButton? I would like to increase the size of the "X's" and "O's". I am relatively new at programming so sorry if these are simple fixes. My code is below:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Connect implements ActionListener {
private JFrame window = new JFrame();
private JPanel myPanel = new JPanel();
private JPanel myPanelB = new JPanel();
private JButton[][] myButtons = new JButton[6][7];
private JButton[] buttons = new JButton[7];
private boolean win = false;
private int count = 5;
private int count2 = 5;
private int count3 = 5;
private int count4 = 5;
private int count5 = 5;
private int count6 = 5;
private int count7 = 5;
private int countA = 0;
private String letter = "";
public boolean checkHorizontalWin(String letter) {
for (int y = 0; y < myButtons.length; y++) {
// going to length-3 to avoid IndexOutOfBounds exception
for (int x = 0; x < myButtons[y].length - 3; x++) {
if (myButtons[y][x].getText().equals(letter)
&& myButtons[y][x + 1].getText().equals(letter)
&& myButtons[y][x + 2].getText().equals(letter)
&& myButtons[y][x + 3].getText().equals(letter)
) {
return true;
}
}
}
return false;
}
public boolean checkVerticalWin(String letter) {
for (int y = 0; y < myButtons.length - 3; y++) {
for (int x = 0; x < myButtons[y].length; x++) {
if (myButtons[y][x].getText().equals(letter)
&& myButtons[y + 1][x].getText().equals(letter)
&& myButtons[y + 2][x].getText().equals(letter)
&& myButtons[y + 3][x].getText().equals(letter)
) {
return true;
}
}
}
return false;
}
public boolean checkDiagonalToTheLeftWin(String letter) {
for (int y = 0; y < myButtons.length - 3; y++) {
for (int x = 0; x < myButtons[y].length - 3; x++) {
if (myButtons[y][x].getText().equals(letter)
&& myButtons[y + 1][x + 1].getText().equals(letter)
&& myButtons[y + 2][x + 2].getText().equals(letter)
&& myButtons[y + 3][x + 3].getText().equals(letter)
) {
return true;
}
}
}
return false;
}
public boolean checkDiagonalToTheRightWin(String letter) {
for (int y = 0; y < myButtons.length - 3; y++) {
for (int x = 3; x < myButtons[y].length; x++) {
if (myButtons[y][x].getText().equals(letter)
&& myButtons[y + 1][x - 1].getText().equals(letter)
&& myButtons[y + 2][x - 2].getText().equals(letter)
&& myButtons[y + 3][x - 3].getText().equals(letter)
) {
return true;
}
}
}
return false;
}
public Connect(){
window.setSize(800,700);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myPanel.setLayout(new GridLayout(1,7));
myPanelB.setLayout(new GridLayout(6,7));
for (int i = 0; i < buttons.length; i ++){
buttons[i] = new JButton();
myPanel.add(buttons[i]);
buttons[i].addActionListener(this);
}
for (int i = 0; i < 6; i ++){
for (int j = 0; j < 7; j ++){
myButtons[i][j] = new JButton();
myPanelB.add(myButtons[i][j]);
}
}
window.add(myPanel, BorderLayout.NORTH);
window.add(myPanelB, BorderLayout.CENTER);
window.setVisible(true);
}
public void actionPerformed(ActionEvent e){
countA++;
if (countA % 2 == 0)
letter = "X";
else
letter = "O";
if (e.getSource() == buttons[0]){
myButtons[count][0].setText(letter);
count --;
}
if (e.getSource() == buttons[1]){
myButtons[count2][1].setText(letter);
count2 --;
}
if (e.getSource() == buttons[2]){
myButtons[count3][2].setText(letter);
count3--;
}
if (e.getSource() == buttons[3]){
myButtons[count4][3].setText(letter);
count4--;
}
if (e.getSource() == buttons[4]){
myButtons[count5][4].setText(letter);
count5--;
}
if (e.getSource() == buttons[5]){
myButtons[count6][5].setText(letter);
count6--;
}
if (e.getSource() == buttons[6]){
myButtons[count7][6].setText(letter);
count7--;
}
if (myButtons[0][0].getText().equals("O") || myButtons[0][0].getText().equals("X")){
buttons[0].setEnabled(false);
}
if (myButtons[0][1].getText().equals("O") || myButtons[0][1].getText().equals("X")){
buttons[1].setEnabled(false);
}
if (myButtons[0][2].getText().equals("O") || myButtons[0][2].getText().equals("X")){
buttons[2].setEnabled(false);
}
if (myButtons[0][3].getText().equals("O") || myButtons[0][3].getText().equals("X")){
buttons[3].setEnabled(false);
}
if (myButtons[0][4].getText().equals("O") || myButtons[0][4].getText().equals("X")){
buttons[4].setEnabled(false);
}
if (myButtons[0][5].getText().equals("O") || myButtons[0][5].getText().equals("X")){
buttons[5].setEnabled(false);
}
if (myButtons[0][6].getText().equals("O") || myButtons[0][6].getText().equals("X")){
buttons[6].setEnabled(false);
if (myButtons[0][6].getText().equals("O") || myButtons[0][6].getText().equals("X")){
buttons[6].setEnabled(false);
if (checkHorizontalWin(letter)
|| checkVerticalWin(letter)
|| checkDiagonalToTheLeftWin(letter)
|| checkDiagonalToTheRightWin(letter)
) {
win = true;
if (win == true) {
JOptionPane.showMessageDialog(null, letter + " has won!");
System.exit(0);
}
}
}
if(win == true){
JOptionPane.showMessageDialog(null, letter + " has won!");
System.exit(0);
} else if(count == 42 && win == false){
JOptionPane.showMessageDialog(null, "tie game");
System.exit(0);
}
}
}
public static void main(String[] args){
new Connect();
}
}
Identation helps.
if (myButtons[0][6].getText().equals("O") || myButtons[0][6].getText().equals("X"))
{
buttons[6].setEnabled(false);
// Missing brace on previous if
// checkXWin methods only invoked inside the above if-statement.
if (checkHorizontalWin(letter)
|| checkVerticalWin(letter)
|| checkDiagonalToTheLeftWin(letter)
|| checkDiagonalToTheRightWin(letter)
) {
win = true;
if (win == true) {
JOptionPane.showMessageDialog(null, letter + " has won!");
ystem.exit(0);
}
}
}
You haven't closed a brace in one of your if statements properly in the actionPerformed method. As a result, your program will only check for a win once the last column is full.
It also seems the condition if (myButtons[0][6].getText().equals("O") || myButtons[0][6].getText().equals("X") is repeated twice. That wouldn't be the cause of your issue but I think you might want to remove one of those statements.
Your brackets on your if statements are incorrectly placed.
if (myButtons[0][6].getText().equals("O") || myButtons[0][6].getText().equals("X")){
buttons[6].setEnabled(false);
if (myButtons[0][6].getText().equals("O") || myButtons[0][6].getText().equals("X")){
buttons[6].setEnabled(false);
On both of theses if statements you have opening brackets but the closing brackets do not come until the end of the actionPerformed method.
This means the code to check for a winner does not get executed unless both of these conditions resulted in true, which is not what you want and I'm pretty sure is impossible...
I'm making a game for my java class in school, and needed to write onto a file. I copied some code from a working program I had made before, but whenever I rune it, I get a Access Denied error. My java teacher said I have full read and write access to the file, but it still spits out the error.
The file Hiscore.txt does exist and is spelled exactly like that.
The error is in the method MakeOutputFile, sphecifically where the printwriter is initialized. It does also occur in CheckOutputFile, but that method is currently commented out.
I'm new to this website, so I'm not quite sure how to put code, so the results will be quite shoddy.
Exception in thread "AWT-EventQueue-1" java.security.AccessControlException:
access denied ("java.io.FilePermission" "Hiscore.txt" "write")
Code
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.io.File;
import java.io.PrintWriter;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class TowerDefence extends JApplet implements MouseListener {
int xpos, ypos, money, attackspawn, attackcount, lives, attackerhealth, hiscore,
laser; // x,y location of current square
private DrawingArea canvas; // JPanel canvas on which to draw grid
private int[][] numbers;
private int[][] damage;
JPanel startscreen;
File ifile, ofile, qfile;
Scanner input, output, questionreader;
boolean start, play, checkhiscore, fileexists, end, inquestionstate;
long totaldamage;
Timer timer;
boolean [][] moved;
JButton button;
public File fargle;
PrintWriter makesOutput;
//JButton begin;
// Constructor
public TowerDefence( ) {
inquestionstate = false;
JButton begin = new JButton ("BEGIN");
//begin = new JButton("BEGIN");
checkhiscore = false;
xpos = ypos = attackcount = laser = 4;
button = new JButton("Double Damage for 15 seconds");
money = 200;
attackspawn = 0;
totaldamage = 0;
lives = 10;
attackerhealth = 24;
fileexists = true;
numbers = new int[30][30];
damage = new int [20][20];
moved = new boolean [20][20];
Timer timer;
end = false;
for (int i = 0; i< 20; i++){
for (int j = 0; j< 20; j++){
moved[i][j] = false;
damage [i][j] = 0;
}
}
for (int i = 0; i<30; i++){
for (int j = 0; j<30; j++){
numbers[i][j] = 0;
}
}
start = false;
play = false;
ifile = new File("map.txt");
ofile = new File ("hiscore.txt");
qfile = new File("questions.txt");
RepaintAction action = new RepaintAction();
timer = new Timer(1000, action);
timer.start();
}
private class RepaintAction implements ActionListener {
public void actionPerformed(ActionEvent evt) {
repaint(); // Call the repaint() method in the panel class.
}
}// MANDATORY: required initialization of JApplet
// MANDATORY: required initialization of JApplet
public void init ( ) {
canvas = new DrawingArea(); // create a new Drawing Area
setContentPane(canvas); // connect the canvas to JApplet
canvas.setBackground(Color.lightGray); // make the background lightGray
canvas.addMouseListener(this);
canvas.requestFocus(); // focus keyboard on JApplet'
}
// MANDATORY: Define DrawingArea as a JPanel
class DrawingArea extends JPanel {
JButton begin = new JButton ("BEGIN");
JButton upgrade = new JButton ("upgrade");
JComboBox selectmap = new JComboBox();
String op1, op2 = "yodel";
String askquestion;
String option = "ocean";
String findplace = "";
JRadioButton option1, option2;
JLabel question;
ButtonGroup group = new ButtonGroup();
JFrame questionframe = new JFrame();
public void paintComponent(Graphics g) {
super.paintComponent(g); // MANDATORY: Must be first method called.
if (!play&&!end){
ReadIt1();
StartScreen(g);
StartButton();
}
if (start){
ReadIt();
}
if (play){
ChangeAttackers();
drawGrid(g);
Attack(g);
DamageCheck();
if (attackspawn % 15 == 0){
SpawnAttackers();
ReadQuestions();
}
LifeCheck(g);
}
// CheckOutputFile();
//if (fileexists){
MakeOutputFile();
//}
if (end){
LifeCheck(g);
}
}
public void ReadQuestions(){
if(!inquestionstate){
try{
questionreader = new Scanner(qfile);
}catch(FileNotFoundException e){
System.out.println("ERROR: cannot open file map.txt");
System.exit(1);
}
while (!findplace.equalsIgnoreCase(op2)){
findplace = questionreader.nextLine();
}
askquestion = questionreader.nextLine();
op1 = questionreader.nextLine();
op2 = questionreader.nextLine();
System.out.println(askquestion);
System.out.println(op1);
System.out.println(op2);
question = new JLabel(askquestion);
option1 = new JRadioButton(op1);
option2 = new JRadioButton(op2);
questionframe.setLayout(new GridLayout(0,1));
questionframe.removeAll();
questionframe.getContentPane().add(question);
questionframe.getContentPane().add(option1);
questionframe.getContentPane().add(option2);
questionframe.setVisible(true);
inquestionstate = true;
}
}
public void ReadIt1(){
if (option.equalsIgnoreCase("ocean")){
ifile = new File("oceanmap.txt");
}
else if (option.equalsIgnoreCase("canyon")){
ifile = new File("map.txt");
}
try{
input = new Scanner(ifile);
}catch(FileNotFoundException e){
System.out.println("ERROR: cannot open file map.txt");
System.exit(1);
}
for (int i = 0; i<20; i++){
for (int j = 0; j < 20; j++){
numbers [j+5][i+5] = input.nextInt();
}
}
input.close();
}//end method ReadIt
public void StartScreen(Graphics g){
for (int row = 0; row < 20; row ++){
for (int col = 0; col < 20; col ++){
if (numbers[row+5][col+5] == 0&&option.equalsIgnoreCase("canyon")){
g.setColor(Color.green);
}
else if (option.equalsIgnoreCase("canyon")){
g.setColor(Color.black);
}
else if (option.equalsIgnoreCase("ocean")&&numbers[row+5][col+5] == 0){
g.setColor(Color.yellow);
}
else if (option.equalsIgnoreCase("ocean")){
g.setColor(Color.cyan);
}
g.fillRect(30 + col *22, 30 + row * 22, 21, 21);
g.setFont( new Font ("Serif", Font.BOLD, 48));
g.setColor(Color.red);
g.drawString("TOWER DEFENCE", 10,100);
}
}
}
public void StartButton(){
selectmap.addItem("Ocean");
selectmap.addItem("Canyon");
begin.setVisible(true);
begin.addActionListener(new ButtonListener());
this.setLayout(null);
this.add(begin);
begin.setBounds(0,468,500,32);
selectmap.setVisible(true);
this.add(selectmap);
selectmap.setBounds(300,300, 100,25);
}
// Draw the numbers on the grid
// Draw the Sudoku grid of rectangles
public void LifeCheck(Graphics g){
if(!inquestionstate){
JButton upgrade = new JButton ("upgrade");
upgrade.addActionListener(new ButtonListener());
for (int i = 0; i<20; i++){
for (int j = 19; j<20; j++){
if (numbers [i+5][j+5] == 2){
lives--;
numbers[i+5][j+5] = 1;
}
}
}
if (lives <=0){
play = false;
end = true;
for (int row = 0; row < 20; row ++){
for (int col = 0; col < 20; col ++){
if (numbers[row+5][col+5] == 0&&option.equalsIgnoreCase("Canyon")){
g.setColor(Color.green);
}
else if (numbers [row+5][col+5] == 1&&option.equalsIgnoreCase("Canyon")){
g.setColor(Color.black);
}
else if (numbers [row+5][col+5] == 2){
g.setColor(Color.red);
}
else if (numbers[row+5][col+5] == 0&&option.equalsIgnoreCase("Ocean")){
g.setColor(Color.yellow);
}
else if (numbers [row+5][col+5] == 1&&option.equalsIgnoreCase("Ocean")){
g.setColor(Color.cyan);
}
else if (numbers [row+5][col+5] == 3){
g.setColor(Color.gray);
}
g.fillRect(30 + col *22, 30 + row * 22, 21, 21);
g.setColor(Color.black);
g.drawString("Money: "+money, 420,480);
g.drawString("Lives: "+lives, 360,480);
g.drawString("Laser: "+laser, 240,480);
System.out.print(damage[row][col]);
}
}
this.setLayout(null);
this.add(upgrade);
upgrade.setBounds(0, 475, 100, 25);
Font myFont = new Font ("Arial", Font.BOLD, 25);
g.setFont(myFont);
if (option.equalsIgnoreCase("Ocean")){
g.setColor(Color.red);
}
else if (option.equalsIgnoreCase("Canyon")){
g.setColor(Color.cyan);
}
g.drawString("You have lost. You lasted for " + attackspawn + "seconds.",10,100);
}
}
}
public void SpawnAttackers(){
if(!inquestionstate){
int currentspawn = 0;
attackcount++;
attackerhealth+=3;
if (attackerhealth % 10 == 0){
attackerhealth += (int)(attackerhealth*1.1);
}
if (attackerhealth % 17 == 0){
attackerhealth += (int)(attackerhealth*1.2);
}
if (attackerhealth % 12 == 0){
attackerhealth += (int)(attackerhealth*1.3);
}
if (attackerhealth % 2 == 0){
attackerhealth += 1+(int)(attackerhealth * 1.05);
}
for (int i = 0; i < 20; i++){
for (int j = 0; j< 20; j++){
if (numbers [j+5][i+5] == 1){
numbers [j+5][i+5] = 2;
currentspawn++;
if (currentspawn == attackcount){
i = j = 100;
}
}
}
}
}
}
public void drawGrid(Graphics g) {
if(!inquestionstate){
money++;
attackspawn++;
}
upgrade.addActionListener(new ButtonListener());
for (int row = 0; row < 20; row ++){
for (int col = 0; col < 20; col ++){
if (numbers[row+5][col+5] == 0&&option.equalsIgnoreCase("Canyon")){
g.setColor(Color.green);
}
else if (numbers [row+5][col+5] == 1&&option.equalsIgnoreCase("Canyon")){
g.setColor(Color.black);
}
else if (numbers[row+5][col+5] == 0&&option.equalsIgnoreCase("Ocean")){
g.setColor(Color.yellow);
}
else if (numbers [row+5][col+5] == 1&&option.equalsIgnoreCase("Ocean")){
g.setColor(Color.cyan);
}
else if (numbers [row+5][col+5] == 2){
g.setColor(Color.red);
}
else if (numbers [row+5][col+5] == 3){
g.setColor(Color.gray);
}
g.fillRect(30 + col *22, 30 + row * 22, 21, 21);
g.setColor(Color.black);
g.drawString("Money: "+money, 420,480);
g.drawString("Lives: "+lives, 360,480);
g.drawString("Laser: "+laser, 240,480);
g.drawString("Wave: " + (int)(attackspawn/15), 170,480);
g.drawString("Total Damage: " + totaldamage, 170,20);
System.out.print(damage[row][col]);
}
System.out.println();
}
this.setLayout(null);
this.add(upgrade);
upgrade.setBounds(0, 475, 100, 25);
System.out.println();
}
public void ReadIt(){
if(!inquestionstate){
if (option.equalsIgnoreCase("ocean")){
ifile = new File("oceanmap.txt");
}
else if (option.equalsIgnoreCase("canyon")){
ifile = new File("map.txt");
}
try{
input = new Scanner(ifile);
}catch(FileNotFoundException e){
System.out.println("ERROR: cannot open file map.txt");
System.exit(1);
}
for (int i = 0; i<20; i++){
for (int j = 0; j < 20; j++){
numbers [j+5][i+5] = input.nextInt();
}
}
start = false;
play = true;
input.close();
}
}//end method ReadIt
public void DamageCheck(){
if(!inquestionstate){
for (int i = 0; i<20; i++){
for (int j = 0; j<20; j++){
if (damage[i][j] >=attackerhealth){
numbers[i+5][j+5] = 1;
damage[i][j] = 0;
money+=25;
}
}
}
}
}
public void Attack(Graphics g){
if(!inquestionstate){
for (int i = 0; i<20; i++){
for (int j = 0; j<20; j++){
if (numbers [i+5][j+5] == 3){
for (int o = -3; o<4; o++){
for (int e = -3; e<4; e++){
if (numbers [i+o+5][j+e+5] == 2){
damage [i+o][j+e] +=laser;
totaldamage+=laser;
g.setColor(Color.white);
g.drawLine(40+j*22, 40+i*22, 40+(j+e)*22, 40+(i+o)*22);
}
}
}
}
}
}
}
}
public void ChangeAttackers(){
if(!inquestionstate){
for (int i = 0; i<20; i++){
for (int j = 0; j<20; j++){
moved[i][j] = false;
}
}
for (int i = 0; i<20; i++){
for (int j = 0; j<20; j++){
if (numbers[i+5][j+5] == 2){
if (numbers[i+5][j+6] == 1&&moved[i][j] == false){
numbers [i+5][j+5] = 1;
numbers [i+5][j+6] = 2;
damage[i][j+1] = damage[i][j];
damage[i][j] = 0;
moved [i][j+1] = true;
System.out.println("Move Right");
}
else if ((i>13)||(i<9&&i>=7)){
if (numbers[i+4][j+5] == 1&&moved [i][j] == false){
numbers [i+5][j+5] = 1;
numbers [i+4][j+5] = 2;
moved [i-1][j] = true;
damage[i-1][j] = damage[i][j];
damage[i][j] = 0;
System.out.println("Move Up");
}
else if (numbers [i+6][j+5] == 1&&moved[i][j] == false){
numbers [i+5][j+5] = 1;
numbers [i+6][j+5] = 2;
moved [i+1][j] = true;
damage[i+1][j] = damage[i][j];
damage[i][j] = 0;
System.out.println("Move Down");
}
}
else if ((i<=13&&i>=10)||(i<7)){
if (numbers [i+6][j+5] == 1&&moved[i][j] == false){
numbers [i+5][j+5] = 1;
numbers [i+6][j+5] = 2;
moved [i+1][j] = true;
damage[i+1][j] = damage[i][j];
damage[i][j] = 0;
System.out.println("Move Down");
}
else if (numbers[i+4][j+5] == 1&&moved [i][j] == false){
numbers [i+5][j+5] = 1;
numbers [i+4][j+5] = 2;
moved [i-1][j] = true;
damage[i-1][j] = damage[i][j];
damage[i][j] = 0;
System.out.println("Move Up");
}
}
else if (j!=0){
if (numbers[i+5][j+4] == 1&&j!=0&&moved[i][j] == false){
numbers [i+5][j+5] = 1;
numbers [i+5][j+4] = 2;
moved[i][j-1] = true;
damage[i][j-1] = damage[i][j];
damage[i][j] = 0;
System.out.println("Move Left");
}
}
}
}
}
}
}
public void CheckOutputFile(){
int number;
try{
output = new Scanner(ofile);
}catch(FileNotFoundException e){
System.out.println("ERROR: cannot open file hiscore.txt");
fileexists = true;
// System.exit(1);
}
if (fileexists){
hiscore = output.nextInt();
checkhiscore = true;
output.close();
}
}
public void MakeOutputFile ( ) {
fargle = new File ("Hiscore.txt");
try {
makesOutput = new PrintWriter ( fargle );
}catch ( IOException e ){
System.out.println("Cannot create file to be written to");
System.exit(1);
}// end catch
makesOutput.println("\nHiscore :\t" + attackspawn);
makesOutput.println ( );
System.exit(1);
}// end method MakeOutput File
class ButtonListener implements ActionListener{
public void actionPerformed(ActionEvent evt){
System.out.println("RAWR");
if (evt.getSource() == begin){
System.out.println("Button Pressed");
begin.setVisible(false);
selectmap.setVisible(false);
play = true;
start = true;
option = (String)selectmap.getSelectedItem();
System.out.println(option);
}
if (evt.getSource() == upgrade){
if (money>=50){
money+=-50;
laser+=1+(int)(laser*.1);
}
}
}
}
}
public void mousePressed(MouseEvent m){
int x = m.getX();
int y = m.getY();
for (int row = 0; row < 20; row ++){
for (int col = 0; col < 20; col ++){
if (x>30+col*22&&x<51+col*22&&y>30+row*22&&y<51+row*22){
if (numbers [row+5][col+5] == 1&&money>200){
numbers [row+5][col+5] = 0;
money+=-200;
repaint();
}
else if (numbers [row+5][col+5] == 0&&money>50){
System.out.println(row+" " +col);
money+=-50;
numbers [row+5][col+5] = 3;
repaint();
}
}
}
}
}
public void mouseClicked(MouseEvent m){}
public void mouseReleased(MouseEvent m){}
public void mouseEntered(MouseEvent m){}
public void mouseExited(MouseEvent m){}
}
An untrusted applet is not permitted to read/write File objects on the client computer.
The alternatives are to:
Store the information on the server.
Digitally sign the applet and get the user to OK it when asked to trust it.
Deploy for a Plug-In 2 JRE and use the JNLP API services to mediate the file write.