Graphics g/ KeyEvent e incompatibility - java

When I attempt to draw the objects in the array it successfully displays them if there is no KeyEvent e in the header, but if KeyEvent e is in the header like is shown (and to my knowledge it needs to be in order to call the method) it does not print anything out.
How can I use the method I created that moves an object in the array if I cannot have KeyEvent e in the header?
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class Field extends Applet
{
public void paint(Graphics g, KeyEvent e)
{
drawField(g,e);
}
public void drawField(Graphics g, KeyEvent e)
{
int Field[][] = new int[1000][1000];
int Roadl[][] = new int[1000][1000];
Field[100][100] = 1;
Field[100][300] = 2;
Field[100][500] = 3;
Roadl[100][500] = 500;
Field[300][100] = 4;
Roadl[300][100] = 500;
Field[600][600] = 6;
moveCar(Field,600,600,e);
for(int i = 0; i < Field.length; i++)
{
for (int k = 0; k < Field[i].length; k++)
{
if (Field[i][k] == 1)
{
VertBuilding vb1 = new VertBuilding(i,k,g);
}
else if (Field[i][k] == 2)
{
HorizBuilding hb1 = new HorizBuilding(i,k,g);
}
else if (Field[i][k] == 3)
{
VertRoad vr1 = new VertRoad(i,k,Roadl[i][k],g);
}
else if (Field[i][k] == 4)
{
HorizRoad hr1 = new HorizRoad(i,k,Roadl[i][k],g);
}
else if (Field[i][k] == 5)
{
Coin c1 = new Coin(i,k,g);
}
else if (Field[i][k] == 6)
{
HorizCar car1 = new HorizCar(i,k,g);
}
else if (Field[i][k] == 7)
{
VertCar car1 = new VertCar(i,k,g);
}
}
}
}
public void moveCar(int[][] arr1, int i, int k, KeyEvent e)
{
i += keyTypedH(e);
k += keyTypedV(e);
arr1[i][k] = carD(e);
}
public int keyTypedV (KeyEvent e) {
char c = e.getKeyChar();
int y = 0;
if (c == 's')
{
y+=10;
}
else if (c == 'w')
{
y-=10;
}
return y;
}
public int keyTypedH (KeyEvent e) {
char c = e.getKeyChar();
int x = 0;
if (c == 'a')
{
x-=10;
}
else if (c == 'd')
{
x+=10;
}
return x;
}
public int carD (KeyEvent e) {
char c = e.getKeyChar();
int carLocation = 0;
if (c == 'a')
{
carLocation = 6;
}
else if (c == 'd')
{
carLocation = 6;
}
else if (c == 's')
{
carLocation = 7;
}
else if (c == 'w')
{
carLocation = 7;
}
return carLocation;
}
}

Related

I need to create a program that will read a text file, figure out in the parentheses are valid, and solve the equation

This is my assignment on number 6:
And this is what I have so far. It's not working properly and I am not sure why. Any help would be greatly appreciated. I showed what error I get at the bottom of the code. I'm not sure how to fix it and where to go from here.
import java.util.Arrays;
public class st {
public static void main(String[] args) {
String aa = "8 + (2+2)";
Init init = new Init(aa);
}
}
public final class Init {
public int top = 1;
Integer[] stack = new Integer[10];
String[] queue = new String[10];
int number, x, y, z, op, front, rear;
int finalValue;
int CurrValue;
String queueOperand;
Character s;
public Init(String s) {
ValidateEquation(s);
int finalVal = postFix(s);
System.out.printf("The answer is " + finalVal + "\n");
}
void ValidateEquation(String s) {
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '(') {
push(c);
} else if (c == ')') {
if (isStackEmpty()) {
System.out.printf("Error: Too many ')'");
System.exit(0);
} else {
int closeParen = pop();
}
}
}
}
public int postFix(String s) {
int CurrentCalculation;
int i = 0;
while (i < s.length()) {
char c = s.charAt(i);
if ((int) c > 47 && (int) c < 58) {
int numVal = Character.getNumericValue(c);
push(numVal);
} else if ((int) c > 41 && (int) c < 48) {
String StrVal = Character.toString(c);
pushQ(StrVal);
}
if (c == '(' || c == ')' || i == s.length()-1) {
String newString = "";
for (Integer stack1 : stack) {
/* iterate through the stack */
if (stack1 != null) {
newString = newString + stack1 + " ";
}
}
for (String queue1 : queue) {
/* iterate through the queue */
if (queue1 != null) {
newString = newString + queue1 + " ";
queueOperand = queue1;
}
}
if (newString.length() > 2) {
int CurrValue = calculateEquation(newString);
if ("+".equals(queueOperand)) {
finalValue = finalValue + CurrValue;
} else if ("-".equals(queueOperand)) {
finalValue = finalValue - CurrValue;
} else if ("*".equals(queueOperand)) {
finalValue = finalValue * CurrValue;
} else if ("/".equals(queueOperand)) {
finalValue = finalValue / CurrValue;
}
popAll();
}
}
i++;
}
return finalValue;
}
int calculateEquation(String s) {
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if ((int) c > 47 && (int) c < 58) {
int numVal = Character.getNumericValue(c);
push(numVal);
}
if ((int)c > 41 && (int)c < 48) {
if (s.length() <= 4) {
x = pop();
if (c == '*' || c == '/') {
y = 1;
} else {
y = 0;
}
} else {
x = pop();
y = pop();
}
System.out.println("\n" + x + " " + y + " " + c);
if (c == '+') {
z = x + y;
} else if (c == '-') {
z = x - y;
} else if (c == '*') {
z = x * y;
} else if (c == '/') {
z = x / y;
}
}
}
return z;
}
void push(int x) {
top = top + 1;
/* Increment stack pointer. */
stack[top] = x;
/* Place x on top of stack. */
}
void pushQ(String x) {
rear = rear + 1;
/* Increment stack pointer. */
queue[rear] = x;
/* Place x on top of stack. */
}
int pop() {
int x;
x = stack[top];
/* Retrieve item from top of stack. */
top = top - 1;
/* Decrement stack. */
return x;
}
void popAll() {
Arrays.fill(stack, null);
Arrays.fill(queue, null);
}
boolean isStackEmpty() {
boolean empty;
empty = false;
if (top == -1) {
/* If top = -1, that indicates an empty stack. */
empty = true;
}
return empty;
}
}
This is the error I get:
"/st.java:12: error: class Init is public, should be declared in a file named Init.java
public final class Init {"
You should put each public class in separate file and file name must be class name.

SPOJ ISLHOP java wrong answer

I am trying to solve http://www.spoj.com/problems/ISLHOP/
The solution I have tried works for the sample input/output but fails the judging process for having the wrong answer.
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
class Main {
public static void main(String[]args){
Scanner in = new Scanner(System.in);
int group = 0;
while(in.hasNextLine()) {
int numberOfIsland = in.nextInt();
if(numberOfIsland == 0)
{
break;
}
group++;
in.nextLine();
ArrayList<Island> isl = new ArrayList<Island>();
for(int i = 0; i < numberOfIsland; i++){
String s = in.nextLine();
String[] inputList = s.split("\\s+");
Island newIsland = new Island(Integer.parseInt(inputList[0]),Integer.parseInt(inputList[1]),Integer.parseInt(inputList[2]),-1);
isl.add(newIsland);
}
double result = solve(isl);
System.out.print("Island Group: "+group+" Average ");
System.out.println(String.format("%.2f", result));
}
}
public static double solve(ArrayList<Island> islands) {
TreeSet<Island> islandSet = new TreeSet<Island>();
double time = 0;
islandSet.add(islands.get(0));
Island current;
while(!islandSet.isEmpty()){
current = islandSet.first();
current.queued = true;
islandSet.remove(current);
Island parent = current.parent;
if(parent != null)
{
if(current.parent.curmax < current.curdis)
{
current.curmax = current.curdis;
}
else{
current.curmax = current.parent.curmax;
}
time += current.num * current.curmax;
}
for(int i=0; i< islands.size(); i++)
{
Island next = islands.get(i);
if(!next.queued){
double dis = Math.sqrt(
Math.pow(current.x-next.x,2)
+Math.pow(current.y-next.y,2));
if(islandSet.contains(next))
{
if(next.curdis > dis){
islandSet.remove(next);
next.parent = current;
next.curdis = dis;
islandSet.add(next);
}
}
else{
next.parent = current;
next.curdis = dis;
islandSet.add(next);
}
}
}
}
double total = 0;
for(int i = 0; i < islands.size(); i++)
{
total += islands.get(i).num;
}
return time/total;
}
}
class Island implements Comparable<Island>{
public int x, y, num;
public Island parent;
public double curdis, curmax;
public boolean queued;
public Island(int x, int y, int num, double dis){
this.x = x;
this.y = y;
this.num = num;
this.queued = false;
curdis = 0;
curmax = 0;
}
#Override
public int compareTo(Island o) {
if(curdis > o.curdis)
{
return 1;
}
if(curdis == o.curdis)
{
return 0;
}
return -1;
}
}
class FasterScanner{
private InputStream mIs;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public FasterScanner() {
this(System.in);
}
public FasterScanner(InputStream is) {
mIs = is;
}
public boolean hasNext(){
try{
if( read() < 0 )
{
return false;
}
}
catch(InputMismatchException e)
{
return false;
}
return true;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = mIs.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public String nextString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public long nextLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int nextInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
}
I tried simply implementing it using Scanner rather than FasterScanner because I couldn't figure out how to write the hasNext() for FasterScanner.
I can't figure out what's wrong with my code as it works for the given sample input.
Does anyone know of a working solution or what is wrong with this one?

need help on my tic tac toe demo invalid top level statement

public class TicTacToe
{
private char currentPlayer;
private char[][] board;
public TicTacToe()
{
board = new char [3][3];
currentPlayer = 'x';
startBoard();
}
public void startBoard()
{
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
board[i][j] = '-';
}
}
}
public void makeBoard()
{
System.out.println("---------------");
for (int i = 0; i < 3; i++)
{
System.out.print("| ");
for (int j = 0; j < 3; j++)
{
System.out.print(board[i][j] + " | ");
}
System.out.println();
System.out.println("---------------");
}
}
public boolean fullBoard()
{
boolean full = true;
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
if (board[i][j] == '-')
{
full = false;
}
}
}
return full;
}
public boolean win()
{
return (rowWin() || columnWin() || diagWin());
}
private boolean rowWin()
{
for (int i = 0; i < 3; i++)
{
if (rowColumn(board[i][0], board[i][1], board[i][2]) == true)
{
return true;
}
}
return false;
}
private boolean columnWin()
{
for (int i = 0; i < 3; i++)
{
if (rowColumn(board[0][i], board[1][i], board[2][i]) == true)
{
return true;
}
}
return false;
}
private boolean diagWin()
{
return ((rowColumn(board[0][0], board[1][1], board[2][2]) == true) ||
(rowColumn(board[0][2], board[1][1], board[2][0]) == true));
}
private boolean rowColumn(char rc1, char rc2, char rc3)
{
return ((rc1 != '-') && (rc1 == rc2) && (rc2 == rc3));
}
public void playerChange()
{
if (currentPlayer == 'x')
{
currentPlayer = 'o';
}
else
{
currentPlayer = 'x';
}
}
public boolean placeMark(int row, int column)
{
if ((row >= 0) && (row < 3))
{
if ((column >= 0) && (column < 3))
{
if (board[row][column] == '-')
{
board[row][column] = currentPlayer;
return true;
}
}
}
return false;
}
}
public class TicTacToedemo
{
public static void main(String[] args)
{
TicTacToe demo = new TicTacToe();
demo.makeBoard();
if (demo.win())
System.out.println("Winner! Hooray!");
else if (demo.fullBoard())
System.out.println("Cat Scratch, Draw.");
demo.playerChange();
}
}
I am not sure how to play the game right, every time I input numbers when I run it, I get the error code. What have I done wrong with this? The code can be compiled and runs and displays the board but when I go to put in the place I want the x or the o to go I get the error code " invalid Top level statement "
You have to use the Scanner class to make a player input using import java.util.Scanner then storing the input. After the import it going to look like this:
Scanner sc = new Scanner(System.in);
int input = sc.nextInt();
And you have to manage the sc.nextInt() result, in this example the input variable.

Delaying Attacks With TimerTask Not Working Well

I'm making a fighting game and I want the actions of the player to be timed so you can't spam the attack key and win easily.
Here is where I do the keyboard stuff and delay. It does delay the first time, but then it the delay slowly decreases in time and ends up being 0 and lets you spam the key. As you can see I've done many things to try and stop the key from registering in the delay etc.
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (isAction == false) {
if (key == KeyEvent.VK_LEFT) {
dx = -1;
if (nHeroX < -10) {
dx = 0;
}
isRight = false;
isMoving = true;
} else if (key == KeyEvent.VK_RIGHT) {
dx = 1;
if (nHeroX > 1200) {
dx = 0;
}
isRight = true;
isMoving = true;
} else if (key == KeyEvent.VK_C) {
dx = 0;
isAction = true;
isMoving = false;
isBlock = true;
nImage = 1;
} else if (key == KeyEvent.VK_X) {
dx = 0;
isAction = true;
isMoving = false;
isWeak = true;
nImage = 2;
} else if (key == KeyEvent.VK_Z) {
dx = 0;
isAction = true;
isMoving = false;
isStrong = true;
nImage = 3;
} else if (key == KeyEvent.VK_P) {
if (!pause) {
pause = true;
} else if (pause) {
pause = false;
}
}
}
}
public void keyReleased(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_LEFT || key == KeyEvent.VK_RIGHT && !isAction) {
dx = 0;
isMoving = false;
nState = nImage = 1;
} else if (key == KeyEvent.VK_C && !isWeak && !isStrong) {
delayTask = new DelayTask();
tmrDelay.schedule(delayTask, 0, 500);
} else if (key == KeyEvent.VK_X && !isBlock && !isStrong) {
z = new DelayTask();
tmrDelay.schedule(z, 0, 450);
} else if (key == KeyEvent.VK_Z && !isBlock && !isWeak) {
x = new DelayTask();
tmrDelay.schedule(x, 0, 1200);
}
nImgNum = (int) (Math.random() * 6 + 1);
nDelay = 0;
}
//http://www.javaprogrammingforums.com/java-se-api-tutorials/883-how-use-tmrDelay-java.html
class DelayTask extends TimerTask {
public int nTimes = 0;
#Override
public void run() {
nTimes++;
if (nTimes == 2) {
isAction = isBlock = isStrong = isWeak = false;
nState = nImage = 1;
}
}
}
Can someone explain why my delay is messed up? Thank you.
Also this code:
private class Keys extends KeyAdapter {
#Override
public void keyPressed(KeyEvent e) {
hero.keyPressed(e);
}
#Override
public void keyReleased(KeyEvent e) {
hero.keyReleased(e);
if (hero.getPause()) {
repaint();
}
}
}
The simplest way to do this is just to remember the last time.
So:
private long lastTime = 0;
void doAction() {
long timeNow = System.currentTimeMillis()
if (lastTime + MIN_DELAY < timeNow) {
return;
}
lastTime = timeNow;
// Do action
}
All the stuff with timers etc is just approaching this from a much more complicated architecture than you need to.

Java connect four victory check

I am a beginner at programming and I have been teaching myself as much as I can. I need help in a simpler way of checking for a victory instead of hard coding every possible combination.
I have no idea what to do.
here is my current code:
import java.awt.*;
import javax.swing.event.*;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class connectfour extends JFrame implements ActionListener
{
JLabel board[][] = new JLabel[8][7];
//JLabel board[] = new JLabel[64];
JButton action[] = new JButton[8];
JButton start;
JButton clear;
JFrame Frame = new JFrame();
ImageIcon red = new ImageIcon("red piece.jpeg");
ImageIcon black = new ImageIcon("blackpiece.jpeg");
boolean players = true;
//Integer[] numclick = new Integer[8];
int x;
int numclick1 = 7;
int numclick2 = 7;
int numclick3 = 7;
int numclick4 = 7;
int numclick5 = 7;
int numclick6 = 7;
int numclick7 = 7;
int numclick0 = 7;
public connectfour()
{
Frame.setSize(100,120);
Frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
Frame.setLayout(null);
Frame.setVisible(true);
start = new JButton("Start");
start.setBounds(0,0,100,100);
start.setVisible(true);
start.addActionListener(this);
Frame.add(start);
}
public void game()
{
for(int x = 0; x < 8 ; x++)
{
action[x] = new JButton();
action[x].setSize(100,40);
action[x].setLocation((x*100) + 50, 0);
action[x].addActionListener(this);
action[x].setVisible(true);
Frame.add(action[x]);
}
/**
board[1][1] = new JLabel();
board[1][1].setBounds(50,40,100,100);
board[1][1].setVisible(true);
board[1][1].setOpaque(true);
board[1][1].setBorder(BorderFactory.createLineBorder(Color.black));
Frame.add(board[1][1]);
**/
for(int i = 0; i < 8; i++)
{
for(int j = 0; j < 7; j++)
{
board[i][j] = new JLabel();
board[i][j].setSize(100,100);
board[i][j].setLocation((i*100)+50,(j*100)+40);
board[i][j].setOpaque(true);
board[i][j].setVisible(true);
board[i][j].setBorder(BorderFactory.createLineBorder(Color.black));
Frame.add(board[i][j]);
}
}
clear = new JButton("Clear");
clear.setBounds(850,100,100,50);
clear.addActionListener(this);
clear.setVisible(true);
Frame.add(clear);
}
public void boardsize()
{
Frame.setSize(950,800);
}
public static void main(String args[])
{
new connectfour();
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == start)
{
boardsize();
start.setVisible(false);
game();
}
for(x = 0;x < 8 ;x ++)
{
if(e.getSource() == action[x])
{
//numclick[x]++;
if(x == 0)
{
numclick0--;
if(players == true)
{
board[x][numclick0].setIcon(red);
players = false;
break;
}
if(players == false)
{
board[x][numclick0].setIcon(black);
players = true;
break;
}
}
if(x == 1)
{
numclick1--;
if(players == true)
{
board[x][numclick1].setIcon(red);
players = false;
break;
}
if(players == false)
{
board[x][numclick1].setIcon(black);
players = true;
break;
}
}
if(x == 2)
{
numclick2--;
if(players == true)
{
board[x][numclick2].setIcon(red);
players = false;
break;
}
if(players == false)
{
board[x][numclick2].setIcon(black);
players = true;
break;
}
}
if(x == 3)
{
numclick3--;
if(players == true)
{
board[x][numclick3].setIcon(red);
players = false;
break;
}
if(players == false)
{
board[x][numclick3].setIcon(black);
players = true;
break;
}
}
if(x == 4)
{
numclick4--;
if(players == true)
{
board[x][numclick4].setIcon(red);
players = false;
break;
}
if(players == false)
{
board[x][numclick4].setIcon(black);
players = true;
break;
}
}
if(x == 5)
{
numclick5--;
if(players == true)
{
board[x][numclick5].setIcon(red);
players = false;
break;
}
if(players == false)
{
board[x][numclick5].setIcon(black);
players = true;
break;
}
}
if(x == 6)
{
numclick6--;
if(players == true)
{
board[x][numclick6].setIcon(red);
players = false;
break;
}
if(players == false)
{
board[x][numclick6].setIcon(black);
players = true;
break;
}
}
if(x == 7)
{
numclick7--;
if(players == true)
{
board[x][numclick7].setIcon(red);
players = false;
break;
}
if(players == false)
{
board[x][numclick7].setIcon(black);
players = true;
break;
}
}
System.out.println(x);
System.out.println();
}
}
if(e.getSource() == clear)
{
for(int x = 0; x < 8; x++)
{
for(int y = 0; y < 7; y++)
{
board[x][y].setIcon(null);
numclick1 = 7;
numclick2 = 7;
numclick3 = 7;
numclick4 = 7;
numclick5 = 7;
numclick6 = 7;
numclick7 = 7;
numclick0 = 7;
players = true;
for(int j = 0; j < 8 ; j++)
{
action[j].setEnabled(true);
}
}
}
}
if(numclick0 == 0)
{
action[0].setEnabled(false);
}
if(numclick1 == 0)
{
action[1].setEnabled(false);
}
if(numclick2 == 0)
{
action[2].setEnabled(false);
}
if(numclick3 == 0)
{
action[3].setEnabled(false);
}
if(numclick4 == 0)
{
action[4].setEnabled(false);
}
if(numclick5 == 0)
{
action[5].setEnabled(false);
}
if(numclick6 == 0)
{
action[6].setEnabled(false);
}
if(numclick7 == 0)
{
action[7].setEnabled(false);
}
}
public void winner()
{
}
}
I would use a recursive method that checks the horizontal, vertical, and both diagonals.
As i was reading your code I realized you don't keep track(may have missed it) of where players are.. I recommend and array for this called grid[][] Mapping an array to your JLabels will go a long way.
Ill give an example of negative vertical check..
public Boolean checkVertical(Boolean player, int x, int y){
if(solveHelper(player, x, y, -1, 0) => 4) return true;
return false;
}
public int solveHelper(Boolean player, int x, int y, int addX, int addY){
if(x == 0 || x == size || y == 0 || y == size || grid[x][y].player != player)
return 0;
return solverHelper(player, x+addX, y+addY, addX, addY) + 1);
}
Now how can you create and use these methods for yourself?
you need to create a new methods for each of the horizontal, vertical, and both diagonals to check for all of them you call solveHelper with different properties in addX and addY that correspond with the direction you want to go. For instance, if you want to check the horizontal you need do make addY == 1 and addY == -1 with both values for addX == 0 by doing a solveHelper + solverHelper with these two values changed.
Other notes...
Some things you need to need to keep in mind is that how connect four actually runs. When you click on a row a piece falls down to the smallest unoccupied element in that particular column. Just something you should keep in mind when writing your game logic.
Cheers.

Categories