How to keep track of winner in Connect Four Java game - java

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.

Related

How to output players normally in the connect four game

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();
}
}

Check for win in four in a row

I coded this to check if someone won, but it looks like it will only check for if someone won by horizontal, any ideas to check if someone won by vertical and diagonal?
public boolean checkForVictory() {
int xInRow = 0;
int oInRow = 0;
boolean playerOneWins = false;
boolean playerTwoWins = false;
//loop through the map and check if every cell contains x or o and then add the number. If in the next cell is another character, then put it back to 0
for(int i=0; i<7; i++){
for(int j=0; j<6; j++){
if(j == 0){
xInRow = 0;
oInRow = 0;
}
if(Map.getInstance().map[i][j].contains("x")){
xInRow++;
oInRow = 0;
}
if(Map.getInstance().map[i][j].contains("o")){
oInRow++;
xInRow = 0;
}
if(xInRow == 4)
playerOneWins = true;
if(oInRow == 4)
playerTwoWins = true;
}
}
if(playerOneWins){
GameModel.getInstance().player1.playerVictory = true;
return true;
}
if(playerTwoWins){
GameModel.getInstance().player2.playerVictory = true;
return true;
}
return false;
}

Assistance with Tic Tac Toe program

I've been working on for awhile but i can't seem to fix it and get it to wrong correctly. It tells me where the exception is but I don't see any problems.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at TicTacToe.displayWinner(TicTacToe.java:243)
at TicTacToe.playerMove(TicTacToe.java:151)
at TicTacToe.playGame(TicTacToe.java:303)
at TicTacToeTester.main(TicTacToeTester.java:20)
Java Result: 1
import java.util.Scanner; //Used for player's input in game
public class TicTacToe
{
//instance variables
private char[][] board; //Tic Tac Toe Board, 2d array
private boolean xTurn; // true when X's turn, false if O's turn
private Scanner input; // Scanner for reading input from keyboard
//Constants for creation of gameboard
public final int ROWS = 3; //total rows
public final int COLS = 3; //total columns
public final int WIN = 3; //amount needed to win
public TicTacToe()
{
//creates the board
board = new char[ROWS][COLS];
for(int r = 0; r < ROWS; r++)
{
for(int c = 0; c < COLS; c++)
{
board[r][c] = ' ';
}
}
//X's turn when game starts
xTurn = true;
//creates our input object for the turn player
input = new Scanner(System.in);
}
//shows game board
public void displayBoard()
{
int colNum = 0; //number of columns
int rowNum = 0; //number of rows
//creates column labels
System.out.println(" \n");
System.out.println(" Columns ");
for (int num = 0; num < COLS; num++)
{
System.out.print(" " + colNum);
colNum++;
}
//creates vertical columns and spaces between each spot
System.out.println(" \n");
for (int row = 0; row < ROWS; row++)
{
//numbers rows
System.out.print(" " + rowNum + " ");
rowNum++;
for (int col = 0; col < COLS; ++col)
{
System.out.print(board[row][col]); // print each of the cells
if (col != COLS - 1)
{
System.out.print(" | "); // print vertical partition
}
}
System.out.println();
//creates seperation of rows
if (row != ROWS - 1)
{
System.out.println(" ------------"); // print horizontal
partition
}
}
//labels row
System.out.println("Rows \n");
}
//displays turn player
public void displayTurn()
{
if (xTurn)
{
System.out.println("X's Turn");
}
else
{
System.out.println("O's Turn");
}
}
//allows you to make move
public boolean playerMove()
{
boolean invalid = true;
int row = 0;
int column = 0;
while(invalid)
{
System.out.println("Which row (first) then column (second)
would you like to \n"
+ "play this turn? Enter 2 numbers between 0-2 as \n"
+ "displayed on the board, seperated by a space to
\n"
+ "choose your position.");
row = input.nextInt();
column = input.nextInt();
//checks if spot is filled
if (row >= 0 && row <= ROWS - 1 &&
column >= 0 && column <= COLS - 1)
{
if (board[row][column] != ' ')
{
System.out.println("Spot is taken \n");
}
else
{
invalid = false;
}
}
else
{
System.out.println("Invalid position");
}
//fills spot if not taken
if (xTurn)
{
board[row][column] = 'X';
}
else
{
board[row][column] = 'O';
}
}
return displayWinner(row,column);
}
public boolean displayWinner(int lastR, int lastC)
{
boolean winner = false;
int letter = board[lastR][lastC];
//checks row for win
int spotsFilled = 0;
for (int c = 0; c < COLS; c++)
{
if(board[lastR][c] == letter)
{
spotsFilled++;
}
}
if (spotsFilled == WIN)
{
winner = true;
if (xTurn)
{
System.out.println("X won");
displayBoard();
}
else
{
System.out.println("O won");
displayBoard();
}
}
//checks columns for win
spotsFilled = 0;
for (int r = 0; r < ROWS; r++)
{
if(board[r][lastC] == letter)
{
spotsFilled++;
}
}
if (spotsFilled == WIN)
{
winner = true;
if (xTurn)
{
System.out.println("X won");
displayBoard();
}
else
{
System.out.println("O won");
displayBoard();
}
}
//checks diagonals for win
spotsFilled = 0;
for (int i = 0; i < WIN; i++)
{
if(board[i][i] == letter)
{
spotsFilled++;
}
}
if(spotsFilled == WIN)
{
winner = true;
if (xTurn)
{
System.out.println("X won");
displayBoard();
}
else
{
System.out.println("O won");
displayBoard();
}
}
//checks other diagonal
spotsFilled = 0;
for(int i = 0; i < WIN; i++)
{
if(board[i][COLS-i] == letter)
{
spotsFilled++;
}
}
if(spotsFilled == WIN)
{
winner = true;
if (xTurn)
{
System.out.println("X won");
displayBoard();
}
else
{
System.out.println("O won");
displayBoard();
}
}
return winner;
}
//checks if board is full
public boolean fullBoard()
{
int filledSpots = 0;
for(int r = 0; r < ROWS; r++)
{
for (int c = 0; c < COLS; c++)
{
if (board[r][c] == 'X' || board[r][c] == 'O')
{
filledSpots++;
}
}
}
return filledSpots == ROWS*COLS;
}
//plays game
public void playGame()
{
boolean finish = true;
System.out.println("Are your ready to start?");
System.out.println("1 for Yes or 0 for No? : ");
int choice = input.nextInt();
if (choice == 1)
{
while (finish)
{
displayBoard();
displayTurn();
if (playerMove())
{
displayBoard();
}
else if (fullBoard())
{
displayBoard();
System.out.println("Draw");
}
else
{
xTurn=!xTurn;
}
}
}
}
}
my tester
public class TicTacToeTester {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
TicTacToe tictactoe = new TicTacToe();
tictactoe.playGame();
}
}
Your Player Move method has an issue take a look at this if you notice you have commented saying "// fills spot when not taken" but you misplaced the while loop bracket and included move part inside it so it threw that exception, just close the while loop bracket before moving as follows (also follow #oblivion Creations Answer these are the two issues with your code) :-
public boolean playerMove()
{
boolean invalid = true;
int row = 0;
int column = 0;
while (invalid)
{
System.out.println("Which row (first) then column (second)" + "would you like to \n"
+ "play this turn? Enter 2 numbers between 0-2 as \n"
+ "displayed on the board, seperated by a space to" + "\n" + "choose your position.");
row = input.nextInt();
column = input.nextInt();
// checks if spot is filled
if (row >= 0 && row <= ROWS - 1 && column >= 0 && column <= COLS - 1)
{
if (board[row][column] != ' ')
{
System.out.println("Spot is taken \n");
}
else
{
invalid = false;
}
}
else
{
System.out.println("Invalid position");
}
} // close while loop here
// fills spot if not taken
if (xTurn)
{
board[row][column] = 'X';
}
else
{
board[row][column] = 'O';
}
return displayWinner(row, column);
}
The reason you are getting your exception is this section of code inside your displayWinner method:
//checks other diagonal
spotsFilled = 0;
for(int i = 0; i < WIN; i++)
{
if(board[i][COLS-i] == letter)
{
spotsFilled++;
}
}
When i = 0 then COLS-i will be 3. This is outside the bounds of your array.
There are multiple ways to solve this, one would be to increase i by 1 during comparison.
//checks other diagonal
spotsFilled = 0;
for(int i = 0; i < WIN; i++)
{
if(board[i][COLS-(i+1)] == letter)
{
spotsFilled++;
}
}
Edit: also make sure you check out Null Saints answer, as it will cause you headaches later if you don't address it now.

Determining a winner in a NXN Tic Tac Toe game

I've tried to create a Tic Tac Toe game class with the play and hasWon methods.
public class TicTacToe {
private enum State{Blank, X, O}
private int grid;
private State[][] board = new State[grid][grid];
private int moves;
//Default Constructor
public TicTacToe(int grid){
board = new State[grid][grid];
moves = 0;
}
public void play(State s, int m, int n){
if (board[m][n] == State.Blank){
board[m][n] = s;
}
moves++;
}
public boolean hasWon(State[][] board){
//check winner in rows
boolean state = false;
int j = 0;
int i = 0;
while(j <= grid) {
for (i = 0; i <= grid; i++) {
if (board[j][i] == board[j][i + 1])
state = true;
else state = false;
break;
}
if(state == false)
j++;
else return true;
}
//check winner in columns
while(j <= grid) {
for (i = 0; i < grid; i++) {
if (board[i][j] == board[i + 1][j])
state = true;
else state = false;
break;
}
if (state == true)
j++;
else return true;
}
//check winner in top diagonal
while(j <= grid && i <= grid){
if (board[i][j] == board[i+1][j+1])
state = true;
else state = false;
break;
i++;
j++;
return true;
}
//check winner in bottom diagonal
int k = grid;
int l = grid;
while(k >= 0 && l >= 0){
if (board[k][l] == board[k-1][l-1])
state = true;
else state = false;
break;
k--;
l--;
return true;
}
return false;
}
}
However when called in the Main class the program behaves erratically. Is there a logical problem in the code.
When checking your rows with
for (i = 0; i < n; i++) {
if (board[j][i] == board[j][i + 1])
state = true;
}
this code always sets the state to true if the last two chars in the row are the same, independently of the chars previous in that row.
The same thing for columns and the diagonal (of which you are checking only as Todd said).
You want to stop comparing values for that row if you find some values that are not equal:
for (i = 0; i < n; i++) {
if (board[j][i] == board[j][i + 1]) {
state = true;
} else {
state = false;
break;
}
}
Same for rows and diagonal(s).
Edit:
Furthermore: You are not setting your field grid in the constructor, so it always is 0 and you are not checking your complete rows, columns, diagonals
Missing:
this.grid = grid;

Access Denied? JAVA

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.

Categories