如何解决如何从活动中获取Surface View属性? 表面视图和活动
我正在编程一个吃豆人,游戏是在SurfaceView中绘制的,但是我无法暂停它并在运行时获取属性(我没有设置它们)
例如,我设置了一个信号量,该信号量应在“活动”和“游戏”视图中进行引用,并且设置为正确,但是当游戏视图的线程正在运行时,尝试释放该信号量表示NullPointerException。
另一方面,当我尝试暂停游戏时,该游戏过去一直在后台运行,而当我继续运行时,它不再运行
我确定问题出在内存中的引用,当我将其设置和归为静态时,我可以从两者访问(视图和曲面视图是同一对象)。我不知道为什么会这样。
简要履历:AppCompatActivity(即PlayActivity)具有SurfaView(即GameView),而此SurfaceView具有GameManager(此刻具有pacman的所有功能)。 AppCompatActivity尝试获取某些SurfaceView(例如gameManager)时的引用在执行中丢失。 这里的代码
PlayActivity
public class PlayActivity extends AppCompatActivity {
private TextView playerNickname;
private TextView scoreTv;
private TextView maxscore;
private SurfaceView gameSurfaceView;
private GameView gameView;
private static Semaphore CHANGE_LIFES_MUTEX=new Semaphore(0,true);
private static Semaphore CHANGE_score_MUTEX=new Semaphore(0,true);
private static Semaphore CHANGE_DIRECTION_MUTEX=new Semaphore(0,true);
private Thread changescoreThread,changeDirectionThread;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Modified code
setContentView(R.layout.activity_game);
//we get text view that we will use
playerNickname=(TextView) this.findViewById(R.id.tv_player);
scoreTv=(TextView) this.findViewById(R.id.tv_current_score);
maxscore=(TextView) this.findViewById(R.id.tv_current_max_score);
gameSurfaceView= (GameView) this.findViewById(R.id.game_view);
//set text view initial values
playerNickname.setText(getIntent().getExtras().getString("playerNickname"));
scoreTv.setText("0");
maxscore.setText("To modify");
this.gameView=new GameView(gameSurfaceView.getContext());
this.gameView.setSemaphores(CHANGE_score_MUTEX,CHANGE_DIRECTION_MUTEX);
this.gameSurfaceView.getHolder().addCallback(this.gameView);
}
protected void onResume(){
super.onResume();
this.gameView.resume();
this.initChangerThreads();
}
public void updatescoreTv(int score){
this.scoreTv.setText(""+score);
}
protected void onPause(){
super.onPause();
this.gameView.pause();
//in order to stop the threads
CHANGE_score_MUTEX.release();
CHANGE_DIRECTION_MUTEX.release();
}
public void onLose(int score){
//We try to save the score,if there is a prevIoUs register we write only if this score
//is better that the one before
DBManager manager;
long raw;
score scoreToSave;
manager=new DBManager(this);
scoreToSave=new score(this.playerNickname.toString(),score);
if(manager.savescore(scoreToSave)==-1){
//if i Couldn't save the score
if(manager.updatescore(scoreToSave)!=-1){
//if my new score is better than the one prevIoUs
}else{
//if my new score is worse or equal than the one prevIoUs
}
}
}
private void initChangerThreads() {
this.changescoreThread = new Thread(new Runnable() {
public void run() {
while (gameView.isDrawing()) {
//Log.i("score ",""+gameManager.getscore());
try {
CHANGE_score_MUTEX.acquire();
runOnUiThread(new Runnable() {
@Override
public void run() {
updatescoreTv(gameView.getGameManager().getscore());
}
});
}catch (Exception e){}
}
Log.i("score Thread","ended");
}
});
this.changescoreThread.start();
}
}
GameView
public class GameView extends SurfaceView implements Runnable,SurfaceHolder.Callback,GestureDetector.OnGestureListener {
private static final float SWIPE_THRESHOLD = 2;
private static final float SWIPE_VELociTY = 2;
private static boolean CAN_DRAW = false;
private boolean GHOST_INICIALIZED=false;
private GestureDetector gestureDetector;
private GameManager gameManager;
private Thread thread; //game thread
private SurfaceHolder holder;
private int blockSize; // Ancho de la pantalla,ancho del bloque
private static int movementFluencyLevel=8; //this movement should be a multiple of the blocksize and multiple of 4,if note the pacman will pass walls
private int totalFrame = 4; // Cantidad total de animation frames por direccion
private int currentArrowFrame = 0; // animation frame de arrow actual
private long frameTicker; // tiempo desde que el ultimo frame fue dibujado
//----------------------------------------------------------------------------------------------
//Constructors
public GameView(Context context) {
super(context);
this.constructorHelper(context);
}
public GameView(Context context,AttributeSet attrs) {
super(context,attrs);
this.constructorHelper(context);
}
public GameView(Context context,AttributeSet attrs,int defStyle) {
super(context,attrs,defStyle);
this.constructorHelper(context);
}
private void constructorHelper(Context context) {
this.gestureDetector = new GestureDetector(this);
setFocusable(true);
this.holder = getHolder();
this.holder.addCallback(this);
this.frameTicker = (long) (1000.0f / totalFrame);
this.gameManager=new GameManager();
int screenWidth=getResources().getdisplayMetrics().widthPixels;
this.blockSize = ((((screenWidth/this.gameManager.getGameMap().getMapWidth())/movementFluencyLevel)*movementFluencyLevel)/4)*4;
this.holder.setFixedSize(blockSize*this.gameManager.getGameMap().getMapWidth(),blockSize*this.gameManager.getGameMap().getMapHeight());
this.gameManager.getGameMap().loadBonusBitmaps(this.getBlockSize(),this.getResources(),this.getContext().getPackageName());
this.gameManager.setPacman(new Pacman("pacman","",this.movementFluencyLevel,this.gameManager.getGameMap().getPacmanSpawnPosition(),this.blockSize,this.getContext().getPackageName()));
Ghost.loadCommonBitmaps(this.blockSize,this.getContext().getPackageName());
}
//----------------------------------------------------------------------------------------------
//Getters and setters
public int getBlockSize() {
return blockSize;
}
public GameManager getGameManager() {
return gameManager;
}
public boolean isDrawing(){
return CAN_DRAW;
}
//----------------------------------------------------------------------------------------------
private synchronized void initGhost(){
if(!GHOST_INICIALIZED){
GHOST_INICIALIZED=true;
this.gameManager.initGhosts(this.blockSize,this.getContext().getPackageName(),movementFluencyLevel);
}
}
@RequiresApi(api = Build.VERSION_CODES.N)
@Override
public void run() {
long gameTime;
Canvas canvas;
while (!holder.getSurface().isValid()) {
}
this.initGhost();
this.setFocusable(true);
while (CAN_DRAW) {
gameTime=System.currentTimeMillis();
if(gameTime > frameTicker + (totalFrame * 15)){
canvas = holder.lockCanvas();
if(canvas!=null){
if(this.updateFrame(gameTime,canvas)){
try {
Thread.sleep(3000);
}catch (Exception e){}
}
holder.unlockCanvasAndPost(canvas);
if(this.gameManager.checkWinLevel()){
CAN_DRAW=false;
this.gameManager.cancelThreads();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {}
//animation
Log.i("Game","You win");
}else if(!this.gameManager.getPacman().hasLifes()){
//we lost
CAN_DRAW=false;
this.gameManager.cancelThreads();
//animation
Log.i("Game","You lose");
}
}
}
}
}
// Method to capture touchEvents
@Override
public boolean onTouchEvent(MotionEvent event) {
//To swipe
//https://www.youtube.com/watch?v=32RSS4tE-mc
this.gestureDetector.onTouchEvent(event);
super.onTouchEvent(event);
return true;
}
//Chequea si se deberia actualizar el frame actual basado en el
// tiempo que a transcurrido asi la animacion
//no se ve muy rapida y mala
@RequiresApi(api = Build.VERSION_CODES.N)
private boolean updateFrame(long gameTime,Canvas canvas) {
Pacman pacman;
Ghost[] ghosts;
boolean pacmanIsDeath;
pacman=this.gameManager.getPacman();
ghosts=this.gameManager.getGhosts();
// Si el tiempo suficiente a transcurrido,pasar al siguiente frame
frameTicker = gameTime;
canvas.drawColor(Color.BLACK);
this.gameManager.getGameMap().draw(canvas,Color.BLUE,this.gameManager.getLevel());
this.gameManager.moveGhosts(canvas,this.blockSize);
pacmanIsDeath=pacman.move(this.gameManager,canvas);
if(!pacmanIsDeath){
// incrementar el frame
pacman.changeFrame();
for(int i=0; i<ghosts.length;i++){
ghosts[i].changeFrame();
}
currentArrowFrame++;
currentArrowFrame%=7;
}else{
pacman.setNextDirection(' ');
for(int i=0; i<ghosts.length;i++){
ghosts[i].respawn();
}
}
return pacmanIsDeath;
}
public int getscore(){
return this.getGameManager().getscore();
}
public void setSemaphores(Semaphore changescoreSemaphore,Semaphore changeDirectionSemaphore){
this.gameManager.setChangescoreSemaphore(changescoreSemaphore);
this.gameManager.getPacman().setChangeDirectionSemaphore(changeDirectionSemaphore);
Log.i("Semaphore","setted");
}
//----------------------------------------------------------------------------------------------
//Callback methods
@RequiresApi(api = Build.VERSION_CODES.N)
@Override
public void surfaceCreated(SurfaceHolder holder) {
CAN_DRAW = true;
this.thread= new Thread(this);
this.thread.start();
}
@Override
public void surfaceChanged(SurfaceHolder holder,int format,int width,int height) {
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
Log.i("Surface","destroyed");
}
//----------------------------------------------------------------------------------------------
public void resume() {
CAN_DRAW = true;
thread = new Thread(this);
thread.start();
}
public void pause() {
CAN_DRAW = false;
while (true) {
try {
thread.join();
} catch (InterruptedException e) {
// retry
}
break;
}
this.thread=null;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1,MotionEvent e2,float distanceX,float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent downEvent,MotionEvent moveEvent,float veLocityX,float veLocityY) {
//To swipe
//https://www.youtube.com/watch?v=32RSS4tE-mc
boolean result;
float diffX,diffY;
Pacman pacman;
Log.i("Fling","detected");
result=false;
diffX = moveEvent.getX() - downEvent.getX();
diffY = moveEvent.getY() - downEvent.getY();
pacman=this.gameManager.getPacman();
if (Math.abs(diffY) > SWIPE_THRESHOLD && Math.abs(veLocityY) > SWIPE_VELociTY){
if (Math.abs(diffX) > Math.abs(diffY)) {
if (diffX > 0) {
//right
pacman.setNextDirection('r');
} else {
//left
pacman.setNextDirection('l');
}
}else{
if (diffY > 0) {
//down
pacman.setNextDirection('d');
} else {
//up
pacman.setNextDirection('u');
}
}
result=true;
}
return result;
}
}
GameManager
public class GameManager {
private static final int TOTAL_LEVELS=256;
private static int score=0;
private GameMap gameMap;
private int level,bonusResetTime;//,score;
private CountDownScareGhosts scareCountDown;
private Pacman pacman;
private Ghost[] ghosts;
private boolean fruitHasBeenInTheLevel;
private static Semaphore CHANGE_score_MUTEX;
public GameManager(){
this.fruitHasBeenInTheLevel=false;
//this.score=0;
this.gameMap=new GameMap();
this.gameMap.loadMap1();
this.level=1;
this.ghosts=new Ghost[4];
this.bonusResetTime = 5000;
this.scareCountDown=null;
}
public void setChangescoreSemaphore(Semaphore changescoreSemaphore) {
CHANGE_score_MUTEX = changescoreSemaphore;
//if(this.changescoreSemaphore==null){
// Log.i("Change score Semaphore","I'm null");
//}else{
// Log.i("Change score Semaphore","I'm not null");
//}
}
public void addscore(int s){
//this.score+=s;
score+=s;
CHANGE_score_MUTEX.release();
/*if(this.changescoreSemaphore==null){
Log.i("Change score Semaphore","I'm null");
}else{
Log.i("Change score Semaphore","I'm not null");
}*/
//this.changescoreSemaphore.release();
}
public int getscore() {
return score;
//return this.score;
}
public int getLevel() {
return this.level;
}
public GameMap getGameMap() {
return this.gameMap;
}
public Ghost[] getGhosts(){
return this.ghosts;
}
public Pacman getPacman(){
return this.pacman;
}
public void setPacman(Pacman pacman){
this.pacman=pacman;
}
public void eatPallet(int posXMap,int posYMap){
score+=10;
CHANGE_score_MUTEX.release();
//this.score+=10;
Log.i("score GM",""+score);
//Log.i("score GM",""+this.score);
this.gameMap.getMap()[posYMap][posXMap]=0;
//this.changescoreSemaphore.release();
//if(this.changescoreSemaphore==null){
// Log.i("Change score Semaphore","I'm not null");
//}
}
public void eatBonus(int posXMap,int posYMap){
score+=500;
CHANGE_score_MUTEX.release();
//this.score+=500;
//Log.i("score",Double.toString(this.score).substring(0,Double.toString(this.score).indexOf('.')));
this.gameMap.getMap()[posYMap][posXMap]=0;
//this.changescoreSemaphore.release();
}
public void eatSuperPallet(int posXMap,int posYMap){
score+=50;
CHANGE_score_MUTEX.release();
//this.score+=50;
this.gameMap.getMap()[posYMap][posXMap]=0;
//Si hay un timer andando lo cancelo y ejecuto otro
if (this.scareCountDown != null){
this.scareCountDown.cancel();
}
this.scareCountDown = new CountDownScareGhosts(this.ghosts,this.gameMap.getMap());
this.scareCountDown.start();
//this.changescoreSemaphore.release();
}
public void tryCreateBonus(){
//only if pacman has eaten 20 pallets we should allow the fruit appear
if(!this.fruitHasBeenInTheLevel && this.gameMap.getEatenPallets()>=20){
//to not allow the fruit be again in the level
this.fruitHasBeenInTheLevel=true;
new CountdownBonusThread(this.gameMap,this.bonusResetTime).start();
}
}
@RequiresApi(api = Build.VERSION_CODES.N)
public void moveGhosts(Canvas canvas,int blocksize) {
for (int i = 0; i < ghosts.length; i++) {
ghosts[i].move(this.gameMap.getMap(),this.pacman);
ghosts[i].draw(canvas);
}
}
public synchronized void initGhosts(int blocksize,Resources res,String packageName,int movementFluency) {
int[][]spawnPositions,cornersPositions,notupdownPositions,defaultTargets;
defaultTargets=this.gameMap.getDefaultGhostTarget();
notupdownPositions=this.gameMap.getNotupdownDecisionPositions();
spawnPositions=this.gameMap.getGhostsspawnPositions();
cornersPositions=this.gameMap.getGhostsScatterTarget();
//start position
// 5 blinky spawn [13,11]
// 6 pinky spawn [15,11]
// 7 inky spawn [13,16]
// 8 clyde spawn [15,16]
this.ghosts=new Ghost[4];
ghosts[0] = new Ghost("blinky",spawnPositions[0],cornersPositions[0],new BehaviorChaseAgressive(notupdownPositions,movementFluency,defaultTargets[0]),'l',defaultTargets[0],blocksize,res,packageName);
ghosts[1] = new Ghost("pinky",spawnPositions[1],cornersPositions[1],new BehaviorChaseAmbush(notupdownPositions,defaultTargets[1]),'r',defaultTargets[1],packageName);
ghosts[2] = new Ghost("inky",spawnPositions[2],cornersPositions[2],new BehaviorChasePatrol(notupdownPositions,this.ghosts[0],packageName);
ghosts[3] = new Ghost("clyde",spawnPositions[3],cornersPositions[3],new BehaviorChaseRandom(notupdownPositions,packageName);
try{
Thread.sleep(200);
}catch(Exception e){}
for (int i=0;i<ghosts.length;i++){
ghosts[i].onLevelStart(1);
}
}
public boolean checkWinLevel() {
//player win the level if he has eaten all the pallet
return this.gameMap.countPallets()==0;
}
public void onResume(){
for (int i=0 ; i<this.ghosts.length;i++){
this.ghosts[i].cancelBehavoirThread();
}
if(this.scareCountDown!=null && !this.scareCountDown.hasEnded()){
this.scareCountDown.start();
}
}
public void onPause(){
for (int i=0 ; i<this.ghosts.length;i++){
this.ghosts[i].cancelBehavoirThread();
}
if(this.scareCountDown!=null && !this.scareCountDown.hasEnded()){
this.scareCountDown=this.scareCountDown.onPause();
}
}
public void cancelThreads(){
for (int i=0 ; i<this.ghosts.length;i++){
this.ghosts[i].cancelBehavoirThread();
}
if(this.scareCountDown!=null){
this.scareCountDown.cancel();
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。