Beispiel #1
0
        private void RemoveSessionFromTable()
        {
            // When the lobby form first comes up, we want to fill the table with the active sessions from the server
            // Get the session id for my user
            int sessionID = -1;

            for (int i = 0; i < lobbyTable.Rows.Count; ++i)
            {
                if ((string)lobbyTable.Rows[i].Cells[2].Value == me.Username)
                {
                    sessionID = (int)lobbyTable.Rows[i].Cells[0].Value;
                    break;
                }
            }

            // Session not found. Return.
            if (sessionID == -1)
            {
                return;
            }

            // Create the signal to send
            TCPSignal signal = new TCPSignal()
            {
                SignalType = Signal.DeleteSession,
                SessionID  = sessionID
            };

            // Send the json over to the server
            string json = JsonConvert.SerializeObject(signal) + "\r";

            byte[] jsonBytes = ASCIIEncoding.ASCII.GetBytes(json);
            stream.Write(jsonBytes, 0, jsonBytes.Length);
        }
Beispiel #2
0
        private void addStandardGame_Click(object sender, EventArgs e)
        {
            if (UserHasActiveGame())
            {
                MessageBox.Show("Error: You already have a game queued in the lobby table!\nDelete this game and try again.");
                return;
            }

            // Set mine and enemy's color...
            Random rand     = new Random(Guid.NewGuid().GetHashCode());
            double randNum  = rand.NextDouble();
            bool   hostTurn = true;// (randNum < 0.5);

            moveLogic.myTurn  = hostTurn;
            moveLogic.myColor = moveLogic.myTurn ?
                                moveLogic.myColor = MoveLogic.pieceColor.white :
                                                    moveLogic.myColor = MoveLogic.pieceColor.black;

            MoveLogic.pieceColor guestColor = (moveLogic.myColor == MoveLogic.pieceColor.white) ?
                                              MoveLogic.pieceColor.black :
                                              MoveLogic.pieceColor.white;

            // Create the new session to add to the lobby table
            Session mySession = new Session()
            {
                HostPlayer       = me.Username,
                GuestPlayer      = "",
                GameTimerSeconds = 1200,
                MoveTimerSeconds = 120,
                CustomGameMode   = 0,
                GuestColor       = (int)guestColor
            };

            // Create the signal to send
            TCPSignal signal = new TCPSignal()
            {
                SignalType = Signal.CreateSession,
                NewSession = mySession
            };

            // Send the json over to the server
            string json = JsonConvert.SerializeObject(signal) + "\r";

            byte[] jsonBytes  = ASCIIEncoding.ASCII.GetBytes(json);
            byte[] readBuffer = new byte[65536];
            stream.Write(jsonBytes, 0, jsonBytes.Length);

            RefreshTable();

            // Set the session ID
            mySession.SessionID = (int)lobbyTable.Rows[lobbyTable.Rows.Count - 1].Cells[0].Value;

            GameSession session = new GameSession(me, new User("", ""), stream, mySession, this, moveLogic);

            session.ShowDialog();
        }
Beispiel #3
0
 private void tcpClientWorker2_DoWork(object sender, DoWorkEventArgs e)
 {
     while (!tcpClientWorker2.CancellationPending)
     {
         object[]      parameters = (object[])e.Argument;
         TCPSignal     signal     = (TCPSignal)parameters[0];
         NetworkStream gameStream = (NetworkStream)parameters[1];
         //GameSession session = new GameSession(me, new User(signal.GuestPlayerName == me.Username ? signal.HostPlayerName : signal.GuestPlayerName, ""), gameStream);
         //session.ShowDialog();
         tcpClientWorker2.CancelAsync();
     }
 }
Beispiel #4
0
        public void RefreshTable()
        {
            // When the lobby form first comes up, we want to fill the table with the active sessions from the server
            // Create the signal to send
            TCPSignal signal = new TCPSignal()
            {
                SignalType = Signal.GetSessions
            };

            // Send the json over to the server
            string json = JsonConvert.SerializeObject(signal) + "\r";

            byte[] jsonBytes  = ASCIIEncoding.ASCII.GetBytes(json);
            byte[] readBuffer = new byte[65536];
            stream.Write(jsonBytes, 0, jsonBytes.Length);

            json = "";
            stream.Read(readBuffer, 0, readBuffer.Length);
            json += ASCIIEncoding.ASCII.GetString(readBuffer).Replace("\0", "");
            while (stream.DataAvailable)
            {
                stream.Read(readBuffer, 0, readBuffer.Length);
                json += ASCIIEncoding.ASCII.GetString(readBuffer).Replace("\0", "");
            }

            // Add the sessions to the table
            List <Session> sessions = new List <Session>();

            sessions = (List <Session>)JsonConvert.DeserializeObject(json, typeof(List <Session>));
            clearTable();
            if (sessions != null)
            {
                foreach (Session session in sessions)
                {
                    bool   isCustomGame = (session.CustomGameMode == 3);
                    string un           = session.HostPlayer;
                    int    gameTime     = session.GameTimerSeconds;
                    int    moveTime     = session.MoveTimerSeconds;
                    int    sessionID    = session.SessionID;
                    int    gameID       = session.GameID;

                    // Create the row in the table
                    AddGameToLobbyTable(sessionID, isCustomGame, un, moveTime, gameTime, gameID);
                }
            }
        }
Beispiel #5
0
        private void RemoveGameFromLobby()
        {
            // Remove the game from the lobby table
            int sessionID = sessionInfo.SessionID;

            // Create the signal to send
            TCPSignal signal = new TCPSignal()
            {
                SignalType = Signal.DeleteSession,
                SessionID  = sessionID
            };

            // Send the json over to the server
            string json = JsonConvert.SerializeObject(signal) + "\r";

            byte[] jsonBytes = ASCIIEncoding.ASCII.GetBytes(json);
            stream.Write(jsonBytes, 0, jsonBytes.Length);
            Thread.Sleep(1000);
        }
Beispiel #6
0
        private void join_Click(object sender, EventArgs e)
        {
            if (lobbyTable.SelectedRows.Count > 0)
            {
                // Pop up to ask the user if they are sure that they want to join X's game.
                // Get the game text
                string       userGame = (string)lobbyTable.SelectedRows[0].Cells[2].Value + "'s game?";
                DialogResult result   = MessageBox.Show("Are you sure you would like to join " + userGame, "Join " + userGame, MessageBoxButtons.YesNoCancel);

                if (result == DialogResult.Yes)
                {
                    // Verify this game can be joined. Send the signal to the other user.
                    TCPSignal signal = new TCPSignal
                    {
                        SignalType      = Signal.JoinSession,
                        GuestPlayerName = me.Username,
                        HostPlayerName  = (string)lobbyTable.SelectedRows[0].Cells[2].Value,
                        SessionID       = (int)lobbyTable.SelectedRows[0].Cells[0].Value
                    };
                    string json = JsonConvert.SerializeObject(signal) + "\r";
                    byte[] data = ASCIIEncoding.ASCII.GetBytes(json);

                    stream.Write(data, 0, data.Length);

                    byte[] joined = new byte[1];
                    stream.Read(joined, 0, 1);

                    // Opponent accepted match
                    if (joined[0] == 1)
                    {
                        byte[] data2 = new byte[65535];
                        stream.Read(data2, 0, data2.Length);
                        json = ASCIIEncoding.ASCII.GetString(data2).Replace("\0", "");
                        TCPSignal signal2 = (TCPSignal)JsonConvert.DeserializeObject(json, typeof(TCPSignal));

                        moveLogic.myColor = (MoveLogic.pieceColor)signal2.NewSession.GuestColor;

                        GameSession session = new GameSession(me, new User(signal2.NewSession.HostPlayer, ""), stream, signal2.NewSession, this, moveLogic);
                        session.ShowDialog();
                    }
                }
            }
        }
Beispiel #7
0
 private void tcpClientWorker_DoWork(object sender, DoWorkEventArgs e)
 {
     while (!tcpClientWorker.CancellationPending)
     {
         byte[] data = new byte[65535];
         if (lobbyTable.Rows.Count == 0)
         {
             Thread.Sleep(10);
             continue;
         }
         stream.Read(data, 0, data.Length);
         string    json   = ASCIIEncoding.ASCII.GetString(data).Replace("\0", "");
         TCPSignal signal = (TCPSignal)JsonConvert.DeserializeObject(json, typeof(TCPSignal));
         if (signal.SignalType == Signal.StartSession)
         {
             tcpClientWorker2.RunWorkerAsync(new object[] { signal, stream });
             while (!tcpClientWorker2.CancellationPending)
             {
                 Thread.Sleep(10);
             }
         }
     }
 }
Beispiel #8
0
        private void gameWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            while (!gameWorker.CancellationPending)
            {
                if (opponentName == "")
                {
                    byte[] data = new byte[65535];
                    try
                    {
                        stream.Read(data, 0, data.Length);
                    }
                    catch (Exception)
                    {
                        continue;
                    }

                    string    json   = ASCIIEncoding.ASCII.GetString(data).Replace("\0", "");
                    TCPSignal signal = (TCPSignal)JsonConvert.DeserializeObject(json, typeof(TCPSignal));
                    if (signal.SignalType == Signal.StartSession)
                    {
                        // Host
                        Invoke(new Action(() =>
                        {
                            moveLogic.gameStarted = true;
                            //TODO add timers, etc
                            opponentName = enemyUsername.Text = signal.NewSession.GuestPlayer;
                        }));
                    }
                }
                else
                {
                    // TODO: Perform server move logic, timers, etc.

                    // Guest
                    Invoke(new Action(() =>
                    {
                        enemyUsername.Text = opponentName;
                        if (moveLogic.myTurn)
                        {
                            timer.Start();
                        }
                    }));
                    byte[] data = new byte[65535];

                    try
                    {
                        stream.Read(data, 0, data.Length);
                    }
                    catch (Exception)
                    {
                        continue;
                    }
                    string    json   = ASCIIEncoding.ASCII.GetString(data).Replace("\0", "");
                    TCPSignal signal = (TCPSignal)JsonConvert.DeserializeObject(json, typeof(TCPSignal));

                    if (signal.SignalType == Signal.MakeAMove)
                    {
                        Invoke(new Action(() =>
                        {
                            Coordinates destination = signal.PlayerMove.Destination;
                            Piece pieceMoved        = signal.PlayerMove.Source;

                            string pieceTag = pieceMoved.Name;
                            Coordinates c   = pieceMoved.Coordinates;

                            Button originSquare = moveLogic.GetButtonOn(c.X, c.Y, board);
                            Button newSquare    = moveLogic.GetButtonOn(destination.X, destination.Y, board);

                            originSquare.Tag   = "NoPiece";
                            originSquare.Image = null;
                            newSquare.Tag      = pieceTag;
                            newSquare.Image    = ChessUtils.Settings.Image.GetImageForTag(pieceTag);

                            // Update check logic...
                            checkLogic = new CheckLogic(board);
                            ChessUtils.CheckState checkState = checkLogic.CetCheckState();

                            if (checkState == ChessUtils.CheckState.Check)
                            {
                                checkLabel.Show();
                            }

                            else if (checkState == ChessUtils.CheckState.NoCheck)
                            {
                                checkLabel.Hide();
                            }

                            else if (checkState == ChessUtils.CheckState.Checkmate)
                            {
                                // I lost, send the lose signal
                                // They won, send the win signal
                            }

                            else if (checkState == ChessUtils.CheckState.Stalemate)
                            {
                                // We tied, send tie signal for both
                            }

                            // It is now my turn
                            moveLogic.myTurn = !moveLogic.myTurn;

                            if (totalTimeRemaining > originalTimeRemaining)
                            {
                                turnTimeRemaining = originalTimeRemaining;
                            }
                            else
                            {
                                turnTimeRemaining = totalTimeRemaining;
                            }
                            myTimeRemaining.Text      = ChessUtils.ConvertSecondsToTimeString(turnTimeRemaining);
                            myTotalTimeRemaining.Text = ChessUtils.ConvertSecondsToTimeString(totalTimeRemaining);
                        }));
                    }
                }
            }
        }
Beispiel #9
0
        private void ButtonClicked(object sender, EventArgs args)
        {
            Button currentButton = sender as Button;

            selectedButton = currentButton;
            Coordinates c = ChessUtils.Settings.GetCoordinatesOfButton(currentButton);
            Coordinates pc;
            Coordinates cc;
            Piece       piece     = moveLogic.GetPieceOnSquare(c.X, c.Y, board);
            bool        isMyPiece = moveLogic.myColor == piece.Color;

            // If there is a piece on the selected square that is current player's color
            if (isMyPiece)
            {
                List <Button> possibleMoves = moveLogic.GetPossibleMovesForPiece(currentButton, board);
                moveLogic.HighlightButtons(possibleMoves);
            }

            // Potential square to move to from a selected piece
            else
            {
                if (SelectedPieceCanMoveTo(currentButton))
                {
                    pc = ChessUtils.Settings.GetCoordinatesOfButton(previousButton);
                    cc = ChessUtils.Settings.GetCoordinatesOfButton(currentButton);
                    Piece thisPiece = moveLogic.GetPieceOnSquare(pc.X, pc.Y, board);
                    isMyPiece = moveLogic.myColor == thisPiece.Color;

                    if (isMyPiece)
                    {
                        // Move piece to new square
                        currentButton.Tag   = previousButton.Tag;
                        currentButton.Image = previousButton.Image;

                        // Take piece off selected square
                        previousButton.Tag   = "";
                        previousButton.Image = null;

                        bool promoted = false;

                        // Check for pawn promotion
                        if (cc.X % 7 == 0 && currentButton.Tag.ToString().Contains("Pawn"))
                        {
                            // White promotion
                            if (thisPiece.Color == pieceColor.white)
                            {
                                promoted = true;
                                var whiteForm = new PawnPromotionFormWhite();

                                // Pick based off of button
                                if (whiteForm.ShowDialog() == DialogResult.OK)
                                {
                                    switch (whiteForm.GetValue())
                                    {
                                    case "Queen":
                                        currentButton.Tag   = "wQueen";
                                        currentButton.Image = ChessUtils.Settings.Image.WhiteQueen;
                                        break;

                                    case "Rook":
                                        currentButton.Tag   = "wRook";
                                        currentButton.Image = ChessUtils.Settings.Image.WhiteRook;
                                        break;

                                    case "Knight":
                                        currentButton.Tag   = "wKnight";
                                        currentButton.Image = ChessUtils.Settings.Image.WhiteKnight;
                                        break;

                                    case "Bishop":
                                        currentButton.Tag   = "wBishop";
                                        currentButton.Image = ChessUtils.Settings.Image.WhiteBishop;
                                        break;
                                    }
                                }

                                // If form is closed, default to a queen
                                else
                                {
                                    currentButton.Tag   = "wQueen";
                                    currentButton.Image = ChessUtils.Settings.Image.WhiteQueen;
                                }
                            }

                            // Black promotion
                            else
                            {
                                promoted = true;
                                var blackForm = new PawnPromotionFormBlack();
                                // Pick based off of button
                                if (blackForm.ShowDialog() == DialogResult.OK)
                                {
                                    switch (blackForm.GetValue())
                                    {
                                    case "Queen":
                                        currentButton.Tag   = "bQueen";
                                        currentButton.Image = ChessUtils.Settings.Image.BlackQueen;
                                        break;

                                    case "Rook":
                                        currentButton.Tag   = "bRook";
                                        currentButton.Image = ChessUtils.Settings.Image.BlackRook;
                                        break;

                                    case "Knight":
                                        currentButton.Tag   = "bKnight";
                                        currentButton.Image = ChessUtils.Settings.Image.BlackKnight;
                                        break;

                                    case "Bishop":
                                        currentButton.Tag   = "bBishop";
                                        currentButton.Image = ChessUtils.Settings.Image.BlackBishop;
                                        break;
                                    }
                                }

                                // If form is closed, default to a queen
                                else
                                {
                                    currentButton.Tag   = "bQueen";
                                    currentButton.Image = ChessUtils.Settings.Image.BlackQueen;
                                }
                            }
                        }

                        // switch turns
                        moveLogic.myTurn = !moveLogic.myTurn;

                        // Send the move to the server to send to the other client
                        Piece sendPieceLimitedInfo = new Piece();
                        sendPieceLimitedInfo.Coordinates = thisPiece.Coordinates;

                        string pieceName;
                        if (promoted)
                        {
                            pieceName = currentButton.Tag.ToString();
                        }
                        else
                        {
                            pieceName = (moveLogic.myColor == pieceColor.white) ?
                                        "w" : "b";
                            pieceName += thisPiece.Name;
                        }
                        sendPieceLimitedInfo.Name = pieceName;

                        Move move = new Move()
                        {
                            Source      = sendPieceLimitedInfo,
                            Destination = cc
                        };

                        TCPSignal signal = new TCPSignal()
                        {
                            SignalType = Signal.MakeAMove,
                            PlayerMove = move
                        };

                        // Send the json over to the server
                        string json      = JsonConvert.SerializeObject(signal) + "\r";
                        byte[] jsonBytes = ASCIIEncoding.ASCII.GetBytes(json);
                        stream.Write(jsonBytes, 0, jsonBytes.Length);

                        // Clear highlights
                        moveLogic.ClearChessBoardColors(board);
                    }
                }
                else
                {
                    moveLogic.ClearChessBoardColors(board);
                }
            }

            previousButton = currentButton;
        }
Beispiel #10
0
        private void addGameButton_Click(object sender, EventArgs e)
        {
            if (gamesList.SelectedRows.Count > 0)
            {
                // Get the game ID from the row
                int gameId = (int)gamesList.SelectedRows[0].Cells[0].Value;

                // Match the game ID with the appropriate CustomGame in the list
                CustomGame game = gameList.Single(x => x.GameID == gameId);

                // Convert the list of pieces into a double array (board)
                MoveLogic.Piece[][] pieces = new MoveLogic.Piece[8][];
                for (int i = 0; i < 8; ++i)
                {
                    pieces[i] = new MoveLogic.Piece[8];
                }
                foreach (MoveLogic.Piece piece in game.Pieces)
                {
                    MoveLogic.Coordinates c = piece.Coordinates;
                    pieces[c.X][c.Y] = new MoveLogic.Piece();
                    pieces[c.X][c.Y] = piece;
                }

                Random rand     = new Random(Guid.NewGuid().GetHashCode());
                double randNum  = rand.NextDouble();
                bool   hostTurn = true;// (randNum < 0.5);

                moveLogic.myTurn  = hostTurn;
                moveLogic.myColor = moveLogic.myTurn ?
                                    moveLogic.myColor = MoveLogic.pieceColor.white :
                                                        moveLogic.myColor = MoveLogic.pieceColor.black;

                MoveLogic.pieceColor guestColor = (moveLogic.myColor == MoveLogic.pieceColor.white) ?
                                                  MoveLogic.pieceColor.black :
                                                  MoveLogic.pieceColor.white;

                // Create the new session to add to the lobby table
                Session mySession = new Session()
                {
                    HostPlayer       = game.Username,
                    GuestPlayer      = "",
                    GameTimerSeconds = game.GameTimer,
                    MoveTimerSeconds = game.MoveTimer,
                    CustomGameMode   = 3 /* Custom game */,
                    BoardPieces      = pieces,
                    GameID           = gameId,
                    GuestColor       = (int)guestColor
                };

                // Create the signal to send
                TCPSignal signal = new TCPSignal()
                {
                    SignalType = Signal.CreateSession,
                    NewSession = mySession
                };

                // Send the json over to the server
                string json       = JsonConvert.SerializeObject(signal) + "\r";
                byte[] jsonBytes  = ASCIIEncoding.ASCII.GetBytes(json);
                byte[] readBuffer = new byte[65535];
                lobby.stream.Write(jsonBytes, 0, jsonBytes.Length);

                lobby.RefreshTable();
                mySession.SessionID = (int)lobby.GetLobbyTable().Rows[lobby.GetLobbyTable().Rows.Count - 1].Cells[0].Value;

                GameSession session = new GameSession(me, new User("", ""), stream, mySession, lobby, moveLogic, game);
                session.ShowDialog();
                Hide();
                Close();
            }
        }