LearnWithTouch/Assets/scripts/CountGame.cs

864 lines
27 KiB
C#

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using UnityEngine.Video;
using TMPro;
public class CountGame : MonoBehaviour
{
public List<Trial> trials = new List<Trial>();
public RawImage TutorialPlayer;
public VideoClip count_tut;
private VideoPlayer vp;
private VideoSource videoSource;
//Audio
private AudioSource audioSource;
//public Text number;
public TMP_Text number;
public TMP_Text level;
public Camera cam;
private string game;
public SpriteRenderer background;
private int touchCount = 0;
const float sw= 1.5f;//stopwatch
private float targetTime = sw;
private float maxTargetTime = sw; //must be = targetTime
private float targetTime2 = 0.1f;
private float targetTime3 = 1.0f;
private float targetTime4 = 0.8f;
private ArrayList completed5 = new ArrayList();
private ArrayList completed10 = new ArrayList();
private int stage;
//private UnityEngine.Random rnd = new UnityEngine.Random();
private int count = 0;
private int score = 0;
private int[] numbers10 = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
private int[] numbers5 = { 1, 2, 3, 4, 5 };
private ArrayList s_numbers10 = new ArrayList();
private ArrayList s_numbers5 = new ArrayList();
private int[] numberCount = { 0, 0, 0, 0, 0 };
private int[] numberCount10 = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
public new List<AudioSource> audio = new List<AudioSource>();
public Button startButton;
public Button exitButton;
public Image fuel;
public Image progressBar;
public Image EvaluateTimer;
public GameObject[] hand = new GameObject[10];
private bool[] fingers = new bool[10];
private int trialCount = 0;
private bool logged = false;
private bool logged2 = false;
private bool logged3 = false;
//private float duration = 0.2f;
//private Color color1 = Color.blue;
//private Color color2 = Color.green;
//private Color color3 = Color.blue;
//private Color color4 = Color.red;
private int fingerCount=0;
private Trial trial;
public GameObject scoreStar;
public GameObject Finn;
//private Vector3 posStar = new Vector3();
//private int scoreCount = 0;
private bool evaluated=false;
private int response = 0;
private bool tutorialIsPlaying;
private bool playNextTrial;
private int error_count=0;
private bool kurze_pause=false;
//private bool switched=false;
private void Awake()
{
scoreStar.SetActive(false);
background.GetComponent<Animator>().SetInteger("fade", 0);
background.GetComponent<Animator>().Play("Background_Idle", -1, 0f);
StartCoroutine(prepareVideo());
}
IEnumerator prepareVideo() {
vp = gameObject.AddComponent<VideoPlayer>();
//Add AudioSource
audioSource = gameObject.AddComponent<AudioSource>();
//Disable Play on Awake for both Video and Audio
vp.playOnAwake = false;
audioSource.playOnAwake = false;
vp.source = VideoSource.VideoClip;
vp.audioOutputMode = VideoAudioOutputMode.AudioSource;
//Assign the Audio from Video to AudioSource to be played
vp.EnableAudioTrack(0, true);
vp.SetTargetAudioSource(0, audioSource);
audioSource.volume = 0.8f;
//We want to play from video clip not from url
vp.clip = count_tut;
//Set video To Play then prepare Audio to prevent Buffering
vp.Prepare();
//Wait until video is prepared
while (!vp.isPrepared)
{
Debug.Log("Preparing Video");
yield return null;
}
Debug.Log("Done Preparing Video");
//Assign the Texture from Video to RawImage to be displayed
TutorialPlayer.texture = vp.texture;
}
void Start()
{
number.text = " ";
number.gameObject.SetActive(false);
level.text = "LEVEL " + Gamestate.Instance.getLevel();
foreach (GameObject go in hand)
{
go.GetComponent<SpriteRenderer>().enabled = false;
}
for(int i=0; i<10;i++)
{
fingers[i] = false;
}
s_numbers10 = new ArrayList(reshuffle(numbers10));
s_numbers5 = new ArrayList(numbers5);
progressBar.fillAmount = 0;
EvaluateTimer.fillAmount=0;
EvaluateTimer.fillClockwise = true;
stage = 1;
}
int[] reshuffle(int[] numbers)
{
// Knuth shuffle algorithm :: courtesy of Wikipedia :)
for (int t = 0; t < numbers.Length; t++)
{
int tmp = numbers[t];
int r = UnityEngine.Random.Range(t, numbers.Length);
numbers[t] = numbers[r];
numbers[r] = tmp;
}
return numbers;
}
int selectRandomNumber_5()
{
if (s_numbers5.Count == 0) s_numbers5 = new ArrayList(reshuffle(numbers5));
int r = (int)s_numbers5[0];
s_numbers5.RemoveAt(0);
return r;
}
int selectRandomNumber_10()
{
if (s_numbers10.Count == 0) s_numbers10 = new ArrayList(reshuffle(numbers10));
int r = (int)s_numbers10[0];
s_numbers10.RemoveAt(0);
return r;
}
public void setProgressBar(int val)
{
Debug.Log("setProgressBar: " + val.ToString());
float t = Gamestate.Instance.getNumberTrials()*10f;
progressBar.fillAmount = val / t;
}
public void setEvaluateTimer(float val)
{
Debug.Log("setEvaluate: " + val.ToString());
//float t = Gamestate.Instance.getNumberTrials()*10f;
EvaluateTimer.fillAmount = val/maxTargetTime;//(Gamestate.Instance.getNumberTrials()*10) ;
}
void evaluateTouchInput()
{
foreach (Touch touch in Input.touches)
{
TouchSer tser = new TouchSer();
tser.TouchID = touch.fingerId.ToString();
tser.Timestamp = touch.deltaTime.ToString();
tser.X = touch.position.x;
tser.Y = touch.position.y;
trial.T.Add(tser);
}
Debug.Log("trial.t.:" + trial.T.Count.ToString());
Debug.Log("-------------------------------");
Debug.Log("count: " + count.ToString());
Debug.Log("touchCount: " + touchCount.ToString());
Debug.Log("+++++++++++++++++++++++++++++++");
evaluated = true;
//targetTime = 2.0f;
//targetTime2 = 0.1f;
fingerCount = 0;
//do your stuff here.
for (int i=0; i<10; i++)
{
if (fingers[i] == true) fingerCount += 1;
}
if (fingerCount == count)
{
Debug.Log("Level: " + Gamestate.Instance.getLevel());
Debug.Log("parsed Level: " + int.Parse(Gamestate.Instance.getLevel()).ToString());
trial.Correct = "y";
error_count = 0;
if (stage == 1)
{
numberCount[count - 1] += 1;
if (numberCount[count - 1] >= Gamestate.Instance.getMaxCorrect())
completed5.Add(count);
}
if (stage == 2)
{
numberCount10[count - 1] += 1;
if (numberCount10[count - 1] >= Gamestate.Instance.getMaxCorrect())
completed10.Add(count);
}
if (completed5.Count == 5)
{
stage = 2;
}
score = score + 10;
audio[11].Play();
scoreStar.SetActive(true);
scoreStar.GetComponent<Animator>().Play("StarMove", -1, 0f);
setProgressBar(score);
if (int.Parse(Gamestate.Instance.getLevel()) > 1)
{
audio[count - 1].Play();
}
if (int.Parse(Gamestate.Instance.getLevel()) > 2)
{
audio[count - 1].Play();
number.text = count.ToString();
//Debug.Log("------ GameState.getAnimPlaying: " + Gamestate.Instance.getAnimPlaying());
//if (!Gamestate.Instance.getAnimPlaying())
number.GetComponent<Animator>().Play("NumberAnim2", -1, 0f);
}
response = 1;
//game = "green_blink";
}
else
{
//game = "wrong";
//game = "red_blink";
number.text = " ";
//number.GetComponent<Animator>().Play("NumberAnim", -1, 0f);
audio[12].Play();
trial.Correct = "n";
response = 2;
error_count +=1;
}
}
void Update()
{
switch (game)
{
case "running":
if (!logged)
{
Debug.Log("running");
logged = true;
}
targetTime -= Time.deltaTime;
if (fingers[0] == true) {
//if (!EvaluateTimer.GetComponent<SpriteRenderer>().enabled) EvaluateTimer.GetComponent<SpriteRenderer>().enabled=true;
setEvaluateTimer(targetTime);
}
if (targetTime <= 0.0f & fingers[0] == true)
{
game = "evaluate";
break;
//evaluateTouchInput();
}
foreach (Touch touch in Input.touches)
{
switch (touch.phase)
{
case TouchPhase.Began:
Debug.Log("phase began");
touchCount += 1;
fingers[touchCount-1] = true;
audio[13].Play();
if (int.Parse(Gamestate.Instance.getLevel()) > 1)
{
audio[touchCount-1].Play();
}
if (touchCount < count & touchCount < 10)
{
hand[touchCount].GetComponent<SpriteRenderer>().enabled = true;
hand[touchCount].GetComponent<Animator>().SetBool("fadeout", false);
hand[touchCount].GetComponent<Animator>().Play("StarFadeIn", -1,0f);
}
targetTime = sw;
break;
case TouchPhase.Ended:
Debug.Log("phase ended");
if (touchCount > 1) touchCount -= 1;
fingers[touchCount] = false;
hand[touchCount+1].GetComponent<Animator>().SetBool("fadeout", true);
hand[touchCount+1].GetComponent<SpriteRenderer>().enabled = false;
targetTime = sw;
break;
default:
break;
}
}
break;
case "evaluate":
if (!logged2)
{
Debug.Log("evaluate");
logged2 = true;
}
if (!evaluated) evaluateTouchInput();
targetTime3 -= Time.deltaTime;
if (targetTime3 <= 0.0f)
{
if (response == 1) game = "green_blink";
if (response == 2) game = "red_blink";
trials.Add(trial);
}
break;
case "kurze_pause":
targetTime3 -= Time.deltaTime;
//level.text ="Weiter so!!!";
//tutorialIsPlaying=false;
//game="tutorial";
if (targetTime3 <= 0.0f)
{
if (Input.touchCount > 0) {
background.GetComponent<Animator>().SetInteger("fade", 2);
Debug.Log("-------------------------------------------------HALBZEIT---------------------------------------");
level.text = " ";
kurze_pause=true;
Finn.SetActive(false);
game = "next_trial";
//trials.Add(trial);
}
}
break;
case "green_blink":
targetTime -= Time.deltaTime;
//float t = Mathf.PingPong(Time.time, duration) / duration;
//cam.backgroundColor = Color.Lerp(color1, color2, t);
if (targetTime <= 0.0f)
{
number.text = " ";
for (int i = 0; i < 10; i++)
{
hand[i].GetComponent<Animator>().SetBool("fadeout", true);
}
targetTime2 -= Time.deltaTime;
if (targetTime2 <= 0.0f) {
playNextTrial=false;//nextTrial();
game="next_trial";
}
}
break;
case "red_blink":
targetTime -= Time.deltaTime;
//float t2 = Mathf.PingPong(Time.time, duration) / duration;
//cam.backgroundColor = Color.Lerp(color3, color4, t2);
if (targetTime <= 0.0f)
{
//cam.backgroundColor = Color.blue;
number.text = " ";
for (int i = 0; i < 10; i++)
{
hand[i].GetComponent<Animator>().SetBool("fadeout", true);
}
if (error_count >= 5) {
tutorialIsPlaying=false;
game="tutorial";
break;
}
targetTime2 -= Time.deltaTime;
if (targetTime2 <= 0.0f) {
playNextTrial=false;//nextTrial();
game="next_trial";
}
}
break;
case "tutorial":
targetTime4 -= Time.deltaTime;
//background = GetComponent<Animator>().SetBool("fadeout", true);
background.GetComponent<Animator>().SetInteger("fade", 1);
exitButton.gameObject.SetActive(false);
startButton.gameObject.SetActive(false);
fuel.gameObject.SetActive(false);
progressBar.gameObject.SetActive(false);
level.text=" ";
//background.GetComponent<Animator>().Play("Background_Fader", -1,0f);
if (targetTime4 <= 0.0f)
{
if(!tutorialIsPlaying) {
Debug.Log("background anim state1 = "+background.GetComponent<Animator>().GetCurrentAnimatorStateInfo(0).fullPathHash.ToString());
StartCoroutine(playTutorial());
}
}
break;
case "next_trial":
if(!playNextTrial) nextTrial();
break;
case "ending":
if (!logged3)
{
Debug.Log("ended");
number.text = " ";
trialCount = 0;
/* switch(Gamestate.Instance.getLevel())
{
case "1":
if(!switched)
{
Gamestate.Instance.setLevel("2");
switched = true;
}
break;
case "2":
if(!switched)
{
Gamestate.Instance.setLevel("3");
switched = true;
}
break;
}*/
targetTime -= Time.deltaTime;
//float t = Mathf.PingPong(Time.time, duration) / duration;
//cam.backgroundColor = Color.Lerp(color1, color2, t);
if (targetTime <= 0.0f)
{
logged3 = true;
trial.Score=score;
Gamestate.Instance.setGamePoints(score);
//foreach(Trial t in trials) {
// dump(t);
//}
savePlayerData();
//cam.backgroundColor = Color.black;
DontDestroyOnLoad(Gamestate.Instance);
Gamestate.Instance.startScoreScene();
}
}
break;
}
}
public void startProc() {
if (Gamestate.Instance.getTutorial())
{
tutorialIsPlaying=false;
Debug.Log("background anim state0 = "+background.GetComponent<Animator>().GetCurrentAnimatorStateInfo(0).fullPathHash.ToString());
game="tutorial";
//return;
} else
{
playNextTrial = false;
game="next_trial";//nextTrial();
}
}
/* Start of the game. Starts by pressing the play-button*/
public void nextTrial()
{
background.GetComponent<Animator>().SetInteger("fade",3);
targetTime4 = 0.8f;
Debug.Log("background anim state3 = "+background.GetComponent<Animator>().GetCurrentAnimatorStateInfo(0).fullPathHash.ToString());
//background.GetComponent<Animator>().SetInteger("fade",0);
progressBar.gameObject.SetActive(true);
level.text = " ";
foreach (GameObject go in hand)
{
go.GetComponent<SpriteRenderer>().enabled = false;
}
for (int i = 0; i < fingerCount; i++)
{
hand[i].GetComponent<Animator>().SetBool("fadeout", false);
}
if (trialCount > 0 && trialCount < Gamestate.Instance.getNumberTrials() && trialCount % 8 == 0 && !kurze_pause) {
background.GetComponent<Animator>().SetInteger("fade",1);
exitButton.gameObject.SetActive(false);
startButton.gameObject.SetActive(false);
Finn.SetActive(true);
fuel.gameObject.transform.localPosition = new Vector3(311,-213,0);
progressBar.gameObject.transform.localPosition = new Vector3(311.6f,-232,0);
float i = UnityEngine.Random.value;
if (error_count < 3) {
if (i < 0.25) {
level.text = "Super !!!";
audio[14].PlayDelayed(0.2f);
} else if (i >=0.25 && i < 0.5) {
level.text = "Toll !!!";
audio[15].PlayDelayed(0.2f);
} else if (i >= 0.5 && i < 0.75) {
level.text = "Sehr gut !!!";
audio[16].PlayDelayed(0.2f);
} else {
level.text = "Prima !!!";
audio[17].PlayDelayed(0.2f);
}
} else {
level.text = "Bleib dran !!!";
audio[18].PlayDelayed(0.2f);
}
game= "kurze_pause";
return;
}
else if (trialCount < Gamestate.Instance.getNumberTrials())
{
game = "running";
}
else
{
targetTime = sw;
game = "ending";
return;
}
//background.GetComponent<Animator>().SetBool("fade_in",false);
playNextTrial=true;
kurze_pause=false;
Finn.SetActive(false);
fuel.gameObject.transform.localPosition = new Vector3(900,600,0);
progressBar.gameObject.transform.localPosition = new Vector3(900.6f,577.8f,0);
hand[0].GetComponent<SpriteRenderer>().enabled = true;
hand[0].GetComponent<Animator>().Play("StarFadeIn", -1, 0f);
trial = new Trial();
trial.ID = Gamestate.Instance.getID();
trial.Game = Gamestate.Instance.getGame();
trial.Level = Gamestate.Instance.getLevel();
trial.Date = DateTime.Now.Date.ToShortDateString();
trial.Time = DateTime.Now.TimeOfDay.ToString();
trial.Onset = Time.time.ToString();
trial.Correct2 = "e";
trial.T.Clear();
/*if (trialCount < Gamestate.Instance.getNumberTrials())
{
game = "running";
}
else
{
targetTime = sw;
game = "ending";
return;
}*/
evaluated = false;
Gamestate.Instance.setAnimPlaying(true);
scoreStar.SetActive(false);
startButton.gameObject.SetActive(false);
//exitButton.gameObject.SetActive(false);
exitButton.gameObject.SetActive(true);
fuel.gameObject.SetActive(true);
if (Gamestate.Instance.getLevel() == "1")
number.gameObject.SetActive(false);
else
number.gameObject.SetActive(true);
Debug.Log("nextTrial CountGame");
//count = numbers10[trialCount];// UnityEngine.Random.Range(1, 5);
if (stage == 1) count = selectRandomNumber_5();
if (stage == 2) count = selectRandomNumber_10();
//if (count ==109)
Debug.Log("count = " + count.ToString());
trial.R = count;
trial.Y=0;
trial.X=0;
trial.Op = "n";
touchCount = 0;
targetTime = sw;
targetTime2 = 0.1f;
targetTime3 = 1.0f;
for (int i = 0; i < 10; i++)
{
fingers[i] = false;
}
trialCount += 1;
trial.TrialCounter = trialCount;
//Debug.Log("bis hierher.............................");
}
public void exitGame()
{
//Gamestate.Instance.setGamePoints(score);
//Gamestate.Instance.setGame("Count");
//Gamestate.Instance.setLevel("1");
if(game != "ending") {
savePlayerData();
}
DontDestroyOnLoad(Gamestate.Instance);
Gamestate.Instance.menuState();
}
private void OnApplicationPause(bool pauseStatus) {
if(game != "ending") {
savePlayerData();
}
}
private void OnApplicationQuit() {
if(game != "ending") {
savePlayerData();
}
}
public void savePlayerData()
{
// string bauen und zeilenweise rausschreiben
Debug.Log("save data on "+Application.persistentDataPath+"/playerData"+Gamestate.Instance.GetPlayerData().ID+".txt");
StreamWriter sw = new StreamWriter(Application.persistentDataPath+"/playerData"+Gamestate.Instance.getID()+".txt", true);
//File.Open(Application.persistentDataPath+"/playerData"+Gamestate.Instance.GetPlayerData().ID+".dat",FileMode.Append);
//BinaryFormatter bf = new BinaryFormatter();
string header= "Date Time TrialOnset ID Game Level Trial TargetNum1 TargetNum2 TargetNum3 TargetOp Score Correct Correct2 Attempt t1ID t1X t1Y t1deltaTime " +
"t2ID t2X t2Y t2deltaTime t3ID t3X t3Y t3deltaTime t4ID t4X t4Y t4deltaTime t5ID t5X t5Y t5deltaTime t6ID t6X t6Y t6deltaTime "+
"t7ID t7X t7Y t7deltaTime t8ID t8X t8Y t8deltaTime t9ID t9X t9Y t9deltaTime t10ID t10X t10Y t10deltaTime";
sw.WriteLine(header);
foreach (Trial t in trials)
{
string line = t.Date + " " + t.Time + " " + t.Onset + " " + t.ID + " " + t.Game + " " + t.Level + " " + t.TrialCounter + " " + t.X + " " + t.Y
+ " " + t.R + " " + t.Op + " " + t.Score + " " + t.Correct + " " + t.Correct2 + " " + t.Attempt;
int i=0;
foreach(TouchSer item in t.T) {
line = line + " " + item.TouchID + " " + item.X.ToString() + " " + item.Y.ToString() + " " + item.Timestamp;
i++;
}
for (int j = i; j <10; j++) {
line = line + " " + "99" + " " + "0" + " " + "0" + " " + "0";
}
Debug.Log("line: " + line);
//dump(trial);
sw.WriteLine(line);
}
sw.Close();
}
IEnumerator playTutorial()
{
tutorialIsPlaying = true;
TutorialPlayer.enabled=true;
//Add VideoPlayer to the GameObject
//Play Video
vp.Play();
//Play Sound
audioSource.Play();
Debug.Log("Playing Video");
while (vp.isPlaying)
{
//Debug.LogWarning("Video Time: " + Mathf.FloorToInt((float)vp.time));
yield return null;
}
//TutorialPlayer.GetComponent<Animator>().SetBool("fadeout",true);//.Play("tutorial2", -1, 0f);
TutorialPlayer.enabled = false;
background.GetComponent<Animator>().SetInteger("fade",2);
Debug.Log("background anim state2 = "+background.GetComponent<Animator>().GetCurrentAnimatorStateInfo(0).fullPathHash.ToString());
//Debug.Log("background anim state3 = "+background.GetComponent<Animator>().GetCurrentAnimatorStateInfo(0).fullPathHash.ToString());
/*var currentState = background.GetComponent<Animator>().GetCurrentAnimatorStateInfo(0);
while(currentState.fullPathHash == Animator.StringToHash("Base Layer.Player_standing"))
{
yield return null;
}*/
//yield return new WaitForSeconds(0.3f);
Debug.Log("Done Playing Video");
//background.GetComponent<Animator>().SetBool("fade_out", false);
//background.GetComponent<Animator>().SetBool("idle_in",false);
error_count=0;
playNextTrial=false;
//targetTime4 = 0.3f;
game="next_trial";
}
public void dump(Trial t) {
Debug.Log("------------------TRIAL-START------------------");
Debug.Log("date: " + t.Date);
Debug.Log("time: " + t.Time);
Debug.Log("trialOnset: " + t.Onset);
Debug.Log("game: " + t.Game);
Debug.Log("level: " + t.Level);
Debug.Log("score: " + t.Score);
Debug.Log("attempt_count: " + t.Attempt);
Debug.Log("ID: " + t.ID);
Debug.Log("Trial_counter: " + t.TrialCounter);
Debug.Log("Number: " + t.X);
Debug.Log("Number: " + t.Y);
Debug.Log("Number: " + t.R);
Debug.Log("Correct: " + t.Correct);
Debug.Log("Correct2: " + t.Correct2);
foreach (TouchSer item in t.T)
{
Debug.Log("touch.id: " + item.TouchID);
Debug.Log("touch.x: " + item.X.ToString());
Debug.Log("touch.y: " + item.Y.ToString());
Debug.Log("touch.time: " + item.Timestamp);
}
Debug.Log("------------------TRIAL-END------------------");
}
}