<repo_name>RiccardoCantoni/spaceInvadersAI<file_sep>/Space Invaders/Assets/Scripts/fuzzy/behaviours/FuzzyBehaviour.cs
﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class FuzzyBehaviour {

	public bool spacebarOutput;
	public float movementOutput;
	protected Sensor sensor;
	protected GameObject displayObject;

	public virtual void updateOutputs (){
	}
		
	public void init(Sensor s, GameObject display){
		this.sensor = s;
		this.displayObject = display;
	}

	protected void setDisplayMessage(List<string> msg){
		displayObject.GetComponent<Display> ().stringList = msg;
	}

}






<file_sep>/Space Invaders/Assets/Scripts/fuzzy/behaviours/AttackLowest.cs
﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class AttackLowest : FuzzyBehaviour {
	
	#region targetPosition

	FuzzyClass targetCloseRight = new FuzzyClass (0, 0.5f, 1, 3);
	FuzzyClass targetRight = new FuzzyClass (1, 3, 5, 7);
	FuzzyClass targetFarRight = new FuzzyClass (5, 7, 16, 17);
	FuzzyClass targetCloseLeft = new FuzzyClass (-3, -1, -0.5f, 0);
	FuzzyClass targetLeft = new FuzzyClass (-7, -5, -3, -1);
	FuzzyClass targetFarLeft = new FuzzyClass (-17, -16, -7, -5);
	
	#endregion

	#region shield

	CrispClass underShield = new CrispClass (-0.8f, 0.8f);

	#endregion

	#region alienSpeed

	FuzzyClass speedLowPositive = new FuzzyClass (0, 0.75f, 1.15f, 1.45f);
	FuzzyClass speedMediumPositive = new FuzzyClass (1.15f, 1.45f, 1.95f, 2.35f);
	FuzzyClass speedHighPositive = new FuzzyClass (1.95f, 2.35f, 2.75f, 3);
	FuzzyClass speedLowNegative = new FuzzyClass (-1.45f, -1.15f, -0.75f, 0);
	FuzzyClass speedMediumNegative = new FuzzyClass (-2.35f, -1.95f, -1.45f, 1.15f);
	FuzzyClass speedHighNegative = new FuzzyClass (-3, -2.75f, -2.35f, -1.95f);

	#endregion

	public override void updateOutputs(){

		//variabile composta
		float targetPosition = sensor.lowestAlienDistance + sensor.lowestAlienLead;

		//fuzzyficazione
		float tgp, tgpp, tgppp, tgn, tgnn, tgnnn;
		tgp = targetCloseRight.calculateMembership (targetPosition);
		tgpp = targetRight.calculateMembership (targetPosition);
		tgppp = targetFarRight.calculateMembership (targetPosition);
		tgn = targetCloseLeft.calculateMembership (targetPosition);
		tgnn = targetLeft.calculateMembership (targetPosition);
		tgnnn = targetFarLeft.calculateMembership (targetPosition);

		float shield;
		shield = underShield.calculateMembership (sensor.shieldDistance);

		float sp, spp, sppp, sn, snn, snnn;
		sp = speedLowPositive.calculateMembership (sensor.alienVelocity);
		spp = speedMediumPositive.calculateMembership (sensor.alienVelocity);
		sppp = speedHighPositive.calculateMembership (sensor.alienVelocity);
		sn = speedLowNegative.calculateMembership (sensor.alienVelocity);
		snn = speedMediumNegative.calculateMembership (sensor.alienVelocity);
		snnn = speedHighNegative.calculateMembership (sensor.alienVelocity);

		//FAM
		float hardRight, right, hardLeft, left;
		float tgMovingRight, tgMovingLeft;
		float tgIsRight, tgIsLeft;

		// tgppp 
		//OR 
		// tgpp & (mvright | sn) 
		//OR
		// shield & isright
		tgMovingRight = FuzzyLib.fuzzyOr(sp, spp, sppp);
		tgIsRight = FuzzyLib.fuzzyOr (tgp, tgpp, tgppp);
		hardRight = tgppp;
		hardRight = FuzzyLib.fuzzyOr(hardRight, FuzzyLib.fuzzyAnd(tgpp, FuzzyLib.fuzzyOr(tgMovingRight, sn)));
		hardRight = FuzzyLib.fuzzyOr(hardRight, FuzzyLib.fuzzyAnd (shield, tgIsRight));

		// tgp 
		//OR
		// (tgpp & (tgnn | tgnnn))
		tgMovingLeft = FuzzyLib.fuzzyOr(tgnn, tgnnn);
		right = FuzzyLib.fuzzyOr (tgp, FuzzyLib.fuzzyAnd (tgpp, tgMovingLeft));
		right = FuzzyLib.fuzzyAnd (right, FuzzyLib.fuzzyNot (shield));

		// tgn
		//OR
		// (tgnn & (tgpp | tgppp))
		tgMovingRight = FuzzyLib.fuzzyOr(tgpp, tgppp);
		left = FuzzyLib.fuzzyOr (tgn, FuzzyLib.fuzzyAnd (tgnn, tgMovingRight));
		left = FuzzyLib.fuzzyAnd (left, FuzzyLib.fuzzyNot (shield));

		// tgnnn 
		//OR
		// (tgnn & (mvleft | sp)
		//OR
		// shield & isleft
		tgMovingLeft = FuzzyLib.fuzzyOr(sn, snn, snnn);
		tgIsLeft = FuzzyLib.fuzzyOr (tgn, tgnn, tgnnn);
		hardLeft = tgnnn;
		hardLeft = FuzzyLib.fuzzyOr(hardLeft, FuzzyLib.fuzzyAnd(tgnn, FuzzyLib.fuzzyOr(tgMovingLeft, sp)));
		hardLeft = FuzzyLib.fuzzyOr(hardLeft, FuzzyLib.fuzzyAnd(shield, tgIsLeft));

		//defuzzyficazione
		movementOutput = (-0.8f)*hardLeft +(-0.4f)*left + 0.4f*right + 0.8f*hardRight ;

		if ((left + hardLeft  + right + hardRight)>1)
			Debug.Log (left.ToString("F2") +  hardLeft.ToString("F2")  + right .ToString("F2")+ hardRight.ToString("F2"));


		spacebarOutput = FuzzyLib.toBool (FuzzyLib.fuzzyNot(shield));

		//display
		List<string> message = new List<string>();
		message.Add ("==ATK LOWEST==");
		message.Add ("target distance:");
		message.Add (tgnnn.ToString("F2") + "|" + tgnn.ToString ("F2") + "|" + tgn.ToString ("F2") + (" l"));
		message.Add (tgp.ToString("F2") + "|" + tgpp.ToString("F2") + "|" + tgppp.ToString("F2") + (" r"));
		message.Add ("target velocity:");
		message.Add (snnn.ToString ("F2") + "|" + snn.ToString ("F2") + "|" + sn.ToString ("F2")+ (" l"));
		message.Add (sp.ToString ("F2") + "|" + spp.ToString ("F2") + "|" + sppp.ToString ("F2")+ (" r"));
		message.Add ("shield:");
		message.Add (shield.ToString("F2"));
		message.Add ("movement:");
		message.Add (hardLeft.ToString("F2") + "|" + left.ToString("F2") + "|" + right.ToString("F2") + "|" + hardRight.ToString("F2"));
		message.Add ("shooting");
		message.Add (spacebarOutput.ToString());

		setDisplayMessage (message);

	}
		
}
<file_sep>/Space Invaders/Assets/Scripts/aliens/MovementManager.cs
﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MovementManager : MonoBehaviour {

	public float initialVerticalSpeed;
	public float finalVerticalSpeed;
	public float initialHorizontalSpeed;
	public float finalHorizontalSpeed;


	float horizontalSpeedIncrease;
	float verticalSpeedIncrease;

	public Vector2 alienVelocityVector;

	void Start(){
		horizontalSpeedIncrease = (finalHorizontalSpeed - initialHorizontalSpeed) / 55f;
		verticalSpeedIncrease = (finalVerticalSpeed - initialVerticalSpeed) / 55f;
	}

	public void DownLeft(float timeDown){
		StartCoroutine (DownLeftCoroutine (timeDown));
	}

	public void DownRight(float timeDown){
		StartCoroutine (DownRightCoroutine (timeDown));
	}

	IEnumerator DownRightCoroutine(float timeDown){
		alienVelocityVector = (Vector3.down * initialVerticalSpeed);
		yield return new WaitForSeconds (timeDown);
		alienVelocityVector = (Vector3.right * initialHorizontalSpeed);
	}

	IEnumerator DownLeftCoroutine(float timeDown){
		alienVelocityVector = (Vector3.down * initialVerticalSpeed);
		yield return new WaitForSeconds (timeDown);
		alienVelocityVector = (Vector3.left * initialHorizontalSpeed);
	}

	public void initiate (Vector3 vector){
		alienVelocityVector = (vector*initialHorizontalSpeed);
	}

	public void increaseGameSpeed(){
		initialVerticalSpeed += verticalSpeedIncrease;
		initialHorizontalSpeed += horizontalSpeedIncrease;
		updateVelocityVector ();
		}

	private void updateVelocityVector(){
		Vector3 dir = alienVelocityVector.normalized;
		if (dir.x == 0) { // up down
			alienVelocityVector = dir * initialVerticalSpeed;
		} else {	//left right
			alienVelocityVector = dir * initialHorizontalSpeed;
		}
	}
}
<file_sep>/Space Invaders/Assets/Scripts/fuzzy/fuzzyLogic/CrispClass.cs
﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CrispClass{

	float p1, p2;

	public CrispClass(float p1, float p2){
		this.p1 = p1;
		this.p2 = p2;
	}

	public float calculateMembership(float inputValue){
		if (inputValue <= p1)
			return 0;
		if (inputValue < p2)
			return 1;
		return 0;
	}


}
<file_sep>/Space Invaders/Assets/Scripts/player units/player controllers/playerController.cs
﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class playerController : MonoBehaviour {

	public float Velocity;
	public float timeBetweenShots;
	public GameObject bullet;
	public float bound;

	Vector3 initialPos;
	float nextShootingWindow;

	void Start(){
		initialPos = transform.position;
		nextShootingWindow = Time.time;
	}
		
	void Update () {
		float input = Input.GetAxis ("Horizontal");
		Vector3 newpos = transform.position + Vector3.right * input * Velocity * Time.deltaTime;
		if (newpos.x > initialPos.x - bound & newpos.x < initialPos.x + bound) {
			transform.position = newpos;
		}
		if (Input.GetKeyDown ("space")) {
			shoot ();
		}
	}

	void shoot() {
		if (Time.time > nextShootingWindow) {
			Instantiate (bullet, transform.position, transform.rotation);
			nextShootingWindow = Time.time + timeBetweenShots;
		}
	}

}
<file_sep>/Space Invaders/Assets/Scripts/fuzzy/behaviours/AttackRedShip.cs
﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class AttackRedShip : FuzzyBehaviour {

	#region targetPosition

	FuzzyClass targetCloseRight = new FuzzyClass (0, 0.5f, 1, 3);
	FuzzyClass targetRight = new FuzzyClass (1, 3, 5, 7);
	FuzzyClass targetFarRight = new FuzzyClass (5, 7, 16, 17);
	FuzzyClass targetCloseLeft = new FuzzyClass (-3, -1, -0.5f, 0);
	FuzzyClass targetLeft = new FuzzyClass (-7, -5, -3, -1);
	FuzzyClass targetFarLeft = new FuzzyClass (-17, -16, -7, -5);

	#endregion

	#region shield

	CrispClass underShield = new CrispClass (-0.8f, 0.8f);

	#endregion

	public override void updateOutputs(){

		//variabile composta
		float targetPosition = sensor.redShipDistance + sensor.redShipLead;

		//fuzzyficazione
		float tgp, tgpp, tgppp, tgn, tgnn, tgnnn;
		tgp = targetCloseRight.calculateMembership (targetPosition);
		tgpp = targetRight.calculateMembership (targetPosition);
		tgppp = targetFarRight.calculateMembership (targetPosition);
		tgn = targetCloseLeft.calculateMembership (targetPosition);
		tgnn = targetLeft.calculateMembership (targetPosition);
		tgnnn = targetFarLeft.calculateMembership (targetPosition);

		float shield;
		shield = underShield.calculateMembership (sensor.shieldDistance);

		//FAM

		float hardLeft, left, right, hardRight;

		hardLeft = FuzzyLib.fuzzyOr (tgn, FuzzyLib.fuzzyOr (tgnn, tgnnn));
		hardRight = FuzzyLib.fuzzyOr (tgp, FuzzyLib.fuzzyOr (tgpp, tgppp));
		left = 0;
		right = 0;

		//defuzzyficazione
		movementOutput = -0.8f*hardLeft -0.4f*left + 0.4f*right + 0.8f*hardRight ;
		spacebarOutput = FuzzyLib.toBool (FuzzyLib.fuzzyNot(shield));

		//display
		List<string> message = new List<string>();
		message.Add ("==ATK RED SHIP==");
		message.Add ("target distance:");
		message.Add (tgnnn.ToString("F2") + "|" + tgnn.ToString ("F2") + "|" + tgn.ToString ("F2") + (" l"));
		message.Add (tgp.ToString("F2") + "|" + tgpp.ToString("F2") + "|" + tgppp.ToString("F2") + (" r"));
		message.Add ("shooting");
		message.Add (spacebarOutput.ToString());

		setDisplayMessage (message);

	}

}<file_sep>/Space Invaders/Assets/Scripts/fuzzy/MainFuzzyController.cs
﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MainFuzzyController : MonoBehaviour {

	public float horizontalAxisInput;
	public bool spacebarInput;
	public int behaviourIndex;
	public GameObject behaviourDisplay, selectorDisplay;

	BehaviourSelector behaviourSelector = new BehaviourSelector ();
	FuzzyBehaviour avoidBehavior = new Avoid ();
	FuzzyBehaviour shelterBehavior = new Shelter ();
	FuzzyBehaviour atkRedShipBehaviour = new AttackRedShip ();
	FuzzyBehaviour atkClosestBehaviour = new AttackClosest ();
	FuzzyBehaviour atkLowestBehaviour = new AttackLowest ();
	FuzzyBehaviour currentBehaviour;

	GameObject marker;
	Sensor sensor;

	void Start(){
		sensor = gameObject.GetComponent<Sensor>();
		sensor.initSensor ();
		behaviourSelector.init (sensor, selectorDisplay);
		avoidBehavior.init (sensor, behaviourDisplay);
		shelterBehavior.init (sensor, behaviourDisplay);
		atkRedShipBehaviour.init (sensor, behaviourDisplay);
		atkClosestBehaviour.init (sensor, behaviourDisplay);
		atkLowestBehaviour.init (sensor, behaviourDisplay);
	}

	void Update(){
		sensor.updateSensor ();
		behaviourSelector.selectBehaviour ();
		switch (behaviourSelector.behaviourIndex) {
		case 0:
			currentBehaviour = avoidBehavior;
			break;
		case 1:
			currentBehaviour = shelterBehavior;
			break;
		case 2:
			currentBehaviour = atkRedShipBehaviour;
			break;
		case 3:
			currentBehaviour = atkClosestBehaviour;
			break;
		case 4:
			currentBehaviour = atkLowestBehaviour;
			break;
		default:
			Debug.Log ("index error");
			Time.timeScale = 0;
			break;
		}
		currentBehaviour.updateOutputs ();
		horizontalAxisInput = currentBehaviour.movementOutput;
		spacebarInput = currentBehaviour.spacebarOutput;
		if (Mathf.Abs (currentBehaviour.movementOutput) > 1) {
			Debug.Log ("input error, behaviour " + behaviourIndex);
		}
	}

}
<file_sep>/Space Invaders/Assets/Scripts/game mechanics/ExplosionManager.cs
﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ExplosionManager : MonoBehaviour {

	public GameObject explosion;

	public void explode(){
		Instantiate (explosion, transform.position, transform.rotation);
	}

}
<file_sep>/Space Invaders/Assets/menu/SelectorScript.cs
﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SelectorScript : MonoBehaviour {

	public GameObject selectorPrefab;
	public List<GameObject> buttons;
	public GameObject placeholder;

	GameObject selector;

	public void onHover(int parameter){
		if (selector == null) {
			selector = Instantiate (selectorPrefab);
			selector.transform.parent = transform;
		}
		switch (parameter) {
		case 0:
			selector.transform.position = new Vector3 (placeholder.transform.position.x, buttons[0].transform.position.y, 100);
			break;
		case 1:
			selector.transform.position = new Vector3 (placeholder.transform.position.x, buttons[1].transform.position.y, 100);
			break;
		case 2:
			selector.transform.position = new Vector3 (placeholder.transform.position.x, buttons[2].transform.position.y, 100);
			break;
		default:
			break;
		}
	}
}
<file_sep>/Space Invaders/Assets/Scripts/player units/shields/ShieldStage.cs
﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ShieldStage : MonoBehaviour {


	void OnCollisionEnter2D () {
		ShieldScript shield = transform.parent.gameObject.GetComponent<ShieldScript> ();
		shield.isHit ();
	}
}
<file_sep>/Space Invaders/Assets/Scripts/player units/player controllers/autoPlayerController.cs
﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class autoPlayerController: MonoBehaviour {

	public float Velocity;
	public float timeBetweenShots;
	public GameObject bullet;
	public float bound;

	public float input;

	float nextShootingWindow;

	MainFuzzyController MFC;

	void Start(){
		nextShootingWindow = Time.time;
		MFC = gameObject.GetComponent<MainFuzzyController> ();
	}

	void Update () {
		input = MFC.horizontalAxisInput;
		Vector3 newpos = transform.position + Vector3.right * input * Velocity * Time.deltaTime;
		if (newpos.x > (-1f*bound) & newpos.x < bound) {
			transform.position = newpos;
		}
		if (MFC.spacebarInput) {
			shoot ();
		}
	}

	void shoot() {
		if (Time.time > nextShootingWindow) {
			Instantiate (bullet, transform.position, transform.rotation);
			nextShootingWindow = Time.time + timeBetweenShots;
		}
	}
}
<file_sep>/Space Invaders/Assets/Scripts/aliens/ShootingManager.cs
﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ShootingManager : MonoBehaviour {

	public float FireDelay;

	List<GameObject> aliens=new List<GameObject>();

	public void Initiate () {
		StartCoroutine (commandShoot());
	}

	IEnumerator commandShoot(){
		while (true) {
			yield return new WaitForSeconds (FireDelay);
			aliens.Clear ();
			foreach (Transform child in transform) {
				aliens.Add (child.gameObject);
			}
			if (aliens.Count>0){
				int i = Random.Range (0, aliens.Count);
				alienController shooter = aliens [i].GetComponent<alienController> ();
				shooter.shoot ();
			}
		}
	}

}
<file_sep>/Space Invaders/Assets/Scripts/player units/shields/ShieldScript.cs
﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ShieldScript : MonoBehaviour {

	public int hp;
	public GameObject st1;
	public GameObject st2;
	public GameObject st3;

	GameObject curStage;

	void Start () {
		hp = 3;
		curStage=Instantiate (st1, transform.position, transform.rotation);
		curStage.transform.parent = transform;
	}
	
	public void isHit(){
		hp--;
		Destroy (curStage);
		switch (hp) {
		case 2:
			curStage = Instantiate (st2, transform.position + Vector3.down*0, transform.rotation);
			curStage.transform.parent = transform;
			break;
		case 1:
			curStage = Instantiate (st3, transform.position + Vector3.down*0, transform.rotation);
			curStage.transform.parent = transform;
			break;
		case 0:
			Destroy (gameObject);
			break;
		}
	}
		
}
<file_sep>/Space Invaders/Assets/Scripts/aliens/RedShipController.cs
﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class RedShipController : MonoBehaviour {

	public float velocity;
	public Vector2 direction;

	Rigidbody2D rb;

	void Start(){
		rb = gameObject.GetComponent<Rigidbody2D> ();
	}

	public void initiate(Vector3 dir){
		direction = new Vector2 (dir.x, dir.y);
	}

	void Update () {
		rb.MovePosition (rb.position + direction * velocity * Time.deltaTime);
	}

}
<file_sep>/Space Invaders/Assets/Scripts/game mechanics/TimeToLive.cs
﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TimeToLive : MonoBehaviour {

	public float time;

	void Start(){
		StartCoroutine (selfDestruct());
	}


	IEnumerator selfDestruct(){
		yield return new WaitForSeconds (time);
		Destroy (gameObject);
	}
}
<file_sep>/Space Invaders/Assets/menu/GameData.cs
﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public static class GameData{
	
	public static bool gameWon;
	public static bool gameHuman;
	public static int gameScore;
	public static GameManager gameManager;
	public static bool hasData;
	public static float startTime;
	public static float gameDuration;

}
<file_sep>/Space Invaders/Assets/Scripts/fuzzy/fuzzyLogic/FuzzyLib.cs
﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FuzzyLib{

	public static float fuzzyAnd(float a, float b){
		return Mathf.Min (a, b);
	}

	public static float fuzzyAnd (float a, float b, float c){
		return fuzzyAnd (a, fuzzyAnd (b, c));
	}

	public static float fuzzyOr(float a, float b){
		return Mathf.Max (a, b);
	}

	public static float fuzzyOr(float a, float b, float c){
		return fuzzyOr (a, fuzzyOr (b, c));
	}

	public static float fuzzyNot(float a){
		return 1f - a;
	}

	public static float fuzzyOrMultiple(List<float> list){
		return Mathf.Max (list.ToArray ());
	}

	public static bool toBool (float f){
		if (f == 0) {
			return false;
		}
		return true;
	}

}
<file_sep>/Space Invaders/Assets/Scripts/aliens/gridManager.cs
﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class gridManager : MonoBehaviour {

	public GameObject alien;
	public Vector3 startPos;
	public float cellWidth;
	public float cellHeight;
	public float rightBound;
	public float leftBound;
	public float timeDown;

	int state = 0; //right
	int rows = 5;
	int columns = 11;
	MovementManager movementmanager;
	ShootingManager shootingmanager;


	void Start () {
		spawnGrid ();
		shootingmanager = gameObject.GetComponent<ShootingManager> ();
		shootingmanager.Initiate ();
		movementmanager = gameObject.GetComponent<MovementManager> ();
		movementmanager.initiate (Vector3.right);
	}
	
	public void spawnGrid(){
		GameObject a;
		alienController script;
		Vector3 pos = startPos;
		for (int r = 0; r < rows; r++) {
			for (int c = 0; c < columns; c++) {
				a=Instantiate (alien, pos, transform.rotation);
				a.transform.parent = transform;
				script = a.GetComponent<alienController> ();
				script.gridpos = new Vector2 (c,r);
				pos += Vector3.right * cellWidth;
			}
			pos.x = startPos.x;
			pos += Vector3.down * cellHeight;
		}
	}

	void Update(){
		foreach (Transform child in transform) {
			if (state==0 && child.transform.position.x>=rightBound){
				state = 1;
				movementmanager.DownLeft (timeDown);
			}

			if (state==1 & child.transform.position.x<=leftBound){
				state = 0;
				movementmanager.DownRight (timeDown);
			}
		}
	}
}
<file_sep>/Space Invaders/Assets/Scripts/fuzzy/fuzzyLogic/FuzzyClass.cs
﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class FuzzyClass {

	float p1, p2, p3, p4;

	public FuzzyClass(float p1, float p2, float p3, float p4){
		this.p1 = p1;
		this.p2 = p2;
		this.p3 = p3;
		this.p4 = p4;
	}

	public FuzzyClass(float p1, float p2, float p3){
		this.p1 = p1;
		this.p2 = p2;
		this.p3 = p2;
		this.p4 = p3;
	}

	public float calculateMembership(float inputValue){
		float ratio;
		if (inputValue <= p1 | inputValue >= p4) {  
			return 0;
		}

		if (inputValue > p1 & inputValue < p2 ) {
			ratio = Mathf.Abs(inputValue - p1) / Mathf.Abs(p2 - p1);
			return (Mathf.Lerp(0,1,ratio));
		}

		if (inputValue >= p2 & inputValue <= p3) {
			return 1;
		}

		if (inputValue > p3 & inputValue < p4) {
			ratio = Mathf.Abs(inputValue - p3) / Mathf.Abs(p4 - p3);
			return (Mathf.Lerp(1,0,ratio));
		}
		return 0;
	}

	public static FuzzyClass mirrorPositive(FuzzyClass x){
		return new FuzzyClass (x.p4 * (-1), x.p3 * (-1), x.p2 * (-1), x.p1 * (-1));
	}


		
}
<file_sep>/Space Invaders/Assets/Scripts/fuzzy/MyUtils.cs
﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;

public class MyUtils{

	public static float closest(List<float> list, float playerPos){
		float minDistance = Mathf.Abs (list [0] - playerPos);
		int closestIndex = 0;
		for (int i = 1; i < list.Count; i++) {
			float d = Mathf.Abs (list [i] - playerPos);
			if (d < minDistance) {
				minDistance = d;
				closestIndex = i;
			}
		}
		return list[closestIndex];
	}

	public static float calculateLead(float tgSpeed, float tgHeight, float projectileSpeed){
		float res = Mathf.Abs(tgSpeed * tgHeight / projectileSpeed);
		if (tgSpeed > 0) {
			return res;
		} else {
			return res *(-1);
		}
	}

	public static Vector3 gridToVector3(int x, int y, GameObject offsetMarker) {
		return new Vector3 (x * 1.36f + offsetMarker.transform.position.x - 7.8f, y * -1 + offsetMarker.transform.position.y + 4, -10);
	}

	public static int argmax(float[] values){
		int minIndex = -1;
		float minValue = 0;
		for (int i = 0; i < values.Length; i++) {
			if (values [i] > minValue) {
				minIndex = i;
			}
		}
		return minIndex;
	}

	public static void appendToFile(string filename, string text){
		System.IO.File.AppendAllText (filename, text+Environment.NewLine);
	}

}
<file_sep>/Space Invaders/Assets/Scripts/others/Display.cs
﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Display : MonoBehaviour {

	public string title;
	public List<string> stringList;

	Text text;

	void Start () {
		stringList = new List<string> ();
		text = gameObject.transform.GetChild (0).transform.GetChild (0).GetComponent<Text> ();
	}

	void Update () {
		string newText = title + "\n";
		foreach (string s in stringList) {
			newText = newText + (s + "\n");
		}
		text.text = newText;
	}
}
<file_sep>/Space Invaders/Assets/Scripts/others/markerMover.cs
﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class markerMover : MonoBehaviour {

	MovementManager mvm;
	Rigidbody2D rb ;

	void Start(){
		mvm = GameObject.Find ("alienManager").GetComponent<MovementManager> ();
		rb = gameObject.GetComponent<Rigidbody2D> ();
	}

	void Update () {
		rb.MovePosition (rb.position + mvm.alienVelocityVector*Time.deltaTime);
	}

}
<file_sep>/Space Invaders/Assets/menu/ButtonScript.cs
﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ButtonScript : MonoBehaviour {

	GameManager gm;

	public void buttonClicked(int parameter){
		gm = GameObject.Find ("GameMaster").GetComponent<GameManager> ();
		switch (parameter) {
		case 0:
			Application.Quit ();
			break;
		case 1:
			gm.startGameHuman ();
			break;
		case 2:
			gm.startGameAuto ();
			break;
		default:
			MyUtils.appendToFile ("log.txt", "=====");
			Application.Quit ();
			break;
		}

	}

}
<file_sep>/Space Invaders/Assets/Scripts/others/GameManager.cs
﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class GameManager : MonoBehaviour {

	public bool logging;

	int alienCount;

	void Awake(){
		GameData.gameManager = this;
		if (GameObject.FindObjectsOfType (GetType ()).Length>1) {
			Destroy (gameObject);
		}
	}

	public void startGameAuto () {
		Cursor.visible = false;
		alienCount = 55;
		GameData.gameHuman = false;
		SceneManager.LoadScene ("auto");
		GameData.startTime = Time.time;
	}

	public void startGameHuman () {
		Cursor.visible = false;
		alienCount = 55;
		GameData.gameHuman = true;
		SceneManager.LoadScene ("human");
		GameData.startTime = Time.time;
	}

	public void endGame (bool won, bool human, int finalScore){
		GameData.gameDuration = Time.time - GameData.startTime;
		GameData.gameWon = won;
		GameData.gameHuman = human;
		GameData.gameScore = finalScore;
		GameData.hasData = true;
		if (logging)
			logLastGame ("log.txt");
		Cursor.visible = true;
		SceneManager.LoadScene ("menu");
	}

	public void alienDead(){
		alienCount--;
		if (alienCount == 0) {
			Score score = GameObject.Find ("score").GetComponent<Score>();
			endGame (true, GameData.gameHuman, score.totalScore);
		}
	}

	public void playerDead() {
		Score score = GameObject.Find ("score").GetComponent<Score>();
		endGame (false, GameData.gameHuman, score.totalScore);
	}
		
	private void logLastGame(string filename){
		MyUtils.appendToFile(filename, "-----");
		MyUtils.appendToFile(filename, "won: " + GameData.gameWon.ToString ());
		MyUtils.appendToFile(filename, "human: " + GameData.gameHuman.ToString ());
		MyUtils.appendToFile(filename, "score: " + GameData.gameScore.ToString ());
		MyUtils.appendToFile(filename, "duration: " + GameData.gameDuration.ToString ("F2"));
	}
		
}
<file_sep>/Space Invaders/Assets/Scripts/fuzzy/behaviours/Shelter.cs
﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Shelter : FuzzyBehaviour {

	FuzzyClass shieldFarLeft = new FuzzyClass (-16f, -15f, -2f, -1.5f);
	FuzzyClass shieldLeft = new FuzzyClass (-2.5f, -2f, -0.2f, 0.1f);
	FuzzyClass shieldRight = new FuzzyClass (-0.1f, 0.2f, 2f, 2.5f);
	FuzzyClass shieldFarRight = new FuzzyClass (1.5f, 2f, 15f, 16f);

	float sfl, sl, sr, sfr;

	float hardLeft, left, right, hardRight;

	public override void updateOutputs(){
		
		//fuzzyficazione
		sfl = shieldFarLeft.calculateMembership(sensor.shieldDistance);
		sl = shieldLeft.calculateMembership (sensor.shieldDistance);
		sr = shieldRight.calculateMembership (sensor.shieldDistance);
		sfr = shieldFarRight.calculateMembership (sensor.shieldDistance);

		//FAM
		hardLeft = FuzzyLib.fuzzyOr (sl,sfl);
		left = 0;
		right = 0;
		hardRight = FuzzyLib.fuzzyOr (sr,sfr);

		//defuzzyficazione
		spacebarOutput = false;
		movementOutput = hardLeft * (-0.8f) + left * (-0.4f) + right * (0.4f) + hardRight * (0.8f);

		//display
		List<string> message = new List<string>();
		message.Add ("==SHELTER==");
		message.Add ("shield distance:");
		message.Add (sfl.ToString("F2") + "|" + sl.ToString ("F2") + "|" + sr.ToString ("F2") + "|" + sfr.ToString ("F2") );
		message.Add ("movement:");
		message.Add (hardLeft.ToString("F2") + "|" + left.ToString("F2") + "|" + right.ToString("F2") + "|" + hardRight.ToString("F2"));
		message.Add ("shooting");
		message.Add (spacebarOutput.ToString());

		setDisplayMessage (message);

	}
}
<file_sep>/Space Invaders/Assets/Scripts/game mechanics/ConstantMover.cs
﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ConstantMover : MonoBehaviour {

	public float velocity;
	Rigidbody2D rb;

	void Start(){
		rb = gameObject.GetComponent<Rigidbody2D> ();
	}

	void Update () {
		rb.MovePosition (rb.position + Vector2.up * velocity * Time.deltaTime);
	}
}
<file_sep>/Space Invaders/Assets/menu/PauseScript.cs
﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class PauseScript : MonoBehaviour {

	bool paused;

	GameObject menu;

	void Start(){
		menu = gameObject.transform.GetChild (0).gameObject;
	}

	void Update () {
		if (Input.GetKeyDown ("escape")) {
			if (SceneManager.GetActiveScene ().buildIndex > 0) {
				if (paused) {
					unpause (1);
				} else {
					pause (1);
				}
			}
		}
	}

	public void pause(int trash){
		Cursor.visible = true;
		Time.timeScale = 0;
		paused = true;
		menu.SetActive (true);
	}
		
	public void unpause(int trash){
		Cursor.visible = false;
		menu.SetActive (false);
		paused = false;
		Time.timeScale = 1;
	}

	public void backToMenu(int trash){
		unpause (0);
		GameData.gameManager.endGame (false, GameData.gameHuman, GameObject.Find ("score").GetComponent<Score> ().totalScore);
	}
}
<file_sep>/Space Invaders/Assets/menu/LastGameText.cs
﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class LastGameText : MonoBehaviour {

	Text text;
	string firstLine = "last game results: \n";
	string playerType, gameResult, score, time;

	void Start(){
		if (GameData.hasData) {
			text = gameObject.GetComponent<Text> ();
			playerType = GameData.gameHuman ? "human" : "auto";
			gameResult = GameData.gameWon ? "victory" : "defeat";
			score = GameData.gameScore.ToString ();
			time = GameData.gameDuration.ToString ("F2");
			text.text = 
			firstLine +
			"player: " + playerType + "\n" +
			"result: " + gameResult + "\n" +
			"score: " + score + "\n" +
			"game duration: " + time;
		}
	}
			
}
<file_sep>/Space Invaders/Assets/Scripts/aliens/RedShipSpawner.cs
﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class RedShipSpawner : MonoBehaviour {

	public float spawnTimer;
	private float timerOffset;
	public GameObject redShip;

	GameObject newShip;
	Sensor sensor;

	void Start () {
		StartCoroutine (spawnCoroutine ());
		if (!GameData.gameHuman) {
			sensor = GameObject.Find ("autoPlayer").GetComponent<Sensor> ();
		}
	}
		
	IEnumerator spawnCoroutine(){
		while (true) {
			timerOffset = Random.value * 3f;
			yield return new WaitForSeconds (spawnTimer + timerOffset);
			spawnRandomised ();
		}
	}

	void spawnRandomised(){
		int x = Random.Range(0,2);
		if (x == 0) {
			newShip = Instantiate (redShip, transform.position + new Vector3 (-8.3f, 0, 0), transform.rotation);
			RedShipController rsc = newShip.GetComponent<RedShipController> ();
			rsc.initiate (Vector3.right);
		} else {
			newShip = Instantiate (redShip, transform.position + new Vector3 (8.3f, 0, 0), transform.rotation);
			RedShipController rsc = newShip.GetComponent<RedShipController> ();
			rsc.initiate (Vector3.left);
		}
		if (!GameData.gameHuman) {
			sensor.setRedShip (newShip);
		}
	}

}
<file_sep>/Space Invaders/Assets/tester.cs
﻿using System.Collections;
using System.Collections.Generic;
using System;
using UnityEngine;

public class tester : MonoBehaviour {


	// Use this for initialization
	void Start () {
		string str = "test test line1"+Environment.NewLine;
		string str2 = "test line2";
		MyUtils.appendToFile ("output.txt", str);
		MyUtils.appendToFile ("output.txt", str2);
		print ("done");

	}
	

}
<file_sep>/Space Invaders/Assets/AutoRestarter.cs
﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class AutoRestarter : MonoBehaviour {

	void Start () {
		StartCoroutine (restartCoroutine (1));
	}
	
	IEnumerator restartCoroutine(float time){
		yield return new WaitForSeconds (time);
		GameObject.Find ("MainMenu").GetComponent<ButtonScript> ().buttonClicked (2);
	}
}
<file_sep>/Space Invaders/Assets/Scripts/game mechanics/Score.cs
﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Score : MonoBehaviour {

	public int alienScore;
	public int redShipScore;

	public int totalScore;
	Text scoreText;
	GameManager gm;

	void Start () {
		totalScore = 0;
		scoreText = GameObject.Find ("ScoreText").GetComponent<Text>();
		gm = GameObject.Find ("GameMaster").GetComponent<GameManager> ();
	}

	public void updateScore(GameObject obj){
		if (obj.tag == "Alien") {
			totalScore += alienScore;
			gm.alienDead ();
		} else {
			totalScore += redShipScore;
		}
		scoreText.text = "SCORE: " + totalScore;
	}

}
<file_sep>/Space Invaders/Assets/Scripts/fuzzy/behaviours/BehaviourSelector.cs
﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class BehaviourSelector : FuzzyBehaviour {

	int avoid = 0;
	int shelter = 1;
	int atkRedship = 2;
	int atkClosest = 3;
	int atkLowest = 4;

	public int behaviourIndex;

	float[] behaviours = new float[5];

	#region danger

	FuzzyClass dangerLow = new FuzzyClass(-0.1f, 0, 0.2f, 0.5f);
	FuzzyClass dangerMedium = new FuzzyClass (0.2f, 0.5f, 0.8f);
	FuzzyClass dangerHigh = new FuzzyClass (0.5f, 0.8f, 5, 10);

	#endregion

	#region shield

	FuzzyClass shieldClose = new FuzzyClass (-1, 0, 0.9f, 1.35f);
	FuzzyClass shieldFar = new FuzzyClass (0.9f, 1.35f, 100, 101);

	#endregion

	#region redship

	CrispClass redShipPresent = new CrispClass (0.75f, 1.25f);

	FuzzyClass screenWeak = new FuzzyClass (-1, 0, 4, 9);
	FuzzyClass screenMedium = new FuzzyClass (4, 9, 16, 21);
	FuzzyClass screenStrong = new FuzzyClass (16, 21, 35, 36);

	#endregion

	#region grid

	FuzzyClass distributionHorizontal = new FuzzyClass(0,1,1.4f,1.8f);
	FuzzyClass distributionUndefined = new FuzzyClass(1.4f, 1.8f, 2.3f, 2.7f);
	FuzzyClass distributionVertical = new FuzzyClass(2.3f, 2.7f, 10f, 11f);

	FuzzyClass lowestAlienLow = new FuzzyClass(-1, 0, 2.5f, 4.5f);
	FuzzyClass lowestAlienHigh = new FuzzyClass(2.5f, 4.5f, 10, 11);


	#endregion

	public override void updateOutputs(){
		Debug.Log ("ERROR: updateOutputs called on selector");
	}

	public void selectBehaviour(){

		//fuzzyficazione
		float dngl, dngm, dngh;
		dngl = dangerLow.calculateMembership (sensor.danger);
		dngm = dangerMedium.calculateMembership (sensor.danger);
		dngh = dangerHigh.calculateMembership (sensor.danger);

		float shc, shf;
		shc = shieldClose.calculateMembership (Mathf.Abs(sensor.shieldDistance));
		shf = shieldFar.calculateMembership (Mathf.Abs(sensor.shieldDistance));

		float rs;
		rs = redShipPresent.calculateMembership (sensor.redShipPresent);

		float sw, sm, ss; 
		sw = screenWeak.calculateMembership (sensor.redShipScreen);
		sm = screenMedium.calculateMembership (sensor.redShipScreen);
		ss = screenStrong.calculateMembership (sensor.redShipScreen);

		float dh, du, dv;
		dh = distributionHorizontal.calculateMembership (sensor.alienDistributionIndex);
		du = distributionUndefined.calculateMembership (sensor.alienDistributionIndex);
		dv = distributionVertical.calculateMembership (sensor.alienDistributionIndex);

		float lwh, lwl;
		lwh = lowestAlienHigh.calculateMembership (sensor.lowestAlienHeight);
		lwl = lowestAlienLow.calculateMembership (sensor.lowestAlienHeight);

		//FAM
		float defend = FuzzyLib.fuzzyOr (dngm, dngh); 
		float attack = dngl; 

		//avoid = defend & !shc
		behaviours[avoid] = FuzzyLib.fuzzyAnd(defend, shf);

		//shelter = defend & shc
		behaviours [shelter] = FuzzyLib.fuzzyAnd (defend, shc);

		//atkred = attack & pres & (sw | dv | (sm & du & lwh))
		behaviours[atkRedship] = FuzzyLib.fuzzyAnd(
			attack, 
			rs, 
			FuzzyLib.fuzzyOr(sw, dv, FuzzyLib.fuzzyAnd(sm, du, lwh)));
		
		//atkClosest = attack & lwh & (dh | (!rs & (du | dv))) 
		behaviours[atkClosest] = FuzzyLib.fuzzyAnd(
			attack, 
			lwh, 
			FuzzyLib.fuzzyOr(
				dh,
				FuzzyLib.fuzzyAnd(
					FuzzyLib.fuzzyNot(rs), 
					FuzzyLib.fuzzyOr(du, dv))));
		
		//atkLowest = attack & lwl
		behaviours[atkLowest] = FuzzyLib.fuzzyAnd(attack, lwl);

		//defuzzyficazione
		behaviourIndex = MyUtils.argmax (behaviours);

		//display
		List<string> message = new List<string>();
		message.Add ("==SELECTOR==");
		message.Add ("danger level:");
		message.Add (dngl.ToString("F2") + "|" + dngm.ToString ("F2") + "|" + dngh.ToString ("F2"));
		message.Add ("shield:");
		message.Add (shc.ToString("F2") + "|" + shf.ToString ("F2"));
		message.Add ("red ship present:");
		message.Add (rs.ToString("F2"));
		if (sensor.redShipPresent > 0) {
			message.Add ("red ship screen:");
			message.Add (sw.ToString ("F2") + "|" + sm.ToString ("F2") + "|" + ss.ToString ("F2"));
		}
		message.Add ("alien distribution:");
		message.Add (dh.ToString("F2") + "|" + du.ToString ("F2") + "|" + dv.ToString ("F2"));
		message.Add ("lowest alien height:");
		message.Add (lwh.ToString("F2") + "|" + lwl.ToString ("F2"));
		message.Add ("behavior index:");
		message.Add (behaviourIndex.ToString());

		setDisplayMessage (message);
	}
}
<file_sep>/Space Invaders/Assets/Scripts/aliens/alienController.cs
﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class alienController : MonoBehaviour {

	public GameObject bomb;
	public Vector2 gridpos;

	MovementManager mvm;
	Rigidbody2D rb ;
	GameObject bombHolder;

	void Start(){
		mvm = transform.root.GetComponent<MovementManager> ();
		rb = gameObject.GetComponent<Rigidbody2D> ();
	}

	void Update () {
		rb.MovePosition (rb.position + mvm.alienVelocityVector*Time.deltaTime);
	}

	public void shoot(){
		Instantiate (bomb, transform.position+(Vector3.back), transform.rotation);
	}
		
}
<file_sep>/Space Invaders/Assets/Scripts/game mechanics/CollisionManager.cs
﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CollisionManager : MonoBehaviour {

	Sensor sensor;
	GameManager gm;

	void Start(){
		gm = GameData.gameManager;
	}

	void OnCollisionEnter2D (Collision2D col){
		if (gameObject.tag == "Alien") {
			Score score = GameObject.Find ("score").GetComponent<Score> ();
			score.updateScore (gameObject);
			MovementManager mm = GameObject.Find ("alienManager").GetComponent<MovementManager> ();
			mm.increaseGameSpeed ();
			if (!GameData.gameHuman) {
				Sensor s = GameObject.Find ("autoPlayer").GetComponent<Sensor> ();
				s.removeFromGrid (gameObject.GetComponent<alienController> ().gridpos);
			}
			ExplosionManager e = gameObject.GetComponent<ExplosionManager> ();
			e.explode();
		}

		if (gameObject.tag == "RedShip") {
			Score score = GameObject.Find ("score").GetComponent<Score> ();
			score.updateScore (gameObject);
			if (!GameData.gameHuman) {
				if (sensor == null) {
					sensor = GameObject.Find ("autoPlayer").GetComponent<Sensor> ();
				}
				sensor.setRedShip (null);
			}
		}

		if (gameObject.tag == "FinishLine" && col.gameObject.tag == "Alien") {
			gm.startGameAuto ();
		}

		if (gameObject.tag == "Player") {
			gm.playerDead ();
		}

		if (gameObject.tag != "FinishLine") {
			Destroy (gameObject);
		}
	}
}
<file_sep>/Space Invaders/Assets/Scripts/fuzzy/sensors/Sensor.cs
﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Sensor : MonoBehaviour {

	public float bombFunction;
	public float boundDistance;
	public float shieldDistance;
	public float alienVelocity;
	public float lowestAlienDistance;
	public float lowestAlienLead;
	public float lowestAlienHeight;
	public float closestAlienDistance;
	public float closestAlienHeight;
	public float closestAlienLead;
	public float redShipPresent;
	public float redShipDistance;
	public float redShipLead;
	public float redShipScreen;
	public float danger;
	public float alienDistributionIndex;

	private List <GameObject> bombList= new List<GameObject>();
	private int alienNumber = 55;

	GameObject offsetMarker;
	MovementManager movementManager;
	GameObject currentRedShip;
	GameObject debug;

	public void initSensor(){
		offsetMarker = GameObject.Find("offsetMarker");
		debug = GameObject.CreatePrimitive (PrimitiveType.Sphere);
		movementManager = GameObject.Find ("alienManager").GetComponent<MovementManager> ();
	}

	public void updateSensor(){
		updateBombFunction (transform.position, 6);
		updateBoundDistance ();
		updateShieldDistance ();
		updateAlienVelocity ();
		updateLowestAlienData ();
		updateLowestAlienLead ();
		updateClosestAlienData ();
		updateClosestAlienLead ();
		updateRedShipPresent ();
		if (currentRedShip != null) {
			updateRedShipDistance ();
			updateRedShipLead ();
			updateRedShipScreen ();
		}
		updateDanger (4,10);
		updateAlienDistributionIndex ();
	}
		
	#region bombs

	private void updateBombFunction(Vector3 playerPos, float maxDistance){
		List<Vector3> nearbyBombs = new List<Vector3> ();
		Vector3 nearest = new Vector3(100,100,100);
		float nearestDistance = 100;
		float currentDistance = 100;
		updateBombList ();
		foreach (GameObject b in bombList){
			currentDistance = Vector3.Distance (playerPos, b.transform.position);
			if (currentDistance <= maxDistance) {
				if (currentDistance < nearestDistance) {
					nearest = b.transform.position;
					nearestDistance = currentDistance;
				}
				nearbyBombs.Add (b.transform.position);
			}
		}
		float res = nearest.x;
		nearbyBombs.Remove (nearest);
		bombFunction = res-playerPos.x;
	}

	private void updateBombList(){
		bombList.Clear ();
		bombList.AddRange(GameObject.FindGameObjectsWithTag ("AlienBullet"));
	}

	#endregion

	#region bounds

	private void updateBoundDistance (){
		if (transform.position.x <= 0) {
			boundDistance = (-8.7f) - transform.position.x;
		} else {
			boundDistance =  8.7f - transform.position.x;
		}
	}

	#endregion

	#region shields

	private void updateShieldDistance(){
		shieldDistance = calculateShieldDistance();
	}

	private float calculateShieldDistance(){
		GameObject[] shields = GameObject.FindGameObjectsWithTag ("Shield");
		float closestDistance = 100;
		float shieldDistance = 100;
		foreach (GameObject s in shields) {
			float currentDistance = Mathf.Abs (s.transform.position.x - transform.position.x);
			if (currentDistance < closestDistance) {
				closestDistance = currentDistance;
				shieldDistance = s.transform.position.x - transform.position.x;
			}
		}
		return shieldDistance;
	}

	#endregion

	#region grid
	bool[,] alienGrid = new bool[11,5];  //F -> alive , T-> dead

	public void removeFromGrid (Vector2 pos){
		alienGrid [(int)pos.x,(int)pos.y] = true;
		alienNumber--;
	}

	private bool isAlive(int x, int y){
		if (alienGrid [x, y]==false) return true;
		return false;
	}

	private int getNumberOfRows(){
		bool foundHighest = false;
		int highest = 0; 
		int lowest = 4;
		for (int r = 0; r < 5; r++) {
			if (!foundHighest) {
				if (isAliveRow (r)) {  //highest
					highest = r;
					foundHighest = true;
				}
			} else {
				if (!isAliveRow (r)) { //lowest+1
					lowest = r-1;
					break;
				}
			}
		}
		return lowest - highest + 1;
	}

	private bool isAliveRow(int rowDown){
		for (int i = 0; i < 11; i++) {
			if (isAlive (i, rowDown)) {
				return true;
			}
		}
		return false;
	}

	#endregion

	#region lowest

	void updateLowestAlienData(){
		List<float> lowestLevel = new List<float> ();
		lowestLevel.Clear ();
		int lowestY = 4;
		for (int y = 4; y >= 0; y--) {
			for (int x = 0; x < 11; x++) {
				if (isAlive (x, y)) {
					lowestLevel.Add (MyUtils.gridToVector3(x, y, offsetMarker).x);
				}
			}
			if (lowestLevel.Count > 0) {
				lowestY = y;
				break;
			}
		}
		if (lowestLevel.Count > 0) {  //game ends
			lowestAlienDistance = MyUtils.closest (lowestLevel, transform.position.x) - transform.position.x;
			lowestAlienHeight = MyUtils.gridToVector3 (0, lowestY, offsetMarker).y + 5.3f;
		}
	}

	void updateLowestAlienLead(){
		lowestAlienLead = MyUtils.calculateLead (alienVelocity, lowestAlienHeight, 10f);
	}

	#endregion

	#region closest

	void updateClosestAlienData(){
		Vector3 closest = Vector3.zero;
		float minDistance = 100;
		for (int y = 0 ; y < 5; y++) {
			for (int x = 0; x < 11; x++) {
				if (isAlive (x, y)) {
					Vector3 curPos = MyUtils.gridToVector3 (x, y, offsetMarker);
					float curDistance = Vector3.Distance (transform.position, curPos);
					if (curDistance < minDistance) {
						closest = curPos;
						minDistance = curDistance; 
					}
				}
			}
		}
		closestAlienDistance = closest.x - transform.position.x;
		closestAlienHeight = closest.y - transform.position.y;
	}

	void updateClosestAlienLead(){
		closestAlienLead = MyUtils.calculateLead (alienVelocity, closestAlienHeight, 10f);
	}

	#endregion

	#region alienVelocity

	void updateAlienVelocity(){
		alienVelocity = movementManager.alienVelocityVector.x;
	}

	#endregion

	#region redship

	public void setRedShip(GameObject rs){
		currentRedShip = rs;
	}

	void updateRedShipDistance(){
		redShipDistance = currentRedShip.transform.position.x - transform.position.x;
	}

	void updateRedShipLead(){
		float absoluteLead = MyUtils.calculateLead (currentRedShip.GetComponent<RedShipController> ().velocity, 10.37f, 10);
		if (currentRedShip.GetComponent<RedShipController> ().direction.x > 0) {
			redShipLead = absoluteLead;
		} else {
			redShipLead = (-1)*absoluteLead;
		}
	}

	void updateRedShipScreen(){
		float lead = Mathf.Abs (redShipLead);
		Vector3 boxCenter = new Vector3 (currentRedShip.transform.position.x + redShipLead, 0, -10);
		redShipScreen = Physics2D.OverlapBoxAll (boxCenter, new Vector2 (lead, 8), 0, 1<<8).Length; 
		//Debug.DrawLine (boxCenter + new Vector3 (-lead/2f, 4, 0), boxCenter + new Vector3 (lead/2f, -4, 0));
		//Debug.Log (redShipScreen);

		//Debug.DrawLine (boxCenter + new Vector3 (boxWidth/2f, boxHeight/2f, 0), boxCenter + new Vector3 (-boxWidth/2f, -boxHeight/2f, 0));
	}

	void updateRedShipPresent(){
		if (currentRedShip != null) {
			redShipPresent = 1;
		} else {
			redShipPresent = -1;
		}
	}

	#endregion

	#region danger

	void updateDanger(float boxWidth, float boxHeight){
		Vector3 boxCenter = transform.position+Vector3.up*(boxHeight/2f - 0.5f);
		Collider2D[] bombColliders = Physics2D.OverlapBoxAll (boxCenter, new Vector2 (boxWidth, boxHeight+1), 0, 1 << 10);
		float res = 0;
		foreach (Collider2D col in bombColliders) {
			res += 1 / Vector3.Distance (col.transform.position, transform.position);
		}
		danger = res;
	}


	#endregion

	#region distribution

	void updateAlienDistributionIndex(){
		float rows = getNumberOfRows ();
		float res = (rows*11f / (float)alienNumber);
		if (res > 10) {
			alienDistributionIndex = 10;
		} else {
			alienDistributionIndex = res;
		}
	}

	#endregion

}
<file_sep>/Space Invaders/Assets/Scripts/game mechanics/onDestroy.cs
﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class onDestroy : MonoBehaviour {

	void OnDestroy(){
		Score score = GameObject.Find ("score").GetComponent<Score> ();
		score.updateScore (gameObject);
	}
}
<file_sep>/Space Invaders/Assets/Scripts/fuzzy/behaviours/Avoid.cs
﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Avoid : FuzzyBehaviour{

	static float maxDistance = 6;

	#region bombs

	FuzzyClass bombsFarLeft = new FuzzyClass (
		(-1) * maxDistance - 1, 
		(-1) * maxDistance, 
		maxDistance / -2f - 0.5f, 
		maxDistance / -2f + 0.5f);
	FuzzyClass bombsLeft = new FuzzyClass (
		maxDistance / -2f - 0.5f,
		maxDistance / -2f + 0.5f,
		-0.1f,
		0.5f);
	FuzzyClass bombsRight = new FuzzyClass (
		0,
		0.1f,
		maxDistance / 2f - 0.5f,
		maxDistance / 2f + 0.5f);
	FuzzyClass bombsFarRight = new FuzzyClass (
		maxDistance / 2f - 0.5f,
		maxDistance / 2f + 0.5f,
		maxDistance,
		maxDistance + 1);
	
	#endregion

	#region bounds

	float bfl, bl, br, bfr;

	FuzzyClass boundCloseLeft = new FuzzyClass (
        -3,
        -0.5f,
        -0.1f,
        0);
	FuzzyClass boundCloseRight = new FuzzyClass (
         0,
         0.1f,
         0.5f,
         3);

	float bdl, bdr;

	#endregion

	float hardLeft, left, right, hardRight;

	public override void updateOutputs(){
		//fuzzyficazione
		bfl = bombsFarLeft.calculateMembership (sensor.bombFunction);
		bl = bombsLeft.calculateMembership (sensor.bombFunction);
		br = bombsRight.calculateMembership (sensor.bombFunction);
		bfr = bombsFarRight.calculateMembership (sensor.bombFunction);

		bdl = boundCloseLeft.calculateMembership (sensor.boundDistance);
		bdr = boundCloseRight.calculateMembership (sensor.boundDistance);

		//FAM
		hardLeft = FuzzyLib.fuzzyOr(br, bdr);
		left = bfr;
		right = bfl;
		hardRight = FuzzyLib.fuzzyOr(bl, bdl);

		//defuzzyficazione
		movementOutput = hardLeft * (-0.8f) + left * (-0.4f) + right * (0.4f) + hardRight * (0.8f);

		//display
		List<string> message = new List<string>();
		message.Add ("==AVOID==");
		message.Add ("bombs distance:");
		message.Add (bfl.ToString("F2") + "|" + bl.ToString("F2") + "|" + br.ToString("F2") + "|" + bfr.ToString("F2"));
		message.Add ("bound distance:");
		message.Add (bdl.ToString ("F2") + "|" + bdr.ToString ("F2"));
		message.Add ("movement:");
		message.Add (hardLeft.ToString("F2") + "|" + left.ToString("F2") + "|" + right.ToString("F2") + "|" + hardRight.ToString("F2"));
		message.Add ("shooting");
		message.Add ("false");

		setDisplayMessage (message);

	}

}
