Ejemplo n.º 1
0
        private void CheckActivity(object sender, EventArgs e)
        {
            // Check buffer for TCP messages
            try
            {
                EndPoint localEndPoint     = remoteEndPoint;
                byte[]   ReceiveBuffer     = new byte[1024];
                int      iReceiveByteCount = tcpSocket.connectionSocket.ReceiveFrom(ReceiveBuffer, ref localEndPoint);
                byte[]   data = new byte[iReceiveByteCount];
                Array.Copy(ReceiveBuffer, data, iReceiveByteCount); //make sure byte[] is the same length as the recieved byte[]

                // If there is a message deserialize it and pass it into the TCP Message Manager
                if (0 < iReceiveByteCount)
                {
                    try
                    {
                        GameMessageStruct gameMessage = PDU.DeserializeStruct(data); //convert byte[] to structure so it can be read

                        TCPMessageManager(gameMessage);
                    }
                    catch (Exception error)
                    {
                        Console.WriteLine(error.Message);
                    }
                }
            }
            catch
            {
            }
        }
Ejemplo n.º 2
0
        // Convert array of Bytes into PDU
        public static GameMessageStruct DeserializeStruct(byte[] message)
        {
            // Allocate unmanaged memory
            IntPtr ip = Marshal.AllocHGlobal(message.Length);

            // Copy the byte to the unmanaged memory
            Marshal.Copy(message, 0, ip, message.Length);

            // Marshal the unmanaged memory contents to the GameMessageStruct
            GameMessageStruct structure = (GameMessageStruct)Marshal.PtrToStructure(ip, typeof(GameMessageStruct));

            // Free unmanaged memory
            Marshal.FreeHGlobal(ip);
            return(structure);
        }
Ejemplo n.º 3
0
        private void UpdateTotalTime(object sender, ElapsedEventArgs e)
        {
            // Shows elasped time the game has lasted
            try
            {
                Invoke(new Action(() =>
                {
                    secTotal += 1;
                    if (secTotal == 60)
                    {
                        secTotal  = 0;
                        minTotal += 1;
                    }
                    if (minTotal == 60)
                    {
                        // Close Game and set player status to available
                        MessageBox.Show("Game Time Expired");
                        try
                        {
                            GameMessageStruct gameMessage = new GameMessageStruct {
                                messageType  = 6,
                                playerName   = MainMenu.player.PlayerName,
                                playerStatus = 0,
                            };

                            byte[] data = PDU.SerializeStruct(gameMessage);

                            tcpSocket.connectionSocket.Send(data, SocketFlags.None);
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex.Message);
                        }
                        BtnLeave_Click(sender, e);
                    }
                    // Format timer
                    lblTotalTimer.Text = string.Format("{0}:{1}", minTotal.ToString().PadLeft(2, '0'), secTotal.ToString().PadLeft(2, '0'));
                }
                                  ));
            }
            catch
            {
            }
        }
Ejemplo n.º 4
0
        public void TCPMessageManager(GameMessageStruct gameMessage)
        {
            switch (gameMessage.messageType)
            {
            case 0:
                // Start the game
                gameManagement.StoreCharacterChoice(gameMessage.characterChoice, gameMessage.playerName, currentGame);
                break;

            case 1:
                // Player Timer has elapsed
                gameManagement.RanOutOfTime(gameMessage.playerName, currentGame);
                break;

            case 2:
                // Question Received
                gameManagement.QuestionAsked(gameMessage.text, gameMessage.playerName, currentGame);
                break;

            case 3:
                // Guess Received
                gameManagement.GuessMade(gameMessage.guess, gameMessage.playerName, currentGame);
                break;

            case 4:
                // Response to guess
                gameManagement.ResponseMade(gameMessage.response, gameMessage.playerName, currentGame);
                break;

            case 5:
                // Chat messages
                gameManagement.ChatMessageSent(gameMessage.text, gameMessage.playerName, currentGame);
                break;

            case 6:
                // Player Status Change
                //StatusManager(gameMessage.text, gameMessage.playerName, currentGame);
                break;
            }
        }
Ejemplo n.º 5
0
        private void BtnNo_Click(object sender, EventArgs e)
        {
            // Response to question received sent back
            try
            {
                GameMessageStruct gameMessage = new GameMessageStruct
                {
                    messageType = 4,
                    playerName  = MainMenu.player.PlayerName,
                    response    = false
                };

                byte[] data = PDU.SerializeStruct(gameMessage);

                tcpSocket.connectionSocket.Send(data, SocketFlags.None);
                DisableControls();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
Ejemplo n.º 6
0
        private void UpdateTurnTime(object sender, ElapsedEventArgs e)
        {
            Invoke(new Action(() =>
            {
                // Shows time remaining for player's turn
                secRemaining -= 1;
                if (secRemaining == 0)
                {
                    // Player ran out of time
                    try
                    {
                        GameMessageStruct gameMessage = new GameMessageStruct {
                            messageType = 1,
                            playerName  = MainMenu.player.PlayerName
                        };

                        byte[] data = PDU.SerializeStruct(gameMessage);

                        tcpSocket.connectionSocket.Send(data, SocketFlags.None);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                    DisableControls();
                    turnTimer.Stop();
                }
                if (secRemaining <= 10)
                {
                    lblTurnTimer.ForeColor = Color.Red;
                }
                else
                {
                    lblTurnTimer.ForeColor = Color.Black;
                }
                lblTurnTimer.Text = string.Format("00:{0}", secRemaining.ToString().PadLeft(2, '0'));
            }
                              ));
        }
Ejemplo n.º 7
0
        private void BtnAskQ_Click(object sender, EventArgs e)
        {
            // Send players question to server to relay to opponent
            try
            {
                GameMessageStruct gameMessage = new GameMessageStruct {
                    messageType = 2,
                    playerName  = MainMenu.player.PlayerName,
                    text        = txtQuestion.Text
                };

                byte[] data = PDU.SerializeStruct(gameMessage);

                tcpSocket.connectionSocket.Send(data, SocketFlags.None);

                txtQuestion.Clear();
                DisableControls();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
Ejemplo n.º 8
0
        private void SendGameMessage()
        {
            // Add text to chatbox
            //chatContents.Items.Add($"{MainMenu.player.PlayerName}: {messasgeTextBox.Text}");

            // Send message to server to relay to opponent
            try
            {
                GameMessageStruct gameMessage = new GameMessageStruct {
                    messageType = 5,
                    playerName  = MainMenu.player.PlayerName,
                    text        = messasgeTextBox.Text
                };
                byte[] data = PDU.SerializeStruct(gameMessage);

                tcpSocket.connectionSocket.Send(data, SocketFlags.None);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            messasgeTextBox.Clear();
        }
Ejemplo n.º 9
0
        private void SelectedChar(PictureBox picbox)
        {
            // Get the image name
            string imageName = picbox.Tag.ToString();
            string grey      = "Grey";

            // Choose a character to be your choice
            if (pbSelected.Image == null)
            {
                pbSelected.Image = picbox.Image;
                userCharacter    = picbox.Tag.ToString();

                Console.WriteLine($"{MainMenu.player.PlayerName} has selected {userCharacter} as their charcter");
                lblTimer.Stop();
                lblSelectCharacter.Dispose();

                // Sent selected choice to server
                try
                {
                    GameMessageStruct gameMessage = new GameMessageStruct
                    {
                        messageType     = 0,
                        playerName      = MainMenu.player.PlayerName,
                        characterChoice = userCharacter
                    };

                    byte[] data = PDU.SerializeStruct(gameMessage);

                    tcpSocket.connectionSocket.Send(data, SocketFlags.None);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
            }
            // Make a guess
            else if (guessing && imageName.Contains(grey) == false)
            {
                DialogResult result = MessageBox.Show($"You have guessed {imageName}", "YOU HAVE MADE A GUESS!!!", MessageBoxButtons.YesNo);
                if (result == DialogResult.Yes)
                {
                    // Send guess to server
                    try
                    {
                        GameMessageStruct gameMessage = new GameMessageStruct
                        {
                            messageType = 3,
                            playerName  = MainMenu.player.PlayerName,
                            guess       = imageName
                        };

                        byte[] data = PDU.SerializeStruct(gameMessage);

                        tcpSocket.connectionSocket.Send(data, SocketFlags.None);

                        txtQuestion.Clear();
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                    BtnGuess_Click(new object(), new EventArgs());
                }
                else
                {
                    BtnGuess_Click(new object(), new EventArgs());
                }
            }
            // Toggle Grayscale image
            else
            {
                if (imageName.Contains(grey) == false)
                {
                    picbox.Image = Image.FromFile(Directory.GetCurrentDirectory() + $"\\{peopleSet}\\{picbox.Tag}{grey}.JPG");
                    picbox.Tag   = $"{imageName}{grey}";
                }
                else
                {
                    if (guessing == false)
                    {
                        picbox.Tag   = imageName.Remove(imageName.IndexOf(grey), grey.Length);
                        picbox.Image = Image.FromFile(Directory.GetCurrentDirectory() + $"\\{peopleSet}\\{picbox.Tag}.JPG");
                    }
                }
            }
        }
Ejemplo n.º 10
0
        public void TCPMessageManager(GameMessageStruct gameMessage)
        {
            // Based on the message type trigger different methods
            switch (gameMessage.messageType)
            {
            case 0:
                // Display characters based on servers list of names
                DisplayPeople(peopleSet, gameMessage.nameslist);
                break;

            case 1:
                // Decide which players turn
                if (gameMessage.activeTurn == true)
                {
                    TurnControls();
                    turnTimer.Start();
                }
                totalTimer.Start();
                break;

            case 2:
                // Player ran out of time
                MessageBox.Show("Opponent ran out of time");
                TurnControls();
                StartTurn();
                break;

            case 3:
                // Question Recieved
                txtQuestion.Text = gameMessage.text;
                ResponseControls();
                StartTurn();
                break;

            case 4:
                // Guess made
                if (gameMessage.guess == "win")
                {
                    MessageBox.Show("You Guessed Right, You Win!!");
                    // Shut down timer, close socket and finally close the form
                    CloseGame();
                }
                else if (gameMessage.guess == "lose")
                {
                    MessageBox.Show($"{MainMenu.opp.PlayerName} guessed Right, You Lose!!");
                    CloseGame();
                }
                else if (gameMessage.guess == "youwrong")
                {
                    MessageBox.Show("Wrong guess");
                    DisableControls();
                }
                else if (gameMessage.guess == "theywrong")    // wrong guess
                {
                    MessageBox.Show($"{MainMenu.opp.PlayerName} guessed wrong");
                    StartTurn();
                }
                break;

            case 5:
                // Display characters based on servers list of names
                if (gameMessage.response)
                {
                    MessageBox.Show("YES");
                }
                else
                {
                    MessageBox.Show("NO");
                }
                break;

            case 6:
                // Receive chat message
                chatContents.Items.Add($"{gameMessage.playerName} : {gameMessage.text}");
                unreadMessages++;
                btnChat.Text = $"Chat({unreadMessages})";
                break;
            }
        }
Ejemplo n.º 11
0
        private void CheckTCPActivity(object sender, EventArgs myEventArgs)
        {
            // Check TCP Connections Backlog for connection requests
            try
            {
                if (playerNumber < 2)
                {
                    try
                    {
                        // Add each player as a new socket
                        currentGame[playerNumber]          = tcpSocket.connectionSocket.Accept();
                        currentGame[playerNumber].Blocking = false;
                        playerNumber++;

                        if (playerNumber == 2)
                        {
                            gameStarted = true;
                        }
                    }
                    catch (SocketException se)                              // Handle socket-related exception
                    {                                                       // If an exception occurs, display an error message
                        if (10053 == se.ErrorCode || 10054 == se.ErrorCode) // Remote end closed the connection
                        {
                            tcpSocket.CloseSocket();
                        }
                        else if (10035 != se.ErrorCode)
                        {   // Ignore error messages relating to normal behaviour of non-blocking sockets
                            MessageBox.Show(se.Message);
                        }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e);
                    }
                }
                else if (gameStarted == true)
                {
                    // Diagnostics message
                    listBoxStatus.Items.Add("Game Has Started");
                    gameStarted = false;

                    // Send same list of characters to each client
                    GameMessageStruct gameMessage = new GameMessageStruct
                    {
                        messageType = 0,
                        nameslist   = gameManagement.DisplayPeople()
                    };

                    byte[] data = PDU.SerializeStruct(gameMessage);

                    foreach (Socket client in currentGame)
                    {
                        client.Send(data, SocketFlags.None);
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }

            // Then check for game activity
            for (int i = 0; i < 2; i++)
            {
                try
                {
                    EndPoint localEndPoint     = tcpSocket.endPoint;
                    byte[]   ReceiveBuffer     = new byte[1024];
                    int      iReceiveByteCount = currentGame[i].ReceiveFrom(ReceiveBuffer, ref localEndPoint);
                    byte[]   data = new byte[iReceiveByteCount];
                    Array.Copy(ReceiveBuffer, data, iReceiveByteCount); //make sure byte[] is the same length as the recieved byte[]

                    if (0 < iReceiveByteCount)
                    {
                        try
                        {
                            GameMessageStruct gameMessage = PDU.DeserializeStruct(data); //convert byte[] to structure so it can be read

                            TCPMessageManager(gameMessage);
                        }
                        catch (Exception error)
                        {
                            Console.WriteLine(error.Message);
                        }
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                }
            }
        }
Ejemplo n.º 12
0
 public void TCPMessageManager(GameMessageStruct gameMessageStruct)
 {
     // Method implemented from IMessage manager Interface, but not needed
 }