cupid added

This commit is contained in:
2026-02-15 12:12:55 +05:30
parent b7d8bb1c8c
commit 3108262326
46 changed files with 4152 additions and 260 deletions
+72
View File
@@ -0,0 +1,72 @@
using System.Collections;
using System.Collections.Generic;
using Mirror;
using UnityEngine;
public class CupidConnector : MonoBehaviour
{
public kcp2k.KcpTransport transport;
void Start()
{
#if UNITY_SERVER
//Server code
string[] args = System.Environment.GetCommandLineArgs();
for (int i = 0; i < args.Length; i++)
{
if (args[i].Contains("-port"))
{
Cupid.RoomPort = int.Parse(args[i+1]);
Logger.SetFileName(Cupid.RoomPort.ToString());
}
}
if(Cupid.RoomPort < 0){
Logger.Log("Invalid port, Did you pass the -port arguement?");
return;
}
transport.Port = (ushort)Cupid.RoomPort;
Logger.Log($"Starting server at port {Cupid.RoomPort}");
NetworkManager.singleton.StartServer();
#else
//Client code
if(Cupid.RoomPort <0){
Logger.Log("Invalid Room port");
return;
}
transport.Port = (ushort)Cupid.RoomPort;
NetworkManager.singleton.networkAddress = Cupid.ServerAddress;
Logger.Log($"Starting client at ${Cupid.ServerAddress}:{Cupid.RoomPort}");
NetworkManager.singleton.StartClient();
#endif
}
#if UNITY_SERVER
float t=0;
int _t = 0;
void Update(){
if(t < 60){
t += Time.deltaTime;
}else{
if(NetworkServer.connections.Count <= 0){
Logger.Log("Closing port " + Cupid.RoomPort + " due to no players");
Application.Quit();
}
}
if((int)t !=_t){
_t = (int)t;
Logger.Log(NetworkServer.connections.Count.ToString());
}
}
#else
void Update(){
// Debug.Log(NetworkServer.connections.Count);
}
#endif
void OnValidate(){
if(GetComponent<NetworkManager>()!=null){
GetComponent<NetworkManager>().headlessStartMode= HeadlessStartOptions.DoNothing;
}
if(transport == null){
transport = GetComponent<kcp2k.KcpTransport>();
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: f3c99e609d4d9cd49aa4a36bbaaf539e
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
+91
View File
@@ -0,0 +1,91 @@
using System;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.Networking;
public static class Cupid
{
private static string serverAddress;
public static string ServerAddress => serverAddress;
public static string CupidURI => "http://" + serverAddress + ":" + port;
private static int port;
public static int Port => port;
private static string password;
private static CupidSettings settings = null;
public static CupidSettings Settings => settings;
public static bool isInitialized => settings!=null;
public static int RoomPort =-1;
public static async Task Init(string _serverAddress, int _port, string _password){
serverAddress= _serverAddress;
port = _port;
password = _password;
using (UnityWebRequest www = UnityWebRequest.Get(CupidURI + "/settings?password="+password))
{
var operation = www.SendWebRequest();
while (!operation.isDone)
{
await Task.Yield();
}
try{
settings = JsonUtility.FromJson<CupidSettings>(www.downloadHandler.text);
if(settings==null){throw new NullReferenceException();}
Logger.Log("Cupid init success");
}catch(Exception e){
Logger.Log("Error retreiving settings from server " + e.Message);
Logger.Log(www.downloadHandler.text);
}
}
}
public static string RandomUsername{
get{
string pool="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
string output ="";
for(int i=0; i < 5; i++){
output += pool.ToCharArray()[UnityEngine.Random.Range(0,pool.Length)];
}
return output;
}
}
public static CupidRoom? ParseRoom(string data){
CupidRoom? room = null;
try{
room = JsonUtility.FromJson<CupidRoom>(data);
}catch{}
return room;
}
}
[System.Serializable]
public class CupidSettings
{
public int minimum_players;
public int maximum_players;
public int waiting_time;
}
[System.Serializable]
public struct CupidRoom{
public CupidQueueEntry[] Players;
public int Port;
public uint InitTime;
}
[System.Serializable]
public struct CupidQueueEntry{
string Name;
uint LastSeen;
}
+11
View File
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: c2c877cb30cc2fe44b30ab3681e44604
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
+118
View File
@@ -0,0 +1,118 @@
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class CupidLobby : MonoBehaviour
{
[SerializeField]private GameObject MatchmakingUI;
[SerializeField]private string GameScene;
[Header("Server info")]
[SerializeField]private string serverAddress = "xx.xx.xxx.xx";
[SerializeField]private int cupidPort = 1601;
[SerializeField]private string password = "xyz@123";
public static string Username
{
get
{
if (PlayerPrefs.HasKey("username"))
{
return PlayerPrefs.GetString("username");
}else{
string username = Cupid.RandomUsername;
PlayerPrefs.SetString("username",username);
PlayerPrefs.Save();
return username;
}
}
}
void Start()
{
Cupid.Init(serverAddress, cupidPort, password);
}
bool matchmaking = false;
public void Matchmake()
{
Logger.Log("Starting matchmake as " + Username);
StartCoroutine(matchmake());
}
IEnumerator matchmake()
{
matchmaking = true;
while (matchmaking)
{
RefreshMatchmakingPanel();
WWW req = new WWW(Cupid.CupidURI + "/?password=" + password + "&&username=" + Username);
yield return req;
// Debug.Log(req.text);
CupidRoom? room = Cupid.ParseRoom(req.text);
if(room == null){
Logger.Log("No room : " + req.text);
}else{
CupidRoom _room = (CupidRoom)room;
Logger.Log("Got into a room");
Logger.Log(req.text);
Logger.Log("Setting cupid to load game scene");
Cupid.RoomPort = _room.Port;
matchmaking=false;
Logger.Log("Loading game scene");
SceneManager.LoadScene(GameScene);
}
// string[] data = req.text.Split(',');
// if(data.Length ==2){
// Logger.Log(req.text);
// if(data[0] == "1"){
// //Game started
// Logger.Log("Setting cupid room to " + data[1]);
// Cupid.RoomPort = int.Parse(data[1]);
// Logger.Log("Loading scene " + GameScene);
// SceneManager.LoadScene(GameScene);
// matchmaking=false;
// break;
// }else{
// //Game not started gotta continue
// }
// int gamePort = -1;
// try{
// gamePort = int.Parse(data[1]);
// }catch(Exception e){
// Logger.Log("Couldn't parse game port: " + req.text);
// }
// }
yield return new WaitForSeconds(1);
}
}
IEnumerator CancelMatchmake(){
WWW www = new WWW(Cupid.CupidURI + "/cancel?password=" + password + "&&username=" + Username);
yield return www;
if(www.text == "1"){
Logger.Log("Cancelled matchmaking success");
}else{
Logger.Log("Matchmaking cancellation said " + www.text);
}
}
public void Cancel()
{
matchmaking = false;
StartCoroutine(CancelMatchmake());
RefreshMatchmakingPanel();
}
void RefreshMatchmakingPanel()
{
MatchmakingUI.SetActive(matchmaking);
}
}
+11
View File
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 87b7650ffdc115443a13b24670850ce2
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
+67
View File
@@ -0,0 +1,67 @@
using System;
using System.IO;
using UnityEngine;
public class Logger
{
public static bool Enabled = true;
private static Logger m_instance = null;
private static string ApplicationDirectory
{
get
{
string path = Application.dataPath;
if (Application.platform == RuntimePlatform.OSXPlayer)
{
path += "/../../";
}
else if (Application.platform == RuntimePlatform.WindowsPlayer)
{
path += "/../";
}
return path;
}
}
public string LogFilePath {get; private set;}
public static Logger instance
{
get
{
if (m_instance == null)
{
m_instance = new Logger();
}
return m_instance;
}
}
public Logger()
{
if(!Enabled){return;}
Debug.Log("Starting logger @ " + ApplicationDirectory);
if(LogFilePath == null){
LogFilePath = ApplicationDirectory + "Log.txt";
}
File.WriteAllText(LogFilePath, "Logger initiated at " + DateTime.Now + "\n\n");
}
public void log(string message){
if(!Enabled){return;}
File.AppendAllText(LogFilePath,$"[{DateTime.Now}] {message}\n");
Debug.Log(message);
}
public static void Log(string message){
instance.log(message);
}
public static void SetFileName(string fileName){
instance.LogFilePath = ApplicationDirectory+fileName + ".txt";
}
public static void SetFilePath(string path){
instance.LogFilePath= path;
}
}
+11
View File
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 672122f9a9766e549b1df8ea295585a6
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
+8
View File
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: b055694d5c52d6642a9accb5a18af808
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,22 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraFollower : MonoBehaviour
{
[SerializeField]private Vector3 offset;
[SerializeField]private bool autoOffset = false;
[SerializeField]private Transform target;
[SerializeField]private float smoothness = 0.1f;
void LateUpdate()
{
if(target==null){return;}
transform.position = Vector3.Lerp(transform.position, target.position + offset,smoothness);
}
public void SetTarget(Transform _target){
target = _target;
offset = transform.position - target.position;
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 7d2364b6fed7b904bb0ad40b7b79de7c
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
+52
View File
@@ -0,0 +1,52 @@
using System.Collections;
using System.Collections.Generic;
using Mirror;
using UnityEngine;
public class Player : NetworkBehaviour
{
[SerializeField]private float movingSpeed;
[SyncVar]
private Vector2 input;
[SyncVar(hook = nameof(OnColorChanged))]
private Color color;
void Start()
{
if(isServer){
SetPlayer();
}
if(isLocalPlayer){
FindObjectOfType<CameraFollower>().SetTarget(transform);
}
}
void SetPlayer(){
color = new Color(Random.Range(0f,1f),Random.Range(0f,1f),Random.Range(0f,1f));
}
void OnColorChanged(Color oldValue, Color newValue){
GetComponent<MeshRenderer>().material.color = newValue;
}
// Update is called once per frame
void Update()
{
if(isLocalPlayer){
Vector2 m_input = new Vector2(Input.GetAxis("Horizontal"),Input.GetAxis("Vertical"));
if(isServer){
input = m_input;
}else{
CmdSetInput(m_input);
}
}
if(isServer){
transform.Translate(new Vector3(input.x,0,input.y)*movingSpeed);
}
}
[Command]
void CmdSetInput(Vector2 _input){
input = _input;
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 3a7be0347e7dc43449adcbd1121e447e
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant: