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.
Related
This is my board class
public class Board {
char[][] grid;
int width;
int height;
int count;
char player;
public Board(int height, int width){
count = 0;
grid = new char[height][width];
this.width = width;
this.height = height;
for(int i = 0; i < height; i++) {
for(int j = 0; j < width; j++){
if(i == 0 && j == 0){
grid[i][j] = '┌';
}
else if(j % 2 == 1) {
grid[i][j] = '─';
}
else if (i == 0 && j == width - 1){
grid[i][j] = '┐';
}
else if (i == height-1 && j == 0){
grid[i][j] = '└';
}
else if (i == height - 1 && j == width - 1){
grid[i][j] = '┘';
}
else if (i == 0){
grid[i][j] = '┬';
}
else if (j == 0){
grid[i][j] = '├';
}
else if (i == height - 1){
grid[i][j] = '┴';
}
else if (j == width - 1){
grid[i][j] = '┤';
}
else
grid[i][j] = '┼';
}
}
}
public void print(){
for(int i=0; i<height; i++){
for(int j=0; j<width; j++)
System.out.print(grid[i][j]);
System.out.println();
}
}
Below is the put function of the board class. The problem is the put function. You must enter a line from the selectline function and have the player appear on the desired line.
However, no matter how hard I modify the conditional statement, it only appears in the first line.
How do I modify the conditional statement of the put function?
public void put(SelectLine setLine) {
int y=setLine.getY();
int x = grid.length-1;
if(count%2 == 0) {
player = '●';
}
else {
player = '○';
}
for(int i = grid.length-1; i >=0; i--) {
if(grid[i][(y-1)*2] != player) {
grid[i][(y-1)*2] = player;
count++;
break;
}
}
System.out.println("────────" + player + "'s Turn ────────");
this.print();
}
}
public class SelectLine {
int line;
public void input(){
System.out.print("Select Line : ");
Scanner sc = new Scanner(System.in);
line = sc.nextInt();
}
public int getY(){
return line;
}
}
The goal is to keep stacking up like the picture below.
enter image description here
Modify your SelectLine class as follows:
class SelectLine {
int line;
public int input(){
System.out.print("Select Line : ");
Scanner sc = new Scanner(System.in);
line = sc.nextInt();
return line;
}
public int getY(){
return input();
}
Working code:
https://onlinegdb.com/ryhum-Eu_
You need to take into account that a user may input negative values or such exceeding grid size, though.
Regards.
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Board b = new Board(10, 10);
b.print();
b.put(new SelectLine());
System.out.println("Hello World");
}
}
class Board {
char[][] grid;
int width;
int height;
int count;
char player;
public Board(int height, int width){
count = 0;
grid = new char[height][width];
this.width = width;
this.height = height;
for(int i = 0; i < height; i++) {
for(int j = 0; j < width; j++){
if(i == 0 && j == 0){
grid[i][j] = '┌';
}
else if(j % 2 == 1) {
grid[i][j] = '─';
}
else if (i == 0 && j == width - 1){
grid[i][j] = '┐';
}
else if (i == height-1 && j == 0){
grid[i][j] = '└';
}
else if (i == height - 1 && j == width - 1){
grid[i][j] = '┘';
}
else if (i == 0){
grid[i][j] = '┬';
}
else if (j == 0){
grid[i][j] = '├';
}
else if (i == height - 1){
grid[i][j] = '┴';
}
else if (j == width - 1){
grid[i][j] = '┤';
}
else
grid[i][j] = '┼';
}
}
}
public void print(){
for(int i=0; i<height; i++){
for(int j=0; j<width; j++)
System.out.print(grid[i][j]);
System.out.println();
}
}
public void put(SelectLine setLine) {
int y=setLine.getY();
int x = grid.length-1;
if(count%2 == 0) {
player = '●';
}
else {
player = '○';
}
for(int i = grid.length-1; i >=0; i--) {
if(grid[i][(y-1)*2] != player) {
grid[i][(y-1)*2] = player;
count++;
break;
}
}
System.out.println("────────" + player + "'s Turn ────────");
this.print();
}
}
class SelectLine {
int line;
public int input(){
System.out.print("Select Line : ");
Scanner sc = new Scanner(System.in);
line = sc.nextInt();
return line;
}
public int getY(){
return input();
}
}
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;
}
}
}
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.
This is a class that creates the game connect four in console and drawing panel, and I am having trouble in the connectedFour method where it determines if someone has gotten 4 discs in a row. The problem is, is that I am not sure how to set up my for loops to check through the array for four discs in a row
Here is my code:
import java.util.*;
import java.awt.*;
public class ConnectFour{
public static void main(String[] args){
//board
DrawingPanel panel = new DrawingPanel(550,550);
int rowAvailable;
Graphics g = panel.getGraphics();
g.drawLine(0,0,0,500);
g.drawLine(0,0,500,0);
g.drawLine(500,0,500,427);
g.drawLine(0,427,500,427);
for(int i = 0; i< 6; i++){
for(int j= 0; j<= 6; j++){
g.setColor(Color.YELLOW);
g.fillRect(j*71,i*71,71,71);
g.setColor(Color.WHITE);
g.fillOval(j*71,i*71,71,71);
}
}
//setBlankArray
Scanner console = new Scanner(System.in);
char[][] board = new char[6][7];
for(int j = 0;j <= 6; j++){
for(int i= 0; i < 6; i++){
board[i][j] = ' ';
}
}
boolean isBlack = true;
boolean isRed = false;
int column = 0;
boolean playersTurn = true;
boolean rightNum = false;
//oneTurn
while(getWinner(board, playersTurn)){
//while(playersTurn == true){
rightNum = false;
if(isBlack == true){
// displayCurrentPlayer
System.out.println("Black's Turn");
g.setColor(Color.WHITE);
g.drawString("Red Disc's Turn",200, 450);
g.setColor(Color.BLACK);
g.drawString("Black Disc's Turn",200, 450);
}
else{
// displayCurrentPlayer
System.out.println("Red's Turn");
g.setColor(Color.WHITE);
g.drawString("Black Disc's Turn",200, 450);
g.setColor(Color.RED);
g.drawString("Red Disc's Turn",200, 450);
}
System.out.print("Choose a column to place your disk (1-7): ");
while(rightNum == false){
column = (console.nextInt()) -1;
if(column >= 0 && column < 7 && board[0][column] == ' '){
rightNum = true;
}
else{
System.out.print("Try again: ");
}
}
drawBoard(column, board, isBlack, isRed, board, g);
isBlack = !isBlack;
}
if(isBlack == false){System.out.println("Congratulations Black Player");}
else{System.out.println("Congratulations Red Player");}
// use the while loop to say try again if the column is filled.
}
public static void drawBoard(int column, char[][] board, boolean isBlack, boolean isRed, char[][] availability,Graphics g){
char player = ' ';
if(isBlack == true){
g.setColor(Color.BLACK);
player = 'b';
}
else{
g.setColor(Color.RED);
player = 'r';
}
int x = 0;
int row = 5;
while(board[row-x][column] != ' '){
x++;
}
row = row-x;
g.fillOval((column * 71),(row * 71), 71,71);
board[row][column] = player;
}
public static boolean getWinner(char[][] board, boolean playersTurn){
int verticalCount = 0;
boolean isVertical = false;
for(int i = 6; i >= 0; i--){
verticalCount = 0;
for(int j = 5; j > 0; j--){
if(board[j][i] == board[j-1][i] && board[j][i] != ' '){
verticalCount++;
}
if(verticalCount == 4){
isVertical = true;
}
}
}
int horizontalCount = 0;
boolean isHorizontal = false;
for(int i =1; i <= 5; i++){
for(int j =1; j<6; j++){
if(board[j][i] == board[j][i+1] && board[j][i] != ' '){
horizontalCount++;
}
if(horizontalCount == 3){
isHorizontal = true;
}
}
}
int diagonalCount = 0;
boolean isDiagonal = false;
// for(int i = 0; i<=6; i++){
// for(int j =0; j<6; j++){
// if(board[i][j-1] == board[i][j]){
// diagonalCount++;
// }
// }
// }
if(isVertical || isHorizontal || isDiagonal){
playersTurn = false;
}
else{
playersTurn = true;}
return playersTurn;
}
}
I would implement this by checking if the game-winning condition is met after a disc has been placed. This way you aren't iterating over the entire board after each move.
Regardless, try this:
replace
while (gameWon == false ){
with
while (!connectedFour(board, playersTurn)) {
I don't think this will completely fix your problems as it looks like there are a handful of other things wrong with the code you've posted.
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...