Skip to content

Instantly share code, notes, and snippets.

@rdeioris
Created April 1, 2019 18:08
Show Gist options
  • Save rdeioris/96bd12c8064a291c69746376f326aefd to your computer and use it in GitHub Desktop.
Save rdeioris/96bd12c8064a291c69746376f326aefd to your computer and use it in GitHub Desktop.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
public class EvenAndOdd : MonoBehaviour
{
[System.Serializable]
class Match
{
public string id;
public int player1_move;
public int player2_move;
}
UnityWebRequestAsyncOperation asyncOperation;
bool dataReceived;
delegate void PairAndOddState();
PairAndOddState currentState;
float nextPollTimer;
void MakeCreateMatchRequest()
{
UnityWebRequest request = new UnityWebRequest("http://127.0.0.1:5000/create_match");
request.SetRequestHeader("PairAndOdd", "odd");
request.downloadHandler = new DownloadHandlerBuffer();
asyncOperation = request.SendWebRequest();
currentState = CheckCreateRequest;
}
void CheckCreateRequest()
{
if (asyncOperation.isDone)
{
Debug.Log(asyncOperation.webRequest.responseCode);
currentState = MakePollRequest;
}
}
void MakePollRequest()
{
UnityWebRequest request = new UnityWebRequest("http://127.0.0.1:5000/poll");
request.downloadHandler = new DownloadHandlerBuffer();
asyncOperation = request.SendWebRequest();
currentState = CheckPollRequest;
}
void CheckPollRequest()
{
if (asyncOperation.isDone)
{
Debug.Log(asyncOperation.webRequest.responseCode);
Match match = JsonUtility.FromJson<Match>(asyncOperation.webRequest.downloadHandler.text);
Debug.Log(match.id);
Debug.Log(match.player1_move);
Debug.Log(match.player2_move);
nextPollTimer = 3;
currentState = WaitForNextPoll;
}
}
void WaitForNextPoll()
{
nextPollTimer -= Time.deltaTime;
if (nextPollTimer <= 0)
currentState = MakePollRequest;
}
void Start()
{
currentState = MakeCreateMatchRequest;
}
void Update()
{
currentState();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment