aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/Assets/Scripts/Controllers/GameController.cs
blob: c9cb0ce53f9efac920661acc2ea20509dfb27300 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
using System;
using System.Collections;
using JetBrains.Annotations;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

namespace Controllers
{
  /// <summary>
  /// The controller for the basketball-game logic.
  /// </summary>
  public class GameController : MonoBehaviour
  {
    private State state = State.JumpBall; // A basketball game always starts with a jump ball.
    internal Animator BallAnimation;

    public Player player;
    public Player enemy;
    
    public bool freezeMotion;

    private float startTime;
    public static float timeLimit;
    
    /// <summary>
    /// The single ball for the game.
    /// </summary>
    [SerializeField] public Ball ball;

    [SerializeField] private float dribbleHeight;
    [SerializeField] private float dribbleSpeed;
    private Vector3 ballTarget;
    
    [SerializeField] public SpriteRenderer[] trenchCoatSegments;

    [Header("Spawn Points")]
    [SerializeField] private SpawnPoints PlayerSpawnPoints;
    [SerializeField] private SpawnPoints EnemySpawnPoints;

    [Header("Hoops")]
    [SerializeField] public Hoop PlayerHoop;
    [SerializeField] public Hoop EnemyHoop;

    [Header("SFX")]
    [SerializeField] public AudioSource dribbleSound;
    [SerializeField] public AudioSource airhornSound;

    [Header("UI")]
    [SerializeField] private Text playerScoreText;
    [SerializeField] private Text enemyScoreText;
    [SerializeField] private Text timerText;
    
    [SerializeField] private GameObject resultOverlay;
    [SerializeField] private Text resultText;
    [SerializeField] private GameObject actionsUI;

    private void Awake()
    {
      player = new Player { isEnemy = false, controller = this };
      enemy = new Player { isEnemy = true, controller = this };
      ball.controller = this;
      PlayerHoop.controller = this;
      EnemyHoop.controller = this;
      BallAnimation = ball.GetComponentInChildren<Animator>();
    }

    private void Start()
    {
      startTime = Time.time - 2f;
      freezeMotion = true;
      StartCoroutine(FadeInCoat());
    }

    private IEnumerator FadeInCoat()
    {
      foreach (var trenchCoat in trenchCoatSegments)
        trenchCoat.material.color = new Color(1, 1, 1, 0);
      
      yield return new WaitForSeconds(1f);
      
      for (float t = 0; t < 1f; t += Time.deltaTime / 1)
      {
        foreach (var trenchCoat in trenchCoatSegments)
          trenchCoat.material.color = new Color(1, 1, 1, Mathf.Lerp(0, 1, t));
        yield return null;
      }

      yield return new WaitForSeconds(1f);

      freezeMotion = false;
      startTime = Time.time;
      ball.Rigidbody.velocity = new Vector2(0, 10f);
    }

    private void Update()
    {
      UpdateUI();
    }

    private void FixedUpdate()
    {
      if (player.HasBall || enemy.HasBall)
      {
        ball.transform.position = ballTarget - new Vector3(0, (Mathf.Sin(Time.time * dribbleSpeed) + 1f) * (ballTarget.y - 0.75f) * dribbleHeight, 0);
      }
    }

    private bool gameover;
    private void UpdateUI()
    {
      playerScoreText.text = $"{player.score}";
      enemyScoreText.text = $"{enemy.score}";

      var remainingRaw = timeLimit - (Time.time - startTime);
      var remaining = TimeSpan.FromSeconds(Mathf.Clamp(remainingRaw, 0, float.MaxValue));
      timerText.text = $"{remaining.Minutes:00}:{remaining.Seconds:00}";

      if (remainingRaw <= 0 && !gameover)
      {
        airhornSound.Play();
        var outcome = player.score == enemy.score ? "TIE GAME" : player.score < enemy.score ? "AWAY TEAM WINS" : "HOME TEAM WINS";
        actionsUI.SetActive(true);
        ShowModal($"{outcome}\n{player.score}-{enemy.score}");

        freezeMotion = true;
        gameover = true;
      }
    }

    public struct Player
    {
      /// <summary>
      /// Whether this player is the AI-enemy.
      /// </summary>
      internal bool isEnemy;
      
      /// <summary>
      /// A back-reference to the containing GameController.
      /// </summary>
      internal GameController controller;
      
      internal int score;

      private Vector2 lastShotPosition;
      public void Score(Vector2 Rim)
      {
        if (Vector2.Distance(lastShotPosition, Rim) >= 10)
        {
          score += 3;
        }
        else
        {
          score += 2;
        }
        
        // They made a shot! Now respawn the players and give possession to the opposite player.
        controller.Respawn(isEnemy ? Possession.Player : Possession.Enemy, $"{controller.player.score}-{controller.enemy.score}");
      }

      private State dribble => isEnemy ? State.EnemyDribble : State.PlayerDribble;
      private State shoot => isEnemy ? State.EnemyShoot : State.PlayerShoot;

      private Hoop hoop => isEnemy ? controller.EnemyHoop : controller.PlayerHoop;

      public bool HasBall => controller.state == dribble;

      /// <summary>
      /// When dribbling, move the ball with the player.
      /// </summary>
      /// <param name="handPosition">The position of the hand dribbling the ball.</param>
      public void Move(Vector2 handPosition)
      {
        if (controller.state == (isEnemy ? State.EnemyDribble : State.PlayerDribble)) // Make sure they're dribbling.
          controller.ballTarget = handPosition;
      }

      /// <summary>
      /// Grab the ball if possible given the current game state.
      /// </summary>
      /// <param name="handPosition">The position of the hand to attempt grabbing from.</param>
      /// <returns>Whether or not the ball was able to be picked up.</returns>
      public bool GrabBall(Vector2 handPosition)
      { 
        // Don't allow the ball to be picked up if someone shot it. Also don't try picking it up if we're already holding it.
        if (controller.state == shoot || controller.state == dribble) return false;
        
        // Make sure its within their grab area.
        if (Vector2.Distance(controller.ball.transform.position, handPosition) >= 1f) return false;
        
        controller.state = dribble;
        controller.BallAnimation.enabled = false;
        controller.dribbleSound.Play();
        Move(handPosition);

        controller.ball.Rigidbody.bodyType = RigidbodyType2D.Kinematic;
        
        return true;
      }

      /// <summary>
      /// Shoot the ball if possible.
      /// </summary>
      /// <param name="playerTransform"></param>
      /// <param name="time"></param>
      /// <returns>Whether or not the ball was shot</returns>
      public bool Shoot(Transform playerTransform, float time)
      {
        if (controller.state != dribble) return false; // We must be dribbling the ball to shoot it.
        controller.BallAnimation.enabled = true;
        controller.dribbleSound.Stop();
        controller.state = shoot;
        controller.ball.Rigidbody.bodyType = RigidbodyType2D.Dynamic;
        controller.ball.Shoot(hoop, time);
        lastShotPosition = playerTransform.position;
        return true;
      }

      public void Foul(string reason)
      {
        // Give the other player the ball on a foul.
        controller.Respawn(isEnemy ? Possession.Player : Possession.Enemy, reason);
      }
    }

    internal void BallDropped()
    {
      BallAnimation.enabled = true;
      dribbleSound.Stop();
      ball.Rigidbody.bodyType = RigidbodyType2D.Dynamic;
      state = State.Idle;
    }

    private void Respawn(Possession possession, string message)
    {
      BallDropped();
      
      PlayerSpawnPoints.body.transform.position = new Vector3(PlayerSpawnPoints.character.position.x, PlayerSpawnPoints.character.position.y, PlayerSpawnPoints.body.transform.position.y);
      PlayerSpawnPoints.body.GetComponent<Rigidbody2D>().velocity = Vector2.zero;

      if (PlayerSpawnPoints.secondBody is { })
      {
        if (PlayerSpawnPoints.secondCharacter is { })
          PlayerSpawnPoints.secondBody.transform.position = new Vector3(PlayerSpawnPoints.secondCharacter.position.x, PlayerSpawnPoints.secondCharacter.position.y, PlayerSpawnPoints.body.transform.position.y);
        PlayerSpawnPoints.secondBody.GetComponent<Rigidbody2D>().velocity = Vector2.zero;
      }

      PlayerSpawnPoints.body.transform.localRotation = Quaternion.identity;
      EnemySpawnPoints.body.transform.position = new Vector3(EnemySpawnPoints.character.position.x, EnemySpawnPoints.character.position.y, EnemySpawnPoints.body.transform.position.y);
      ball.transform.position = possession switch
      {
        Possession.Player => new Vector3(PlayerSpawnPoints.ball.position.x, PlayerSpawnPoints.ball.position.y, ball.transform.position.y),
        Possession.Enemy => new Vector3(EnemySpawnPoints.ball.position.x, EnemySpawnPoints.ball.position.y, ball.transform.position.y),
        _ => ball.transform.position
      };
      
      // Set a cooldown so they can stop trying to wrangle the player while it respawns.
      StartCoroutine(RespawnCooldown(possession, message));
    }

    private IEnumerator RespawnCooldown(Possession possession, string message)
    {
      // Show the new score.
      var possessionText = possession == Possession.Player ? "HOME" : "AWAY";
      ShowModal($"{message}\n{possessionText}'S POSSESSION");

      freezeMotion = true;
      
      yield return new WaitForSeconds(1f);
      
      HideModal();
      
      freezeMotion = false;
    }

    private void ShowModal(string text)
    {
      if (gameover) return;
      resultOverlay.SetActive(true);
      resultText.text = text;
    }

    private void HideModal()
    {
      if (gameover) return;
      resultOverlay.SetActive(false);
    }

    public void Restart() => SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);

    public void MainMenu() => SceneManager.LoadScene("Menu");

    internal enum State
    {
      Idle,
      JumpBall,
      PlayerDribble,
      PlayerShoot,
      EnemyDribble,
      EnemyShoot,
    }

    [Serializable]
    private struct SpawnPoints
    {
      [SerializeField] internal Transform body;
      [SerializeField] [CanBeNull] internal Transform secondBody;
      [SerializeField] internal Transform ball;
      [SerializeField] internal Transform character;
      [SerializeField] [CanBeNull] internal Transform secondCharacter;
    }

    private enum Possession
    {
      Player,
      Enemy
    }
  }

  internal static class GameControllerStateExtensions
  {
    internal static bool IsShot(this GameController.State state)
    {
      return state == GameController.State.EnemyShoot || state == GameController.State.PlayerShoot;
    }
    
    internal static bool IsDribble(this GameController.State state)
    {
      return state == GameController.State.EnemyDribble || state == GameController.State.PlayerDribble;
    }
  }
}