package sample.game.controller;


import java.util.ArrayList;

import library.core.debug.CoreLog;
import library.core.mainAI.RiverCrossingAI;
import library.core.model.CoreModel;
import library.core.object.CoreTextObjectFactory;
import sample.game.ai.AiSystem;
import sample.game.ai.AiSystemType1;
import sample.game.ai.Memory;
import sample.game.main.MainActivity;
import sample.game.main.MainActivity.gameSeType;
import sample.game.manager.EndIsland;
import sample.game.manager.Island;
import sample.game.manager.LayoutManager;
import sample.game.manager.StartIsland;
import sample.game.model.AiChara;
import sample.game.model.BackToTitleButton;
import sample.game.model.BoatModel;
import sample.game.model.ButtonNextTurn;
import sample.game.model.CharaModel;
import sample.game.model.CharaModel.TARGET_TYPE;
import sample.game.model.CrossButton;
import sample.game.model.ExampleBox;
import sample.game.model.NumBox;
import sample.game.model.OnemorePlayButton;
import sample.game.model.OppositeIcon;
import android.view.MotionEvent;



public class GameController {

	private CoreTextObjectFactory textFactory;
	private ArrayList<CharaModel> targets;
	private ArrayList<CharaModel> allCharacter;
	private BoatModel boat;
	private StartIsland startIsland;
	private EndIsland endIsland;
	private LayoutManager layoutManager;
	private ButtonNextTurn turnChangeButton;
	private MainActivity palent;

	private ArrayList<OppositeIcon> oppositeRightIcons;
	private ArrayList<OppositeIcon> oppositeLeftIcons;
	private ArrayList<CoreModel> selectIcons;
	private AiChara aiChara;
	private CrossButton crossButton;
	private ExampleBox exampleBox;
	private OnemorePlayButton onemorePlayButton;
	private BackToTitleButton backToTitleButton;
	private CoreModel fadeMask;
	private CoreModel perfectLogo;
	private CoreModel clearLogo;
	private NumBox numbox;
	private NumBox numboxS;
	private CoreModel backScreen;
	private CoreModel gameoverScreenTypeWolf;
	private CoreModel gameoverScreenTypeCabbage;
	private CoreModel gameoverScreenTypeAi;
	private CoreModel returnBackScreen;
	private CoreModel returnIcon;


	private int moveNum;	//移動したキャラの数
	private int moveNumMax;

	private float time=0;
	private float bifTouchX;
	private float bifTouchY;

	//ターゲットの移動前座標
	private float targetBifX;
	private float targetBifY;

	private boolean isEndGame=false;
	private boolean nowTurnChangePhase=false;	//ターン変更中の演出用
	private boolean nowCharaMovePhase=false;	//キャラの移動演出フラグ
	private boolean nowBackScreenMovePhase=false;
	private boolean nowCharaGetOffPhase=false;	//キャラが船から降りるフェーズ
	private boolean isUseAi=true;
	private boolean isStopUpdate=false;
	private boolean isStopUpdate2=false;
	private boolean isRestarGamePhase=false;
	private boolean isGameEndPhase=false;


	private boolean initProduction;


	//ＡＩに使用するもの
	private AiSystem ai;

	private Memory moveData;	//移動情報の保存
	private boolean isNowReturnPhase=false;
	private boolean isNowReturnPhaseIfBoatMode=false;
	private boolean isNowReturnPhaseIfNormal=false;
	private boolean isNowboatBackMove=false;	//ボートを急に後ろ向きに動かすフラグ

	private int bifMoveMinisterNum=0;
	private int bifMoveWolfNum=0;
	private int bifMoveCabbageNum=0;
	private int bifMoveCattleMoveNum=0;

	private int count=0;
	private float returnTime=0;


	/**
	 * 初期演出をするかどうか
	 * @param isInitProduction
	 */
	public GameController(boolean isInitProduction){
		oppositeRightIcons=new ArrayList<OppositeIcon>();
		oppositeLeftIcons=new ArrayList<OppositeIcon>();
		selectIcons=new ArrayList<CoreModel>();
		targets=new ArrayList<CharaModel>();
		allCharacter=new ArrayList<CharaModel>();


		this.initProduction=isInitProduction;



		this.isNowReturnPhase=false;
		this.isNowReturnPhaseIfBoatMode=false;
		this.isNowboatBackMove=false;

		RiverCrossingAI.getBgmPlayer().play("bgm/game.ogg", 0);

	}


	/**
	 * 初期化
	 * @param palent
	 * @param textFactory
	 * @param startIsland
	 * @param endIsland
	 * @param nextButton
	 * @param boat
	 * @param layoutManager
	 */
	public void init(MainActivity palent,StartIsland startIsland,EndIsland endIsland,
			ButtonNextTurn nextButton,
			BoatModel boat,LayoutManager layoutManager){


		this.startIsland=startIsland;
		this.endIsland=endIsland;
		this.palent=palent;
		this.boat=boat;
		this.turnChangeButton=nextButton;
		this.layoutManager=layoutManager;

		this.targets.clear();

		this.moveNum=0;

		moveNumMax=boat.getRideMaxMenberNum();
		//moveNumMax=4;
	}

	/**
	 * 初期演出を行うかどうかの判定
	 */
	public void checkInitProduction(){
		//初期演出をする場合、入力を一定時間だけ切る
		if(initProduction){
			//initの呼ばれるタイミングでは、すべてのフィールドの準備が完了していることを想定
			for(int i=0;i<allCharacter.size();i++){
				allCharacter.get(i).setCanTouch(false);
			}

			fadeMask.setAlpha(255);
			fadeMask.setShowView(true);
			time=0;
		}
	}


	public void update(float deltaTime){


		if(isStopUpdate || isStopUpdate2){
			CoreLog.debug("stop update");
			return;
		}

		//最初の演出
		if(initProduction){

			if(deltaTime>0.5f){
				deltaTime=0.5f;
			}
			time+=deltaTime;


			float rate=time/1.5f;
			if(rate>1) rate=1f;
			RiverCrossingAI.getBgmPlayer().setVolume(rate);
			fadeMask.setAlpha((int)((1-rate)*255));

			if(time>1.5f){
				RiverCrossingAI.getBgmPlayer().setVolume(1f);
				CoreLog.debug("end :"+time);
				time=0;

				fadeMask.setShowView(false);

				for(int i=0;i<allCharacter.size();i++){
					allCharacter.get(i).setCanTouch(true);
				}

				//this.saveMemory();
				initProduction=false;
			}

			return;
		}


		if(isEndGame){

			if(isRestarGamePhase || isGameEndPhase){
				time+=deltaTime;

				float rate=time/1f;
				if(rate>1) rate=1f;
				RiverCrossingAI.getBgmPlayer().setVolume(1f-rate);
				fadeMask.setAlpha((int)(rate*255));

				if(time>1f){
					RiverCrossingAI.getBgmPlayer().stop();
					if(isRestarGamePhase){
						this.reStartGame();
					}else{
						this.endGame();
					}
				}
			}
			/*time+=deltaTime;
			CoreLog.debug("end");
			if(time>2){
				//これでタイトル行くとバグる
				if(startIsland.checkGaemClear()){	//クリアーした場合はタイトル画面に戻す
					palent.moveTitle();
				}

				//ゲームオーバーの場合はリスタートでも良いが、今回はタイトルに戻す
				this.endGame();
			}*/
			return;
		}




		/**
		 * ゲームの巻き戻し処理
		 */

		if(isNowReturnPhase && !isNowReturnPhaseIfBoatMode){
			CoreLog.debug("--");

			time+=deltaTime;
			returnTime+=deltaTime;

			if(returnTime>=0.5f){
				returnTime=0;
				//矢印の反転
				returnIcon.setShowView(!returnIcon.isShowView());
			}

			if(time>=0.01f && !nowTurnChangePhase){
				time=0;

				if(count==0){
					count++;
					bifMoveMinisterNum=moveData.getMinisterMoveNum();
					bifMoveWolfNum=moveData.getWolfMoveNum();
					bifMoveCabbageNum=moveData.getCabbageMoveNum();
					bifMoveCattleMoveNum=moveData.getCattleMoveNum();
					CoreLog.debug("--2"+bifMoveMinisterNum+"/"+bifMoveWolfNum+"/"+bifMoveCabbageNum+"/"+bifMoveCattleMoveNum);

					//戻る情報をセットしてから、後ろのメモリーに置き換える
					moveData=moveData.getBifMemory();
					moveData.removeNextmemorys(0);
				}else{
					Island island=null;

					if(startIsland.getNowTurn()){
						island=startIsland;
					}else{
						island=endIsland;
					}


					if(bifMoveMinisterNum>0){
						bifMoveMinisterNum--;
						CoreLog.debug(""+island.getMinisters().size());
						//island.getMinisters().get(island.getMinisters().size()-1).onTouchDown();


						ArrayList<CharaModel> c=island.getMinisters();
						for(int i=c.size()-1;i>=0;i--){
							if(!c.get(i).isNowTarget()){
								c.get(i).onTouchDown();
								break;
							}
						}

					}else if(bifMoveWolfNum>0){
						bifMoveWolfNum--;
						//island.getWolfs().get(island.getWolfs().size()-1).onTouchDown();

						ArrayList<CharaModel> c=island.getWolfs();
						for(int i=c.size()-1;i>=0;i--){
							if(!c.get(i).isNowTarget()){
								c.get(i).onTouchDown();
								break;
							}
						}

					}else if(bifMoveCabbageNum>0){
						bifMoveCabbageNum--;
						//island.getCabbages().get(island.getCabbages().size()-1).onTouchDown();

						ArrayList<CharaModel> c=island.getCabbages();
						for(int i=c.size()-1;i>=0;i--){
							if(!c.get(i).isNowTarget()){
								c.get(i).onTouchDown();
								break;
							}
						}

					}else if(bifMoveCattleMoveNum>0){
						bifMoveCattleMoveNum--;
						//island.getCattles().get(island.getCattles().size()-1).onTouchDown();

						ArrayList<CharaModel> c=island.getCattles();
						for(int i=c.size()-1;i>=0;i--){
							if(!c.get(i).isNowTarget()){
								c.get(i).onTouchDown();
								break;
							}
						}

					}else{
						//flag=true;

						//ボートの方向変更
						if(!startIsland.getNowTurn()){
							boat.changeAnimation(0);
						}else{
							boat.changeAnimation(1);
						}

						this.changeTurn(true);
					}

					/*if(bifMoveMinisterNum>0){
						bifMoveMinisterNum--;
						island.getMinisters().get(island.getMinisters().size()-1).onTouchDown();
					}else if(bifMoveWolfNum>0){
						bifMoveWolfNum--;
						island.getWolfs().get(island.getWolfs().size()-1).onTouchDown();
					}else if(bifMoveCabbageNum>0){
						bifMoveCabbageNum--;
						island.getCabbages().get(island.getCabbages().size()-1).onTouchDown();
					}else if(bifMoveCattleMoveNum>0){
						bifMoveCattleMoveNum--;
						island.getCattles().get(island.getCattles().size()-1).onTouchDown();
					}else{
						this.changeTurn(true);
					}*/
				}
				return;
			}




			if(nowTurnChangePhase){
				CoreLog.debug("/");
				if(nowCharaMovePhase){	//キャラを船に乗せる移動処理
					//////////////////////////////////////////////////////////////
					//キャラを船に乗せるフェーズ
					/////////////////////////////////////////////////////////////


					if(layoutManager.charaMove2Boat(targets, deltaTime, 1f)){
						nowCharaMovePhase=false;
						nowBackScreenMovePhase=true;
						layoutManager.moveBackScreenInit(backScreen, boat, targets,aiChara, !startIsland.getNowTurn());//怪しいかも
					}

				}else if(nowBackScreenMovePhase){
					//////////////////////////////////////////////////////////////
					//背景移動フェーズ（船の移動）
					/////////////////////////////////////////////////////////////


					if(layoutManager.moveBackScreen(this,backScreen, boat, targets,aiChara,numbox, deltaTime, 1.5f,false)){
						nowBackScreenMovePhase=false;
						nowCharaGetOffPhase=true;

						if(!startIsland.getNowTurn()){
							for(int i=0;i<targets.size();i++){
								layoutManager.addLeft(targets.get(i),false);
							}
						}else{
							for(int i=0;i<targets.size();i++){
								layoutManager.addRight(targets.get(i),false);
							}
						}

						//上のlayoutManagerへの配置処理の後に呼ぶ
						layoutManager.charaGetOffInit(targets,!startIsland.getNowTurn());

						//アニメーションの変更
						for(int i=0;i<targets.size();i++){
							if(targets.get(i).getType()!=TARGET_TYPE.CABBAGE){
								if(!startIsland.getNowTurn()){
									targets.get(i).changeAnimation(2);
								}else{
									targets.get(i).changeAnimation(1);
								}
							}
						}

					}

				}else if(nowCharaGetOffPhase){
					//////////////////////////////////////////////////////////////
					//キャラを船から下ろすフェーズ
					/////////////////////////////////////////////////////////////

					if(layoutManager.charaGetOff(targets, deltaTime,1f )){

						//移動数のカウント
					/*	boat.addMoveNum();
						numbox.setNmber(boat.getMoveNum());
						if(!startIsland.getNowTurn()){
							numbox.setCenterX(1280-170);
						}else{
							numbox.setCenterX(170);
						}
						numbox.setShowView(true);*/

						/*//ボートの方向変更
						if(!startIsland.getNowTurn()){
							boat.changeAnimation(0);
						}else{
							boat.changeAnimation(1);
						}*/




						//向こう岸アイコンを表示にする	//islandの更新の後に行う必要がある
						ArrayList<OppositeIcon> icons=null;
						Island land=null;
						if(!startIsland.getNowTurn()){
							icons=oppositeLeftIcons;
							land=startIsland;
						}else{
							icons=oppositeRightIcons;
							land=endIsland;
						}

						for(int i=0;i<icons.size();i++){
							OppositeIcon icon=icons.get(i);
							icon.setIcon(land.getCharaNum(icon.getType()));
							icons.get(i).setShowView(true);
						}



						//特に何もなければ続行
						startNextTurn();
						this.turnBack();

					}
				}


			}





			return;
		}

		/**
		 * 通常の巻き戻し演出用
		 */
		if(isNowReturnPhaseIfNormal){

		}


		/**
		 * 船の途中巻き戻し処理
		 */
		if(isNowReturnPhaseIfBoatMode){

			CoreLog.debug("?");

			returnTime+=deltaTime;

			if(returnTime>=0.5f){
				returnTime=0;
				//矢印の反転
				returnIcon.setShowView(!returnIcon.isShowView());
			}


			if(nowBackScreenMovePhase){
				//////////////////////////////////////////////////////////////
				//背景移動フェーズ（船の移動）
				/////////////////////////////////////////////////////////////

				if(layoutManager.moveBackScreen(this,backScreen, boat, targets,aiChara,numbox, deltaTime, 1.5f,isNowboatBackMove)){
					nowBackScreenMovePhase=false;
					nowCharaGetOffPhase=true;

					isNowboatBackMove=false;		//巻き戻しの一部で使用するため（使ったらfalse）

					if(!startIsland.getNowTurn()){
						for(int i=0;i<targets.size();i++){
							layoutManager.addLeft(targets.get(i),false);
						}
					}else{
						for(int i=0;i<targets.size();i++){
							layoutManager.addRight(targets.get(i),false);
						}
					}

					//上のlayoutManagerへの配置処理の後に呼ぶ
					layoutManager.charaGetOffInit(targets,!startIsland.getNowTurn());

					//アニメーションの変更
					for(int i=0;i<targets.size();i++){
						if(targets.get(i).getType()!=TARGET_TYPE.CABBAGE){
							if(!startIsland.getNowTurn()){
								targets.get(i).changeAnimation(2);
							}else{
								targets.get(i).changeAnimation(1);
							}
						}
					}

				}

			}else if(nowCharaGetOffPhase){
				//////////////////////////////////////////////////////////////
				//キャラを船から下ろすフェーズ
				/////////////////////////////////////////////////////////////

				if(layoutManager.charaGetOff(targets, deltaTime,1f )){





					//向こう岸アイコンを表示にする	//islandの更新の後に行う必要がある
					ArrayList<OppositeIcon> icons=null;
					Island land=null;
					if(!startIsland.getNowTurn()){
						icons=oppositeLeftIcons;
						land=startIsland;
					}else{
						icons=oppositeRightIcons;
						land=endIsland;
					}

					for(int i=0;i<icons.size();i++){
						OppositeIcon icon=icons.get(i);
						icon.setIcon(land.getCharaNum(icon.getType()));
						icons.get(i).setShowView(true);
					}




					isNowReturnPhaseIfBoatMode=false;

					//特に何もなければ続行
					//this.startNextTurn();
					count=0;

					startNextTurn();
					this.turnBack();

				}
			}
			return;
		}









		if(nowTurnChangePhase){

			//CoreLog.debug("now turn change");

			if(nowCharaMovePhase){	//キャラを船に乗せる移動処理
				//////////////////////////////////////////////////////////////
				//キャラを船に乗せるフェーズ
				/////////////////////////////////////////////////////////////


				if(layoutManager.charaMove2Boat(targets, deltaTime, 1f)){
					RiverCrossingAI.getSePlayer().play(gameSeType.CROSS.ordinal());
					nowCharaMovePhase=false;
					nowBackScreenMovePhase=true;
					layoutManager.moveBackScreenInit(backScreen, boat, targets,aiChara, !startIsland.getNowTurn());//怪しいかも
				}

			}else if(nowBackScreenMovePhase){
				//////////////////////////////////////////////////////////////
				//背景移動フェーズ（船の移動）
				/////////////////////////////////////////////////////////////


				if(layoutManager.moveBackScreen(this,backScreen, boat, targets,aiChara,numbox, deltaTime, 1.5f,false)){
					RiverCrossingAI.getSePlayer().stop(gameSeType.CROSS.ordinal());

					nowBackScreenMovePhase=false;
					nowCharaGetOffPhase=true;

					if(!startIsland.getNowTurn()){
						for(int i=0;i<targets.size();i++){
							layoutManager.addLeft(targets.get(i),false);
						}
					}else{
						for(int i=0;i<targets.size();i++){
							layoutManager.addRight(targets.get(i),false);
						}
					}

					//上のlayoutManagerへの配置処理の後に呼ぶ
					layoutManager.charaGetOffInit(targets,!startIsland.getNowTurn());

					//アニメーションの変更
					for(int i=0;i<targets.size();i++){
						if(targets.get(i).getType()!=TARGET_TYPE.CABBAGE){
							if(!startIsland.getNowTurn()){
								targets.get(i).changeAnimation(1);
							}else{
								targets.get(i).changeAnimation(2);
							}
						}
					}

				}

			}else if(nowCharaGetOffPhase){
				//////////////////////////////////////////////////////////////
				//キャラを船から下ろすフェーズ
				/////////////////////////////////////////////////////////////

				if(layoutManager.charaGetOff(targets, deltaTime,1f )){


					//ボートの方向変更
					if(!startIsland.getNowTurn()){
						boat.changeAnimation(1);
					}else{
						boat.changeAnimation(0);
					}


					//クリア判定
					if(checkGameClear()){
						this.gameClear();
						return;
					}


					//向こう岸アイコンを表示にする	//islandの更新の後に行う必要がある
					ArrayList<OppositeIcon> icons=null;
					Island land=null;
					if(!startIsland.getNowTurn()){
						icons=oppositeLeftIcons;
						land=startIsland;
					}else{
						icons=oppositeRightIcons;
						land=endIsland;
					}

					for(int i=0;i<icons.size();i++){
						OppositeIcon icon=icons.get(i);
						icon.setIcon(land.getCharaNum(icon.getType()));
						icons.get(i).setShowView(true);
					}



					//特に何もなければ続行
					this.startNextTurn();

				}
			}

		/*	if(boat.move(deltaTime)){

				this.startNextTurn();


			}*/

		}else{
			//AIを使用する場合
			if(isUseAi){
				this.ai.update(deltaTime);
			}
		}


	}

	/**
	 * ゲーム状態の判定 ｹﾞｰﾑオーバー判定のいろいろしているバージョン
	 */
	public void checkGameState(){
		if(isNowReturnPhase){
			boat.difMoveNum();
			numbox.setNmber(boat.getMoveNum());
			return;	//巻き戻し中には無効にする
		}




		//ゲームの状態判定
		if(checkGameOver()){
			if(isUseAi){
			//	isStopUpdate=true;
				ai.callGameOver();
				return;
			}else{
				gameOver();
			}
		}

		if(!isUseAi){
			//ゲーム続行の場合、座標を記録
			this.saveCharacterPosition();
			this.saveMemory();
		}


		boat.addMoveNum();
		numbox.setNmber(boat.getMoveNum());

	}


	public void onTouch(MotionEvent event,int touchX,int touchY){

		int tX=touchX;
		int tY=touchY;


		switch (event.getAction()){
		case MotionEvent.ACTION_DOWN:

			if(isUseAi){
				//AI使用時はキャラの移動速度を変化
				this.ai.changeAiMoveCharaSpeed();
				this.boat.changeAiMoveCharaSpeed();

				//ボートの速度とAIの速度は同しであることが前提である
				//rightText.setText("速度×"+this.ai.getMoveSpeed());
			}

			break;
		case MotionEvent.ACTION_UP:
		/*	if(target!=null && !isUseAi){

				this.target.setXY(tX,tY);


				if(checkMoveCharacter()){
					CoreLog.debug("1");
					moveCharacter(target);
					if(checkNextTurn()){
						changeTurn();
					}
				}else{
					this.target.setXY(targetBifX, targetBifY);
				}
				this.changeTouchTarget(null);
			}*/
			break;
		case MotionEvent.ACTION_MOVE:


			float mX=tX-bifTouchX;
			float mY=tY-bifTouchY;

			//

			bifTouchX=tX;
			bifTouchY=tY;
			break;
		default:
			break;
		}
	}



	/**
	 * ターンの交代
	 */
	public void changeTurn(boolean isReturn){

		if(!isUseAi){
			RiverCrossingAI.getSePlayer().play(gameSeType.RIDE.ordinal());
		}

		this.isStopUpdate=true;

		this.count=0;	//巻き戻しの処理に利用

		crossButton.setShowView(false);
		turnChangeButton.setShowView(false);

		time=0;

		if(!isReturn){
			nowTurnChangePhase=true;
			nowCharaMovePhase=true;
		}else{
			nowTurnChangePhase=true;
			nowCharaMovePhase=true;
		}

		if(startIsland.getNowTurn()){
			startIsland.setNowTurn(false);
			endIsland.setNowTurn(true);
		}else{
			startIsland.setNowTurn(true);
			endIsland.setNowTurn(false);
		}

		startIsland.setMove(false);
		endIsland.setMove(false);
///////////////////////////////////////////////////////
		layoutManager.charaMove2BoatInit(boat, targets);

		//アニメーションの変更
		for(int i=0;i<targets.size();i++){
			if(targets.get(i).getType()!=TARGET_TYPE.CABBAGE){
				if(!startIsland.getNowTurn()){
					if(!isReturn){
						targets.get(i).changeAnimation(1);
					}else{
						targets.get(i).changeAnimation(2);
					}
				}else{
					if(!isReturn){
						targets.get(i).changeAnimation(2);
					}else{
						targets.get(i).changeAnimation(1);
					}
				}
			}
		}

		//移動が確定したので、移動するものを登録から外す
		for(int i=0;i<targets.size();i++){
			if(!startIsland.getNowTurn()){		//上でislandのターン交代をしてしまっているのでここでは逆で考える
				layoutManager.removeRight(targets.get(i));
			}else{
				layoutManager.removeLeft(targets.get(i));
			}
		}

		//すべてのキャラのタッチを封印する
		for(int i=0;i<allCharacter.size();i++){
			allCharacter.get(i).setCanTouch(false);
		}


		//向こう岸アイコンを非表示にする
		ArrayList<OppositeIcon> icons=null;
		if(!startIsland.getNowTurn()){
			icons=oppositeRightIcons;
		}else{
			icons=oppositeLeftIcons;
		}

		for(int i=0;i<icons.size();i++){
			icons.get(i).setShowView(false);
		}

		//セレクトアイコンを遠くに飛ばす
		for(int i=0;i<selectIcons.size();i++){
			selectIcons.get(i).setXY(-100, -100);
		}

		//ターゲットになったキャラ専用の設定を戻す
		for(int i=0;i<targets.size();i++){
			targets.get(i).setNowTarget(false);
		}

		//説明欄を削除
		exampleBox.setShowView(false);


		//isLandの情報更新
		for(int i=0;i<targets.size();i++){
			//管理情報の更新
			if(!startIsland.getNowTurn()){
				startIsland.removeCharacter(targets.get(i));
				endIsland.addCharacter(targets.get(i));
			}else{
				endIsland.removeCharacter(targets.get(i));
				startIsland.addCharacter(targets.get(i));
			}
		}



///////////////////////////////////////////////////////
		moveNum=0;


		CoreLog.debug("start chenging turn");

		this.isStopUpdate=false;
	}





	/**
	 * ターンの交代判定
	 */
	public boolean checkNextTurn(){
		if(moveNum>=moveNumMax){
			return true;
		}
		return false;
	}


	/**
	 * 渡るボタンが押せるかどうか
	 * @return
	 */
	public void checkCrossButton(){

		boolean selectMinister=false;
		for(int i=0;i<targets.size();i++){
			if(targets.get(i).getType()==TARGET_TYPE.MINISTART){
				selectMinister=true;
			}
		}

		//一人以上を選択していて、牧師を選んでいる場合
		if(selectMinister&&(moveNum>0)){
			crossButton.setCanMove(true);
			if(startIsland.getNowTurn()){
				crossButton.setXY(boat.getCenterX(), boat.getCenterY());
			}else{
				crossButton.setXY(boat.getCenterX()-30, boat.getCenterY());
			}
		}else{
			crossButton.setCanMove(false);
			crossButton.setXY(-100,-100);
		}

	}


	public void startNextTurn(){

		//すべてのキャラのタッチを封印解除
		for(int i=0;i<allCharacter.size();i++){
			allCharacter.get(i).setCanTouch(true);
		}

		//ターゲットキャラを解放
		targets.clear();

		//渡るボタンを非表示にする
		turnChangeButton.setShowView(false);

		//説明欄の表示
		if(!startIsland.getNowTurn()){
			exampleBox.setCenterX(1280-920);
		}else{
			exampleBox.setCenterX(920);
		}


		exampleBox.setExample(moveNumMax-moveNum);
		exampleBox.setShowView(true);


		boat.clearRideMenber();




		if(startIsland.getNowTurn()){
			startIsland.setMove(true);
		}else{
			endIsland.setMove(true);
		}

	//	this.saveMemory();

		nowTurnChangePhase=false;

		CoreLog.debug("startNextTurn end");


	}




	/**
	 * 移動したかどうかの判定
	 * @return
	 */
	public boolean checkMoveCharacter(){

		/**
		 * 船の乗船ゾーンに存在すれば移動と見なす
		 */
		if(this.boat.isMountTarget()){
			return true;
		}

		return false;
	}


	/**
	 * ゲームオーバー判定
	 * @return
	 */
	public boolean checkGameOver(){
		if(startIsland.cheakGameOver() || endIsland.cheakGameOver()){
			return true;
		}
		return false;
	}



	public boolean checkGameClear(){
		if(startIsland.checkGaemClear()){
			return true;
		}
		return false;
	}






	/**
	 * 未実装（いらないかも）
	 */
	public void saveCharacterPosition(){
	}

	/**
	 * 移動情報の保存用のデータを作成
	 */
	public void memoryInit(){
		moveData =new Memory(null, startIsland.clone(),
				endIsland.clone(), boat.clone(), 0, 0,0, 0);
	}

	public void memoryInit(Memory m){
		moveData=m;
	}


	/**
	 * AIの生成　（初期生成時に情報を作成する場合があるため、IsLandの情報が確定した後に呼ぶ）
	 */
	public void aiInit(){
		if(!isUseAi) return;
		this.ai=new AiSystemType1(this, boat, startIsland, endIsland);
		/*rightText=new ViewText("速度×"+this.ai.getMoveSpeed(), TEXT_TYPE.CENTER, gameScreen.getWidth()*0.8f, gameScreen.getHeight()*0.06f);
		rightText.setSize(gameScreen.getWidth()*0.03f);
		gameScreen.addViewText(rightText);*/
	}

	public void aiInit(Memory memory){
		if(!isUseAi) return;
		this.ai=new AiSystemType1(memory,this, boat, startIsland, endIsland);
	/*	rightText=new ViewText("速度×"+this.ai.getMoveSpeed(), TEXT_TYPE.CENTER, gameScreen.getWidth()*0.8f, gameScreen.getHeight()*0.06f);
		rightText.setSize(gameScreen.getWidth()*0.03f);
		gameScreen.addViewText(rightText);*/
	}


	/**
	 * 途中からゲームを再開する
	 */
	public void reStart(StartIsland sIsland,EndIsland eIsland ,BoatModel boat){
		palent.resumeStartGame(sIsland, eIsland, boat);
	}


	/**
	 * ターゲットの変更
	 * @param cView
	 */
/*	public void changeTouchTarget(CharaModel chara){

		if(chara!=null){
			this.target=chara;
			this.target.setNowTarget(true);
		}else{
			this.target.setNowTarget(false);
			this.target=null;
		}

	}*/

	/**
	 * ターゲットを増やす
	 * @param chara
	 */
	public boolean addTarget(CharaModel chara){
		if(moveNum<moveNumMax){

			moveNum++;

			exampleBox.setExample(moveNumMax-moveNum);

			//現在の最大のＩＤを取得
			int maxIndex=-1;		//targetsへの登録順に使用　用途は、selectbuttonなどのindexに使用
			for(int i=0;i<targets.size();i++){
				int tmp=targets.get(i).getTargetId();
				if(tmp>maxIndex) maxIndex=tmp;
			}

			if(maxIndex==-1){	//ターゲットのＩＤが登録されていなかった場合
				maxIndex=0;
			}else{		//登録されている場合は次のＩＤを振る
				maxIndex+=1;
			}

			this.selectIcons.get(maxIndex).setXY(chara.getCenterX(), chara.getCenterY());
			chara.setTargetId(maxIndex);


			this.targets.add(chara);

			//渡るボタンの判定
			checkCrossButton();

			CoreLog.debug("a1");
			return true;
		}

		CoreLog.debug("b1");
		return false;
	}

	public void removeTarget(CharaModel chara){
		//this.selectIcons.get(chara.getTargetId()).setXY(500+100*moveNum,100);

		int targetId=chara.getTargetId();

		//ターゲットＩＤの途中の数字が消える場合、整列のためにそれ以上上の数字の数を減らす
		for(int i=0;i<targets.size();i++){
			int tmpId=targets.get(i).getTargetId();
			if(tmpId>targetId){
				targets.get(i).setTargetId(tmpId-1);
			}
		}

		//targetIDの整理後、登録を削除
		this.targets.remove(chara);

		//残りのtargetsでselectButtonを整理
		//表示の問題でselectButtonも整列し直す
		for(int i=0;i<4;i++){
			if(i<targets.size()){
				this.selectIcons.get(i).setXY(targets.get(i).getCenterX(), targets.get(i).getCenterY());
			}else{
				this.selectIcons.get(i).setXY(-100,-100);
			}
		}


		moveNum--;

		exampleBox.setExample(moveNumMax-moveNum);

		//渡るボタンの判定
		checkCrossButton();

	}




	/**
	 * キャラの移動
	 * @param character
	 */
	public void moveCharacter(CharaModel character){

		//target.getModel().setCanMove(false);
		//layoutManager.move2Boat(character);

		///////////////////////////////////////////////////////
		if(startIsland.getNowTurn()){
			layoutManager.moveRightBoat(character);
		}else{
			layoutManager.moveLeftBoat(character);
		}
		///////////////////////////////////////////////////////

		boat.addCharacter(character);
		moveNum++;

		character.setCanMove(false);

		if(moveNumMax-1==moveNum){	//あと１キャラしか移動できない場合
			//牧師を一人も船に乗せていない場合
			if(boat.getRideMenberNum(TARGET_TYPE.MINISTART)==0){
				if(startIsland.getNowTurn()){
					startIsland.setMoveType2(false);
				}else{
					endIsland.setMoveType2(false);
				}
				//centerText.setText("牧師が＠"+(moveNumMax-moveNum)+"回動かせるよ");
			}else{
				//centerText.setText("＠"+(moveNumMax-moveNum)+"回動かせるよ");
			}
		}else{
			//centerText.setText("＠"+(moveNumMax-moveNum)+"回動かせるよ");
		}

		if(boat.getRideMenberNum(TARGET_TYPE.MINISTART)>0){
			turnChangeButton.setShowView(true);
		}


	}


	public void gameOver(){
		RiverCrossingAI.getBgmPlayer().setVolume(0.5f);
		
		//すべてのキャラのタッチを封印解除
		for(int i=0;i<allCharacter.size();i++){
				allCharacter.get(i).setCanTouch(false);
		}

		if(isUseAi){
			RiverCrossingAI.setCanTouch(true);	//タッチの有効化
		}

		RiverCrossingAI.getSePlayer().play(gameSeType.FAILUER.ordinal());

		backToTitleButton.setShowView(true);
		onemorePlayButton.setShowView(true);


		//centerText.setText("ゲームオーバー");
		int id=0;
		if(!startIsland.getNowTurn()){
			id=startIsland.getGameOverTypeId();
		}else{
			id=endIsland.getGameOverTypeId();
		}

		//ゲームオーバー画面の表示
		if(isUseAi){
			gameoverScreenTypeAi.setShowView(true);
		}else{
			if(id==1){
				gameoverScreenTypeWolf.setShowView(true);
			}else if(id==2){
				gameoverScreenTypeCabbage.setShowView(true);
			}
		}


		time=0;
		isEndGame=true;
	}

	public void gameClear(){
		RiverCrossingAI.getBgmPlayer().setVolume(0.5f);
		
		//すべてのキャラのタッチを封印解除
		for(int i=0;i<allCharacter.size();i++){
				allCharacter.get(i).setCanTouch(false);
		}

		if(isUseAi){
			RiverCrossingAI.setCanTouch(true);	//タッチの有効化
		}

		backToTitleButton.setShowView(true);

		//クリアアニメーションに変更
		for(int i=0;i<allCharacter.size();i++){
			if(allCharacter.get(i).getType()!=TARGET_TYPE.CABBAGE){
				allCharacter.get(i).changeAnimation(3);
			}
		}

		//AIのアニメーション変更
		if(isUseAi){
			aiChara.changeAnimation(2);
		}

		if(!isUseAi){
			//最短ルートの表示	(AIの場合はなし)
			numboxS.setNmber(palent.getShortest());
			numboxS.setShowView(true);

			if(boat.getMoveNum()==palent.getShortest()){
				RiverCrossingAI.getSePlayer().play(gameSeType.PARFECT.ordinal());
				perfectLogo.setShowView(true);
			}else{
				RiverCrossingAI.getSePlayer().play(gameSeType.CLEAR.ordinal());
				clearLogo.setShowView(true);
			}

		}else{
			RiverCrossingAI.getSePlayer().play(gameSeType.CLEAR.ordinal());
			clearLogo.setShowView(true);
		}


		//centerText.setText("クリア！");
		time=0;
		isEndGame=true;
	}


	public void endGameProduction(){
		fadeMask.setAlpha(0);
		fadeMask.setShowView(true);
		time=0;
		isGameEndPhase=true;
		backToTitleButton.setTouch(false);
		onemorePlayButton.setTouch(false);


	}

	public void reStartGameProduction(){
		fadeMask.setAlpha(0);
		fadeMask.setShowView(true);
		time=0;
		isRestarGamePhase=true;
		backToTitleButton.setTouch(false);
		onemorePlayButton.setTouch(false);

	}


	/**
	 * ゲームの再スタート
	 */
	private void reStartGame(){
		palent.restartGame();
	}

	/**
	 * ゲームの終了
	 */
	private void endGame(){
		palent.moveTitle();
	}



	public EndIsland getEndIsland() {
		return endIsland;
	}
	public void setEndIsland(EndIsland endIsland) {
		this.endIsland = endIsland;
	}
	public void setStartIsland(StartIsland startIsland) {
		this.startIsland = startIsland;
	}


	public void setNowTurnChangePhase(boolean b){
		this.nowTurnChangePhase=b;
	}

	public boolean isNowTurnChangePhase() {
		return nowTurnChangePhase;
	}

	public AiSystem getAi(){
		return this.ai;
	}

	public boolean isUseAi() {
		return isUseAi;
	}

	public void setUseAi(boolean isUseAi) {
		this.isUseAi = isUseAi;
	}

	public Memory getMoveData() {
		return moveData;
	}





	public void saveMemory(){
		//メモリーにデーターを保存
		this.moveData.addNextMemorys(new Memory(moveData,startIsland.clone(),
				endIsland.clone(), boat.clone(),
				0, 0, 0, 0));
		this.moveData=moveData.getNextMemorys().get(0);
		CoreLog.debug("deep:"+moveData.getDeepNumber());
	}


	/**
	 * AIで主に使用
	 * @return
	 */
	public Memory changeMemoryAndRemoveBifNextRoot(){
		CoreLog.debug("ok1");

		this.moveData=moveData.getNextMemorys().get(0);

		CoreLog.debug("ok1");

		return this.moveData;
	}

	private int turnBackCountMax=0;
	private int turnBackCount=0;


	public void returnGameTurn(int turn,boolean nowTrunChange){

		isStopUpdate2=true;	//処理の衝突対策

		RiverCrossingAI.getBgmPlayer().pause();


		aiChara.changeAnimation(1);
		returnIcon.setShowView(true);
		returnBackScreen.setShowView(true);


		turnBackCountMax=turn;
		turnBackCount=1;



		if(nowTrunChange){	//ターン交代中に呼ばれた場合

			RiverCrossingAI.getSePlayer().stop(gameSeType.CROSS.ordinal());
			CoreLog.debug("boat patern");

			if(startIsland.getNowTurn()){
				startIsland.setNowTurn(false);
				endIsland.setNowTurn(true);
			}else{
				startIsland.setNowTurn(true);
				endIsland.setNowTurn(false);
			}


			//isLandの情報更新
			for(int i=0;i<targets.size();i++){
				//管理情報の更新
				if(!startIsland.getNowTurn()){
					startIsland.removeCharacter(targets.get(i));
					endIsland.addCharacter(targets.get(i));
				}else{
					endIsland.removeCharacter(targets.get(i));
					startIsland.addCharacter(targets.get(i));
				}
			}



			isNowReturnPhaseIfBoatMode=true;	//反対方向へ動かす
			isNowboatBackMove=true;
		}else{	//それ以外で呼ばれた場合
			CoreLog.debug("else patern");

			isNowReturnPhaseIfNormal=true;


			bifMoveMinisterNum=moveData.getMinisterMoveNum();
			bifMoveWolfNum=moveData.getWolfMoveNum();
			bifMoveCabbageNum=moveData.getCabbageMoveNum();
			bifMoveCattleMoveNum=moveData.getCattleMoveNum();

			Island island=null;

			if(startIsland.getNowTurn()){
				island=startIsland;
			}else{
				island=endIsland;
			}




			boolean flag=false;
			CoreLog.debug("--"+bifMoveMinisterNum+"/"+bifMoveWolfNum+"/"+bifMoveCabbageNum+"/"+bifMoveCattleMoveNum);
			while(!flag){
				//CoreLog.debug("--"+island.getMinisters().size()+"/"+island.getWolfs().size()+"/"+island.getCabbages().size()+"/"+island.getCattles().size());

				CoreLog.debug("while");

				if(bifMoveMinisterNum>0){
					bifMoveMinisterNum--;
					CoreLog.debug(""+island.getMinisters().size());
					//island.getMinisters().get(island.getMinisters().size()-1).onTouchDown();


					ArrayList<CharaModel> c=island.getMinisters();
					for(int i=c.size()-1;i>=0;i--){
						if(!c.get(i).isNowTarget()){
							c.get(i).onTouchDown();
							break;
						}
					}

				}else if(bifMoveWolfNum>0){
					bifMoveWolfNum--;
					//island.getWolfs().get(island.getWolfs().size()-1).onTouchDown();

					ArrayList<CharaModel> c=island.getWolfs();
					for(int i=c.size()-1;i>=0;i--){
						if(!c.get(i).isNowTarget()){
							c.get(i).onTouchDown();
							break;
						}
					}

				}else if(bifMoveCabbageNum>0){
					bifMoveCabbageNum--;
					//island.getCabbages().get(island.getCabbages().size()-1).onTouchDown();

					ArrayList<CharaModel> c=island.getCabbages();
					for(int i=c.size()-1;i>=0;i--){
						if(!c.get(i).isNowTarget()){
							c.get(i).onTouchDown();
							break;
						}
					}

				}else if(bifMoveCattleMoveNum>0){
					bifMoveCattleMoveNum--;
					//island.getCattles().get(island.getCattles().size()-1).onTouchDown();

					ArrayList<CharaModel> c=island.getCattles();
					for(int i=c.size()-1;i>=0;i--){
						if(!c.get(i).isNowTarget()){
							c.get(i).onTouchDown();
							break;
						}
					}

				}else{
					flag=true;
				}
			}

			CoreLog.debug("-2 "+targets.size());
			this.changeTurn(true);
			CoreLog.debug("-3");



			//ボートの方向変更
			if(!startIsland.getNowTurn()){
				boat.changeAnimation(1);
			}else{
				boat.changeAnimation(0);
			}

		}



		RiverCrossingAI.getSePlayer().play(gameSeType.RETURN.ordinal());

		//セレクトボタンの表示を消す
		for(int i=0;i<selectIcons.size();i++){
			selectIcons.get(i).setShowView(false);
		}

		moveData=moveData.getBifMemory();
		moveData.removeNextmemorys(0);


		isNowReturnPhase=true;





		CoreLog.debug("back trun1");


		isStopUpdate2=false;

	}

	/**
	 * 巻き戻り処理
	 */
	public void turnBack(){

		CoreLog.debug("back trun /"+turnBackCount+"/"+turnBackCountMax);


		if(turnBackCountMax<=turnBackCount){
			isNowReturnPhase=false;

			//セレクトボタンの表示解放
			for(int i=0;i<selectIcons.size();i++){
				selectIcons.get(i).setShowView(true);
			}
			CoreLog.debugSimple("///////////////////////////////////////////////////////");
			CoreLog.debug("createNewAI");
			Island island=startIsland;
			CoreLog.debug("--"+island.getMinisters().size()+"/"+island.getWolfs().size()+"/"+island.getCabbages().size()+"/"+island.getCattles().size());
			island=endIsland;
			CoreLog.debug("--"+island.getMinisters().size()+"/"+island.getWolfs().size()+"/"+island.getCabbages().size()+"/"+island.getCattles().size());

			island=moveData.getStartIsland();
			CoreLog.debug("--"+island.getMinisters().size()+"/"+island.getWolfs().size()+"/"+island.getCabbages().size()+"/"+island.getCattles().size());
			island=moveData.getEndIsland();
			CoreLog.debug("--"+island.getMinisters().size()+"/"+island.getWolfs().size()+"/"+island.getCabbages().size()+"/"+island.getCattles().size());


			ai=new AiSystemType1(moveData, this, boat, startIsland, endIsland);

			aiChara.changeAnimation(0);

			returnIcon.setShowView(false);
			returnBackScreen.setShowView(false);

			RiverCrossingAI.getBgmPlayer().play();
			RiverCrossingAI.getSePlayer().stop(gameSeType.RETURN.ordinal());

			return ;
		}

		turnBackCount++;

		isNowReturnPhaseIfBoatMode=false;

		/*if(nowTurnChangePhase){	//ターン交代中に呼ばれた場合
			isNowReturnPhaseIfBoatMode=true;	//反対方向へ動かす
			isNowboatBackMove=true;
		}
		isNowReturnPhase=true;*/


		CoreLog.debug("back trun");
	}


	public void setStopUpdate(boolean isStopUpdate) {
		this.isStopUpdate = isStopUpdate;
	}

	public void addoppositeRightIcon(OppositeIcon model,boolean isShow){
		model.setShowView(isShow);
		this.oppositeRightIcons.add(model);
	}

	public void addoppositeLeftIcon(OppositeIcon model,boolean isShow){
		model.setShowView(isShow);
		this.oppositeLeftIcons.add(model);
	}

	public void addSelectIcons(CoreModel selectIcon){
		this.selectIcons.add(selectIcon);
	}

	public void addCrossButton(CrossButton button){
		this.crossButton=button;
	}

	public void setBackScreen(CoreModel model){
		this.backScreen=model;
	}

	public void addAllCharacter(CharaModel model){
		this.allCharacter.add(model);
	}

	public void setNumBox(NumBox box){
		this.numbox=box;
	}

	public void setNumboxS(NumBox numboxS) {
		this.numboxS = numboxS;
	}

	public void setGameoverScreenTypeWolf(CoreModel gameoverScreenTypeWolf) {
		this.gameoverScreenTypeWolf = gameoverScreenTypeWolf;
	}

	public void setGameoverScreenTypeCabbage(CoreModel gameoverScreenTypeCabbage) {
		this.gameoverScreenTypeCabbage = gameoverScreenTypeCabbage;
	}

	public void setGameoverScreenTypeAi(CoreModel gameoverScreenTypeAi) {
		this.gameoverScreenTypeAi = gameoverScreenTypeAi;
	}

	public void setExampleBox(ExampleBox exampleBox) {
		this.exampleBox = exampleBox;
	}

	public void setOnemorePlayButton(OnemorePlayButton onemorePlayButton) {
		this.onemorePlayButton = onemorePlayButton;
	}

	public void setBackToTitleButton(BackToTitleButton backToTitleButton) {
		this.backToTitleButton = backToTitleButton;
	}

	public void setFadeMask(CoreModel fadeMask) {
		this.fadeMask = fadeMask;
	}

	public void setPerfectLogo(CoreModel perfectLogo) {
		this.perfectLogo = perfectLogo;
	}

	public void setClearLogo(CoreModel clearLogo) {
		this.clearLogo = clearLogo;
	}


	public int getMoveNum() {
		return moveNum;
	}

	public void setAiChara(AiChara aiChara) {
		this.aiChara = aiChara;
	}

	public void setReturnBackScreen(CoreModel returnBackScreen) {
		this.returnBackScreen = returnBackScreen;
	}

	public void setReturnIcon(CoreModel returnIcon) {
		this.returnIcon = returnIcon;
	}



}
