java - dealing with multiple player thread and repainting -
i working on java bomber-man game, game works fine have concurrent modification exception thrown repeatedly. in game have 2 players , each have own thread run (thread.run()) @ constant 60fps using timer. tried having repainting run after bother thread run @ end of each player run method.
method 1:
public void loop(){ if(!gameover){ player1_thread.run(); //run player 1 thread player2_thread.run(); //run player 2 thread gui.repaint() //repaint panel }
method 2:
public class player extends character{ //character implements runnable ... @override public void run(){ play(); ... game.render(); }
both of these method throws concurrent modification expected how can avoid error other doing:
player1.run(); //call run method of each player class player2.run();
which gives player1 advantage.
edit:
method 4:
import java.util.timer public class player extends character { //character implements runnable private timer gametimer @ovveride public void run(){ gametimer.scheduleatfixedrate(new timertask(){ @override public void run() { play(); ... game.render(); } }, 0, 1000/60); } public class game extends abstractgame { private void init(){ ... thread player1_thread = new thread(player1); thread player2_thread = new thread(player2); gui = new gamegraphics(this); //subclass of jpanel player1_thread.start(); player2_thread.start(); } /* method called @ constant 60fps(like player timer) in main game timer in abstract game class */ public void gameloop(){ if(!gameover){ render(); ... } }
this throws exception
wrong : calling run() execute instructions using main thread.
correct: call player1.start() start new thread, run() {...} executed in newly started thread.
Comments
Post a Comment