The output will output a "You Won" or "You Lose" into a file more than once. Pressing enter to reset the game resets everything, but will not continue adding a win or lose after the first time and before compiling again. Is there anything that can fix this?
Thank you in advance!
import java.awt.Color;
import java.awt.Font;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.ArrayList;
import java.io.PrintWriter;
/**
* Write a description of class Winner here.
* Added
* @author (your name)
* @version (a version number or a date)
*/
public class Winner extends World
{
private Table tworld;
private int p1Wins;
private int p2Wins;
ArrayList<String> win = new ArrayList<String>();
private PrintWriter output;
private File input;
private Scanner in;
private GreenfootImage image1 = new GreenfootImage("Winner.png");
/**
* Added
* Input/Output states if you won or lost
*/
public Winner(String letter, Table tw, int p1, int p2)throws FileNotFoundException
{
// Create a new world with 600x400 cells with a cell size of 1x1 pixels.
super(550, 400, 1);
tworld = tw; //represents the original world
p1Wins = p1;
p2Wins = p2;
setBackground(image1);
input = new File("text2.txt");
in = new Scanner(input); //created from our file object
while(in.hasNext())
{
win.add(in.nextLine());//red the line in
}
in.close(); //shutdown the scanner
output = new PrintWriter("text2.txt");
}
/**
* added
* updates the number of points when the game is over
*/
public void update(Table tw, int p1, int p2)
{
tworld = tw;
p1Wins = p1;
p2Wins = p2;
}
/**
* Added
* Sets the text on the screen
*/
public void fileWork()
{
GreenfootImage bg = new GreenfootImage(image1); //getting the original background image
setBackground(bg);
Color c = new Color(Greenfoot.getRandomNumber(256), Greenfoot.getRandomNumber(256), Greenfoot.getRandomNumber(256));
bg.setColor(c);
Font f = new Font("sample", Font.ITALIC, 20);
bg.setFont(f);
Color g = new Color(Greenfoot.getRandomNumber(256), Greenfoot.getRandomNumber(256), Greenfoot.getRandomNumber(256));
bg.setColor(g);
bg.drawString("Player = " + p1Wins, 210, 150);
bg.drawString("Computer = " + p2Wins, 200, 200);
bg.drawString("Press Enter To Play Again", 155, 300);
if(p1Wins > p2Wins)
{
bg.drawString("You Win! :)", 210, 250);
}
if(p2Wins > p1Wins)
{
bg.drawString("You lose :(", 210, 250);
}
if(p1Wins > p2Wins)
win.add("You Won!");
else
if(p1Wins < p2Wins)
win.add("You Lose!");
int j = 0;
for(String s : win)
{
output.println(win.get(j));
j++;
}
output.close();
}
/**
* Added
* Resets game
*/
public void act()
{
if(Greenfoot.isKeyDown("enter"))
{
Greenfoot.setWorld(tworld);
}
}
}