Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Diagnostics;
- using System.Linq;
- using Nakama;
- using System.Threading;
- using System.Text;
- using System.Threading.Tasks;
- using SimpleJSON;
- using Nakama.TinyJson;
- //using WindowsInput;
- //using WindowsInput.Native;
- namespace kalameston_robot
- {
- class Class1
- {
- //----------
- int index;
- string[] robots = { "robot1@me.com", "robot2@me.com", "robot3@me.com", "robot4@me.com", "robot5@me.com", };
- //-----------------
- Client client1;
- Dictionary<string, int> letter_score = new Dictionary<string, int>();
- ISocket ic2;
- ISession session1;
- string match_ID = "";
- string userstatus;
- Timer timer;
- List<string> list_answer_words;
- DateTime t1;
- DateTime t2;
- string start_game;
- public class LevelInfo
- {
- public string Letters { get; set; }
- public string[] AnswerArray { get; set; }
- public int Duration { get; set; }
- }
- LevelInfo levelInfo = new LevelInfo();
- Random rnd = new Random();
- int timer_counter = 0;
- public void start()
- {
- index = 0;
- try
- {
- t1 = DateTime.MinValue;//قرار دادن مقدار پیشفرض در t1
- set_letter_score();
- Login1();
- Console.WriteLine("((((((((((((((((((())))))))))))))))))))))))))");
- Console.ReadKey();
- }
- catch (Exception err)
- {
- Console.WriteLine(err.Message);
- }
- }
- private void set_letter_score()
- {
- if (letter_score.Count == 0)
- {
- letter_score.Add("ا", 1);
- letter_score.Add("ی", 1);
- letter_score.Add("ن", 1);
- letter_score.Add("م", 1);
- letter_score.Add("ت", 1);
- letter_score.Add("ر", 1);
- letter_score.Add("ه", 1);
- letter_score.Add("ش", 1);
- letter_score.Add("و", 1);
- letter_score.Add("د", 1);
- letter_score.Add("ب", 2);
- letter_score.Add("ل", 2);
- letter_score.Add("س", 2);
- letter_score.Add("ک", 2);
- letter_score.Add("ف", 2);
- letter_score.Add("ز", 2);
- letter_score.Add("ع", 2);
- letter_score.Add("ق", 2);
- letter_score.Add("گ", 2);
- letter_score.Add("خ", 2);
- letter_score.Add("ج", 3);
- letter_score.Add("پ", 3);
- letter_score.Add("ح", 3);
- letter_score.Add("ص", 3);
- letter_score.Add("آ", 3);
- letter_score.Add("ط", 3);
- letter_score.Add("غ", 4);
- letter_score.Add("چ", 4);
- letter_score.Add("ض", 4);
- letter_score.Add("ذ", 4);
- letter_score.Add("ژ", 5);
- letter_score.Add("ث", 5);
- letter_score.Add("ظ", 5);
- }
- }
- void Login1()
- {
- try
- {
- Console.WriteLine("----------------login1 with +++++++++++ "+robots[index]);
- client1 = new Client("ttyhgbnghju", "127.0.0.1", 7350, false);
- // client1 = new Client("ttyhgbnghju", "192.168.1.20", 7350, false);
- // client1 = new Client("ttyhgbnghju", "157.119.190.92", 7350, false);
- Login_user(robots[index], "robot100");
- if (index < 4)
- index++;
- else index = 0;
- }
- catch (Exception err)
- {
- Debug.Write(err.Message);
- Console.Write("errrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrorr");
- }
- }
- async void Login_user(string email, string password)
- {
- //**********login*****************
- if (session1 == null)
- {
- Console.WriteLine(" try login ............");
- session1 = await client1.AuthenticateEmailAsync(email, password);
- Console.WriteLine(" *******login success********* ");
- }
- Match_users();
- //var score = password;// "sala555";
- //var rpcid = "f_get_level";
- //var pokemonInfo = await client1.RpcAsync(session1, rpcid, score);
- }
- private async void Match_users()
- {
- ////توقف تصادفی ربات برای جلوگیری از وصل شدن سریع کاربر
- //int i = rnd.Next(15, 40);
- //Console.WriteLine("%%%%%%%%%%%%%%%% sleep for {0} second",i);
- //Thread.Sleep(i*1000);
- ////-------------------------
- //try
- //{
- //********************get score***********
- /*
- var rpcid = "f_get_score";
- var score = "salam "; // + em.Substring(0, 2);
- var userInfo = await Client.RpcAsync(session, rpcid, score);
- Debug.LogFormat("GetUserInfoAsync: {0}", userInfo.Payload);
- JSONNode node = JSON.Parse(userInfo.Payload);
- print("==> " + node.AsObject["coins"].ToString());
- print("==> " + node.AsObject["diamonds"].ToString());
- print("==> " + node.AsObject["scores"].ToString());
- PlayerPrefs.SetInt("SCORES", node.AsObject["scores"]);*/
- //score = "salam";
- //rpcid = "f_get_score";
- //var userInfo = await client1.RpcAsync(session1, rpcid, score);
- //Debug.WriteLine(userInfo);
- //********************match make*******************
- Console.WriteLine("initialize match create......");
- var query2 = "*";
- var minCount2 = 2;
- var maxCount2 = 2;
- // var query2 = "+properties.region:iran";
- var stringProperties2 = new Dictionary<string, string>() {
- {"region", "robot"},
- {"type","robot" }
- };
- var numericProperties2 = new Dictionary<string, double>() {
- { "rank", 1},
- { "score_ratio", 1}
- };
- Console.WriteLine(":::::::::::::::::::::::::::::::::::::::::::::::::::1:");
- // var stringProperties2 = new Dictionary<string, string>() { { "region", "europe" }, { "levelwords", "12" },{ "scor_ratio","1"} };
- // var numericProperties2 = new Dictionary<string, double>() { { "rank", 8 } };
- //tttt = DateTime.Now;
- ic2 = client1.CreateWebSocket();
- Console.WriteLine(":::::::::::::::::::::::::::::::::::::::::::::::::::2:");
- //ic2.TimeoutMs = 20000;
- await ic2.ConnectAsync(session1);
- Console.WriteLine(":::::::::::::::::::::::::::::::::::::::::::::::::::3:");
- Console.WriteLine("--------------try match make in loop by 6 second");
- bool repeat = true;
- while (repeat)
- {
- try
- {
- Console.Write("*");
- Thread.Sleep(10000);
- Console.Write("+");
- var matchmakerTicket2 = await ic2.AddMatchmakerAsync(
- query2, minCount2, maxCount2, stringProperties2, numericProperties2);
- repeat = false;
- Console.Write("------------match make is successfull");
- }
- catch (Exception err)
- {
- Debug.Write(err.Message);
- Console.Write(err.Message.ToString());
- query2 = null;
- numericProperties2 = null;
- stringProperties2 = null;
- ic2 = null;
- client1 = null;
- session1 = null;
- end_game("while error");
- return;
- }
- }
- var so = ic2;
- Console.WriteLine("\n :::::::::::::::::::::::::::::::::::::::::::::::::::4:");
- so.OnMatchmakerMatched += async (_, matched) =>
- {
- start_game = "no";//بعد از اتصال کاربر بازی نباید شروع شود تا زمانی که کد 200 از سمت سرور جهت شروع بازی ارسال گردد
- userstatus = "resume";
- Console.WriteLine(":::::::::::::::::::::::::::::::::::::::::::::::::::5:");
- var t = DateTime.Now;
- var opponents = matched.Users.ToArray()[0].Presence.UserId.ToString() + matched.Users.ToArray()[1].Presence.UserId.ToString(); // printable list.
- Console.WriteLine(":::::::::::::::::::::::::::::::::::::::::::::::::::6:");
- Console.WriteLine(matched.Users.ToArray()[0].Presence.UserId.ToString() + " =======VS======= " + matched.Users.ToArray()[1].Presence.UserId.ToString());
- //بررسی وجود ربات در بین بازیکن ها
- bool robot1 = false;
- bool robot2 = false;
- string[] robot_list = new string[5];
- robot_list[0] = "3ad707d7-4f05-4fc8-93c5-cf64ca576d4a";
- robot_list[1] = "d7aedbda-a706-414e-9083-4e6d8a1e2c07";
- robot_list[2] = "ab2da0a3-009f-42df-a53c-e7122b89c838";
- robot_list[3] = "cbf3c9ff-f086-4b2a-8482-b5911de40215";
- robot_list[4] = "d694b240-5144-4ba9-a9b1-5dc73832ab1c";
- for (int i = 0; i < robot_list.Length; i++)
- {
- if (matched.Users.ToArray()[0].Presence.UserId.ToString() == robot_list[i])
- { robot1 = true; Console.WriteLine("+++++++++++player1 is robot"); }
- if (matched.Users.ToArray()[1].Presence.UserId.ToString() == robot_list[i])
- { robot2 = true; Console.WriteLine("+++++++++++player2 is robot"); }
- }
- //اگر ربات به خودش یا ربات دیگر متصل شود بازی باید تمام شود در غیر این صورت ادامه یابد
- if (robot1 == true && robot2 == true)
- {
- Console.WriteLine("!!!!!!!!!!!!!!!!!!!! robot match with self !!!!!!! end_game");
- end_game("--------robot vs robot-------");
- }
- else
- {
- Console.WriteLine("~~~~~~~~~~~~~~~~ play with opponents");
- //*****************************
- await so.JoinMatchAsync(matched);
- Console.WriteLine("************match created ********");
- timer = new Timer(TimerCallback, null, 0, 1000);
- }
- };
- //************دریافت اطلاعات مرحله
- so.OnMatchState += (_, state) =>
- {
- Console.WriteLine("OnMatchState");
- Console.WriteLine("opcode=" + state.OpCode.ToString());
- Console.WriteLine("********OnMatchState*******");
- var content = System.Text.Encoding.UTF8.GetString(state.State);
- //Debug.Log("OnMatchState" + state.OpCode.ToString() + " | " + content);
- Console.WriteLine("state= ", content);
- MJSONNode node;
- switch (state.OpCode)
- {
- case 999:
- Console.WriteLine("InitGame");
- node = JSON.Parse(content);
- Console.WriteLine("Level " + node.AsObject["lvl"].Value);
- Console.WriteLine("Duration " + node.AsObject["duration"].ToString());
- Console.WriteLine("Counter " + node.AsObject["counter"].ToString());
- levelInfo.Duration = node.AsObject["duration"].AsInt;
- levelInfo.Letters = node.AsObject["lvl"].Value.Split('-')[0];
- levelInfo.AnswerArray = node.AsObject["lvl"].Value.Split('-')[1].Split(' ');
- //مرتب کردن کلمات صحیح بر از کلمات کوچک به کلمات بزرگ
- //string[] temp = new string[levelInfo.AnswerArray.Length];
- //int temp_index = 0;
- //for (int i=3;i<10;i++)
- //{
- // for(int j=0;j< levelInfo.AnswerArray.Length;j++)
- // {
- // if(levelInfo.AnswerArray[j].Length==i)
- // {
- // temp[temp_index] = levelInfo.AnswerArray[j];
- // temp_index++;
- // }
- // }
- //}
- //levelInfo.AnswerArray = temp;
- list_answer_words = new List<string>(levelInfo.AnswerArray);
- Console.WriteLine("InitGameCounter= " + node.AsObject["counter"].AsInt.ToString());
- Console.WriteLine("duration= " + node.AsObject["duration"].AsInt.ToString());
- Console.WriteLine("lvl= " + node.AsObject["lvl"].Value.ToString());
- break;
- case 101:
- //Console.WriteLine( "AddScore");
- //node = JSON.Parse(content);
- //Console.WriteLine( "AddScore", node.AsObject["add_score"].ToString());
- //Console.WriteLine( "Counter", node.AsObject["counter"].ToString());
- //if (messageLastCounter < node.AsObject["counter"].AsInt)
- //{
- // messageLastCounter = node.AsObject["counter"].AsInt;
- // UnityMainThreadDispatcher.Instance().Enqueue(() => ScreenManager.Instance.gamePanel.OnScoreGameEvent(state.UserPresence, node.AsObject["add_score"].AsInt,
- // node.AsObject["add_score_word"].AsInt, node.AsObject["add_score_length"].AsInt));
- // // opCode = 101;
- // // Console.WriteLine("NakamaManager", "Update", "AddScore", "true");
- // // Console.WriteLine("NakamaManager", "Update", "AddScoreCounter", messageCounter.ToString());
- // // Console.WriteLine("NakamaManager", "Update", "AddScoreLastCounter", messageLastCounter.ToString());
- //}
- //else
- //{
- // // Console.WriteLine("NakamaManager", "Update", "AddScore", "false");
- // // Console.WriteLine("NakamaManager", "Update", "AddScoreCounter", messageCounter.ToString());
- // // Console.WriteLine("NakamaManager", "Update", "AddScoreLastCounter", messageLastCounter.ToString());
- //}
- break;
- case 110:
- //Console.WriteLine( "UserStatus");
- //// TODO sync func ??? -- automatic send score for test
- node = JSON.Parse(content);
- userstatus = node.AsObject["userStatus"].ToString();
- userstatus = userstatus.Replace("\"", "");
- Console.WriteLine("&&&&&&&&&&&&&& UserStatus= " + userstatus);
- //Console.WriteLine( "Counter", node.AsObject["counter"].ToString());
- //if (messageLastCounter < node.AsObject["counter"].AsInt)
- //{
- // messageLastCounter = node.AsObject["counter"].AsInt;
- // UnityMainThreadDispatcher.Instance().Enqueue(() => ScreenManager.Instance.gamePanel.OnStatusGameEvent(state.UserPresence, node.AsObject["userStatus"]));
- // Console.WriteLine("NakamaManager", "Update", "AddScore", "true");
- // Console.WriteLine("NakamaManager", "Update", "AddScoreCounter", messageCounter.ToString());
- // Console.WriteLine("NakamaManager", "Update", "AddScoreLastCounter", messageLastCounter.ToString());
- //}
- //else
- //{
- // Console.WriteLine("NakamaManager", "Update", "AddScore", "false");
- // Console.WriteLine("NakamaManager", "Update", "AddScoreCounter", messageCounter.ToString());
- // Console.WriteLine("NakamaManager", "Update", "AddScoreLastCounter", messageLastCounter.ToString());
- //}
- break;
- case 200:
- start_game = "ok";
- break;
- default:
- try
- {
- string uname = "";
- if (state.UserPresence.Username != null)
- { uname = state.UserPresence.Username.ToString(); }
- Console.WriteLine("User {0} sent {1}", uname, content);
- }
- catch (Exception err)
- { Debug.Write(err.Message); }
- break;
- }
- };
- //*** user 2
- // چاپ لیست رقبا
- var connectedOpponents = new List<IUserPresence>(0);
- ic2.OnMatchPresence += (_, presence) =>
- {
- connectedOpponents.AddRange(presence.Joins);
- Debug.WriteLine("///////////////" + presence);
- Console.WriteLine("///////////////" + presence);
- match_ID = presence.MatchId.ToString();
- Debug.WriteLine("///////////------------////" + match_ID);
- Console.WriteLine("///////////------------////" + match_ID);
- //var opCode = 1;
- //var newState = new Dictionary<string, string> { { "add_score", "25" } }.ToJson();
- //ic2.SendMatchState(match_ID, opCode, newState);
- foreach (var leave in presence.Leaves)
- {
- connectedOpponents.RemoveAll(item => item.SessionId.Equals(leave.SessionId));
- }
- Debug.WriteLine("ttttttttttt" + connectedOpponents.Count.ToString());
- };
- //*****************************
- //if (i % 20 == 0)
- //{
- // for (int k = 1; k < 4000; k++)
- // {
- // TimeSpan span = tttt[k].Subtract(DateTime.Now);
- // if (span.Seconds > 250)
- // {
- // ic2[k].DisconnectAsync().Dispose();
- // }
- // }
- // Thread.Sleep(5000);
- //}
- //textBox1.Text = "match make";
- //}
- //catch (Exception err)
- //{
- // Console.WriteLine( err.Message.ToString() + Environment.NewLine + "-----------------------" );
- //}
- }
- public void SendDataMessage(int opCode, Dictionary<string, string> newState)
- {
- Console.WriteLine("*********************SendDataMessage************");
- //var newStatse = new Dictionary<string, string> { { "hello", "world" } }.ToJson();
- // Socket.SendMatchState(matchId, opCode, newState.ToJson());
- ic2.SendMatchState(match_ID, opCode, newState.ToJson());
- }
- //public void AddScore(int wordScore, int wordLength)
- //{
- // DebugManager.Log("GamePanel", "AddScore");
- // DebugManager.LogKeyValue("GamePanel", "AddScore", "AddScore", wordScore.ToString());
- // if (gameFinished)
- // return;
- // int k = 0;
- // if (wordLength > 3)
- // k = wordLength;
- // NakamaManager.Instance.SendDataMessage(101, new Dictionary<string, string>()
- //{
- // {KEY_ADD_SCORE, (wordScore+k).ToString() },
- // {KEY_ADD_SCORE_WORD, (wordScore).ToString() },
- // {KEY_ADD_SCORE_LENGTH, (k).ToString() }
- //});
- //}
- private void TimerCallback(Object o)
- {
- if (start_game == "ok")
- {
- if (userstatus == "resume")
- {
- t1 = DateTime.MinValue;//مقدار پیشفرض در t1
- if (levelInfo != null)
- {
- timer_counter++;
- Console.WriteLine(" duration=" + levelInfo.Duration);
- levelInfo.Duration = levelInfo.Duration - 1;
- //ارسال تصادفی امتیاز
- int r = rnd.Next(1, rnd.Next(8, 15));//اگر عدد تصادفی 5 باشد امتیاز یک کلمه ارسال خواهد شد
- if (r == 5 && timer_counter > 3)//در صورتی که عدد تصادفی 5 باشد و 3 ثانیه از شروع بازی گذشته باشد و کلمه ارسال نشده ای نیز وجود داشته باشد
- {
- int opcode = 101;
- int wordScore = 0;
- int k = 0;
- //انتخاب تصادفی کلمه پاسخ
- int rnd_index = rnd.Next(0, list_answer_words.Count - 1);
- string correct_word = list_answer_words[rnd_index].ToString();
- list_answer_words.RemoveAt(rnd_index);
- Console.WriteLine("+++++++++++++++++ list words length= " + list_answer_words.Count.ToString() + " +++++++++++++ correct word length= " + correct_word.Length.ToString() + " ====================== k= " + k.ToString());
- //
- for (int i = 0; i < correct_word.Length; i++)
- {
- int score = 0;
- if (letter_score.TryGetValue(correct_word[i].ToString(), out score))
- {
- wordScore = wordScore + score;
- }
- }
- if (correct_word.Length > 3)
- { k = correct_word.Length; }
- Console.WriteLine("=================== word score= " + wordScore.ToString() + " ====================== k= " + k.ToString());
- Dictionary<string, string> newState = new Dictionary<string, string>()
- {
- {"add_score", (wordScore+k).ToString() },
- {"add_score_word", (wordScore).ToString() },
- {"add_score_length", (k).ToString() }
- };
- SendDataMessage(opcode, newState);
- }
- //حذف تایمر هنگام پایان زمان باری
- if (levelInfo.Duration == 0 || levelInfo.Duration < -2)
- {
- start_game = "no";
- GetMatchResultAsync("finished");
- end_game("1");
- }
- }
- }
- else
- {
- Console.WriteLine("---------------------- user is pause " + userstatus);
- //اگر کاربر متوقف شود
- if (t1 == DateTime.MinValue)
- {
- t1 = DateTime.Now;
- }
- t2 = DateTime.Now;
- TimeSpan diff = t2 - t1;
- if (diff.TotalSeconds >= 10)
- {
- start_game = "no";
- t1 = DateTime.MinValue;
- GetMatchResultAsync("unfinished");
- end_game("2");
- }
- }
- // Display the date/time when this method got called.
- Console.WriteLine("In TimerCallback: " + DateTime.Now);
- // Force a garbage collection to occur for this demo.
- //GC.Collect();
- }
- }
- private void end_game(string code)
- {
- Console.WriteLine("&&&&&&&&&&&&&&&& end_game(" + code + ") &&&&&&&&&&&&&&&&");
- leave();
- //--------------------
- //ic2.Dispose();
- session1 = null;
- //client1 = null;
- //-----------یکبار اجرا--------
- //Thread.Sleep(2000);
- //InputSimulator a = new InputSimulator();
- //a.Keyboard.KeyPress(VirtualKeyCode.SPACE);
- //Environment.Exit(0);
- //-------------------
- if (timer != null) { timer.Dispose(); }
- timer_counter = 0;
- set_letter_score();
- Console.WriteLine("'''''''''''''sleep for 10 second");
- Thread.Sleep(10000);
- Login1();
- // Match_users();
- }
- public async void GetMatchResultAsync(string end_game_state)
- {
- Console.WriteLine("^^^^^^^^^^^^^^^^^^^^^^ call Match Result ^^^^^^^^^^^^^^^^^^^6");
- var rpcid = "f_match_result";
- MJSONObject jsonObject = new MJSONObject();
- jsonObject.Add("match_id", match_ID);
- jsonObject.Add("match_end_status", end_game_state);
- //if (end_game_state)
- // jsonObject.Add("match_end_status", "finished");
- //else
- // jsonObject.Add("match_end_status", "unfinished"); // when opponent player disconnect for ten seconds
- // var score = "[{\"match_id\":::::::::::::::::::::::::::::::::::::::::::::::::::\"b1284e80-0e53-42e7-9d45-8abe9101bfc9.nakama\",\"match_end_status\":::::::::::::::::::::::::::::::::::::::::::::::::::\"finished\"}]";
- // print("=====> " + jsonObject.ToString());
- var result = await client1.RpcAsync(session1, rpcid, jsonObject.ToString());
- //Debug.LogFormat("Retrieved pokemon info: {0}", result);
- // Debug.LogFormat("Retrieved pokemon info: {0}", result.Payload);
- Console.WriteLine(result.Payload);
- //return result.Payload.Substring(1, result.Payload.Length - 2);
- }
- public async Task leave()
- {
- Console.WriteLine("***************leave match*****************");
- await ic2.LeaveMatchAsync(match_ID);
- }
- }
- }
Add Comment
Please, Sign In to add comment