I'm working on an assignment where I have to solve a maze through backtracking (using a stack!) and the logic of the code is basically done, but the main problem is whenever I call pop() on my stack, it does not pop.So for now I have manually added (hardcoded) the parts in the maze where it is supposed to pop(). I am using my own stack that is using Linked Nodes and have ran JUnit and Main tests and it does indeed work (doubting myself here now). I have also used the Java stack and I get the same result.
Here is my code logic: As you can see in the method mazeSolver, at the bottom, I have a few if statements that check if i (operations performed) is at a certain point and it will "backtrack", but I am manually setting the position. The very last else statement is the part where I pop(). Any help would very much be appreciated.
public class MazeSolver {
private char[][] printMaze;
private char[][] solveMaze;
public MazeSolver() {
super();
}
private class Position {
private int x;
private int y;
Position(int y, int x) {
this.x = x;
this.y = y;
}
public int getX() {
return this.x;
}
public int getY() {
return this.y;
}
public void setX(int x) {
this.x = x;
}
public void setY(int y) {
this.y = y;
}
}
public boolean solve(boolean printUpdates) {
char space = ' ';
Stack<Position> stack = new Stack<Position>();
//Stack stack = new Stack();
Position cp = new Position(1, 0);
boolean done = true;
char c = 'C';
char x = 'X';
int i = 0;
while (done) {
// check right
if (printMaze[cp.getY()][cp.getX() + 1] == space && printMaze[cp.getY()][cp.getX() + 1] != x) {
cp.setX(cp.getX() + 1);
stack.push(cp);
printMaze[cp.getY()][cp.getX()] = 'C';
}
// check bottom
else if (printMaze[cp.getY() + 1][cp.getX()] == space && printMaze[cp.getY() + 1][cp.getX()] != x
&& printMaze[cp.getY() + 1][cp.getX()] != x) {
cp.setY(cp.getY() + 1);
stack.push(cp);
printMaze[cp.getY()][cp.getX()] = 'C';
}
// check top
else if (printMaze[cp.getY() - 1][cp.getX()] == space && printMaze[cp.getY() - 1][cp.getX()] != x) {
cp.setY(cp.getY() - 1);
stack.push(cp);
printMaze[cp.getY()][cp.getX()] = 'C';
}
// check left
else if (printMaze[cp.getY()][cp.getX() - 1] == space && printMaze[cp.getY()][cp.getX() - 1] != x) {
cp.setX(cp.getX() - 1);
stack.push(cp);
printMaze[cp.getY()][cp.getX()] = 'C';
}
//else {
/*
if (i == 6) {
printMaze[cp.getY()][cp.getX()] = 'X';
cp.setY(1);
cp.setX(5);
} else if (i == 27) {
printMaze[cp.getY()][cp.getX()] = 'X';
cp.setY(1);
cp.setX(20);
}
else if (i == 37) {
printMaze[cp.getY()][cp.getX()] = 'X';
cp.setY(2);
cp.setX(18);
}
else if (i == 68) {
printMaze[cp.getY()][cp.getX()] = 'X';
cp.setY(13);
cp.setX(22);
} else if (i == 69) {
printMaze[cp.getY()][cp.getX()] = 'X';
cp.setY(14);
cp.setX(22);
}
else if (i == 70) {
printMaze[cp.getY()][cp.getX()] = 'X';
cp.setY(15);
cp.setX(22);
} else if (i == 71) {
printMaze[cp.getY()][cp.getX()] = 'X';
cp.setY(16);
cp.setX(22);
} else if (i == 72) {
printMaze[cp.getY()][cp.getX()] = 'X';
cp.setY(17);
cp.setX(22);
} else if (i == 103) {
printMaze[cp.getY()][cp.getX()] = 'X';
cp.setY(21);
cp.setX(31);
} */else {
printMaze[cp.getY()][cp.getX()] = 'X';
stack.pop();
cp.setY(((Position) stack.top()).getY());
cp.setX(((Position) stack.top()).getX());
}
//}
i++;
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
// System.out.println(stack.top().getX() + ", " + stack.top().getY());
System.out.println(cp.getY() + ", " + cp.getX() + " i = " + i);
printMaze();
}
System.out.println("success");
return false;
}
public void printMaze() {
for (int i = 0; i < printMaze.length; i++) {
for (int j = 0; j < printMaze[i].length; j++) {
System.out.print(printMaze[i][j]);
}
System.out.println("");
}
}
public boolean loadMaze(String filename) {
BufferedReader br = null;
FileReader fr = null;
ArrayList<String> lines = new ArrayList<String>();
try {
fr = new FileReader(filename);
br = new BufferedReader(fr);
String line;
br = new BufferedReader(new FileReader(filename));
while ((line = br.readLine()) != null) {
lines.add(line);
}
printMaze = new char[lines.size()][];
solveMaze = new char[lines.size()][];
for (int i = 0; i < lines.size(); i++) {
printMaze[i] = new char[lines.get(i).length()];
solveMaze[i] = new char[lines.get(i).length()];
for (int j = 0; j < lines.get(i).length(); j++) {
solveMaze[i][j] = lines.get(i).charAt(j);
printMaze[i][j] = lines.get(i).charAt(j);
if (solveMaze[i][j] == 'S') {
// hint you need to do this but you do not have the
// instance variable yet
// start = new Position(i, j);
}
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)
br.close();
if (fr != null)
fr.close();
} catch (IOException ex) {
return false;
}
}
return true;
}
Here is my stack implementation if interested.
public class Stack<Item> implements StackInterface<Item> {
private int size;
private class Link {
private Item data;
public Link next;
public Link(Item data, Link next) {
this.data = data;
this.next = next;
}
public Item getData() {
return data;
}
}
private Link topStackLink = null;
public Stack() {
this.size = 0;
}
#Override
public void push(Item item) {
if (topStackLink == null) {
topStackLink = new Link(item, null);
} else {
topStackLink = new Link(item, topStackLink);
}
this.size++;
}
#Override
public void pop() {
// TODO Auto-generated method stub
if (topStackLink != null) {
topStackLink = topStackLink.next;
this.size--;
} else {
throw new java.util.EmptyStackException();
}
}
#Override
public Item top() {
if (topStackLink != null) {
return topStackLink.data;
} else {
throw new java.util.EmptyStackException();
}
}
#Override
public Item topAndPop() {
// TODO Auto-generated method stub
if (topStackLink != null) {
Item item = topStackLink.data;
pop();
return item;
} else {
throw new java.util.EmptyStackException();
}
}
#Override
public boolean isEmpty() {
if (topStackLink == null) {
return true;
} else {
return false;
}
}
#Override
public void makeEmpty() {
// TODO Auto-generated method stub
topStackLink = null;
this.size = 0;
}
#Override
public int size() {
return this.size;
}
I have made a reset button which doesn't take away the focus of the KeyListener so that the game could still be playable after the clicking of the button. The rest of the button is all about resetting locations, emptying arraylists and arrays and so on. But it seems like whenever I click the restart button, the player object does go to its starting point, x = 2 y = 0. But after that whenever I make a move I see the man object/picture move to the position in was in before so the restart button isn't working at all. The player object is actually still at the location in which it stood when the restart button was clicked. I have read that there might be a second panel added beneath and thus the real panel not changing? I'm not sure and require your help.
My question specific: Why does the reset button not suffice for the changing of the player/man objects location, why is it failing?
package riddle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class GameFrame extends JFrame {
private JPanel p2;
private JButton reset;
private GameDraw component;
private Man m;
public GameFrame() {
this.setTitle("Riddle Man");
this.setSize(719, 850);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
component = new GameDraw();
m = new Man(component);
component.addKeyListener(m);
component.requestFocus();
createButton();
createPanel();
}
private void createButton() {
reset = new JButton("Restart");
ActionListener listener = new ClickListener();
reset.addActionListener(listener);
}
private void createPanel() {
p2 = new JPanel();
p2.setLayout(null);
component.setBounds(0, 0, 800, 800);
reset.setBounds(0, 725, 100, 50);
p2.add(component);
p2.add(reset);
add(p2);
}
class ClickListener implements ActionListener {
public ClickListener(){
}
#Override
public void actionPerformed(ActionEvent e) {
reset.setFocusable(false);
component.resetGame();
}
}
}
package riddle;
import org.apache.commons.lang3.StringUtils;
import java.awt.Color;
import static java.awt.Frame.NORMAL;
import java.util.ArrayList;
import java.util.Arrays;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
public class GameField {
public String[][] field;
private String grass, wall, note, end, theRiddle, theAnswer;
private ArrayList<Integer> arrayG;
private ArrayList<Integer> arrayW;
private ArrayList<Integer> arrayN;
private ArrayList<Integer> arrayE;
private Riddle riddle;
private int instantRight, count, wrongs, retries;
private boolean ok = false;
public GameField() {
field = new String[10][10];
grass = "Grass";
wall = "Wall";
note = "Note";
end = "End";
theRiddle = "";
theAnswer = "";
instantRight = 0;
count = 0;
wrongs = 0;
retries = 0;
arrayG = new ArrayList<Integer>(Arrays.asList(0, 9, 10, 19, 20, 29, 30, 39, 40, 49, 50, 59, 60, 69, 70, 79, 80, 89, 90, 99));
arrayW = new ArrayList<Integer>(Arrays.asList(1, 3, 4, 5, 6, 7, 8, 11, 18, 21, 22, 23, 24, 25, 26, 28, 31, 38, 41, 43, 44, 45, 46, 47, 48, 51, 58, 61, 62, 63, 64, 65, 66, 68, 71, 78, 81, 83, 84, 85, 86, 87, 88, 91, 98));
arrayN = new ArrayList<Integer>(Arrays.asList(17, 35, 32, 54, 57, 76, 72, 94));
arrayE = new ArrayList<Integer>(Arrays.asList(97));
riddle = new Riddle();
fillField();
}
public String checkField(int x, int y) {
String result = "";
if (field[y][x] == "Wall") {
result = wall;
} else if (field[y][x] == "Note") {
result = note;
} else if (field[y][x] == "End") {
result = end;
endGame();
}
return result;
}
private void fillField() {
int k = 0;
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
if (arrayG.contains(k)) {
field[i][j] = grass;
} else if (arrayW.contains(k)) {
field[i][j] = wall;
} else if (arrayN.contains(k)) {
field[i][j] = note;
} else if (arrayE.contains(k)) {
field[i][j] = end;
}
k++;
}
}
}
public void setField(int x, int y) {
field[x][y] = null;
}
public boolean riddleTime() {
boolean check = false;
theRiddle = riddle.generateRiddle();
theAnswer = riddle.getAnswer();
while (!check) {
check = checkReply(theRiddle, theAnswer);
}
return check;
}
public boolean checkReply(String question, String answer) {
ImageIcon image = new ImageIcon(this.getClass().getResource("/resources/bad.png"));
ImageIcon image2 = new ImageIcon(this.getClass().getResource("/resources/good.png"));
String[] option = {"Yes", "Quit"};
String reply = JOptionPane.showInputDialog(question);
if (reply.contains(answer.toLowerCase()) || reply.contains(StringUtils.capitalize(answer)) || reply.contains(answer.toUpperCase())) {
JOptionPane.showMessageDialog(null, riddle.getResponseC(), "", NORMAL, image2);
ok = true;
if (count == 0) {
instantRight++;
} else {
count = 0;
}
} else {
wrongs++;
int selectedValue = JOptionPane.showOptionDialog(null, riddle.getResponseW(), "", JOptionPane.YES_NO_OPTION, JOptionPane.YES_NO_OPTION, image, option, NORMAL);
if (selectedValue == JOptionPane.YES_OPTION) {
checkReply(question, answer);
retries++;
}
if (selectedValue == JOptionPane.NO_OPTION) {
System.exit(0);
}
count++;
}
return ok;
}
private void endGame() {
ImageIcon bad = new ImageIcon(this.getClass().getResource("/resources/endingbad.png"));
ImageIcon good = new ImageIcon(this.getClass().getResource("/resources/endinggood.png"));
ImageIcon info = new ImageIcon(this.getClass().getResource("/resources/info.png"));
if (instantRight >= 6) {
JOptionPane.showMessageDialog(null, "", "", NORMAL, good);
JOptionPane.showMessageDialog(null, "<html><center><br><br>Instant Rights: " + instantRight + "\n" + "\n" + "Wrongs: " + wrongs + "\n" + "\n" + "Retries: " + retries + "\n" + "\n" + " Wisdom Level: " + indicate(instantRight, wrongs, retries), " Statistics", NORMAL, info);
} else {
JOptionPane.showMessageDialog(null, "", "", NORMAL, bad);
JOptionPane.showMessageDialog(null, "\n" + "Instant Rights: " + instantRight + "\n" + "\n" + "Wrongs: " + wrongs + "\n" + "\n" + "Retries: " + retries + "\n" + "\n" + " Wisdom Level: " + indicate(instantRight, wrongs, retries), " Statistics", NORMAL, info);
}
}
public String indicate(int instantRight, int wrongs, int retries) {
String level = "";
if (instantRight >= 6 && wrongs <= 4 && retries <= 4) {
level = "HIGH";
} else if (instantRight <= 3 && wrongs > 6 && retries > 6) {
level = "LOW";
} else {
level = "AVERAGE";
}
return level;
}
public void resetGame(){
fillField();
riddle.resetGame();
instantRight = 0;
wrongs = 0;
retries = 0;
count = 0;
}
}
package riddle;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.JComponent;
public class GameDraw extends JComponent {
private int rows;
private int columns;
private int RWIDTH;
private int RHEIGHT;
private int manX;
private int manY;
private BufferedImage man, grass, wall, note, end;
private Man m;
private GameField f;
public GameDraw() {
//Integer variables
rows = 9;
columns = 9;
RWIDTH = 70;
RHEIGHT = 70;
manX = 2;
manY = 0;
f = new GameField();
m = new Man(this);
this.setFocusable(true);
URL resourceMan = this.getClass().getResource("/resources/man.png");
try {
man = ImageIO.read(resourceMan);
} catch (IOException e) {
System.out.println("Er ging iets mis met het laden van de afbeelding van de speler");
}
}
#Override
public void paintComponent(Graphics g) {
drawField(g);
drawMan(g);
drawObjects(g);
}
private void drawField(Graphics g) {
int x = 0;
int y = 0;
Color lightgray = new Color(192, 192, 192);
for (int i = 0; i < rows + 1; i++) {
for (int j = 0; j < columns; j++) {
g.setColor(lightgray);
g.fillRect(x, y, RWIDTH, RHEIGHT);
x += RWIDTH;
}
g.setColor(lightgray);
g.fillRect(x, y, RWIDTH, RHEIGHT);
x = 0;
y += RHEIGHT;
}
}
private void drawMan(Graphics g) {
g.drawImage(man, manX * RWIDTH, manY * RHEIGHT, RWIDTH, RHEIGHT, this);
}
public void moveMan(int x, int y) {
manX = x;
manY = y;
repaint();
System.out.println(manX + " " + manY);
}
private void drawObjects(Graphics g) {
URL resourceGrass = this.getClass().getResource("/resources/Grassy.png");
URL resourceWall = this.getClass().getResource("/resources/wall.png");
URL resourceNote = this.getClass().getResource("/resources/note.png");
URL resourceEnd = this.getClass().getResource("/resources/chest.png");
//Grass object
try {
grass = ImageIO.read(resourceGrass);
wall = ImageIO.read(resourceWall);
note = ImageIO.read(resourceNote);
end = ImageIO.read(resourceEnd);
} catch (IOException e) {
System.out.println("Er ging iets mis met het laden van de afbeelding van de speler");
}
for (int j = 0; j < rows + 1; j++) {
for (int i = 0; i < columns + 1; i++) {
if (f.field[i][j] == "Grass") {
g.drawImage(grass, j * RWIDTH, i * RHEIGHT, RWIDTH, RHEIGHT, this);
}
if (f.field[i][j] == "Wall") {
g.drawImage(wall, j * RWIDTH, i * RHEIGHT, RWIDTH, RHEIGHT, this);
}
if (f.field[i][j] == "Note") {
g.drawImage(note, j * RWIDTH, i * RHEIGHT, RWIDTH, RHEIGHT, this);
}
if (f.field[i][j] == "End") {
g.drawImage(end, j * RWIDTH, i * RHEIGHT, RWIDTH, RHEIGHT, this);
}
}
}
}
public void repaintField(int x, int y) {
f.field[x][y] = null;
repaint();
}
public void resetGame(){
f.resetGame();
m.resetGame();
System.out.println(manX + " " + manY);
}
}
package riddle;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class Man implements KeyListener {
private int locationX;
private int locationY;
private GameDraw draw;
private GameField field;
public Man(GameDraw draw) {
locationX = 2;
locationY = 0;
this.draw = draw;
field = new GameField();
}
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
String check;
boolean pass;
switch (key) {
case KeyEvent.VK_UP:
locationY--;
if (locationY < 0) {
locationY++;
}
check = field.checkField(locationX, locationY);
if (!"Wall".equals(check) && !"Note".equals(check) && !"End".equals(check)) {
draw.moveMan(locationX, locationY);
} else if (check.equals("Wall") || check.equals("End")) {
locationY++;
} else if (check.equals("Note")) {
pass = field.riddleTime();
if (pass) {
clearNote(locationX, locationY);
draw.moveMan(locationX, locationY);
} else {
locationY++;
}
}
break;
case KeyEvent.VK_DOWN:
locationY++;
if (locationY > 9) {
locationY--;
}
check = field.checkField(locationX, locationY);
if (!"Wall".equals(check) && !"Note".equals(check) && !"End".equals(check)) {
draw.moveMan(locationX, locationY);
}
if (check.equals("Wall") || check.equals("End")) {
locationY--;
} else if (check.equals("Note")) {
pass = field.riddleTime();
if (pass) {
clearNote(locationX, locationY);
draw.moveMan(locationX, locationY);
} else {
locationY--;
}
}
break;
case KeyEvent.VK_LEFT:
locationX--;
;
check = field.checkField(locationX, locationY);
if (!"Wall".equals(check) && !"Note".equals(check) && !"End".equals(check)) {
draw.moveMan(locationX, locationY);
}
if (check.equals("Wall") || check.equals("End")) {
locationX++;
} else if (check.equals("Note")) {
pass = field.riddleTime();
if (pass) {
clearNote(locationX, locationY);
draw.moveMan(locationX, locationY);
} else {
locationX++;
}
}
break;
case KeyEvent.VK_RIGHT:
System.out.println(locationX + " " + locationY);
locationX++;
check = field.checkField(locationX, locationY);
if (!"Wall".equals(check) && !"Note".equals(check) && !"End".equals(check)) {
draw.moveMan(locationX, locationY);
}
if (check.equals("Wall") || check.equals("End")) {
locationX--;
} else if (check.equals("Note")) {
pass = field.riddleTime();
if (pass) {
clearNote(locationX, locationY);
draw.moveMan(locationX, locationY);
} else {
locationX--;
}
}
break;
default:
break;
}
}
#Override
public void keyReleased(KeyEvent e) {
}
public void clearNote(int x, int y) {
field.setField(y, x);
draw.repaintField(y, x);
}
public void resetGame(){
locationX = 2;
locationY = 0;
draw.moveMan(locationX, locationY);
System.out.println(locationX + " " + locationY);
}
}
package riddle;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;
public class Riddle {
private ArrayList<String> riddles;
private ArrayList<String> answers;
private ArrayList<String> correct;
private ArrayList<String> wrong;
private ArrayList<Integer> used;
private ArrayList<Integer> used2;
private Random ran;
private int indexAnswer;
public Riddle() {
riddles = new ArrayList<String>();
answers = new ArrayList<String>();
correct = new ArrayList<String>();
wrong = new ArrayList<String>();
used = new ArrayList<Integer>();
used2 = new ArrayList<Integer>();
ran = new Random();
fillRiddles();
fillAnswers();
fillCorrect();
fillWrong();
}
private void fillRiddles() {
Scanner sc2 = null;
try {
sc2 = new Scanner(new File("C:\\Users\\John\\Documents\\NetBeansProjects\\Riddle\\src\\resources\\riddles.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
while (sc2.hasNextLine()) {
Scanner s2 = new Scanner(sc2.nextLine());
while (s2.hasNext()) {
String s = s2.nextLine();
riddles.add(s);
}
}
}
private void fillAnswers() {
Scanner sc2 = null;
try {
sc2 = new Scanner(new File("C:\\Users\\John\\Documents\\NetBeansProjects\\Riddle\\src\\resources\\answers.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
while (sc2.hasNextLine()) {
Scanner s2 = new Scanner(sc2.nextLine());
while (s2.hasNext()) {
String s = s2.nextLine();
answers.add(s);
}
}
}
private void fillCorrect() {
Scanner sc2 = null;
try {
sc2 = new Scanner(new File("C:\\Users\\John\\Documents\\NetBeansProjects\\Riddle\\src\\resources\\correct.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
while (sc2.hasNextLine()) {
Scanner s2 = new Scanner(sc2.nextLine());
while (s2.hasNext()) {
String s = s2.nextLine();
correct.add(s);
}
}
}
private void fillWrong() {
Scanner sc2 = null;
try {
sc2 = new Scanner(new File("C:\\Users\\John\\Documents\\NetBeansProjects\\Riddle\\src\\resources\\wrong.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
while (sc2.hasNextLine()) {
Scanner s2 = new Scanner(sc2.nextLine());
while (s2.hasNext()) {
String s = s2.nextLine();
wrong.add(s);
}
}
}
public String generateRiddle() {
String theRiddle = "";
int index = ran.nextInt(riddles.size());
if (!used.contains(index)) {
theRiddle = riddles.get(index);
indexAnswer = index;
used.add(index);
} else {
theRiddle = generateRiddle();
}
return theRiddle;
}
public String getAnswer() {
String theAnswer = answers.get(indexAnswer);
return theAnswer;
}
public String getResponseC() {
String response = "";
int index = ran.nextInt(correct.size());
if (!used2.contains(index)) {
response = correct.get(index);
used2.add(index);
} else {
response = getResponseC();
}
return response;
}
public String getResponseW() {
String response = "";
int index = ran.nextInt(wrong.size());
response = wrong.get(index);
return response;
}
public void resetGame(){
riddles.clear();
answers.clear();
wrong.clear();
correct.clear();
used.clear();
used2.clear();
fillRiddles();
fillAnswers();
fillCorrect();
fillWrong();
indexAnswer = 0;
}
}
I have problem with this code for test this is the error error 1 error 2
and this is the code
first class
import java.util.LinkedList;
import java.util.List;
public class Position {
public char[] board;
public char turn;
public int dim =3;
private int l;
public Position() {
this.board = " ".toCharArray();
this.turn = 'x';
}
public Position(char[] board, char turn) {
this.board = board;
this.turn = turn;
}
public Position(String str) {
this.board = str.toCharArray();
this.turn = 'x';
}
public Position(String str, char turn) {
this.board = str.toCharArray();
this.turn = turn;
}
public String toString () {
return new String(board);
}
public Position move (int idx) {
char[] newBoard = board.clone();
newBoard[idx] = turn;
return new Position(newBoard, turn == 'x' ? 'o' :'x');
}
public Integer[] possibleMoves() {
List<Integer> list = new LinkedList<Integer>();
for (int i = 0; i < board.length; i++) {
if (board[i] == ' ') {
list.add(i);
}
}
Integer[] array = new Integer[list.size()];
list.toArray(array);
return array;
}
public boolean win_line(char turn, int start, int step) {
for (int i = 0; i < 3; i++) {
if (board[start + step*i] != turn) {
return false;
}
}
return true;
}
public boolean win(char turn) {
for (int i = 0; i < dim; i++) {
if (win_line(turn, i*dim, l) || win_line(turn, i,dim)) {
return true;
}
}
if (win_line(turn, dim-1, dim-1) || win_line(turn, 0, dim+1)) {
return true;
}
return false;
}
public int minimax() {
if (win('x')) { return 100; }
if (win('o')) { return -100; }
if (possibleMoves().length == 0) { return 0; }
Integer mm = null;
for (Integer idx : possibleMoves()) {
Integer value = move(idx).minimax();
if (mm == null || turn == 'x' && mm < value || turn == 'o' && value < mm) {
mm = value;
}
}
return mm + (turn == 'x' ? -1 : 1);
}
public int bestMove() {
Integer mm = null;
int best = -1;
for (Integer idx : possibleMoves()) {
Integer value = move(idx).minimax();
if (mm == null || turn == 'x' && mm < value || turn == 'o' && value < mm) {
mm = value;
best = idx;
}
}
return best;
}
public boolean gameEnd() {
return win('x') || win('o') || possibleMoves().length ==0;
}
}
Second class for test
import static org.junit.Assert.*;
import org.junit.Test;
public class PositionTest {
#Test
public void testNew() throws Exception {
Position position = new Position();
assertEquals(" ", position.toString());
assertEquals('x', position.turn);
}
#Test
public void testMove() throws Exception {
Position position = new Position().move(1);
assertEquals(" x ", position.toString());
assertEquals('o', position.turn);
}
#Test
public void testPossibleMoves() throws Exception {
Position position = new Position().move(1).move(3).move(4);
assertArrayEquals(new Integer[] {0,2,5,6,7,8}, position.possibleMoves());
}
#Test
public void testWin() throws Exception {
assertFalse(new Position().win('x'));
assertTrue(new Position("xxx ").win('x'));
assertTrue(new Position(" ooo ").win('o'));
assertTrue(new Position("x x x ").win('x'));
assertTrue(new Position(" x x x ").win('x'));
assertTrue(new Position("x x x").win('x'));
}
#Test
public void testMinimax() throws Exception {
assertEquals( 100, new Position("xxx ").minimax());
assertEquals(-100, new Position("ooo ").minimax());
assertEquals( 0, new Position("xoxoxooxo").minimax());
assertEquals( 99, new Position(" xx ").minimax());
assertEquals( -99, new Position(" oo ", 'o').minimax());
}
#Test
public void testBestMove() throws Exception {
assertEquals(0, new Position(" xx ").bestMove());
assertEquals(1, new Position("o o ", 'o').bestMove());
}
#Test
public void testGameEnd() throws Exception {
assertFalse(new Position().gameEnd());
assertTrue(new Position("xxx ").gameEnd());
}
}
third class
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
public class Game {
Position position;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame frame = new JFrame("Java TTT");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridLayout(3, 3));
final Game game = new Game();
final JButton[] buttons = new JButton[9];
for (int i =0; i < 9; i++) {
final int idx = i;
final JButton button = new JButton();
buttons[i] = button;
button.setPreferredSize(new Dimension(100,100));
button.setBackground(Color.BLACK);
button.setOpaque(true);
button.setFont(new Font(null, Font.PLAIN, 100));
button.addMouseListener(new MouseListener() {
public void mouseReleased(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
#Override
public void mouseClicked(MouseEvent e) {
button.setText("" + game.position.turn);
game.move(idx);
if (!game.position.gameEnd()){
int best = game.position.bestMove();
buttons[best].setText("" + game.position.turn);
game.move(best);
}
if (game.position.gameEnd()) {
String message = "";
if (game.position.win('x')) {
message = "You Won !!";
} else if (game.position.win('o')){
message = "Computer Won !!";
} else {
message = "Draw";
}
JOptionPane.showMessageDialog(null, message);
}
}});
frame.add(button);
}
frame.pack();
frame.setVisible(true);
}
});
}
protected void move(int idx) {
position = position.move(idx);
}
}
1- java.lang.AssertionError: array lengths differed, expected.length=6
actual.length=5
2-java.lang.AssertionError: expected:<0> but was:<100>
assertionsErrors within unit testcase runs are telling you that the actual result does not fit the expected one. thus your code does not work properly and you have to fix this.
please post the lines where these errors occurr.
I want to implement a native drag and drop of widgets of a FlexTable without using any third party library in GWT.Im looking for something similar to this
http://tech.pro/tutorial/688/javascript-tutorial-drag-drop-lists
this is in javascript i want to achieve the similar kind of functionality with GWT
I have looked into the answer provided by #BruceLowe over here
Making a drag and drop FlexTable in GWT 2.5
but its is missing a few classes namely DragVerticalHandler and DraggableWidget classes so the code is not working. Does anyone know how to achieve this
After a little Prototyping I was able to make a drag gable flextable.I created a class which extended the flex table.Here is the code
public class DragFlexTable extends FlexTable implements
MouseDownHandler,MouseUpHandler,MouseMoveHandler,
MouseOutHandler
{
private int row,column,draggedrow,draggedcolumn;
private Element td;
private Widget w;
private boolean emptycellclicked;
DragFlexTable()
{
sinkEvents(Event.ONMOUSEOVER | Event.ONMOUSEOUT | Event.ONMOUSEDOWN | Event.ONMOUSEMOVE);
this.addMouseDownHandler(this);
this.addMouseMoveHandler(this);
this.addMouseUpHandler(this);
this.addMouseOutHandler(this);
}
#Override
public void onBrowserEvent(Event event)
{
super.onBrowserEvent(event);
td = getEventTargetCell(event);
if (td == null)
{
return;
}
Element tr = DOM.getParent((com.google.gwt.user.client.Element) td);
Element body = DOM.getParent((com.google.gwt.user.client.Element) tr);
row = DOM.getChildIndex((com.google.gwt.user.client.Element) body, (com.google.gwt.user.client.Element) tr);//(body, tr);
column = DOM.getChildIndex((com.google.gwt.user.client.Element) tr, (com.google.gwt.user.client.Element) td);
}
boolean mousedown;
#Override
public void onMouseDown(MouseDownEvent event)
{
if (event.getNativeButton() == NativeEvent.BUTTON_LEFT)
{
//to ensure empty cell is not clciked
if (!td.hasChildNodes())
{
emptycellclicked = true;
}
event.preventDefault();
start(event);
mousedown = true;
}
}
#Override
public void onMouseMove(MouseMoveEvent event)
{
if (mousedown)
{
drag(event);
}
}
#Override
public void onMouseUp(MouseUpEvent event)
{
if (event.getNativeButton() == NativeEvent.BUTTON_LEFT)
{
if (!emptycellclicked)
{
end(event);
}
emptycellclicked = false;
mousedown = false;
}
}
#Override
public void onMouseOut(MouseOutEvent event)
{
this.getCellFormatter().getElement(row, column).getStyle().clearBorderStyle();
this.getCellFormatter().getElement(row, column).getStyle().clearBorderColor();
this.getCellFormatter().getElement(row, column).getStyle().clearBorderWidth();
w.getElement().getStyle().setOpacity(1);
mousedown = false;
}
private void start(MouseDownEvent event)
{
w = this.getWidget(row, column);
w.getElement().getStyle().setOpacity(0.5);
}
private void drag(MouseMoveEvent event)
{
if (draggedrow != row || draggedcolumn != column)
{
this.getCellFormatter().getElement(draggedrow, draggedcolumn).getStyle().clearBorderStyle();
this.getCellFormatter().getElement(draggedrow, draggedcolumn).getStyle().clearBorderColor();
this.getCellFormatter().getElement(draggedrow, draggedcolumn).getStyle().clearBorderWidth();
this.draggedrow = row;
this.draggedcolumn = column;
this.getCellFormatter().getElement(row, column).getStyle().setBorderStyle(BorderStyle.DASHED);
this.getCellFormatter().getElement(row, column).getStyle().setBorderColor("black");
this.getCellFormatter().getElement(row, column).getStyle().setBorderWidth(2, Unit.PX);
}
}
private void end(MouseUpEvent event)
{
insertDraggedWidget(row, column);
}
private void insertDraggedWidget(int r,int c)
{
this.getCellFormatter().getElement(r, c).getStyle().clearBorderStyle();
this.getCellFormatter().getElement(r, c).getStyle().clearBorderColor();
this.getCellFormatter().getElement(r, c).getStyle().clearBorderWidth();
w.getElement().getStyle().setOpacity(1);
if (this.getWidget(r, c) != null)
{
//pushing down the widgets already in the column
// int widgetheight = (this.getWidget(r, c).getOffsetHeight() / 2) + this.getWidget(r, c).getAbsoluteTop();
// int rw;
//placing the widget above the dropped widget
for (int i = this.getRowCount() - 1; i >= r; i--)
{
if (this.isCellPresent(i, c))
{
this.setWidget(i + 1, c, this.getWidget(i, c));
}
}
}
this.setWidget(r, c, w);
//removes unneccesary blank rows
cleanupRows();
//pushing up the column in the stack
// for (int i = oldrow;i<this.getRowCount()-1 ;i++)
// {
//
// this.setWidget(i ,oldcolumn, this.getWidget(i+1, oldcolumn));
//
// }
}
private void cleanupRows()
{
ArrayList<Integer> rowsfilled = new ArrayList<Integer>();
for (int i = 0; i <= this.getRowCount() - 1; i++)
{
for (int j = 0; j <= this.getCellCount(i) - 1; j++)
{
if (this.getWidget(i, j) != null)
{
rowsfilled.add(i);
break;
}
}
}
//replace the empty rows
for (int i = 0; i < rowsfilled.size(); i++)
{
int currentFilledRow = rowsfilled.get(i);
if (i != currentFilledRow)
{
for (int j = 0; j < this.getCellCount(currentFilledRow); j++)
{
this.setWidget(i, j, this.getWidget(currentFilledRow, j));
}
}
}
for (int i = rowsfilled.size(); i < this.getRowCount(); i++)
{
this.removeRow(i);
}
}
public HandlerRegistration addMouseUpHandler(MouseUpHandler handler)
{
return addDomHandler(handler, MouseUpEvent.getType());
}
public HandlerRegistration addMouseDownHandler(MouseDownHandler handler)
{
return addDomHandler(handler, MouseDownEvent.getType());
}
public HandlerRegistration addMouseMoveHandler(MouseMoveHandler handler)
{
return addDomHandler(handler, MouseMoveEvent.getType());
}
public HandlerRegistration addMouseOutHandler(MouseOutHandler handler)
{
return addDomHandler(handler, MouseOutEvent.getType());
}
}
and the on module load for the above custom widget is
public void onModuleLoad()
{
Label a = new Label("asad");
Label b = new Label("ad");
Label c = new Label("qwad");
Label w = new Label("zxd");
a.setPixelSize(200, 200);
a.getElement().getStyle().setBorderStyle(BorderStyle.SOLID);
a.getElement().getStyle().setBorderWidth(1, Unit.PX);
b.setPixelSize(200, 200);
c.setPixelSize(200, 200);
w.setPixelSize(200, 200);
a.getElement().getStyle().setBackgroundColor("red");
b.getElement().getStyle().setBackgroundColor("yellowgreen");
c.getElement().getStyle().setBackgroundColor("lightblue");
w.getElement().getStyle().setBackgroundColor("grey");
DragFlexTable d = new DragFlexTable();
d.setWidget(0, 0, a);
d.setWidget(0, 1, b);
d.setWidget(1, 0, c);
d.setWidget(1, 1, w);
d.setCellPadding(20);
RootPanel.get().add(d);
}
I am learning how to use Java and I want to make a text scroller for my website.
I have found a similar scroller that I want to add but I want to look at the code to see how it was done.
The applet can be found here: http://www.javascriptkit.com/java/java20.shtml
The problem is when I try to open the class file within notepad the encoding or text shows up with strange characters instead of showing me the code.
Please can someone let me know if there is any possible way of me seeing the code for this class.
Thanks
That is a class file meaning it is compiled code so you can not see it's source.
In order to see the source, you need the .java file which is the file which you compile to get the byte code.
It seems the site is just providing the compiled class, and you never know using it they might have some hidden functionality in the class as well e.g to send information to the owner servers etc.
EDIT:
So here is the de-compiled code of applet written by ProScroll version 2.3 by Slava Pestov
import java.applet.Applet;
import java.applet.AppletContext;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Event;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.Toolkit;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Enumeration;
import java.util.StringTokenizer;
import java.util.Vector;
public class ProScroll extends Applet
implements Runnable
{
private Thread thread;
private Image image;
private int scrollLength;
private int scrolled;
private int speed = 10;
private int imgsWidth;
private URL url;
private String target;
private Color bgColor;
public void init()
{
int i = 12; int j = 0;
String str2 = getParameter("TEXT");
String str3 = getParameter("TEXTURL");
if ((str2 == null) && (str3 == null)) {
str2 = "No TEXT or TEXTURL parameter specified";
}
if (str3 != null)
{
localObject = new StringBuffer();
try
{
InputStream localInputStream = new URL(str3)
.openConnection().getInputStream();
while (true)
{
int k = localInputStream.read();
if (k == -1) break;
if (k != 10) {
if (k == 9) { ((StringBuffer)localObject).append(' '); continue; }
((StringBuffer)localObject).append((char)k);
}
}
localInputStream.close();
str2 = ((StringBuffer)localObject).toString();
}
catch (Exception localException1)
{
if (str2 == null) {
str2 = "Error loading text from URL: " + localException1;
}
}
}
String str1 = getParameter("FONT");
if (str1 == null) str1 = "TimesRoman";
this.target = getParameter("TARGET");
if (this.target == null) this.target = "_self";
try
{
i = Integer.parseInt(getParameter("SIZE"));
}
catch (Exception localException2)
{
}
Object localObject = getParameter("STYLE");
if ("bold".equals(localObject)) j = 1;
else if ("italic".equals(localObject)) j = 2;
else if ("bolditalic".equals(localObject)) j = 3;
String str4 = getParameter("SPEED");
if ("slow".equals(str4)) this.speed = 20;
else if ("medium".equals(str4)) this.speed = 15; else {
this.speed = 10;
}
try
{
this.url = new URL(getDocumentBase(), getParameter("URL"));
}
catch (Exception localException3)
{
}
this.bgColor = parseColorName(getParameter("BGCOLOR"), Color.black);
Enumeration localEnumeration = parseAndLoadImages(getParameter("IMAGES"));
Font localFont = new Font(str1, j, i);
FontMetrics localFontMetrics = getToolkit().getFontMetrics(localFont);
this.image = createImage(localFontMetrics.stringWidth(str2) + this.imgsWidth + size().width, size().height);
this.scrolled = (-size().width);
parseAndDrawText(this.image.getGraphics(), str2, localFontMetrics, localFont, localEnumeration);
}
private void parseAndDrawText(Graphics paramGraphics, String paramString, FontMetrics paramFontMetrics, Font paramFont, Enumeration paramEnumeration)
{
paramGraphics.setFont(paramFont);
paramGraphics.setColor(this.bgColor);
paramGraphics.fillRect(0, 0, this.image.getWidth(this), this.image.getHeight(this));
paramGraphics.setColor(Color.white);
StringBuffer localStringBuffer = new StringBuffer();
int i = 0; int j = 0;
for (int k = 0; k < paramString.length(); k++)
{
char c = paramString.charAt(k);
if ((c == '#') && (j == 0))
{
if (i != 0)
{
paramGraphics.setColor(parseColorName(localStringBuffer.toString(), Color.white));
localStringBuffer.setLength(0);
i = 0;
}
else
{
i = 1;
}
}
else if ((c == '$') && (i == 0) && (j == 0))
{
try
{
Image localImage = (Image)paramEnumeration.nextElement();
paramGraphics.drawImage(localImage, this.scrollLength, 0, this);
this.scrollLength += localImage.getWidth(this);
}
catch (Exception localException)
{
}
}
else if ((c == '/') && (j == 0))
{
j = 1;
}
else if (i != 0)
{
localStringBuffer.append(c);
}
else
{
if (j == 1) j = 0;
paramGraphics.drawString(String.valueOf(c), this.scrollLength, paramFontMetrics.getAscent());
this.scrollLength += paramFontMetrics.charWidth(c);
}
}
}
private Color parseColorName(String paramString, Color paramColor)
{
if ("red".equals(paramString)) return Color.red;
if ("green".equals(paramString)) return Color.green;
if ("blue".equals(paramString)) return Color.blue;
if ("yellow".equals(paramString)) return Color.yellow;
if ("orange".equals(paramString)) return Color.orange;
if ("white".equals(paramString)) return Color.white;
if ("lightGray".equals(paramString)) return Color.lightGray;
if ("gray".equals(paramString)) return Color.gray;
if ("darkGray".equals(paramString)) return Color.darkGray;
if ("black".equals(paramString)) return Color.black;
if ("cyan".equals(paramString)) return Color.cyan;
if ("magenta".equals(paramString)) return Color.magenta;
if ("pink".equals(paramString)) return Color.pink;
return paramColor;
}
private Enumeration parseAndLoadImages(String paramString)
{
if (paramString == null) return null;
int i = 0;
Vector localVector = new Vector();
StringTokenizer localStringTokenizer = new StringTokenizer(paramString);
MediaTracker localMediaTracker = new MediaTracker(this);
while (localStringTokenizer.hasMoreTokens())
{
try
{
Image localImage = getImage(new URL(getDocumentBase(), localStringTokenizer.nextToken()));
localVector.addElement(localImage);
localMediaTracker.addImage(localImage, i);
localMediaTracker.waitForID(i++);
this.imgsWidth += localImage.getWidth(this);
}
catch (Exception localException)
{
}
}
return localVector.elements();
}
public void start()
{
this.thread = new Thread(this);
this.thread.start();
}
public void stop()
{
this.thread = null;
this.scrolled = (-size().width);
}
public void run()
{
while (Thread.currentThread() == this.thread)
{
long l = System.currentTimeMillis();
if (++this.scrolled > this.scrollLength) this.scrolled = (-size().width);
repaint();
try
{
Thread.sleep(Math.max(this.speed - (System.currentTimeMillis() - l), 0L));
}
catch (InterruptedException localInterruptedException)
{
}
}
}
public boolean mouseEnter(Event paramEvent, int paramInt1, int paramInt2)
{
if (this.url != null) getAppletContext().showStatus("Link: " + this.url.toString());
return true;
}
public boolean mouseExit(Event paramEvent, int paramInt1, int paramInt2)
{
if (this.url != null) getAppletContext().showStatus("");
return true;
}
public boolean mouseUp(Event paramEvent, int paramInt1, int paramInt2)
{
if (this.url != null) getAppletContext().showDocument(this.url, this.target);
return true;
}
public void update(Graphics paramGraphics)
{
paramGraphics.setColor(this.bgColor);
if (this.scrolled < 0)
{
paramGraphics.setColor(this.bgColor);
paramGraphics.fillRect(0, 0, -this.scrolled, size().height);
}
paramGraphics.drawImage(this.image, -this.scrolled, 0, this);
}
public void paint(Graphics paramGraphics)
{
update(paramGraphics);
}
public String getAppletInfo()
{
return "ProScroll version 2.3 by Slava Pestov";
}
}
a java .class file is a compiled file that you cannot read with notepad.
if you want the source code you should try to ask it to the author of the article or you could decompile it.