BlueGit

blue-star ggj-2020

Files

ggj-2020 / Assets / Oculus / Platform / Samples / VrHoops / Scripts / MatchController.cs

MatchController.cs

Project Import
timfa Tim Falken · pushed by timfa · 6 years ago
b77834a1 History
MatchController.cs 13.0 KiB Download Raw
1namespace Oculus.Platform.Samples.VrHoops
2{
3 using UnityEngine;
4 using UnityEngine.Assertions;
5 using UnityEngine.UI;
6 using System.Collections.Generic;
7 using Oculus.Platform.Models;
8
9 // This class coordinates playing matches. It mediates being idle
10 // and entering a practice or online game match.
11 public class MatchController : MonoBehaviour
12 {
13 // Text to display when the match will start or finish
14 [SerializeField] private Text m_timerText = null;
15
16 // the camera is moved between the idle position and the assigned court position
17 [SerializeField] private Camera m_camera = null;
18
19 // where the camera will be when not in a match
20 [SerializeField] private Transform m_idleCameraTransform = null;
21
22 // button that toggles between matchmaking and cancel
23 [SerializeField] private Text m_matchmakeButtonText = null;
24
25 // this should equal the maximum number of players configured on the Oculus Dashboard
26 [SerializeField] private PlayerArea[] m_playerAreas = new PlayerArea[3];
27
28 // the time to wait between selecting Practice and starting
29 [SerializeField] private uint PRACTICE_WARMUP_TIME = 5;
30
31 // seconds to wait to coordinate P2P setup with other match players before starting
32 [SerializeField] private uint MATCH_WARMUP_TIME = 30;
33
34 // seconds for the match
35 [SerializeField] private uint MATCH_TIME = 20;
36
37 // how long to remain in position after the match to view results
38 [SerializeField] private uint MATCH_COOLDOWN_TIME = 10;
39
40 // panel to add most-wins leaderboard entries to
41 [SerializeField] private GameObject m_mostWinsLeaderboard = null;
42
43 // panel to add high-score leaderboard entries to
44 [SerializeField] private GameObject m_highestScoresLeaderboard = null;
45
46 // leaderboard entry Text prefab
47 [SerializeField] private GameObject m_leaderboardEntryPrefab = null;
48
49 // Text prefab to use for achievements fly-text
50 [SerializeField] private GameObject m_flytext = null;
51
52 // the current state of the match controller
53 private State m_currentState;
54
55 // transition time for states that automatically transition to the next state,
56 // for example ending the match when the timer expires
57 private float m_nextStateTransitionTime;
58
59 // the court the local player was assigned to
60 private int m_localSlot;
61
62 void Start()
63 {
64 PlatformManager.Matchmaking.EnqueueResultCallback = OnMatchFoundCallback;
65 PlatformManager.Matchmaking.MatchPlayerAddedCallback = MatchPlayerAddedCallback;
66 PlatformManager.P2P.StartTimeOfferCallback = StartTimeOfferCallback;
67 PlatformManager.Leaderboards.MostWinsLeaderboardUpdatedCallback = MostWinsLeaderboardCallback;
68 PlatformManager.Leaderboards.HighScoreLeaderboardUpdatedCallback = HighestScoreLeaderboardCallback;
69
70 TransitionToState(State.NONE);
71 }
72
73 void Update()
74 {
75 UpdateCheckForNextTimedTransition();
76 UpdateMatchTimer();
77 }
78
79 public float MatchStartTime
80 {
81 get
82 {
83 switch(m_currentState)
84 {
85 case State.WAITING_TO_START_PRACTICE:
86 case State.WAITING_TO_SETUP_MATCH:
87 return m_nextStateTransitionTime;
88
89 default: return 0;
90 }
91 }
92 private set { m_nextStateTransitionTime = value; }
93 }
94
95 #region State Management
96
97 private enum State
98 {
99 UNKNOWN,
100
101 // no current match, waiting for the local user to select something
102 NONE,
103
104 // user selected a practice match, waiting for the match timer to start
105 WAITING_TO_START_PRACTICE,
106
107 // playing a Practice match against AI players
108 PRACTICING,
109
110 // post practice match, time to view the scores
111 VIEWING_RESULTS_PRACTICE,
112
113 // selecting Player Online and waiting for the Matchmaking service to find and create a
114 // match and join the assigned match room
115 WAITING_FOR_MATCH,
116
117 // match room is joined, waiting to coordinate with the other players
118 WAITING_TO_SETUP_MATCH,
119
120 // playing a competative match against other players
121 PLAYING_MATCH,
122
123 // match is complete, viewing the match scores
124 VIEWING_MATCH_RESULTS,
125 }
126
127 void TransitionToState(State newState)
128 {
129 Debug.LogFormat("MatchController State {0} -> {1}", m_currentState, newState);
130
131 if (m_currentState != newState)
132 {
133 var oldState = m_currentState;
134 m_currentState = newState;
135
136 // state transition logic
137 switch (newState)
138 {
139 case State.NONE:
140 SetupForIdle();
141 MoveCameraToIdlePosition();
142 PlatformManager.TransitionToState(PlatformManager.State.WAITING_TO_PRACTICE_OR_MATCHMAKE);
143 m_matchmakeButtonText.text = "Play Online";
144 break;
145
146 case State.WAITING_TO_START_PRACTICE:
147 Assert.AreEqual(oldState, State.NONE);
148 SetupForPractice();
149 MoveCameraToMatchPosition();
150 PlatformManager.TransitionToState(PlatformManager.State.MATCH_TRANSITION);
151 m_nextStateTransitionTime = Time.time + PRACTICE_WARMUP_TIME;
152 break;
153
154 case State.PRACTICING:
155 Assert.AreEqual(oldState, State.WAITING_TO_START_PRACTICE);
156 PlatformManager.TransitionToState(PlatformManager.State.PLAYING_A_LOCAL_MATCH);
157 m_nextStateTransitionTime = Time.time + MATCH_TIME;
158 break;
159
160 case State.VIEWING_RESULTS_PRACTICE:
161 Assert.AreEqual(oldState, State.PRACTICING);
162 PlatformManager.TransitionToState(PlatformManager.State.MATCH_TRANSITION);
163 m_nextStateTransitionTime = Time.time + MATCH_COOLDOWN_TIME;
164 m_timerText.text = "0:00.00";
165 break;
166
167 case State.WAITING_FOR_MATCH:
168 Assert.AreEqual(oldState, State.NONE);
169 PlatformManager.TransitionToState(PlatformManager.State.MATCH_TRANSITION);
170 m_matchmakeButtonText.text = "Cancel";
171 break;
172
173 case State.WAITING_TO_SETUP_MATCH:
174 Assert.AreEqual(oldState, State.WAITING_FOR_MATCH);
175 m_nextStateTransitionTime = Time.time + MATCH_WARMUP_TIME;
176 break;
177
178 case State.PLAYING_MATCH:
179 Assert.AreEqual(oldState, State.WAITING_TO_SETUP_MATCH);
180 PlatformManager.TransitionToState(PlatformManager.State.PLAYING_A_NETWORKED_MATCH);
181 m_nextStateTransitionTime = Time.time + MATCH_TIME;
182 break;
183
184 case State.VIEWING_MATCH_RESULTS:
185 Assert.AreEqual(oldState, State.PLAYING_MATCH);
186 PlatformManager.TransitionToState(PlatformManager.State.MATCH_TRANSITION);
187 m_nextStateTransitionTime = Time.time + MATCH_COOLDOWN_TIME;
188 m_timerText.text = "0:00.00";
189 CalculateMatchResults();
190 break;
191 }
192 }
193 }
194
195 void UpdateCheckForNextTimedTransition()
196 {
197 if (m_currentState != State.NONE && Time.time >= m_nextStateTransitionTime)
198 {
199 switch (m_currentState)
200 {
201 case State.WAITING_TO_START_PRACTICE:
202 TransitionToState(State.PRACTICING);
203 break;
204
205 case State.PRACTICING:
206 TransitionToState(State.VIEWING_RESULTS_PRACTICE);
207 break;
208
209 case State.VIEWING_RESULTS_PRACTICE:
210 TransitionToState(State.NONE);
211 break;
212
213 case State.WAITING_TO_SETUP_MATCH:
214 TransitionToState(State.PLAYING_MATCH);
215 break;
216
217 case State.PLAYING_MATCH:
218 TransitionToState(State.VIEWING_MATCH_RESULTS);
219 break;
220
221 case State.VIEWING_MATCH_RESULTS:
222 PlatformManager.Matchmaking.EndMatch();
223 TransitionToState(State.NONE);
224 break;
225 }
226 }
227 }
228
229 void UpdateMatchTimer()
230 {
231 if (Time.time <= m_nextStateTransitionTime)
232 {
233 switch (m_currentState)
234 {
235 case State.WAITING_TO_START_PRACTICE:
236 case State.WAITING_TO_SETUP_MATCH:
237 m_timerText.text = string.Format("{0:0}", Mathf.Ceil(Time.time - MatchStartTime));
238 break;
239
240 case State.PRACTICING:
241 case State.PLAYING_MATCH:
242 var delta = m_nextStateTransitionTime - Time.time;
243 m_timerText.text = string.Format("{0:#0}:{1:#00}.{2:00}",
244 Mathf.Floor(delta / 60),
245 Mathf.Floor(delta) % 60,
246 Mathf.Floor(delta * 100) % 100);
247 break;
248 }
249 }
250 }
251
252 #endregion
253
254 #region Player Setup/Teardown
255
256 void SetupForIdle()
257 {
258 for (int i = 0; i < m_playerAreas.Length; i++)
259 {
260 m_playerAreas[i].SetupForPlayer<AIPlayer>("* AI *");
261 }
262 }
263
264 void SetupForPractice()
265 {
266 // randomly select a position for the local player
267 m_localSlot = Random.Range(0,m_playerAreas.Length-1);
268
269 for (int i=0; i < m_playerAreas.Length; i++)
270 {
271 if (i == m_localSlot)
272 {
273 m_playerAreas[i].SetupForPlayer<LocalPlayer>(PlatformManager.MyOculusID);
274 }
275 else
276 {
277 m_playerAreas[i].SetupForPlayer<AIPlayer>("* AI *");
278 }
279 }
280 }
281
282 Player MatchPlayerAddedCallback(int slot, User user)
283 {
284 Player player = null;
285
286 if (m_currentState == State.WAITING_TO_SETUP_MATCH && slot < m_playerAreas.Length)
287 {
288 if (user.ID == PlatformManager.MyID)
289 {
290 var localPlayer = m_playerAreas[slot].SetupForPlayer<LocalPlayer>(user.OculusID);
291 MoveCameraToMatchPosition();
292 player = localPlayer;
293 m_localSlot = slot;
294 }
295 else
296 {
297 var remotePlayer = m_playerAreas[slot].SetupForPlayer<RemotePlayer>(user.OculusID);
298 remotePlayer.User = user;
299 player = remotePlayer;
300 }
301 }
302
303 return player;
304 }
305
306 #endregion
307
308 #region Main Camera Movement
309
310 void MoveCameraToIdlePosition()
311 {
312 var ejector = m_camera.gameObject.GetComponentInChildren<BallEjector>();
313 if (ejector)
314 {
315 ejector.transform.SetParent(m_camera.transform.parent, false);
316 m_camera.transform.SetParent(m_idleCameraTransform, false);
317 }
318 }
319
320 void MoveCameraToMatchPosition()
321 {
322 foreach (var playerArea in m_playerAreas)
323 {
324 var player = playerArea.GetComponentInChildren<LocalPlayer>();
325 if (player)
326 {
327 var ejector = player.GetComponentInChildren<BallEjector>();
328 m_camera.transform.SetParent(player.transform, false);
329 ejector.transform.SetParent(m_camera.transform, false);
330 break;
331 }
332 }
333 DisplayAchievementFlytext();
334 }
335
336 #endregion
337
338 #region Match Initiation
339
340 public void StartPracticeMatch()
341 {
342 if (m_currentState == State.NONE)
343 {
344 TransitionToState(State.WAITING_TO_START_PRACTICE);
345 }
346 }
347
348 public void PlayOnlineOrCancel()
349 {
350 Debug.Log ("Play online or Cancel");
351
352 if (m_currentState == State.NONE)
353 {
354 PlatformManager.Matchmaking.QueueForMatch();
355 TransitionToState (State.WAITING_FOR_MATCH);
356 }
357 else if (m_currentState == State.WAITING_FOR_MATCH)
358 {
359 PlatformManager.Matchmaking.LeaveQueue();
360 TransitionToState (State.NONE);
361 }
362 }
363
364 // notification from the Matchmaking service if we succeeded in finding an online match
365 void OnMatchFoundCallback(bool success)
366 {
367 if (success)
368 {
369 TransitionToState(State.WAITING_TO_SETUP_MATCH);
370 }
371 else
372 {
373 TransitionToState(State.NONE);
374 }
375 }
376
377 // handle an offer from a remote player for a new match start time
378 float StartTimeOfferCallback(float remoteTime)
379 {
380 if (m_currentState == State.WAITING_TO_SETUP_MATCH)
381 {
382 // if the remote start time is later use that, as long as it's not horribly wrong
383 if (remoteTime > MatchStartTime && (remoteTime - 60) < MatchStartTime)
384 {
385 Debug.Log("Moving Start time by " + (remoteTime - MatchStartTime));
386 MatchStartTime = remoteTime;
387 }
388 }
389 return MatchStartTime;
390 }
391
392 #endregion
393
394 #region Leaderboards and Achievements
395
396 void MostWinsLeaderboardCallback(SortedDictionary<int, LeaderboardEntry> entries)
397 {
398 foreach (Transform entry in m_mostWinsLeaderboard.transform)
399 {
400 Destroy(entry.gameObject);
401 }
402 foreach (var entry in entries.Values)
403 {
404 GameObject label = Instantiate(m_leaderboardEntryPrefab);
405 label.transform.SetParent(m_mostWinsLeaderboard.transform, false);
406 label.GetComponent<Text>().text =
407 string.Format("{0} - {1} - {2}", entry.Rank, entry.User.OculusID, entry.Score);
408 }
409 }
410
411 void HighestScoreLeaderboardCallback(SortedDictionary<int, LeaderboardEntry> entries)
412 {
413 foreach (Transform entry in m_highestScoresLeaderboard.transform)
414 {
415 Destroy(entry.gameObject);
416 }
417 foreach (var entry in entries.Values)
418 {
419 GameObject label = Instantiate(m_leaderboardEntryPrefab);
420 label.transform.SetParent(m_highestScoresLeaderboard.transform, false);
421 label.GetComponent<Text>().text =
422 string.Format("{0} - {1} - {2}", entry.Rank, entry.User.OculusID, entry.Score);
423 }
424 }
425
426 void CalculateMatchResults()
427 {
428 LocalPlayer localPlayer = null;
429 RemotePlayer remotePlayer = null;
430
431 foreach (var court in m_playerAreas)
432 {
433 if (court.Player is LocalPlayer)
434 {
435 localPlayer = court.Player as LocalPlayer;
436 }
437 else if (court.Player is RemotePlayer &&
438 (remotePlayer == null || court.Player.Score > remotePlayer.Score))
439 {
440 remotePlayer = court.Player as RemotePlayer;
441 }
442 }
443
444 // ignore the match results if the player got into a session without an opponent
445 if (!localPlayer || !remotePlayer)
446 {
447 return;
448 }
449
450 bool wonMatch = localPlayer.Score > remotePlayer.Score;
451 PlatformManager.Leaderboards.SubmitMatchScores(wonMatch, localPlayer.Score);
452
453 if (wonMatch)
454 {
455 PlatformManager.Achievements.RecordWinForLocalUser();
456 }
457 }
458
459 void DisplayAchievementFlytext()
460 {
461 if (PlatformManager.Achievements.LikesToWin)
462 {
463 GameObject go = Instantiate(m_flytext);
464 go.GetComponent<Text>().text = "Likes to Win!";
465 go.transform.position = Vector3.up * 40;
466 go.transform.SetParent(m_playerAreas[m_localSlot].NameText.transform, false);
467 }
468 }
469
470 #endregion
471 }
472}