i'm having trouble from fetching data from my TimerCan class. like String and integers.
i have a method(static method) for getting this data and set it to another class. but every time i run my program i always get NULLPOINTEREXCEPTION in line..
if(opp.equalsIgnoreCase("incrementing")){///heree
startTimer();
if(hour[current]==hhh&&min[current]==mmm&&sec[current]==sss)
{
this.start = false;
this.stop = true;
this.timer.cancel();
}
else if(opp.equalsIgnoreCase("decrementing")){
startTimerD();
if(hour[current]==0&&min[current]==0&&sec[current]==0)
{
this.start = false;
this.stop = true;
this.timer.cancel();
and heres the full code my TimerCan class
public class TimerCan extends Canvas
{
private Timer timer;
private Midlet myMid;
private Player z;
private int hour[],sec[],min[],msec[],maxX,maxY,current,length,x,y;
private String time,opp;
private int strWid,hhh,mmm,sss;
private int strht;
private boolean start;
private boolean stop;
public Image img;
Data data;
public TimerCan(Midlet midlet)
{
this.myMid= midlet;
data = new Data();
opp=data.getData();
hhh=data.getDatah();
mmm=data.getDatam();
sss=data.getDatas();
try
{
this.maxX = this.getWidth();
this.maxY = this.getHeight();
this.current = 0;
this.hour = new int[30];
this.min = new int[30];
this.sec = new int[30];
this.msec = new int[30];
this.start = false;
this.stop = true;
for(int j = 0 ; j <= 30 ; j++)
{
this.hour[j] = 0;
this.min[j] = 0;
this.sec[j] = 0;
this.msec[j] = 0;
}
}catch(Exception e)
{}
}
public void paint(Graphics g)
{
Font font = Font.getFont(0,1,16);
this.strWid = font.stringWidth("this.time");
this.strht = font.getHeight();
if(hour[current] < 10)
{
time = "0"+String.valueOf(this.hour[current])+":";
}
else
{
time = String.valueOf(this.hour[current]) + ":";
}
if(min[current] < 10)
{
time = time+"0"+String.valueOf(this.min[current]) + ":";
}
else
{
time = time+String.valueOf(this.min[current]) + ":";
}
if(sec[current] < 10)
{
time = time+"0"+String.valueOf(this.sec[current]) + ":";
}
else
{
time = time + String.valueOf(this.sec[current]) + ":";
}
if(msec[current] < 10)
{
time = time+"0"+String.valueOf(this.msec[current]);
}
else
{
time = time+String.valueOf(this.msec[current]);
}
this.strWid = font.stringWidth(time);
this.length = this.maxX - this.strWid;
this.length /= 2;
try{
img = Image.createImage("/picture/aa.png");
}
catch(Exception error){
}
x = this.getWidth()/2;
y = this.getHeight()/2;
g.setColor(63,155,191);
g.fillRect(0,0,maxX, maxY);
g.drawImage(img, x, y, Graphics.VCENTER | Graphics.HCENTER);
g.setColor(0,0,0) ;
g.drawString(time,length+15,150,Graphics.TOP|Graphics.LEFT);
}
private void startTimer()
{
TimerTask task = new TimerTask()
{
public void run()
{
msec[current]++ ;
if(msec[current] == 100)
{
msec[current] = 0 ;
sec[current]++ ;
}
else if(sec[current] ==60)
{
sec[current] = 0 ;
min[current]++ ;
}
else if(min[current] == 60)
{
min[current] = 0 ;
hour[current]++ ;
}
else if(hour[current] == 24)
{
hour[current] = 0 ;
}
repaint();
}
};
timer = new Timer();
timer.scheduleAtFixedRate(task,10,10) ;
}
private void startTimerD()
{
TimerTask task = new TimerTask()
{
public void run()
{
msec[current]-- ;
if(msec[current] == 0)
{
msec[current] = 100 ;
sec[current]-- ;
}
else if(sec[current] ==0)
{
sec[current] = sss;
min[current]--;
}
else if(min[current] == 0)
{
min[current] =mmm;
hour[current]--;
}
else if(hour[current] == 0)
{
hour[current] = hhh;
}
repaint();
}
};
timer = new Timer();
timer.scheduleAtFixedRate(task,10,10) ;
}
protected void keyPressed(int keyCode)
{
if(keyCode == Canvas.KEY_NUM1)
{
if(this.start == false)
{
this.start=true;
this.stop=false;
}
else if(this.stop == false)
{
this.start = false ;
this.stop = true ;
this.timer.cancel();
}
if(start == true)
{
check();
}
}
if(keyCode == Canvas.KEY_NUM2)
{
this.min[current]=0;
this.sec[current]=0;
this.msec[current]=0;
this.start = false;
this.stop = true;
this.timer.cancel();
try{
z.deallocate();
}
catch(Exception e){}
repaint();
}
if(keyCode == Canvas.KEY_NUM3)
{
if(this.stop == false)
{
this.start = false;
this.stop = true;
this.timer.cancel();
try{
InputStream inss = getClass().getResourceAsStream("alarm.wav");
InputStreamReader iis= new InputStreamReader(inss);
z = Manager.createPlayer(inss,"audio/x-wav");
z.prefetch();
z.setLoopCount(2);
z.start();
}
catch(Exception e){
}
}
}
if(keyCode==Canvas.KEY_NUM0)
{
try{
z.deallocate();
}
catch(Exception e){}
myMid.exit();
}
}
public void check()
{
if(opp.equalsIgnoreCase("incrementing")){
startTimer();
if(hour[current]==hhh&&min[current]==mmm&&sec[current]==sss)
{
this.start = false;
this.stop = true;
this.timer.cancel();
try{
InputStream inss = getClass().getResourceAsStream("alarm.wav");
InputStreamReader iis= new InputStreamReader(inss);
z = Manager.createPlayer(inss,"audio/x-wav");
z.prefetch();
z.setLoopCount(2);
z.start();
}
catch(Exception e){
}
}
}
else if(opp.equalsIgnoreCase("decrementing")){
startTimerD();
if(hour[current]==0&&min[current]==0&&sec[current]==0)
{
this.start = false;
this.stop = true;
this.timer.cancel();
try{
InputStream inss = getClass().getResourceAsStream("alarm.wav");
InputStreamReader iis= new InputStreamReader(inss);
z = Manager.createPlayer(inss,"audio/x-wav");
z.prefetch();
z.setLoopCount(2);
z.start();
}
catch(Exception e){
}
}
and heres the Data classs
public class Data{
String nameD;
int hhD;
int mmD;
int ssD;
public void setData(String name){
this.nameD = name;
}
public String getData(){
return this.nameD;
}
//hour
public void setDatah(int hhh){
this.hhD = hhh;
}
public int getDatah(){
return this.hhD;
}
//
public void setDatam(int hhh){
this.mmD = hhh;
}
public int getDatam(){
return this.mmD;
}
//
public void setDatas(int sss){
this.ssD = sss;
}
public int getDatas(){
return this.ssD;
}
}
You wrote
data = new Data();
in your TimerCan class. This made a Data object that didn't have nameD set to anything; so when you wrote
opp = data.getData()
later, you were setting opp to null - that is, there wasn't actually an object referenced by opp. When you wrote
if (opp.equalsIgnoreCase("incrementing"))
this caused a problem. You can't call a method, when the object that you're trying to call it on is absent.
If it's legitimate for opp to be null, but you still have code that you want to run when opp is "incrementing" you can write it like this.
if (opp != null && opp.equalsIgnoreCase("incrementing"))
which will check whether opp is null before it calls the equalsIgnoreCase method - and you won't get the NullPointerException.
This happens because you have not initialized variable data, so it remains null. This is the obvious reason of NullPointerException.
You have to call data = new Data(); prior using it.
Related
Hello I'm fairly new to programming and this is my first time posting here so any help would be appreciated so:
my problem is that I"m trying to create some kind of 2D shooter game in java but I don't know if my simple game loop is good because when i shoot a missile it shoots a one every 20 ms and it's too fast and shoots a ton of missiles at once so is there any way to adjust it ? Like to keep some delay between every missile and the other??
and please tell me if i have problems or bad programming in my code !!
this is my game panel where most of the game happens and where my loop and adding missiles method in
public class GamePanel extends JPanel implements KeyListener {
Measurments mesure = new Measurments();
int panel_width = mesure.getUniversalWidth();
int panel_height = mesure.getUniversalHeight();
Timer timer;
Random rand = new Random();
ArrayList<Enemy> enemies = new ArrayList<>();
ArrayList<Missile> missiles = new ArrayList<>();
Player player = new Player(0, 0);
boolean up = false;
boolean down = false;
boolean right = false;
boolean left = false;
boolean isShooting = false;
boolean isRunning = true;
public boolean gameRunning() {
return isRunning;
}
int count = 5;
int missilesCount = 6;
public GamePanel() {
timer = new Timer(20, new ActionListener() {
public void actionPerformed(ActionEvent e) {
StartGame();
repaint();
}
});
setSize(panel_width, panel_height);
addKeyListener(this);
timer.start();
for (int i = 0; i < count; i++) {
addEnemy(new Enemy(rand.nextInt(750), rand.nextInt(500)));
}
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
player.paint(g2d);
for (int i = 0; i < enemies.size(); i++) {
Enemy temp = enemies.get(i);
temp.paint(g2d);
}
for (int i = 0; i < missiles.size(); i++) {
Missile mis = missiles.get(i);
mis.paint(g2d);
mis.behave();
}
}
public void StartGame() {
if (isRunning) {
runGame();
setBackground(Color.YELLOW);
} else {
setBackground(Color.BLACK);
}
}
public void runGame() {
update();
};
public void update() {
player.checkBorders();
checkColls();
if (up) {
player.updateUp();
}
if (down) {
player.updateDown();
}
if (right) {
player.updateRight();
}
if (left) {
player.updateLeft();
}
if (isShooting) {
for (int i = 0; i < 5; i++) {
missiles.add(new Missile(player.getX() + 16, player.getY() + 16));
}
}
for (int i = 0; i < missiles.size(); i++) {
Missile temp = missiles.get(i);
if (temp.getX() == panel_width) {
RemoveMissile(temp);
}
}
}
public void addEnemy(Enemy e) {
enemies.add(e);
}
public void removeEnemy(Enemy e) {
enemies.remove(e);
}
public void addMissile(Missile e) {
missiles.add(e);
}
public void RemoveMissile(Missile e) {
missiles.add(e);
}
public void checkColls() {
for (int i = 0; i < enemies.size(); i++) {
Enemy tempEnm = enemies.get(i);
for (int e = 0; e < missiles.size(); e++) {
Missile tempMis = missiles.get(e);
if (tempMis.missileRect().intersects(tempEnm.enemyRect())) {
enemies.remove(tempEnm);
missiles.remove(tempMis);
}
}
}
}
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == e.VK_UP) {
up = true;
}
if (key == e.VK_DOWN) {
down = true;
}
if (key == e.VK_RIGHT) {
right = true;
}
if (key == e.VK_LEFT) {
left = true;
}
if (key == e.VK_ENTER) {
isRunning = true;
}
if (key == e.VK_SPACE) {
isShooting = true;
}
}
public void keyReleased(KeyEvent e) {
int key = e.getKeyCode();
if (key == e.VK_UP) {
up = false;
}
if (key == e.VK_DOWN) {
down = false;
}
if (key == e.VK_RIGHT) {
right = false;
}
if (key == e.VK_LEFT) {
left = false;
}
if (key == e.VK_SPACE) {
isShooting = false;
}
}
public void keyTyped(KeyEvent e) {
}
}
Thanks in advance !!
private long fired = 0L;
public void update() {
...
// firing missiles: only if the missile count is less than the max., and the elapsed
// time is more than a limit (100 ms)
if ( isShooting && missiles.size() < missilesCount &&
( System.currentTimeMilis() - this.fired ) > 100 ) {
missiles.add( new Missile( player.getX() + 16, player.getY() + 16 ) );
// time of last firing
this.fired = System.currentTimeMilis();
}
...
}
public void RemoveMissile(Missile e) {
// as Guest is asked in another answer, this method should remove, not add...
missiles.remove(e);
}
I'm currently making a space invaders-esque game for my software engineering course. I've already got everything working that satisfies the requirements, so this isn't a 'solve my homework' kind of question. My problem is that the game will lag (at what seems like random times & intervals) to the point where it becomes too frustrating to play. Some things I think might be causing this - though I'm not positive - are as follows:
Problem with timer event every 10 ms (I doubt this because of the very limited resources required for this game).
Problem with collision detection (checking for collision with every visible enemy every 10 ms seems like it would take up a large chunk of resources)
Problem with repainting? This seems unlikely to me however...
#SuppressWarnings("serial")
public class SIpanel extends JPanel {
private SIpanel panel;
private Timer timer;
private int score, invaderPace, pulseRate, mysteryCount, distanceToEdge;
private ArrayList<SIthing> cast;
private ArrayList<SIinvader> invaders, dead;
private ArrayList<SImissile> missileBase, missileInvader;
private SIinvader[] bottomRow;
private SIbase base;
private Dimension panelDimension;
private SImystery mysteryShip;
private boolean gameOver, left, right, mysteryDirection, space, waveDirection;
private boolean runningTimer;
private Music sound;
private void pulse() {
pace();
processInputs();
if (gameOver) gameOver();
repaint();
}
private void pace() {
// IF invaders still live
if (!invaders.isEmpty()) {
invaderPace++;
// Switch back manager
if (distanceToEdge <= 10) {
switchBack();
pulseRate = (pulseRate >= 16) ? (int) (pulseRate*(0.8)) : pulseRate;
waveDirection = !waveDirection;
distanceToEdge = calculateDistanceToEdge();
}
// Move invaders left/right
else if (invaderPace >= pulseRate) {
invaderPace = 0;
distanceToEdge = calculateDistanceToEdge();
moveAI();
invadersFire();
if (!dead.isEmpty()) removeDead();
if (mysteryCount < 1) tryInitMysteryShip();
}
// All invaders are kill, create new wave
} else if (missileBase.isEmpty() && missileInvader.isEmpty() && !cast.contains(mysteryShip)) {
// System.out.println("New Wave!");
newWave();
}
// Every pace
if (!missileBase.isEmpty()) moveMissileBase();
// Every two paces
if (invaderPace % 2 == 0) {
if (!missileInvader.isEmpty()) moveMissileInvader();
if (mysteryCount > 0) moveMysteryShip();
}
}
private void processInputs() {
if (left) move(left);
if (right) move(!right);
if (space) fireMissile(base, true);
}
protected void fireMissile(SIship ship, boolean isBase) {
if(isBase && missileBase.isEmpty()) {
base.playSound();
SImissile m = new SImissile(ship.getX()+(ship.getWidth()/2), ship.getY()-(ship.getHeight()/4));
missileBase.add(m);
cast.add(m);
} else if (!isBase && missileInvader.size()<3) {
base.playSound();
SImissile m = new SImissile(ship.getX()+(ship.getWidth()/2), ship.getY()+(ship.getHeight()/4));
missileInvader.add(m);
cast.add(m);
}
}
private void newWave() {
pulseRate = 50;
int defaultY=60, defaultX=120, defaultWidth=30, defaultHeight=24;
for(int i=0; i<5; i++) {
for(int j=0; j<10; j++) {
if (i<1) invaders.add(new SItop((j*defaultWidth)+defaultX, (i*defaultHeight)+defaultY, defaultWidth, defaultHeight));
else if (i<3) invaders.add(new SImiddle((j*defaultWidth)+defaultX, (i*defaultHeight)+defaultY, defaultWidth, defaultHeight));
else if (i<5) invaders.add(new SIbottom((j*defaultWidth)+defaultX, (i*defaultHeight)+defaultY, defaultWidth, defaultHeight));
}
}
for (SIinvader s: invaders) {
cast.add(s);
}
if (!cast.contains(base)) {
cast.add(base);
}
bottomRow = getBottomRow();
}
private void tryInitMysteryShip() {
Random rand = new Random();
int x=rand.nextInt(1000);
if (x<=3) {
mysteryCount = 1;
if (rand.nextBoolean()) {
mysteryDirection = true;
}
if (mysteryDirection) {
mysteryShip = new SImystery(0, 60, 36, 18);
} else {
mysteryShip = new SImystery(480, 60, 36, 18);
}
cast.add(mysteryShip);
}
}
private void moveMysteryShip() {
int distance = 0;
if (mysteryDirection) {
mysteryShip.moveRight(5);
distance = getWidth() - mysteryShip.getX();
} else {
mysteryShip.moveLeft(5);
distance = 30+mysteryShip.getX()-mysteryShip.getWidth();
}
if (distance <= 5) {
dead.add(mysteryShip);
mysteryShip = null;
mysteryCount = 0;
}
}
private void removeDead() {
#SuppressWarnings("unchecked")
ArrayList<SIinvader> temp = (ArrayList<SIinvader>) dead.clone();
dead.clear();
for (SIinvader s : temp) {
invaders.remove(s);
cast.remove(s);
}
bottomRow = getBottomRow();
}
private void invadersFire() {
int[] p = new int[bottomRow.length];
for (int i=0; i<p.length; i++) {
for (int j=0; j<p.length; j++) {
p[j] = j;
}
Random rand = new Random();
int a=rand.nextInt(101);
if (a>=20) {
int b=rand.nextInt(p.length);
fireMissile(bottomRow[b], false);
}
}
}
private int calculateDistanceToEdge() {
int distance = 0;
SIinvader[] outliers = getOutliers();
if (waveDirection) {
distance = getWidth() - outliers[0].getX()-outliers[0].getWidth();
} else {
distance = outliers[1].getX();
}
return distance;
}
private SIinvader[] getOutliers() {
SIinvader leftMost = invaders.get(0), rightMost = invaders.get(0);
for (SIinvader s : invaders) {
if (s.getX() < leftMost.getX()) {
leftMost = s;
}
if (s.getX() > rightMost.getX()) {
rightMost = s;
}
}
return new SIinvader[] { rightMost, leftMost };
}
private SIinvader[] getBottomRow() {
SIinvader[] x = new SIinvader[(invaders.size()>10)?10:invaders.size()];
for (int i=0; i<x.length; i++) {
x[i] = invaders.get(i);
for (SIinvader s:invaders) {
if (s.getX() == x[i].getX()) {
if (s.getY() > x[i].getY()) {
x[i] = s;
}
}
}
}
return x;
}
private void move(boolean b) {
int defaultX = 5;
if (b) base.moveLeft(defaultX);
else base.moveRight(defaultX);
}
private void moveAI() {
for(SIinvader s : invaders) {
s.changeImage();
int defaultX = 5;
if (waveDirection) s.moveRight(defaultX);
else s.moveLeft(defaultX);
}
}
private void moveMissileBase() {
if (invaders.isEmpty()) return;
int movement = -5, bound = 0;
SImissile missile = missileBase.get(0);
missile.moveDown(movement);
SIinvader lowestInvader = getLowestInvader();
if (missile.getY() < (lowestInvader.getY() + lowestInvader.getHeight())) {
for (SIinvader s:bottomRow) {
if (checkCollision(missile, s)) {
s.setHit();
dead.add(s);
cast.remove(missile);
missileBase.clear();
score += s.value;
return;
}
}
if (mysteryCount > 0) {
if (checkCollision(missile, mysteryShip)) {
mysteryShip.setHit();
dead.add(mysteryShip);
cast.remove(missile);
missileBase.clear();
score += mysteryShip.value;
return;
}
}
if (missile.getY() < bound) {
missileBase.remove(missile);
cast.remove(missile);
}
}
}
private SIinvader getLowestInvader() {
SIinvader lowest = bottomRow[0];
for (SIinvader invader : bottomRow) {
if (invader.getY() > lowest.getY()) {
lowest = invader;
}
}
return lowest;
}
private void moveMissileInvader() {
int movement = 5, bound = (int) panelDimension.getHeight();
for (SImissile missile : missileInvader) {
missile.moveDown(movement);
if(missile.getY() >= base.getY()) {
if (checkCollision(missile, base)) {
base.setHit();
gameOver = true;;
missileInvader.remove(missile);
cast.remove(missile);
return;
} else if (missile.getY() >= bound-25) {
missileInvader.remove(missile);
cast.remove(missile);
return;
}
}
}
}
private boolean checkCollision(SIthing missile, SIthing ship) {
Rectangle2D rect1 = new Rectangle2D.Double(
missile.getX(),
missile.getY(),
missile.getWidth(),
missile.getHeight()
);
Rectangle2D rect2 = new Rectangle2D.Double(
ship.getX(),
ship.getY(),
ship.getWidth(),
ship.getHeight()
);
return rect1.intersects(rect2);
}
private void switchBack() {
int defaultY = 12;
for (SIinvader s : invaders) {
if (s.getY() > getHeight()) {
gameOver = true;
return;
}
s.moveDown(defaultY);
}
}
private void gameOver() {
pause(true);
SI.setGameOverLabelVisibile(true);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.GREEN);
Font font = new Font("Arial", 0, 20);
setFont(font);
String score = "Score: "+this.score;
Rectangle2D rect = font.getStringBounds(score, g2.getFontRenderContext());
int screenWidth = 0;
try { screenWidth = (int) panelDimension.getWidth(); }
catch (NullPointerException e) {}
g2.setColor(Color.GREEN);
g2.drawString(score, (int) (screenWidth - (10 + rect.getWidth())), 20);
for(SIthing a:cast) {
a.paint(g);
}
}
public SIpanel() {
super();
setBackground(Color.BLACK);
cast = new ArrayList<SIthing>();
missileBase = new ArrayList<SImissile>();
score = invaderPace = mysteryCount = pulseRate = 0;
sound = new Music("AmbientMusic.wav");
panel = this;
addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_LEFT : left = true; break;
case KeyEvent.VK_RIGHT : right = true; break;
case KeyEvent.VK_SPACE : space = true; break;
}
}
#Override
public void keyReleased(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_LEFT : left = false; break;
case KeyEvent.VK_RIGHT : right = false; break;
case KeyEvent.VK_SPACE : space = false; break;
}
}
});
setFocusable(true);
timer = new Timer(10, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
pulse();
}
});
}
public void reset() {
SI.setGameOverLabelVisibile(false);
score = invaderPace = mysteryCount = 0;
pulseRate = 50;
cast = new ArrayList<SIthing>();
invaders = new ArrayList<SIinvader>();
dead = new ArrayList<SIinvader>();
missileBase = new ArrayList<SImissile>();
missileInvader = new ArrayList<SImissile>();
base = new SIbase(230, 370, 26, 20);
waveDirection = true;
gameOver = false;
sound.stop();
sound.loop();
panelDimension = SI.getFrameDimensions();
bottomRow = getBottomRow();
newWave();
timer.start();
runningTimer=true;
}
public SIpanel getPanel() {
return this.panel;
}
public void pause(boolean paused) {
if (paused) timer.stop();
else timer.start();
}
}
I believe that collision detection may be the reason for lagging and you should simply investigate it by trying to increase and decrease count of enemies or missiles drastically to see if that makes a difference.
Consider garbage collector your enemy. In your checkCollision method you are instantiating two (very simple) objects. It may not seem like a lot, but consider that your might be creating them for each collision check, and that at 60fps it adds up until it may reach critical mass when GC says "stop the world" and you see noticeable lag.
If that is the case, possible solution to that would be to not instantiate any objects in a method called so frequently. You may create Rectangle2D once, and then update its position, instead of creating a new one each time, so you will avoid unnecessary memory allocation.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
Okey, I have no idea why I am getting this NullPointException. I have been trying for hours now, I AM GOING CRAZY!
Maybe some of u guys can help me. If u need more information, I will try to give it, just ask 4 it.
This is a link to a picture - CLICK ME! - NullPointerException
public class KjedetMengde<T> implements MengdeADT<T> {
private static Random rand = new Random();
private int antall; // antall elementer i mengden
private LinearNode<T> start;
/**
* Oppretter en tom mengde.
*/
public KjedetMengde() {
antall = 0;
start = null;
}//
#Override
public void leggTil(T element) {
if (!(inneholder(element))) {
LinearNode<T> node = new LinearNode<T>(element);
node.setNeste(start);
start = node;
antall++;
}
}
public void leggTilAlle(MengdeADT<T> m2) {
Iterator<T> teller = m2.oppramser();
while (teller.hasNext()) {
leggTil(teller.next());
}
}
#Override
public T fjernTilfeldig() {
LinearNode<T> forgjenger, aktuell;
T resultat = null;
if (!erTom()) {
int valg = rand.nextInt(antall) + 1;
if (valg == 1) {
resultat = start.getElement();
start = start.getNeste();
} else {
forgjenger = start;
for (int nr = 2; nr < valg; nr++) {
forgjenger = forgjenger.getNeste();
}
aktuell = forgjenger.getNeste();
resultat = aktuell.getElement();
forgjenger.setNeste(aktuell.getNeste());
}
antall--;
} // if
return resultat;
}//
#Override
public T fjern(T element) {
boolean funnet = false;
LinearNode<T> forgjenger = null;
LinearNode<T> aktuell = null;
T resultat = null;
if (!erTom()) {
if (start.getElement().equals(element)) {
resultat = start.getElement();
start = start.getNeste();
antall--;
} else {
forgjenger = start;
aktuell = start.getNeste();
for (int i = 1; i < antall && !funnet; i++) {
if (aktuell.getElement().equals(element)) {
funnet = true;
} else {
forgjenger = aktuell;
aktuell = aktuell.getNeste();
}
}
}
if (funnet) {
resultat = aktuell.getElement();
forgjenger.setNeste(aktuell.getNeste());
antall--;
}
}
return resultat;
}//
#Override
public MengdeADT<T> union(MengdeADT<T> m2) {// OBS! En bedre i kladdeopg4
KjedetMengde<T> begge = new KjedetMengde<T>();
LinearNode<T> aktuell = start;
while (aktuell != null) {
begge.leggTil(aktuell.getElement());
aktuell = aktuell.getNeste();
} // while
Iterator<T> teller = m2.oppramser();
while (teller.hasNext()) {
begge.leggTil(teller.next());
}
return begge;
}//
private void settInn(T element) {
LinearNode<T> nyNode = new LinearNode<T>(element);
nyNode.setNeste(start);
start = nyNode;
antall++;
}
#Override
public boolean inneholder(T element) {
boolean funnet = false;
LinearNode<T> aktuell = start;
for (int søk = 0; søk < antall && !funnet; søk++) {
if (aktuell.getElement().equals(element)) {
funnet = true;
} else {
aktuell = aktuell.getNeste();
}
}
return funnet;
}
#Override
public boolean erLik(MengdeADT<T> m2) {
boolean likeMengder = true;
T element = null;
if (antall() == m2.antall()) {
Iterator<T> teller = m2.oppramser();
while (teller.hasNext() && likeMengder) {
element = teller.next();
if (!this.inneholder(element)) {
likeMengder = false;
}
}
}
return likeMengder;
}
#Override
public boolean erTom() {
return antall == 0;
}
#Override
public int antall() {
return antall;
}
#Override
public Iterator<T> oppramser() {
return new KjedetIterator<T>(start);
}
#Override
public MengdeADT<T> snitt(MengdeADT<T> m2) {
KjedetMengde<T> kjede = new KjedetMengde<T>();
KjedetMengde<T> snitt = new KjedetMengde<T>();
LinearNode<T> aktuell = start;
while (aktuell != null) {
kjede.leggTil(aktuell.getElement());
aktuell = aktuell.getNeste();
}
Iterator<T> teller = m2.oppramser();
while (teller.hasNext()) {
T element = teller.next();
if (kjede.inneholder(element)) {
snitt.leggTil(element);
}
}
return snitt;
}
#Override
public MengdeADT<T> differans(MengdeADT<T> m2) { // (m1- m2)
KjedetMengde<T> kjede = new KjedetMengde<T>();
LinearNode<T> aktuell = start;
while (aktuell != null) {
kjede.leggTil(aktuell.getElement());
aktuell = aktuell.getNeste();
}
Iterator<T> teller = m2.oppramser();
while (teller.hasNext()) {
T element = teller.next();
if (kjede.inneholder(element)) {
kjede.fjern(element);
}
}
return kjede;
}
public String toString() {
String resultat = " ";
LinearNode<T> aktuell = start;
while (aktuell != null) {
resultat += aktuell.getElement().toString() + "\t";
aktuell = aktuell.getNeste();
}
return resultat;
}
}// class
public class Hobby {
private String hobbyNavn;
public Hobby (String hobby) {
hobbyNavn = hobby;
}
public String toString() {
return ("< " + hobbyNavn + " >");
}
public boolean equals (Object hobby2) {
Hobby hobbyDenAndre = (Hobby) hobby2;
return(hobbyNavn.equals(hobbyDenAndre.getHobbyNavn()));
}
public String getHobbyNavn() {
return hobbyNavn;
}
} //class
You are not initialising your hobbyer variable. You are even setting it to null in the constructor of Medlem.
Try
hobbyer = new KjedetMengde<Hobby>();
in either line 8 or 13 in your Medlem class.
Im having a problem getting my server to send image over a socket. I need to have 10 1920x1080 images sent to the client in a timecrunch of atleast 5-10 seconds. I seem to get an error anywhere I go or my client/server failsafes go off and make it impossible to send in those certain ways. Could anyone point me in the right direction and tell me a way to implement this without messing up other proccesses?
Client code for nonobject things, and used for UTF packets.
DataInputStream in ;
Client client;
public boolean enabled = true;
Object packet;
String[] tempData;
public Thread thread;
public Data(DataInputStream in , Client client) {
this. in = in ;
this.client = client;
}
#
Override
public void run() {
while (enabled) {
int x = 0, y = 0, width = 0, height = 0, r = 0, g = 0, b = 0, id = 0, mousex = 0, mousey = 0, alpha = 0;
String data = "Invalid";
try {
data = in.readUTF().trim();
} catch(Exception e){
client.comp.printErr("Disconnected from server, " + e.toString());
client.disconnectClient("Socket Closed.");
enabled = false;
}
try{
if (data.contains("id/")) {
data = data.split("id/")[1];
client.id = Integer.valueOf(data);
client.serverHasResponded = true;
client.comp.printOut("Client ID: " + data);
}
if (data.contains("rejected/")) {
data = data.split("rejected/")[1];
//Check to see if server sent packet info;
packet = "null";
try {
if (data.contains("/")) {
tempData = data.split("/");
data = tempData[0];
packet = "null";
for (int i = 1; i < tempData.length; i++) {
if (!packet.equals("null")) {
packet = packet + "/" + tempData[i];
} else packet = tempData[i];
}
}
// Packet info done.
} catch (Exception e) {
client.comp.printErr("Error while splitting packet: " + e.toString());
}
if (Integer.valueOf(data) == 0) {
client.disconnectClient("No Slots Open.");
client.comp.printErr("Rejected from server, no slots open.");
enabled = false;
}
if (Integer.valueOf(data) == 1) {
client.disconnectClient("Invalid Version.");
client.comp.printErr("Rejected from server, invalid version.");
enabled = false;
}
if (Integer.valueOf(data) == 2) {
client.disconnectClient("Kicked.");
client.comp.printErr("Rejected from server, kicked.");
enabled = false;
}
if (Integer.valueOf(data) == 3) {
client.disconnectClient("Unknown Packet.");
client.comp.printErr("Rejected from server, client sent unknown packet on connection? Packet: " + packet);
enabled = false;
}
if (Integer.valueOf(data) == 4) {
client.disconnectClient("Already Logged in.");
client.comp.printErr("Rejected from server, the username " + client.comp.username + " is already logged on?");
enabled = false;
}
if (Integer.valueOf(data) == 5) {
client.disconnectClient("Not Authenticated");
client.comp.printErr("Rejected from server, server requires authentication and were not authenticated?");
enabled = false;
}
if (Integer.valueOf(data) == 6) {
client.disconnectClient("No tick from client.");
client.comp.printErr("Rejected from server, server didnt recieve a tick?");
enabled = false;
}
if (Integer.valueOf(data) == 7) {
client.disconnectClient("No open Canvases.");
client.comp.printErr("Rejected from server, all canvases blacklisted?");
enabled = false;
}
if (Integer.valueOf(data) == 8) {
client.disconnectClient("Banned.");
client.comp.printErr("Rejected from server, Banned.");
enabled = false;
}
}
if(data.contains("servertick/")){
data = data.split("servertick/")[1];
if(Integer.valueOf(data) == client.id){
client.heartbeatManager.serverTicked();
} else {
client.comp.printErr("Server sent an invalid tick.");
}
}
if(data.contains("changeCanvas/")){
data = data.split("changeCanvas/")[1];
client.currentCanvas = Integer.parseInt(data);
}
if(data.contains("changeCanvasFailed/")){
data = data.split("changeCanvasFailed/")[1];
client.popups.add(new Popup(client, "Error", "Access denied to canvas "+data+"."));
}
if(data.contains("overrideChangeCanvas/")){
data = data.split("overrideChangeCanvas/")[1];
client.currentCanvas = Integer.parseInt(data);
client.comp.printOut(data);
}
if(data.contains("broadcastToClient/")){
data = data.split("broadcastToClient/")[1];
client.chat.addChatMessage(data, Color.white);
}
if (data.contains("chatmessage/")) {
data = data.split("chatmessage/")[1];
String[] tokens = data.split("/");
String user = "";
String message = "";
for (int i = 0; i < tokens.length; i++) {
if (i == 0)
user = tokens[0];
if (i == 1)
message = tokens[1];
}
client.chat.addChatMessage(user + ": " + message, Color.white);
}
if (data.contains("drawcircle/")) {
data = data.split("drawcircle/")[1];
String[] tokens = data.split("/");
for (int i = 0; i < tokens.length; i++) {
if (i == 0)
x = Integer.valueOf(tokens[i]);
if (i == 1)
y = Integer.valueOf(tokens[i]);
if (i == 2)
width = Integer.valueOf(tokens[i]);
if (i == 3)
height = Integer.valueOf(tokens[i]);
if (i == 4)
r = Integer.valueOf(tokens[i]);
if (i == 5)
g = Integer.valueOf(tokens[i]);
if (i == 6)
b = Integer.valueOf(tokens[i]);
if (i == 7)
id = Integer.valueOf(tokens[i]);
if (i == 8)
alpha = Integer.valueOf(tokens[i]);
}
client.canvas[id].draw(x, y, width, height, r, g, b, alpha);
}
if (data.contains("erasecircle/")) {
data = data.split("erasecircle/")[1];
String[] tokens = data.split("/");
for (int i = 0; i < tokens.length; i++) {
if (i == 0)
x = Integer.valueOf(tokens[i]);
if (i == 1)
y = Integer.valueOf(tokens[i]);
if (i == 2)
width = Integer.valueOf(tokens[i]);
if (i == 3)
height = Integer.valueOf(tokens[i]);
if (i == 7)
id = Integer.valueOf(tokens[i]);
}
client.canvas[id].erase(x, y, width, height);
}
if (data.contains("playerjoin/")) {
data = data.split("playerjoin/")[1];
client.chat.addChatMessage(data+" has joined the game.", Color.yellow);
}
if (data.contains("playerleave/")) {
data = data.split("playerleave/")[1];
client.chat.addChatMessage(data+" has left the game.", Color.yellow);
}
} catch (Exception e) {
client.comp.printErr("Failed to process a packet, " + e.toString());
}
}
}
public void close() throws Exception{
thread.stop();
enabled = false;
}
public void setThread(Thread t){
thread = t;
}
Client code ment for images (not modified yet) :
Client client;
DataInputStream in;
Thread thread;
public DataObjects(DataInputStream in, Client c){
client = c;
this.in = in;
thread = new Thread(this);
thread.start();
}
#Override
public void run() {
boolean enabled = true;
while(enabled){
}
}
Server code ment to send/recieve and reroute both UTF and Object packets
public DataOutputStream out;
public DataInputStream in;
public User[] user;
public int slots;
public int id;
InetAddress address;
Server server;
public String username = "";
public boolean enabled;
public boolean ticking;
public boolean allDataSent;
int currentCanvas = 0;
private boolean playerConnected;
public boolean imageByteReady=true;
private boolean sendImage;
public User(DataOutputStream out, DataInputStream in, User[] user, int slots, int i, InetAddress inetAddress, Server server, String username){
this.out = out;
this.in = in;
this.user = user;
this.slots = slots;
this.id = i;
address = inetAddress;
this.server = server;
this.username = username;
ticking = true;
}
#Override
public void run() {
enabled = true;
while(enabled){
try {
String data = in.readUTF();
if(valid(data)){
for(int i = 0; i < slots; i++){
if(user[i]!=null){
if(data.contains("timedout/")){
data = data.split("timedout/")[1];
if(Integer.valueOf(data) == 1){
server.printOut(server.disconnectMessage(id, "Client disconnected because server didnt tick."));
user[id] = null;
enabled = false;
} else {
server.printErr("Got an invalid timeout packet. Packet: timedout/"+data);
}
}
if(data.contains("clienttick/")){
data = data.split("clienttick/")[1];
out.writeUTF("servertick/"+data);
server.packetManager.resetClientWithID(Integer.valueOf(data));
}
if(data.contains("drawcircle/") || data.contains("erasecircle/") || data.contains("chatmessage/"))
user[i].out.writeUTF(data);
}
}
if(data.contains("switchcanvas/")){
data = data.split("switchcanvas/")[1];
if(server.canvasaccessmanager.playerCanBeOnCanvas(id, Integer.valueOf(data)) && Integer.valueOf(data) != currentCanvas){
out.writeUTF("changeCanvas/"+data);
currentCanvas = Integer.valueOf(data);
server.printOut(user[id].username+" switched to canvas "+(Integer.valueOf(data)+1));
} else if(!server.canvasaccessmanager.playerCanBeOnCanvas(id, Integer.valueOf(data))){
out.writeUTF("changeCanvasFailed/"+data);
server.printOut(user[id].username+" was denied access to canvas "+(Integer.valueOf(data)+1));
}
}
if(data.contains("sendImage/")){
data = data.split("sendImage/")[1];
sendImage = Boolean.valueOf(data);
}
if (data.contains("drawcircle/")) {
data = data.split("drawcircle/")[1];
String[] tokens = data.split("/");
int x = 0, y = 0, width = 0, height = 0, r = 0, g = 0, b = 0, id = 0, alpha = 0;
for (int i = 0; i < tokens.length; i++) {
if (i == 0)
x = Integer.valueOf(tokens[i]);
if (i == 1)
y = Integer.valueOf(tokens[i]);
if (i == 2)
width = Integer.valueOf(tokens[i]);
if (i == 3)
height = Integer.valueOf(tokens[i]);
if (i == 4)
r = Integer.valueOf(tokens[i]);
if (i == 5)
g = Integer.valueOf(tokens[i]);
if (i == 6)
b = Integer.valueOf(tokens[i]);
if (i == 7)
id = Integer.valueOf(tokens[i]);
if (i == 8)
alpha = Integer.valueOf(tokens[i]);
}
server.canvasManager.drawCircle(x, y, width, height, r, g, b, alpha, id);
}
if (data.contains("erasecircle/")) {
data = data.split("erasecircle/")[1];
String[] tokens = data.split("/");
int x = 0, y = 0, width = 0, height = 0, id = 0;
for (int i = 0; i < tokens.length; i++) {
if (i == 0)
x = Integer.valueOf(tokens[i]);
if (i == 1)
y = Integer.valueOf(tokens[i]);
if (i == 2)
width = Integer.valueOf(tokens[i]);
if (i == 3)
height = Integer.valueOf(tokens[i]);
if (i == 7)
id = Integer.valueOf(tokens[i]);
}
server.canvasManager.eraseCircle(x, y, width, height, id);
}
if(data.contains("chatmessage/")){
data = data.split("chatmessage/")[1];
String[] tokens = data.split("/");
String user = "";
String message = "";
for (int x = 0; x < tokens.length; x++) {
if (x == 0)
user = tokens[0];
if (x == 1)
message = tokens[1];
}
server.printOut(user + " said '" + message+"'");
}
} else {
server.printErr("Caught an overlapped packet from client "+id);
server.packetManager.resetClientWithID(id);
}
} catch (IOException e) {
if(enabled){
server.printOut(server.disconnectMessage(id, "Client socket closed. Manual disconnect?"));
user[id] = null;
enabled = false;
}
}
}
saveUserData();
if(playerConnected)
sendLeaveMessage();
}
private boolean valid(String data) {
String[] tokens = data.split("/");
if(tokens[1].toLowerCase().contains(inputFix(tokens[0]))){
return false;
}
return true;
}
private String inputFix(String data) {
return data.replaceAll("[^a-zA-Z]", "").toLowerCase().trim();
}
private void saveUserData() {
server.playermanager.setUserProperty(username, "currentCanvas", String.valueOf(currentCanvas));
}
public void sendID() {
try {
out.writeUTF("id/"+id);
playerConnected = true;
} catch (IOException e) {
e.printStackTrace();
}
}
public void sendCanvases() {
try{
sendCanvas(0);
server.printOut("Sent canvas 0");
Thread.sleep(1);
} catch(Exception e){
server.printErr("Failed to send canvas 0");
sendCanvases();
}
}
public void sendCanvas(int id) throws Exception{
}
public void sendLeaveMessage(){
for(int i = 0; i < slots; i++){
if(i != id){
if(user[i] != null){
try {
user[i].out.writeUTF("playerleave/"+username);
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
}
public void sendJoinMessage() {
for(int i = 0; i < slots; i++){
if(i != id){
if(user[i] != null){
try {
user[i].out.writeUTF("playerjoin/"+username);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
public void sendData() {
if(server.playermanager.userExists(username)){
int x = Integer.parseInt(server.playermanager.loadUserProperty(username, "currentCanvas"));
currentCanvas = x;
try {
out.writeUTF("overrideChangeCanvas/"+x);
} catch (Exception e) {
e.printStackTrace();
}
return;
}
//If user is new;
int x = server.canvasaccessmanager.nextOpenCanvas(username);
try {
currentCanvas = x;
out.writeUTF("overrideChangeCanvas/"+x);
} catch (Exception e) {
e.printStackTrace();
}
}
public void setUpUserData() {
if(!server.playermanager.userExists(username)){
server.playermanager.createUser(username);
}
}
Client code:
public Dimension dimension;
static final long serialVersionUID = 1L;
public Thread thread;
public int currentfps;
public long start;
public int fps;
static Socket socket;
public static DataInputStream in ;
public Listener listener = null;
public boolean isRunning = true;
public boolean justClicked;
public static int canvasMax = 10;
public Canvas[] canvas = new Canvas[canvasMax];
public int currentCanvas;
public Graphics canvasGraphics;
public Player player;
public DataOutputStream out;
public boolean connectedToServer = false;
public boolean click;
public int id;
public Image screen;
public static Toolkit toolkit = Toolkit.getDefaultToolkit();
public static Image cursor = toolkit.getImage("res/icons/cursor.png");
public static Image tabCanvas = toolkit.getImage("res/image/tabs/tabCanvas.png");
public static Image tabColor = toolkit.getImage("res/image/tabs/tabColor.png");
public Image tabGuide = toolkit.getImage("res/image/tabs/tabGuide.png");;
public static Image[] guideImages = new Image[canvasMax];
public int tabOffset = 0, tabWidth = 200, currentTabWidth = 0, tabHeight = 0;
public boolean ChatOpen;
public CanvasGUI canvasgui;
public int currentColor;
public int colorMax = 10;
public boolean serverHasResponded = false;
public int wait;
public Data data;
public Chat chat;
public int defaultPort = 58828;
public int port = 0;
public String ip = "";
public ColorGUI colorgui;
public GuideGUI guidegui;
public int currentGuide;
public int waitMax = 1000000;
public HeartbeatManager heartbeatManager;
public ArrayList<Popup> popups;
public Integer lastCanvasClick;
private boolean debug;
public ServerLogin serverLogin;
public boolean serverLoginOpen;
public Component comp;
int index;
public boolean started;
private boolean disconnecting;
public boolean clientHasRecieved;
public Client(Component component) {
this.comp = component;
}
public void connectClient(String ip, int port) {
try {
this.ip = ip;
this.port = port;
socket = new Socket(ip, port);
in = new DataInputStream(socket.getInputStream());
out = new DataOutputStream(socket.getOutputStream());
connectedToServer = true;
out.writeUTF("authenticate/" + comp.authenticated);
out.writeUTF("username/" + comp.username);
out.writeUTF("version/" + comp.version);
data = new Data( in , this);
Thread thread = new Thread(data);
data.setThread(thread);
thread.start();
DataObjects dataObjects = new DataObjects(in, this);
} catch (Exception e) {
comp.printErr("Failed to connect to server, " + e.toString());
disconnectClient("Failed to connect");
}
}
public void disconnectClient(String var1) {
if(!disconnecting){
disconnecting = true;
try {
in = null;
out = null;
if (data != null){
data.enabled = false;
data = null;
};
if(connectedToServer)
socket.close();
socket = null;
connectedToServer = false;
serverHasResponded = false;
wait = 0;
String str = "Disconnected from server "+ip+":"+port+", "+var1;
comp.printOut(str);
ip = "";
port = 0;
comp.stopGame();
comp.startWarningMenu(str);
} catch (Exception e) {
e.printStackTrace();
}
}
}
void initializing(int i) {
index = i;
comp.printOut("Index: "+i+".");
tabHeight = comp.height;
isRunning = true;
comp.printOut("Creating Canvases.");
for (int x = 0; x < canvasMax; x++) {
canvas[x] = new Canvas(this);
canvas[x].clear(0, 0, comp.width, comp.height);
comp.printOut("Creating Canvas"+(x+1)+".");
}
comp.printOut("Canvases Created.");
comp.printOut("Loading Guides.");
for (int x = 0; x < guideImages.length; x++) {
guideImages[x] = toolkit.getImage("res/image/guides/guides_" + x + ".png");
if (!new File("res/image/guides/guides_" + x + ".png").exists()) {
guideImages[x] = toolkit.getImage("res/image/guides/guides_0.png");
comp.printErr("Couldnt Locate Guide"+(x+1)+".");
} else {
comp.printOut("Loaded Guide"+(x+1)+".");
}
}
colorgui = new ColorGUI(this);
comp.printOut("Loaded ColorGUI.");
guidegui = new GuideGUI(this);
comp.printOut("Loaded GuideGUI.");
chat = new Chat(this);
comp.printOut("Loaded Chatting Class.");
popups = new ArrayList<Popup>();
comp.printOut("Loaded ArrayList<Popup>.");
currentCanvas = 0;
heartbeatManager = new HeartbeatManager(this);
comp.printOut("Loaded Heartbeat Manager.");
canvasgui = new CanvasGUI(this);
comp.printOut("Loaded CanvasGUI.");
screen = comp.createImage(comp.pixel.width, comp.pixel.height);
comp.printOut("Loaded Screen Component.");
player = new Player(this);
comp.printOut("Loaded Player Class.");
serverLogin = new ServerLogin(this);
comp.printOut("Loaded Server Login GUI.");
started = true;
comp.printOut("Starting Threads. Game Loading done!");
thread = new Thread(this);
thread.setPriority(6);
thread.start();
}
Looks like a case for buffering to get better throughput. I see you instantiating DataInputStream/DataOutputStream, but those aren't buffered so I think you could get a big boost by adding BufferedInput/OutputStream to each side. I don't see your code where you copy the image to the stream. So the following should help:
in = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
out = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()));
Just remember to flush(). The other option you can do is compress your data before sending it over the stream. If you are sending a 1920x1080 image uncompressed would be around 8MB (=1920px * 1080px * 4 bytes / pixel) so 5-10s is not a surprising. Adding a GZipInputStream on top of that is pretty simple, and would compress all data sent. Image specific compression would probably achieve a higher compression, but more involved.
I have this applet and i cant figure out why it doesnt load on html page.I have added full permissions in java.policy file. I use the default html file from NetBeans Applet's output.
/* Hearts Cards Game with AI*/
import java.applet.Applet;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Random;
import javax.swing.JOptionPane;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import java.awt.Graphics;
import java.awt.Image;
import java.security.AccessController;
import javax.swing.ImageIcon;
import javax.swing.*;
import javax.swing.JPanel;
public class Game extends JApplet implements MouseListener, Runnable {
int initNoCards = 13;
int width, height;
boolean endGame = false;
int turn = -1;
int firstCard = 0;
int firstTrick = 0;
String leadingSuit = null;
Cards leadingCard = null;
Cards playCard = null;
String startCard = "c2";
Cards[] trickCards = new Cards[4];
ArrayList<Cards>[] playerCards = new ArrayList[4];
ArrayList<Cards>[] takenCards = new ArrayList[4];
boolean heartsBroken = false;
ArrayList<Cards> cards = new ArrayList<Cards>();
String[] hearts = {"h2", "h3", "h4", "h5", "h6", "h7", "h8", "h9", "h10", "h12", "h13", "h14", "h15"};
String queen = "s13";
int cardHeight = 76;
int cardWidth = 48;
ArrayList<Rectangle> rectangles = new ArrayList<Rectangle>();
int selectedCard = -1;
//set the background image
Image backImage = new ImageIcon("deck\\back2.png").getImage();
public void GetDataFromXML() {
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
DefaultHandler handler = new DefaultHandler() {
boolean name = false;
boolean image = false;
#Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
if (qName.equalsIgnoreCase("NAME")) {
name = true;
}
if (qName.equalsIgnoreCase("IMAGE")) {
image = true;
}
}
#Override
public void endElement(String uri, String localName,
String qName) throws SAXException {
}
#Override
public void characters(char ch[], int start, int length) throws SAXException {
String s = new String(ch, start, length);
if (name) {
cards.add(new Cards(s));
name = false;
}
if (image) {
image = false;
}
}
};
saxParser.parse("deck\\deck.xml", handler);
} catch (Exception e) {
}
}
//function for comparing cards from same suite
public boolean lowerThan(Cards c1, Cards c2) {
int a, b;
a = Integer.parseInt(c1.getName().substring(1));
b = Integer.parseInt(c2.getName().substring(1));
return a < b;
}
//checks if a card is valid to play
public boolean ValidMove(Cards c) {
if (firstCard == 0) {
if (c.getName().equals(startCard)) {
firstCard = 1;
return true;
}
return false;
}
boolean result = playerCards[turn].indexOf(c) >= 0;
if (leadingSuit == null) {
return result;
}
boolean found = false;
for (int i = 0; i < playerCards[turn].size(); i++) {
if (playerCards[turn].get(i).getName().charAt(0) == leadingSuit.charAt(0)) {
found = true;
break;
}
}
if (!found) {
boolean justHearts = true;
for (int i = 0; i < playerCards[turn].size(); i++) {
if (playerCards[turn].get(i).getName().charAt(0) != 'h') {
justHearts = false;
break;
}
}
if (firstTrick == 0) {
if (c.getName().equals(queen)) {
return false;
}
if (!justHearts && c.getName().charAt(0) == 'h') {
return false;
}
} else {
if (c.getName().charAt(0) == 'h' && leadingSuit == null && !heartsBroken && !justHearts) {
return false;
}
}
} else {
if (c.getName().charAt(0) != leadingSuit.charAt(0)) {
return false;
}
}
return result;
}
#Override
public void init() {
GetDataFromXML();
setSize(500, 500);
width = super.getSize().width;
height = super.getSize().height;
setBackground(Color.white);
addMouseListener(this);
for (int i = 0; i < cards.size(); i++) {
System.out.println(cards.get(i).getName());
System.out.println(cards.get(i).getImage());
}
Shuffle();
}
public int GetTrickCount() {
int count = 0;
for (int i = 0; i < trickCards.length; i++) {
if (trickCards[i] != null) {
count++;
}
}
return count;
}
public void ResetTrick() {
for (int i = 0; i < trickCards.length; i++) {
trickCards[i] = null;
}
}
#Override
public void run() {
try {
PlayTurn();
} catch (InterruptedException ex) {
}
}
public void start() {
Thread th = new Thread(this);
th.start();
}
//function for shuffling cards and painting players cards
public void Shuffle() {
for (int i = 0; i < 4; i++) {
playerCards[i] = new ArrayList<Cards>();
takenCards[i] = new ArrayList<Cards>();
}
ArrayList<Cards> list = new ArrayList<Cards>();
list.addAll(cards);
Collections.shuffle(list);
for (int i = 0; i < list.size(); i++) {
System.out.print(list.get(i).getName() + " ");
}
//initializare liste carti
for (int i = 0; i < 4; i++) {
playerCards[i] = new ArrayList<Cards>();
takenCards[i] = new ArrayList<Cards>();
for (int j = 0; j < initNoCards; j++) {
playerCards[i].add((list.get(j + i * initNoCards)));
if (list.get(j + i * initNoCards).getName().equals(startCard)) {
turn = i;
}
}
Collections.sort(playerCards[i], c);
ShowCards(i);
}
for (int i = 0; i < playerCards[0].size() - 1; i++) {
rectangles.add(new Rectangle((141 + 1) + 13 * i - 2, 350 + 1, 13 - 2, cardHeight - 1));
}
rectangles.add(new Rectangle((141 + 1) + 13 * 12 - 2, 350 + 1, cardWidth, cardHeight - 1));
ShowPlayersCards();
}
Comparator<Cards> c = new Comparator<Cards>() {
#Override
public int compare(Cards o1, Cards o2) {
if (o2.getName().charAt(0) != o1.getName().charAt(0)) {
return o2.getName().charAt(0) - o1.getName().charAt(0);
} else {
int a, b;
a = Integer.parseInt(o1.getName().substring(1));
b = Integer.parseInt(o2.getName().substring(1));
return a - b;
}
}
};
public void PlayTurn() throws InterruptedException {
endGame = true;
System.out.println("Its " + turn);
for (int i = 0; i < 4; i++) {
if (!playerCards[i].isEmpty()) {
endGame = false;
}
}
if (endGame) {
System.out.println("Game over!");
GetPlayersScore();
return;
}
if (turn != 0) {
Random r = new Random();
int k = r.nextInt(playerCards[turn].size());
Cards AIcard = playerCards[turn].get(k);
while (!ValidMove(AIcard)) {
k = r.nextInt(playerCards[turn].size());
AIcard = playerCards[turn].get(k);
}
leadingCard = AIcard;
playCard = AIcard;
} else {
System.out.println("\nIt is player's (" + turn + ") turn");
System.out.println("Player (" + turn + ") enter card to play:");
leadingCard = null;
playCard = null;//new Cards(read);
while (true) {
if (playCard != null) {
break;
}
Thread.sleep(50);
}
}
repaint();
Thread.sleep(1000);
repaint();
if (playCard.getName().charAt(0) == 'h') {
heartsBroken = true;
}
playerCards[turn].remove(playCard);
trickCards[turn] = playCard;
if (GetTrickCount() == 1)//setez leading suit doar pentru trickCards[0]
{
leadingSuit = GetSuit(playCard);
}
System.out.println("Leading suit " + leadingSuit);
System.out.println("Player (" + turn + ") chose card " + playCard.getName() + " to play");
ShowTrickCards();
ShowPlayersCards();
if (GetTrickCount() < 4) {
turn = (turn + 1) % 4;
} else {
turn = GetTrickWinner();
leadingSuit = null;
firstTrick = 1;
playCard = null;
repaint();
}
PlayTurn();
}
public void ShowTrickCards() {
System.out.println("Cards in this trick are:");
for (int i = 0; i < 4; i++) {
if (trickCards[i] != null) {
System.out.print(trickCards[i].getName() + " ");
}
}
}
public String GetSuit(Cards c) {
if (c.getName().contains("c")) {
return "c";
}
if (c.getName().contains("s")) {
return "s";
}
if (c.getName().contains("h")) {
return "h";
}
if (c.getName().contains("d")) {
return "d";
}
return null;
}
public String GetValue(Cards c) {
String get = null;
get = c.getName().substring(1);
return get;
}
public int GetTrickWinner() {
int poz = 0;
for (int i = 1; i < 4; i++) {
if (trickCards[poz].getName().charAt(0) == trickCards[i].getName().charAt(0) && lowerThan(trickCards[poz], trickCards[i]) == true) {
poz = i;
}
}
System.out.println("\nPlayer (" + poz + ") won last trick with card " + trickCards[poz].getName());
ResetTrick();
return poz;
}
public void ShowPlayersCards() {
ShowCards(0);
ShowCards(1);
ShowCards(2);
ShowCards(3);
}
public void GetPlayersScore() {
GetScore(0);
GetScore(1);
GetScore(2);
GetScore(3);
}
public void ShowCards(int player) {
System.out.print("\nPlayer (" + player + ") cards: ");
for (int i = 0; i < playerCards[player].size(); i++) {
System.out.print(playerCards[player].get(i).getName() + " ");
}
System.out.println();
}
public int GetScore(int player) {
int score = 0;
for (int i = 0; i < takenCards[player].size(); i++) {
for (int j = 0; j < hearts.length; j++) {
if (takenCards[player].get(i).getName().equals(hearts[j])) {
score++;
break;
}
}
if (takenCards[player].get(i).getName().equals(queen)) {
score += 13;
}
}
return score;
}
#Override
public void paint(Graphics g) {
g.drawImage(backImage, 0, 0, getWidth(), getHeight(), this);
for (int i = 0; i < playerCards[0].size(); i++) {
if (selectedCard == i) {
g.drawImage(playerCards[0].get(i).getImage(), 141 + i * 13, 340, null);
} else {
g.drawImage(playerCards[0].get(i).getImage(), 141 + i * 13, 350, null);
}
if (trickCards[0] != null) {
g.drawImage(trickCards[0].getImage(), 225, 250, 48, 76, null);
}
if (trickCards[1] != null) {
g.drawImage(trickCards[1].getImage(), 177, 174, 48, 76, null);
}
if (trickCards[2] != null) {
g.drawImage(trickCards[2].getImage(), 225, 98, 48, 76, null);
}
if (trickCards[3] != null) {
g.drawImage(trickCards[3].getImage(), 273, 174, 48, 76, null);
}
}
}
#Override
public void mouseClicked(MouseEvent e) {
if (turn != 0) {
return;
}
for (int i = 0; i < rectangles.size(); i++) {
if (rectangles.get(i).contains(e.getPoint())) {
if (i == selectedCard) {
if (ValidMove(playerCards[0].get(i))) {
selectedCard = -1;
rectangles.get(rectangles.size() - 2).width = rectangles.get(rectangles.size() - 1).width;
playCard = playerCards[0].get(i);
leadingCard = playCard;
rectangles.remove(rectangles.size() - 1);
trickCards[0] = playerCards[0].remove(i);
} else {
if (firstCard == 0) {
JOptionPane.showMessageDialog(this, "You have to play 2 of clubs!");
}
}
} else {
selectedCard = i;
rectangles.get(i).y -= 10;
}
repaint();
break;
}
}
}
#Override
public void mousePressed(MouseEvent e) {
}
#Override
public void mouseReleased(MouseEvent e) {
}
#Override
public void mouseEntered(MouseEvent e) {
}
#Override
public void mouseExited(MouseEvent e) {
}
}
class Cards extends JPanel {
private String name;
private String image;
private Image img;
public Cards(String name) {
super();
this.name = name;
this.image = "deck\\" + name + ".png";
this.img = new ImageIcon(image).getImage();
}
public Cards() {
super();
this.name = null;
this.image = null;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Image getImage() {
return img;
}
public void setImage(String image) {
this.image = image;
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof Cards)) {
return false;
}
Cards c = (Cards) obj;
return name.equals(c.getName()) && image.equals(c.getImage());
}
#Override
public int hashCode() {
int hash = 7;
hash = 31 * hash + (this.name != null ? this.name.hashCode() : 0);
hash = 31 * hash + (this.image != null ? this.image.hashCode() : 0);
return hash;
}
#Override
public void paint(Graphics g) {
g.drawImage(img, WIDTH, HEIGHT, this);
}
public boolean lowerThan(Cards c1, Cards c2) {
int a, b;
a = Integer.parseInt(c1.getName().substring(1));
b = Integer.parseInt(c2.getName().substring(1));
return a < b;
}
public int compareTo(Cards c) {
if (c.getName().charAt(0) != name.charAt(0)) {
return c.getName().charAt(0) - name.charAt(0);
} else {
int a, b;
a = Integer.parseInt(name.substring(1));
b = Integer.parseInt(c.getName().substring(1));
return a - b;
}
}
}
HTML
<HTML>
<HEAD>
<TITLE>Applet HTML Page</TITLE>
</HEAD>
<BODY>
<H3><HR WIDTH="100%">Applet HTML Page<HR WIDTH="100%"></H3>
<P>
<APPLET codebase="classes" code="Game.class" width=350 height=200></APPLET>
</P>
<HR WIDTH="100%"><FONT SIZE=-1><I>Generated by NetBeans IDE</I></FONT>
</BODY>
</HTML>
Image backImage = new ImageIcon("deck\\back2.png").getImage();
If I am the user of the applet when it is on the internet, the will cause the JRE to search for a File relative to the current user directory on my PC, either that or the cache of FF. In either case, it will not locate an image by the name of back2.png.
For fear of sounding like a looping Clip:
Resources intended for an applet (icons, BG image, help files etc.) should be accessed by URL.
An applet will not need trust to access those resources, so long as the resources are on the run-time class-path, or on the same server as the code base or document base.
Further
I have added full permissions in java.policy file.
This is pointless. It will not be workable at time of deployment unless you control every machine it is intended to run on. If an applet needs trust in a general environment, it needs to be digitally signed. You might as well sign it while building the app.
cant figure out why it doesnt load on html page.
Something that would assist greatly is to configure the Java Console to open when an applet is loaded. There is a setting in the last tab of the Java Control Panel that configures it.