diff --git a/zsirozas/Common.cs b/zsirozas/Common.cs index 0335dfdfd76ab580f730b625c873da88245f6bfc..0b8abb9bb6e441b02d3b4431bd2db7336f3172cc 100644 --- a/zsirozas/Common.cs +++ b/zsirozas/Common.cs @@ -9,22 +9,22 @@ namespace zsirozas //-- "távoli szerver" [TCP-s üzenetekre]/[SignalR hívásokra] fordítás, ellenirányú üzenet-fogadás és továbbítás interface IServerApiProvider { - void registerWrapper(ServerWrapper _wrapper); + void RegisterWrapper(ServerWrapper _wrapper); string CreateRoom(string userID); void LeaveRoom(string userID); void JoinRoom(string userID, string roomID); //void InviteUser(string roomID, string userID); - //string CreateUser(string nickname, IPAddress IP, int port); helyett string CreateUser(string nickname, ConnectionType type, object backTalk); void RemoveUser(string userID); string NewGame(string roomID); string[] ListRooms(); string[] ListUsers(); ServerInfo ServerInfo(); - //RoomInfo(string roomID); + RoomInfo RoomInfo(string roomID); UserInfo UserInfo(string userID); + //todo uncomment //szobák: létrehoz, belép, kilép, listáz (név, tagok, vezér, ), játékindít //játékosok: meghív, listáz void ParseNextMessage(Stream s, object param); @@ -64,7 +64,7 @@ namespace zsirozas //a szervert ne érdekelje, hogy milyen kapcsolatot használunk public void ConnectClient(ConnectionType type, object backTalk) { - connectionType = type; + ConnectionType = type; switch (type) { case ConnectionType.SignalR: diff --git a/zsirozas/Deck.cs b/zsirozas/Deck.cs index 7d101a424d3edeb47870520eb507a7e37ed70dde..67f9bbc1f7cd171bc1bf29d514c7ec657238c2a4 100644 --- a/zsirozas/Deck.cs +++ b/zsirozas/Deck.cs @@ -91,7 +91,8 @@ namespace zsirozas } } } - catch (IndexOutOfRangeException){ } + catch (ArgumentOutOfRangeException) { } + catch (IndexOutOfRangeException) { } return result; } public override string ToString() diff --git a/zsirozas/Form1.cs b/zsirozas/Form1.cs index 6da579f8d805f16f159b0d58dee6557a64d012fa..35cde201a5a3b6005d562a9e22022d447c2099f2 100644 --- a/zsirozas/Form1.cs +++ b/zsirozas/Form1.cs @@ -18,7 +18,8 @@ namespace zsirozas CardButtons = new Button[] { buttonCard0, buttonCard1, buttonCard2, buttonCard3 }; playerNameLabels = new Label[] { labelPlayerName0, labelPlayerName1, labelPlayerName2, }; playerCardLabels = new Label[] { labelPlayerCards0, labelPlayerCards1, labelPlayerCards2, }; - client = new GameClient(); + client = new GameClient(); + client.gameOver += GameOver; } private void buttonEndTurn_Click(object sender, EventArgs e) @@ -143,7 +144,7 @@ namespace zsirozas //connect if (client.Connect(server_IP, server_port)) { - client.handleServerError += HandleServerError; + client.HandleServerError += HandleServerError; client.cardsChanged += onCardsChanged; client.gameStateCanged += GameStateCanged; buttonStartGame.Enabled = true; @@ -186,7 +187,14 @@ namespace zsirozas void GameOver(object sender, string s) { - MessageBox.Show(s); + if (InvokeRequired) + { + Invoke(new EventHandler<string>(GameOver), sender, s); + } + else + { + MessageBox.Show(s); + } } void RefreshServerInfo() @@ -219,59 +227,97 @@ namespace zsirozas void GameStateCanged(object sender, GameEvent e) { - labelCardsDealt.Text = string.Join(", ", client.gameState.cardsOnTable); - labelDeckCnt.Text = client.gameState.remainsInDeck + "lap"; - if (client.gameState.cardsOnTable.Length > 0) + if (InvokeRequired) { - labelTurnCard.Text = client.gameState.cardsOnTable[0].ToString(); + Invoke(new EventHandler<GameEvent>(GameStateCanged), sender, e); } else { - labelTurnCard.Text = ""; - } - for (int i = 0; i < client.gameState.numofCardsInHands.Length - 1; i++) - { - int idx = (i + client.playerIDX + 1) % client.gameState.numofCardsInHands.Length; - playerNameLabels[i].Visible = true; - playerNameLabels[i].Visible = true; + lock (client.gameState.cardsOnTable) + try + { + labelCardsDealt.Text = string.Join(", ", client.gameState.cardsOnTable); + labelDeckCnt.Text = client.gameState.remainsInDeck + " lap"; + if (client.gameState.cardsOnTable.Length > 0) + { + labelTurnCard.Text = client.gameState.cardsOnTable[0].ToString(); + } + else + { + labelTurnCard.Text = ""; + } + for (int i = 0; i < client.gameState.numofCardsInHands.Length - 1; i++) + { + int idx = (i + client.playerIDX + 1) % client.gameState.numofCardsInHands.Length; + playerNameLabels[i].Visible = true; + playerNameLabels[i].Visible = true; - playerNameLabels[i].Text = client.gameState.playersByOrder[idx]; - playerCardLabels[i].Text = client.gameState.numofCardsInHands[idx].ToString(); - if (client.gameState.startingPlayer == idx) - { - playerNameLabels[i].BackColor = Color.Cyan; - playerNameLabels[i].BackColor = Color.Cyan; - } - else - { - playerNameLabels[i].BackColor = Color.Transparent; - playerNameLabels[i].BackColor = Color.Transparent; - } - if (client.gameState.lastToHit == idx) - { - playerNameLabels[i].BackColor = Color.Yellow; - playerNameLabels[i].BackColor = Color.Yellow; - } - else - { - playerNameLabels[i].BackColor = Color.Transparent; - playerNameLabels[i].BackColor = Color.Transparent; - } + playerNameLabels[i].Text = client.gameState.playersByOrder[idx]; + playerCardLabels[i].Text = client.gameState.numofCardsInHands[idx].ToString(); + if (client.gameState.startingPlayer == idx) + { + playerNameLabels[i].BackColor = Color.Cyan; + playerNameLabels[i].BackColor = Color.Cyan; + } + else + { + playerNameLabels[i].BackColor = Color.Transparent; + playerNameLabels[i].BackColor = Color.Transparent; + } + if (client.gameState.lastToHit == idx) + { + playerNameLabels[i].BackColor = Color.Yellow; + playerNameLabels[i].BackColor = Color.Yellow; + } + else + { + playerNameLabels[i].BackColor = Color.Transparent; + playerNameLabels[i].BackColor = Color.Transparent; + } + } + for (int i = client.gameState.numofCardsInHands.Length - 1; i < playerNameLabels.Length; i++) + { + playerNameLabels[i].Visible = false; + playerCardLabels[i].Visible = false; + } + //MessageBox.Show(e.ToString()); + //if (client.gameState.nextUp==client.playerIDX) + //{ + // MessageBox.Show("Te jössz!"); + //} + //if (client.gameState.startingPlayer==client.playerIDX) + //{ + // buttonEndTurn.Enabled = true; + // if (client.gameState.lastToHit == client.playerIDX) + // { + // buttonEndTurn.Text = "Elvisz"; + // } + // else + // { + // buttonEndTurn.Text = "Elenged"; + // } + //} + //else + //{ + // buttonEndTurn.Enabled = false; + // buttonEndTurn.Text = "Kör vége"; + //} + } + catch (Exception ex) + { + MessageBox.Show("OOOOOOOOOOOOOOOOOOOOOO"); + System.Diagnostics.Debugger.Break(); + throw ex; + } } - for (int i = client.gameState.numofCardsInHands.Length - 1; i < playerNameLabels.Length; i++) - { - playerNameLabels[i].Visible = false; - playerCardLabels[i].Visible = false; - } - MessageBox.Show(e.ToString()); } private void buttonStartGame_Click(object sender, EventArgs e) { - client.gameOver += GameOver; - buttonStartGame.Enabled = false; - client.StartGame(); - ; + if (client.StartGame()) + { + buttonStartGame.Enabled = false; + } } private void Form1_FormClosing(object sender, FormClosingEventArgs e) @@ -301,7 +347,7 @@ namespace zsirozas { brush = Brushes.Aqua; } - else if (info[roomID].playing) + else if (info[roomID].gameID!=null) { brush = Brushes.Red; } diff --git a/zsirozas/Game.cs b/zsirozas/Game.cs index 0b8861031b8962c08f2bf0a49d720ebbbc0de694..ac94471f46e386c28e5f6ffc56f70e8c8e818289 100644 --- a/zsirozas/Game.cs +++ b/zsirozas/Game.cs @@ -16,8 +16,7 @@ namespace zsirozas public void NotifyPlayers(GameEvent @event) { - //string prefix = ServerEvent.GameEvent + "\n"; - string message = "";//prefix + @event; + string message = ""; switch (@event) { case GameEvent.CardAction: @@ -48,7 +47,6 @@ namespace zsirozas } for (int i = 0; i < playersByOrder.Length; i++) { - //gameServer.UsersByID[playersByOrder[i]].client.SendMessage(message); gameServer.UsersByID[playersByOrder[i]].client.InGameNotify(@event, message); } } @@ -184,12 +182,9 @@ namespace zsirozas playersByID[playersByOrder[currentRound.lastToHit]].cardsWon.AddRange(currentRound.playedCards); //check for endGame condition - if (deck.cardsDealtSoFar == deck.IDsByOrder.Count) + if (deck.cardsDealtSoFar == deck.IDsByOrder.Count && !playersByOrder.Any(x => playersByID[x].cardsInHand.Count > 0)) { - if (!playersByOrder.Any(x => playersByID[x].cardsInHand.Count > 0)) - { - EndGame(); - } + EndGame(); } else { @@ -204,7 +199,6 @@ namespace zsirozas playersByID[playersByOrder[index]].cardsInHand.AddRange(sdfsdff[i]); } //notify everyone - NotifyPlayers(GameEvent.NewTurn); } } @@ -262,6 +256,5 @@ namespace zsirozas playersByOrder = playersByOrder, }; } - } } \ No newline at end of file diff --git a/zsirozas/GameClient.cs b/zsirozas/GameClient.cs index ee54e804f249bfd02d2de82de12c2da909a40341..febdcde8380a81c7e1c42a440ea76a3cb96af8a7 100644 --- a/zsirozas/GameClient.cs +++ b/zsirozas/GameClient.cs @@ -79,7 +79,8 @@ namespace zsirozas } catch (ServerErrorException ex) { - handleServerError(this, ex.Message); + HandleServerError(this, ex.Message); + System.Diagnostics.Debugger.Break(); } } return false; @@ -89,7 +90,7 @@ namespace zsirozas // generally talking to server // - public event EventHandler<string> handleServerError; + public event EventHandler<string> HandleServerError = (sender, e) => { }; public IPEndPoint server; public string userID; @@ -102,15 +103,18 @@ namespace zsirozas public IServerApiProvider remoteServer; - public void StartGame() + public bool StartGame() { try { gameID = remoteServer.NewGame(roomID); + return true; } catch (Exception ex) { - handleServerError(this, ex.Message); + HandleServerError(this, ex.Message); + System.Diagnostics.Debugger.Break(); + return false; } } @@ -132,7 +136,8 @@ namespace zsirozas catch (Exception ex) { //TODO: rossz debug módszer.... - handleServerError(this, ex.Message); + HandleServerError(this, ex.Message); + System.Diagnostics.Debugger.Break(); return; } } @@ -215,16 +220,24 @@ namespace zsirozas case ServerEvent.Notice: throw new NotImplementedException(); case ServerEvent.Ping: - throw new NotImplementedException(); + throw new NotImplementedException(); + case ServerEvent.Invalid: + throw new NotImplementedException(); + break; + case ServerEvent.RoomChanged: + //throw new NotImplementedException(); + break; + case ServerEvent.Shutdown: + throw new NotImplementedException(); + break; default: break; } - throw new NotImplementedException(); } public void ParseNextMessage(StreamReader sr) { - //using (var sr = new StreamReader(s)) + if(!sr.EndOfStream) { try { @@ -252,7 +265,8 @@ namespace zsirozas } else { - handleServerError(this, ex.Message); + HandleServerError(this, ex.Message); + System.Diagnostics.Debugger.Break(); return; } } @@ -279,6 +293,13 @@ namespace zsirozas switch (@event) { case GameEvent.NewTurn: + //If unknown, query the gameID + if (gameID==null) + { + gameID = remoteServer.RoomInfo(roomID).gameID; + gameID = "G~RoomZero"; + } + gameState = ser.Deserialize<MidGameState>(param0); //TODO: ezt majd valahol máshol nézegetni... @@ -294,9 +315,10 @@ namespace zsirozas gameStateCanged(this, @event); break; case GameEvent.GameOver: - var dummy = new { ID = "", score = 0 }; - var scores = ser.Deserialize<IEnumerable<object>>(param0).Select((arg) => CastByExample(dummy, arg)); - string msg = string.Join("\n", scores.Select((arg) => arg.ID + "\t" + arg.score).ToArray()); + gameID = null; + //var dummy = new { ID = "", score = 0 }; + var scores = ser.Deserialize<IEnumerable<Dictionary<string, object>>>(param0);//.Select((arg) => CastByExample(dummy, arg)); + string msg = string.Join("\n", scores.Select((arg) => arg["score"] + " \t " + arg["ID"]).ToArray()); gameOver(this, "A játéknak vége!\n" + msg); break; default: @@ -343,7 +365,8 @@ namespace zsirozas } catch (ServerErrorException ex) { - handleServerError(this, ex.Message); + HandleServerError(this, ex.Message); + System.Diagnostics.Debugger.Break(); return false; } } @@ -358,7 +381,8 @@ namespace zsirozas } catch (ServerErrorException ex) { - handleServerError(this, ex.Message); + HandleServerError(this, ex.Message); + System.Diagnostics.Debugger.Break(); return false; } } @@ -367,12 +391,12 @@ namespace zsirozas public event EventHandler<GameEvent> gameStateCanged; //névtelen típusra cast-oláshoz - private static T CastByExample<T>(T typeHolder, Object x) - { - // typeHolder above is just for compiler magic - // to infer the type to cast x to - return (T)x; - } + //private static T CastByExample<T>(T typeHolder, Object x) + //{ + // // typeHolder above is just for compiler magic + // // to infer the type to cast x to + // return (T)x; + //} } diff --git a/zsirozas/GameServer.cs b/zsirozas/GameServer.cs index c755de9c19aaa0b801c651e60fbfc9b2c7d1b8d5..9a2e09ec26b19a075b0da7de5fa28aa3284e0992 100644 --- a/zsirozas/GameServer.cs +++ b/zsirozas/GameServer.cs @@ -12,7 +12,7 @@ namespace zsirozas { public ServerWrapper wrapper; - public void registerWrapper(ServerWrapper _wrapper) + public void RegisterWrapper(ServerWrapper _wrapper) { wrapper = _wrapper; } @@ -83,9 +83,6 @@ namespace zsirozas line = sr.ReadLine(); - //TODO: rájönni, miért néha nullt ad a kliens gameID helyett - if (line == "") { System.Diagnostics.Debugger.Break(); line = "G~RoomZero"; } - string playerID = sr.ReadLine(); string playerAction = sr.ReadLine(); string cardID = sr.ReadLine(); @@ -120,9 +117,11 @@ namespace zsirozas sw.WriteLine("OK"); throw; } - catch (Exception) + catch (Exception ex) { sw.WriteLine("ERR"); + Console.WriteLine("[ERR] error while processing message. Moving on... \t\t" + ex.Message); //todo biztos, hogy logolni akarom? + sw.WriteLine(); } break; case ServerAction.Ping: @@ -457,7 +456,11 @@ namespace zsirozas UsersByID[userID].roomID = roomID; RoomsByID[roomID].userList.Add(userID); Console.WriteLine("[LOG] " + userID + " joined room " + UsersByID[userID].roomID); - //TODO: akarok-e erről üzenni? + //TODO: akarok-e erről üzenni? IGEN! + foreach (var member in RoomsByID[roomID].userList) + { + UsersByID[member].client.SimpleNotify(ServerEvent.RoomChanged, roomID); + } } else throw new InvalidActionException("That room does not exist!"); } @@ -526,7 +529,7 @@ namespace zsirozas { players = RoomsByID[roomID].userList.ToArray(), roomID = roomID, - playing = RoomsByID[roomID].gameID != null, + gameID = RoomsByID[roomID].gameID, }; } } diff --git a/zsirozas/InfoDialog.cs b/zsirozas/InfoDialog.cs index 78949f778625af0102019230d5285dec679f6adc..4cbca574c2c2455f4fcea94299df27f716894746 100644 --- a/zsirozas/InfoDialog.cs +++ b/zsirozas/InfoDialog.cs @@ -38,10 +38,10 @@ namespace zsirozas { dialog.Text = "Room Info"; dialog.labelKey1.Text = "Room ID:"; dialog.labelValue1.Text = room.roomID; if (room.roomID == ownRoom) dialog.labelValue1.ForeColor = Color.Aqua; - dialog.labelKey2.Text = "Playing:"; dialog.labelValue2.Text = room.playing ? "yes" : "no"; + dialog.labelKey2.Text = "Playing:"; dialog.labelValue2.Text = (room.gameID != null) ? "yes" : "no"; dialog.listBox1.Items.AddRange(room.players); dialog.buttonOK.Text = "Join"; - dialog.buttonOK.Enabled = !room.playing && ownRoom == null; + dialog.buttonOK.Enabled = (room.gameID == null) && ownRoom == null; return dialog.ShowDialog() == DialogResult.OK; } } diff --git a/zsirozas/Program.cs b/zsirozas/Program.cs index fc381eed90d1f684912bacb0a785361233f823c6..0aa7cf727ad0bf74943040469cdc039be321fea2 100644 --- a/zsirozas/Program.cs +++ b/zsirozas/Program.cs @@ -11,6 +11,8 @@ namespace zsirozas { if (args.Contains("--server")) { + //TODO: bigroom-ot feltételessé + //TODO: autostop-ot feltételessé var srv = new GameServer(true || args.Contains("--bigroom")); new ServerWrapper(srv).Run(args.Contains("--signalr"), true); } diff --git a/zsirozas/RawTcpTransport.cs b/zsirozas/RawTcpTransport.cs index 1ef08bd4fa77d5c661dd96be3ef5b157d9ca7586..31d68cfe5865465fa20925111291a0faf10861b3 100644 --- a/zsirozas/RawTcpTransport.cs +++ b/zsirozas/RawTcpTransport.cs @@ -39,7 +39,6 @@ namespace zsirozas { messageStreamW.WriteLine(ServerEvent.GameEvent); messageStreamW.WriteLine(@event); - //messageStreamW.WriteLine(new JavaScriptSerializer().Serialize(param0)); messageStreamW.WriteLine(param0); messageStreamW.WriteLine(); messageStreamW.Flush(); @@ -292,8 +291,16 @@ namespace zsirozas if (action == PlayerAction.GetCards) { - status = sr.ReadLine(); - return new JavaScriptSerializer().Deserialize<IEnumerable<Card>>(status).ToArray(); + status = sr.ReadLine(); //todo bug néha ez null, utána kivenni a debug cuccokat + try + { + return new JavaScriptSerializer().Deserialize<IEnumerable<Card>>(status).ToArray(); + } + catch (Exception ex) + { + System.Diagnostics.Debugger.Break(); + throw ex; + } } else { @@ -325,7 +332,7 @@ namespace zsirozas } public ServerWrapper wrapper; - public void registerWrapper(ServerWrapper _wrapper) + public void RegisterWrapper(ServerWrapper _wrapper) { wrapper = _wrapper; } @@ -361,7 +368,8 @@ namespace zsirozas { sw.WriteLine(); string status = null; - sw.WriteLine(ServerAction.ServerInfo); + sw.WriteLine(ServerAction.UserInfo); + sw.WriteLine(userID); sw.Flush(); if ((status = sr.ReadLine()) != "OK") @@ -373,6 +381,29 @@ namespace zsirozas } } + public RoomInfo RoomInfo(string roomID) + { + var tempConn = new TcpClient(); + tempConn.Connect(server); + using (var sw = new StreamWriter(tempConn.GetStream())) + using (var sr = new StreamReader(tempConn.GetStream())) + { + sw.WriteLine(); + string status = null; + sw.WriteLine(ServerAction.RoomInfo); + sw.WriteLine(roomID); + + sw.Flush(); + if ((status = sr.ReadLine()) != "OK") + { + status = sr.ReadLine(); + throw new ServerErrorException(status); + } + return zsirozas.RoomInfo.Parse(sr.ReadLine()); + } + throw new NotImplementedException(); + } + //public bool SendRequest(string userID, ServerAction action, string @params = null) //{ // var tempConn = new TcpClient(); diff --git a/zsirozas/Rooms.cs b/zsirozas/Rooms.cs index 727c415c0329ec9118f60d41196bceb7dea6393d..cca92ef7ae25c4af69d3f82eec6e21c215902370 100644 --- a/zsirozas/Rooms.cs +++ b/zsirozas/Rooms.cs @@ -15,7 +15,7 @@ namespace zsirozas enum ServerEvent { - GameEvent, Invitation, Logout, Notice, Ping + Invalid = -1, GameEvent, Invitation, Logout, Notice, Ping, RoomChanged,/*includes force-join and force - leave*/ Shutdown } partial class User @@ -31,7 +31,7 @@ namespace zsirozas /// For diagnostic purposes. Use this with reflection to access connection details. /// </summary> /// <value>The type of the connection.</value> - public ConnectionType connectionType { get; protected set; } + public ConnectionType ConnectionType { get; protected set; } } /// <summary> @@ -83,7 +83,8 @@ namespace zsirozas struct RoomInfo { public string[] players; - public bool playing; + //public bool playing; + public string gameID;//todo comment public string roomID; public override string ToString() { diff --git a/zsirozas/ServerWrapper.cs b/zsirozas/ServerWrapper.cs index b557d0d34d562c3439e62d8689c05d374411baf9..e962fa5a3ab0654ae4096805508ce6dec051295f 100644 --- a/zsirozas/ServerWrapper.cs +++ b/zsirozas/ServerWrapper.cs @@ -18,7 +18,7 @@ namespace zsirozas public ServerWrapper(IServerApiProvider _serverInstance) { this.serverInstance = _serverInstance; - _serverInstance.registerWrapper(this); + _serverInstance.RegisterWrapper(this); } private Thread controlThread; @@ -31,7 +31,7 @@ namespace zsirozas } if (enableTCP) { - startTcpListener(); + StartTcpListener(); } Start(); controlThread.Join(); @@ -47,7 +47,7 @@ namespace zsirozas public void Exit() { //stopSignalR(); - stopTcpListener(); + StopTcpListener(); controlThread.Abort(); } @@ -73,13 +73,13 @@ namespace zsirozas } //................................................................................................ - public void startTcpListener() + public void StartTcpListener() { requestQueue = new TcpListener(tcp_listening_address, tcp_listening_port); requestQueue.Start(); } - public void stopTcpListener() + public void StopTcpListener() { requestQueue.Stop(); //.... }