예제 #1
0
        /* HÀM SẮP XẾP TÊN Z-A */
        private void SX_CBA(List <gameObject> arr, int l, int r)
        {
            int        i = l; int j = r;
            gameObject temp;
            gameObject pivot = arr[(int)(l + r) / 2];

            do
            {
                while (SortforABC(arr[i].GameTitle, pivot.GameTitle) == 1)
                {
                    i++;
                }
                while (SortforABC(arr[j].GameTitle, pivot.GameTitle) == -1)
                {
                    j--;
                }
                if (i <= j)
                {
                    temp   = arr[i];
                    arr[i] = arr[j];
                    arr[j] = temp;
                    i++;
                    j--;
                }
            } while (i < j);

            if (l < j)
            {
                SX_CBA(arr, l, j);
            }
            if (i < r)
            {
                SX_CBA(arr, i, r);
            }
        }
예제 #2
0
        private void GetPlayerSelectionOptions()
        {
            OptionSelector[] temp = GameObject.FindObjectsOfType <OptionSelector>();

            foreach (OptionSelector t in temp)
            {
                if (t.numoptions.Equals(numOptions.volume))
                {
                    bg_volume = t.bg;
                }
                else if (t.numoptions.Equals(numOptions.p1Pref))
                {
                    bg_p1Pref = t.bg;
                }
                else if (t.numoptions.Equals(numOptions.p2Pref))
                {
                    bg_p2Pref = t.bg;
                }
                else if (t.numoptions.Equals(numOptions.p3Pref))
                {
                    bg_p3Pref = t.bg;
                }
                else if (t.numoptions.Equals(numOptions.p4Pref))
                {
                    bg_p4Pref = t.bg;
                }
                else if (t.numoptions.Equals(numOptions.mainMenu))
                {
                    bg_mainMenu = t.bg;
                }
            }
        }
            public static gameObject Instantiate(string objectName)
            {
                gameObject spawningObject = new gameObject();

                spawningObject.name = objectName;
                Scene.SceneObjects.Add(spawningObject);
                return(spawningObject);
            }
예제 #4
0
    void Mirror()
    {
        if (molecule == null)
        {
            molecule = GameObject.FindGameObjectWithTag("Mol");
        }

        moleculeTwo = new gameObject();
        trackedobj  = GetComponent <SteamVR_TrackedObject>();

        // set molecule two to the first molecules position plus 10 to its x and y values
        Instantiate(molecule, Vector3((molecule.transform.x + 10f), (molecule.transform.y + 10f), (molecule.transform.z)), moleculeTwo);
    }
예제 #5
0
    void Start()
    {
        //if the molecule cannot be retrieved by setting it in the Unity Editor, look for it.
        if (molecule == null)
        {
            molecule = GameObject.FindGameObjectWithTag("Mol");
        }

        moleculeTwo = new gameObject();
        trackedobj  = GetComponent <SteamVR_TrackedObject>();

        // set molecule two to the first molecules position plus 10 to its x and y values
        Instantiate(molecule, Vector3((molecule.transform.x + 10f), (molecule.transform.y + 10f), (molecule.transform.z)), moleculeTwo);
    }
예제 #6
0
    public override void OnCollision(gameObject ObjectCollidedWith)
    {
        for (int loops = 1; loops < 5; loops++)
        {
            System.Console.Beep(loops * 1000, 250);
        }
        score++;
        pickupScript gotPickup = ObjectCollidedWith.GetComponent <pickupScript>();

        if (!(gotPickup == null)) //Check the script exists before using it
        {
            gotPickup.Spawn();    //Then collect the pickup, make it respawn
        }
        gotPickup.fallSpeed += 0.05f;
        pickupTimer          = 0;
    }
예제 #7
0
    public static void Start()
    {
        Scene level1 = new Scene();

        gameObject scoreTextBox = gameObject.Instantiate();

        scoreTextBox.worldTransform.position.x = 1;
        scoreTextBox.worldTransform.position.y = 1;
        TextComponent scoreText = scoreTextBox.attachTextComponent();

        gameObject   player = gameObject.Instantiate();
        playerScript playerControllerScript = new playerScript();

        playerControllerScript.scoreOutputText = scoreText;
        player.attachScript(playerControllerScript);

        gameObject pickup = gameObject.Instantiate();

        pickup.attachScript(new pickupScript());
        level1.Run();
    }
예제 #8
0
    void OnStartDamageSystem(GameObject beater, GameObject beaten)
    {
        gameObject beaterPt = beater.transform.parent.parent.parent;
        gameObject beatenPt = beater.transform.parent.parent.parent;

        if (beaterPt.tag == "Enemy" & beatenPt.tag == "Player")
        {
            EnemytoPlayerDamageSystem(beaterPt, beatenPt, beater);
        }
        if (beaterPt.tag == "Player" & beatenPt.tag == "Enemy")
        {
            PlayertoEnemyDamageSystem(beaterPt, beatenPt, beater);
        }
        if (beaterPt.tag == "Enemy" & beatenPt.tag == "DefMagic")
        {
            EnemytoDefMagicDamageSystem(beaterPt, beatenPt, beater);
        }
        if (beaterPt.tag == "Player" & beatenPt.tag == "DefMagic")
        {
            EnemytoDefMagicDamageSystem(beaterPt, beatenPt, beater);
        }
    }
예제 #9
0
 public void openDoor(gameObject obj)
 {
     if (!isOpen)
     {
         PlayerManager manager = obj.GetComponent <PlayerManager>();
         if (manager)
         {
             if (manager.keyCount > 0)
             {
                 isOpen = true;
                 manager.UseKey();
                 animator.setBool("IsOpen", isOpen);
                 AudioSource.PlayClipAtPoint(soundEffect, transform.position);
                 Debug.Log("Door is Unlocked");
             }
         }
     }
     else
     {
         SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1);
     }
 }
예제 #10
0
        /* Hàm Sắp Xếp Date cũ */
        private void SX_old(List <gameObject> arr, int l, int r) // sap xep tang dan
        {
            int        i = l;
            int        j = r;
            gameObject temp;
            gameObject pivot = arr[(int)(l + r) / 2];

            do
            {
                while (sosanh_Date(arr[i].ReleaseDate, pivot.ReleaseDate) == -1)
                {
                    i++;
                }
                while (sosanh_Date(arr[j].ReleaseDate, pivot.ReleaseDate) == 1)
                {
                    j--;
                }

                if (i <= j)
                {
                    temp   = arr[i];
                    arr[i] = arr[j];
                    arr[j] = temp;
                    i++;
                    j--;
                }
            } while (i < j);

            if (l < j)
            {
                SX_old(arr, l, j);
            }
            if (i < r)
            {
                SX_old(arr, i, r);
            }
        }
예제 #11
0
        /* Hàm Sắp Xếp Date Mới */
        private void SX_new(List <gameObject> arr, int l, int r) // sap xep giam dan
        {
            int        i = l;
            int        j = r;
            gameObject temp;
            gameObject pivot = arr[(int)(l + r) / 2];

            do
            {
                while (sosanh_Date(arr[i].ReleaseDate, pivot.ReleaseDate) == 1)
                {
                    i++;
                }
                while (sosanh_Date(arr[j].ReleaseDate, pivot.ReleaseDate) == -1)
                {
                    j--;
                }

                if (i <= j)
                {
                    temp   = arr[i];
                    arr[i] = arr[j];
                    arr[j] = temp;
                    i++;
                    j--;
                }
            } while (i < j);
            // luc nay i > j chay l -> j va i -> r;
            if (l < j)
            {
                SX_new(arr, l, j);
            }
            if (i < r)
            {
                SX_new(arr, i, r);
            }
        }
예제 #12
0
        /* Hàm Sắp Xếp Giá Giảm Dần*/
        private static void Gia_Giam(List <gameObject> arr, int l, int r)
        {
            int        i = l;
            int        j = r;
            gameObject temp;
            gameObject pivot = arr[(int)(l + r) / 2];

            do
            {
                while (so_sanh_Gia(arr[i].GamePrice, pivot.GamePrice) == 1)
                {
                    i++;
                }
                while (so_sanh_Gia(arr[j].GamePrice, pivot.GamePrice) == -1)
                {
                    j--;
                }
                if (i <= j)
                {
                    temp   = arr[i];
                    arr[i] = arr[j];
                    arr[j] = temp;
                    i++;
                    j--;
                }
            } while (i < j);

            if (l < j)
            {
                Gia_Giam(arr, l, j);
            }
            if (i < r)
            {
                Gia_Giam(arr, i, r);
            }
        }
예제 #13
0
 // Use this for initialization
 void Start()
 {
     player = gameObject.find();
 }
        public static void handleNewConnection(TcpClient client)
        {
            // username of active connection
            string username = "";

            // Username of person they are playing against
            string usernameOpponent = "";

            try
            {
                // get streams
                StreamReader reader = new StreamReader(client.GetStream());
                StreamWriter writer = new StreamWriter(client.GetStream());

                Console.Write("New Delegate created to handle new connection.\n");

                gameObject myGame = new gameObject();
                myGame.lastPlayed = new lastMove[1];

                // Setup where the command data will be stored
                string[] command;

                // Read in from the socket here
                string recieve;

                // While logged in, recieve and process data
                bool loggedIn = true;

                // Does this user have an active game?
                bool isActive = false;

                // Last line of chatroom that has been sent to client
                int lastLine = 0;

                // Recieve input
                do {
                    // Read in from socket
                    recieve = reader.ReadLine();

                    command = recieve.Split(' ');

                    // Switch based on command recieved
                    switch (command[0])
                    {
                        // Login to the server
                        // Expected string "LOGIN username"
                        case "LOGIN":
                            if (command.Length == 2)
                            {
                                username = command[1];
                                Console.WriteLine("Logging in " + username);
                                // make sure there are usernames to check
                                if (userNames.Count > 0)
                                {
                                    // search in use usernames for the desired username
                                    foreach (string user in userNames)
                                    {
                                        // if username already in list, it's already in use, thus log them out
                                        if (user == username)
                                        {
                                            loggedIn = false;
                                            writer.WriteLine("FALSE");
                                            writer.Flush();
                                            break;
                                        }
                                    }
                                }
                                if (loggedIn)
                                {
                                    // if still logged in (i.e. not been logged out because username in use)
                                    // add username to the list of usernames in use
                                    userNames.Add(username);
                                    writer.WriteLine("TRUE");
                                    writer.Flush();

                                }
                                else
                                {
                                    writer.WriteLine("FALSE");
                                    writer.Flush();
                                }
                            }
                            else
                            {
                                // If command login command isn't what was expected let the player know
                                writer.WriteLine("FALSE");
                                writer.Flush();
                            }
                            break;
                        // Start New Game
                        // Expected string "NEW username_of_other_player"
                        case "NEW":
                            if (loggedIn)
                            {
                                bool foundOtherGame = false;
                                usernameOpponent = command[1];
                                // search all games for a game that matches the state I'm expecting
                                foreach (gameObject game in gamesInPlay)
                                {
                                    // if game I'm looking for
                                    if (game.playerOne == username && game.playerTwo == usernameOpponent)
                                    {
                                        writer.WriteLine("EXIST");
                                        writer.Flush();
                                        foundOtherGame = true;
                                        break;
                                    }
                                }
                                if (!foundOtherGame)
                                {
                                    myGame.boardGame = generateDefaultBoard();
                                    myGame.playerOne = username;
                                    usernameOpponent = command[1];
                                    myGame.playerTwo = usernameOpponent;
                                    myGame.lastPlayed[0].recievedMove = true;
                                    isActive = true;
                                    myGame.chatRoom = new List<string>();
                                    gamesInPlay.Add(myGame);
                                    writer.WriteLine("TRUE");
                                    writer.Flush();
                                }
                            }
                            else
                            {
                                writer.WriteLine("FALSE");
                                writer.Flush();
                            }
                            break;
                        // Join a game (other player needs to be expecting user)
                        // Expected string "JOIN username_of_other_player"
                        case "JOIN":
                            if (loggedIn)
                            {
                                bool found = false;
                                Console.WriteLine("ISFINDING");
                                // set opponent username
                                usernameOpponent = command[1];
                                // search all games for a game that matches the state I'm expecting
                                foreach (gameObject game in gamesInPlay)
                                {
                                    // if game I'm looking for
                                    Console.WriteLine("P1: " + game.playerOne + " P2: " + game.playerTwo);
                                    if (game.playerOne == usernameOpponent && game.playerTwo == username && game.isJoined == false)
                                    {
                                        found = true;

                                        // add game to my game
                                        myGame = game;
                                        gamesInPlay.ToArray()[gamesInPlay.IndexOf(game)].isJoined = true;
                                        isActive = true;
                                        Console.WriteLine("ISJOINED");
                                        writer.WriteLine("TRUE");
                                        writer.Flush();
                                        break;
                                    } else if (game.isJoined == true)
                                    {
                                        writer.WriteLine("FALSE");
                                        writer.Flush();
                                    }
                                }
                                if (!found)
                                {
                                    writer.WriteLine("FALSE");
                                    writer.Flush();
                                }
                            }
                            break;
                        // Move a chess piece
                        // Expecting string "MOVE x1 y1 x2 y2"
                        case "MOVE":
                            if (isActive)
                            {
                                // Add moves to last played structure for other player to use
                                myGame.lastPlayed[0].xOrigin = Convert.ToInt32(command[1]);
                                myGame.lastPlayed[0].yOrigin = Convert.ToInt32(command[2]);
                                myGame.lastPlayed[0].xMoved = Convert.ToInt32(command[3]);
                                myGame.lastPlayed[0].yMoved = Convert.ToInt32(command[4]);
                                // flag that I'm the last player
                                myGame.lastPlayed[0].lastPlayer = username;
                                // flag the state as readable by other player
                                myGame.lastPlayed[0].recievedMove = false;
                                // update the game state
                                // move the piece
                                myGame.boardGame[myGame.lastPlayed[0].xMoved, myGame.lastPlayed[0].yMoved]
                                    = myGame.boardGame[myGame.lastPlayed[0].xOrigin, myGame.lastPlayed[0].yOrigin];
                                // clear old square
                                myGame.boardGame[myGame.lastPlayed[0].xOrigin, myGame.lastPlayed[0].yOrigin]
                                    = new gameSquare { colour = chessmanColour.empty, piece = chessman.empty };
                            }
                            break;
                        // Get new moves that have been made
                        case "GETMOVE":
                            if (isActive)
                            {
                                if (myGame.lastPlayed[0].lastPlayer != username && !myGame.lastPlayed[0].recievedMove)
                                {
                                    // flag the state as unreadable by the player
                                    myGame.lastPlayed[0].recievedMove = true;
                                    writer.WriteLine("MOVE " + myGame.lastPlayed[0].xOrigin.ToString() + " "
                                        + myGame.lastPlayed[0].yOrigin.ToString() + " "
                                        + myGame.lastPlayed[0].xMoved.ToString() + " "
                                        + myGame.lastPlayed[0].yMoved.ToString());
                                    writer.Flush();
                                }
                                else
                                {
                                    writer.WriteLine("NOMOVE");
                                    writer.Flush();
                                }
                            }
                            break;
                        // logout from the server
                        case "LOGOUT":
                            if (loggedIn)
                            {
                                Console.WriteLine("Logging out " + username);

                                // logout
                                loggedIn = false;
                                // remove username from list of active users
                                userNames.Remove(username);
                                //Clear the game
                                foreach (gameObject game in gamesInPlay)
                                {
                                    // if game I'm looking for
                                    if (game.playerOne == username && game.playerTwo == usernameOpponent)
                                    {
                                        gamesInPlay.Remove(game);
                                        break;
                                    }
                                }

                            } else
                            {
                                loggedIn = false;
                            }
                            break;
                        // print gamestate to console. It's really more of a debug option
                        case "PRINT":
                            if (isActive)
                            {
                                for (int i = 0; i < 8; i++)
                                {
                                    for (int j = 0; j < 8; j++)
                                    {
                                        switch (myGame.boardGame[i, j].piece)
                                        {
                                            case chessman.Bishop:
                                                Console.Write("B ");
                                                break;
                                            case chessman.King:
                                                Console.Write("K ");
                                                break;
                                            case chessman.Knight:
                                                Console.Write("N ");
                                                break;
                                            case chessman.Pawn:
                                                Console.Write("P ");
                                                break;
                                            case chessman.Queen:
                                                Console.Write("Q ");
                                                break;
                                            case chessman.Rook:
                                                Console.Write("R ");
                                                break;
                                            default:
                                                Console.Write("  ");
                                                break;
                                        }
                                    }
                                    Console.WriteLine("");
                                }
                            }
                            break;
                        // Get new messages that are in the chatroom
                        case "GET":
                            if (isActive)
                            {
                                if (lastLine < myGame.chatRoom.Count)
                                {
                                    // send all unread messages
                                    writer.WriteLine(myGame.chatRoom[lastLine]);
                                    lastLine++;
                                    writer.Flush();
                                }
                                else
                                {
                                    writer.WriteLine("");
                                    writer.Flush();
                              }
                            }

                            break;
                        // default, any other string sent will be posted to the chatroom
                        default:
                            if (isActive)
                            {
                                string connectedString = "";
                                for (int i = 0; i < command.Length; i++)
                                {
                                    // catnate the command string to allow spaces to reform
                                    connectedString = connectedString + " " + command[i];
                                }
                                // add line to chatroom
                                myGame.chatRoom.Add(username + ": " + connectedString);
                            }
                            break;

                    }
                } while (loggedIn);

            }
            catch (Exception E) {
                Console.WriteLine("Exception " + E.GetType());
                Console.WriteLine("Removing  " + username + " from active users.");

                // remove username from list of active users
                userNames.Remove(username);
                foreach (gameObject game in gamesInPlay)
                {
                    // if game I'm looking for
                    if (game.playerOne == username && game.playerTwo == usernameOpponent)
                    {
                        gamesInPlay.Remove(game);
                        break;
                    }
                }

            }
        }
예제 #15
0
    static void Main(string[] args)
    {
        byte gameFieldWidth = 30;
        uint livesCount     = 10; // This is the lives we have in the game.
        uint liveScore      = 0;  // This keeps the score.

        string[] randomColor = { "Gray",     "Blue",      "Green",       "Cyan",     "Red",     "Magenta", "Yellow", "White",
                                 "DarkBlue", "DarkGreen", "DarkMagenta", "DarkCyan", "DarkRed", "DarkYellow" };
        // An array of strings used to select a Random color further in the program.

        Console.BufferHeight = Console.WindowHeight = 20;
        Console.BufferWidth  = Console.WindowWidth = gameFieldWidth;
        // This sets the game area. Height and Width.

        // Initialize and define the Dwarf
        gameObject playerDwarf = new gameObject();

        playerDwarf.x     = 14;                         // This is the starting position of the Dwarf
        playerDwarf.y     = Console.WindowHeight - 1;
        playerDwarf.shape = "<O>";                      // Get the shape of the Dwarf
        playerDwarf.width = playerDwarf.shape.Length;   // Get the width of the Dwarf

        Random            randomRockGen = new Random(); // Initialize a random generator
        List <gameObject> rocks         = new List <gameObject>();

        // Initialize a list to hold the information about all of the falling rocks.

        while (true)
        // To ensure that the game never ends as long as the player plays without loosing all
        // of his lives, a while cycle is implemented.
        {
            {
                // Create a rock, set it's properties and add it to the List of falling rocks.
                gameObject newRock = new gameObject();
                liveScore++;
                newRock.color = (ConsoleColor)Enum.Parse(typeof(ConsoleColor), randomColor[randomRockGen.Next(0, 13)]);
                // Randomly pick a color for the new rock!
                newRock.x = randomRockGen.Next(1, gameFieldWidth);
                // It generates the rock a random position depending within the game field.
                newRock.y     = 1;                                         // It's starts falling from the top, as it should.
                newRock.shape = GetRandomString(randomRockGen.Next(1, 4)); // This is what it looks like.
                newRock.width = newRock.shape.Length;                      // The width of the rock.
                rocks.Add(newRock);                                        // It adds the newly created rock to the list "rocks".
            }

            Console.Clear(); // Clear the console, so it can be filled again.

            PrintOnPosition(0, 0, "Lives: " + livesCount, ConsoleColor.Cyan);
            PrintOnPosition(15, 0, "Score: " + liveScore, ConsoleColor.Cyan);
            // Display how many lives we have.

            foreach (gameObject rock in rocks)
            {
                PrintOnPosition(rock.x, rock.y, rock.shape, rock.color);
                // The cycle foreach draws every rock in the list of rocks.
            }


            while (Console.KeyAvailable)
            {
                ConsoleKeyInfo pressedKey = Console.ReadKey(true); // Gets which key is pressed, if any.
                while (Console.KeyAvailable)
                {
                    Console.ReadKey(true);                          // Ensures the smoothens of the game.
                }
                if (pressedKey.Key == ConsoleKey.LeftArrow)
                {
                    if (playerDwarf.x - 1 >= 0)
                    {
                        playerDwarf.x = playerDwarf.x - 1;
                    }
                }
                else if (pressedKey.Key == ConsoleKey.RightArrow)
                {
                    if (playerDwarf.x + 1 < gameFieldWidth - (playerDwarf.width))
                    {
                        playerDwarf.x = playerDwarf.x + 1;
                    }
                    // This ensures the player stays within the confines of the playing field.
                }
            }

            PrintOnPosition(playerDwarf.x, playerDwarf.y, playerDwarf.shape);
            // This draws the Dwarf.

            List <gameObject> newList = new List <gameObject>();
            for (int i = 0; i < rocks.Count; i++)
            {
                gameObject oldRock = rocks[i]; // It gets the "i" rock from the list of rocks.
                // Then assigns it to the oldRock object (structure).
                gameObject newRock = new gameObject();
                newRock.x     = oldRock.x;
                newRock.y     = oldRock.y + 1; // The rock has moved down.
                newRock.shape = oldRock.shape;
                newRock.color = oldRock.color;
                newRock.width = oldRock.width;
                // After all of the rocks are moved down and saved in the "NewList"
                // the new list becomes the old list and it's ready for the next cycle.


                if (((oldRock.y == playerDwarf.y) &&
                     !((playerDwarf.x + (playerDwarf.width - 1)) < (newRock.x)) ^
                     ((playerDwarf.x) > (newRock.x + (newRock.width - 1)))) && (oldRock.shape == "+"))
                // This checks if the Dwarf and the Rock crash
                {
                    livesCount++;
                    // If the crash is with a "+" rock then it gives you an additional life.
                }
                else if (((oldRock.y == playerDwarf.y) &&
                          !((playerDwarf.x + (playerDwarf.width - 1)) < (newRock.x)) ^
                          ((playerDwarf.x) > (newRock.x + (newRock.width - 1)))) && (oldRock.shape == "$"))
                {
                    // If you catch a dollar sign you'll get 100 points.
                    liveScore = liveScore + 100;
                }
                else if ((oldRock.y == playerDwarf.y) &&
                         !((playerDwarf.x + (playerDwarf.width - 1)) < (newRock.x)) ^
                         ((playerDwarf.x) > (newRock.x + (newRock.width - 1))))
                {
                    // If you crash with anything other then a "+" or "$" rock it takes one life.
                    livesCount--;
                    if (livesCount == 0)
                    {
                        // If your lives run out,the program stops it's execution.
                        PrintOnPosition(10, 15, "GAME OVER!", ConsoleColor.Red);
                        Console.ReadLine();
                        return;
                    }
                }

                if (newRock.y < Console.WindowHeight) // Check if the new rock is within the game field.
                {
                    newList.Add(newRock);             // add the new rock to the new list
                }
            }
            rocks = newList;   // It gets the data from the new list of rocks after they've been moved.
            // Draw score
            Thread.Sleep(200); // Sets the game speed
        }
    }
 public virtual void OnCollision(gameObject ObjectCollidedWith)
 {
 }
예제 #17
0
 // SortingLayerとOrderを設定する
 _view.SetSortingLayerAndOrder(gameObject, level, orderType);
예제 #18
0
        public static void handleNewConnection(TcpClient client)
        {
            // username of active connection
            string username = "";

            // Username of person they are playing against
            string usernameOpponent = "";

            try
            {
                // get streams
                StreamReader reader = new StreamReader(client.GetStream());
                StreamWriter writer = new StreamWriter(client.GetStream());

                Console.Write("New Delegate created to handle new connection.\n");

                gameObject myGame = new gameObject();
                myGame.lastPlayed = new lastMove[1];

                // Setup where the command data will be stored
                string[] command;

                // Read in from the socket here
                string recieve;

                // While logged in, recieve and process data
                bool loggedIn = true;

                // Does this user have an active game?
                bool isActive = false;

                // Last line of chatroom that has been sent to client
                int lastLine = 0;

                // Recieve input
                do
                {
                    // Read in from socket
                    recieve = reader.ReadLine();

                    command = recieve.Split(' ');

                    // Switch based on command recieved
                    switch (command[0])
                    {
                    // Login to the server
                    // Expected string "LOGIN username"
                    case "LOGIN":
                        if (command.Length == 2)
                        {
                            username = command[1];
                            Console.WriteLine("Logging in " + username);
                            // make sure there are usernames to check
                            if (userNames.Count > 0)
                            {
                                // search in use usernames for the desired username
                                foreach (string user in userNames)
                                {
                                    // if username already in list, it's already in use, thus log them out
                                    if (user == username)
                                    {
                                        loggedIn = false;
                                        writer.WriteLine("FALSE");
                                        writer.Flush();
                                        break;
                                    }
                                }
                            }
                            if (loggedIn)
                            {
                                // if still logged in (i.e. not been logged out because username in use)
                                // add username to the list of usernames in use
                                userNames.Add(username);
                                writer.WriteLine("TRUE");
                                writer.Flush();
                            }
                            else
                            {
                                writer.WriteLine("FALSE");
                                writer.Flush();
                            }
                        }
                        else
                        {
                            // If command login command isn't what was expected let the player know
                            writer.WriteLine("FALSE");
                            writer.Flush();
                        }
                        break;

                    // Start New Game
                    // Expected string "NEW username_of_other_player"
                    case "NEW":
                        if (loggedIn)
                        {
                            bool foundOtherGame = false;
                            usernameOpponent = command[1];
                            // search all games for a game that matches the state I'm expecting
                            foreach (gameObject game in gamesInPlay)
                            {
                                // if game I'm looking for
                                if (game.playerOne == username && game.playerTwo == usernameOpponent)
                                {
                                    writer.WriteLine("EXIST");
                                    writer.Flush();
                                    foundOtherGame = true;
                                    break;
                                }
                            }
                            if (!foundOtherGame)
                            {
                                myGame.boardGame = generateDefaultBoard();
                                myGame.playerOne = username;
                                usernameOpponent = command[1];
                                myGame.playerTwo = usernameOpponent;
                                myGame.lastPlayed[0].recievedMove = true;
                                isActive        = true;
                                myGame.chatRoom = new List <string>();
                                gamesInPlay.Add(myGame);
                                writer.WriteLine("TRUE");
                                writer.Flush();
                            }
                        }
                        else
                        {
                            writer.WriteLine("FALSE");
                            writer.Flush();
                        }
                        break;

                    // Join a game (other player needs to be expecting user)
                    // Expected string "JOIN username_of_other_player"
                    case "JOIN":
                        if (loggedIn)
                        {
                            bool found = false;
                            Console.WriteLine("ISFINDING");
                            // set opponent username
                            usernameOpponent = command[1];
                            // search all games for a game that matches the state I'm expecting
                            foreach (gameObject game in gamesInPlay)
                            {
                                // if game I'm looking for
                                Console.WriteLine("P1: " + game.playerOne + " P2: " + game.playerTwo);
                                if (game.playerOne == usernameOpponent && game.playerTwo == username && game.isJoined == false)
                                {
                                    found = true;

                                    // add game to my game
                                    myGame = game;
                                    gamesInPlay.ToArray()[gamesInPlay.IndexOf(game)].isJoined = true;
                                    isActive = true;
                                    Console.WriteLine("ISJOINED");
                                    writer.WriteLine("TRUE");
                                    writer.Flush();
                                    break;
                                }
                                else if (game.isJoined == true)
                                {
                                    writer.WriteLine("FALSE");
                                    writer.Flush();
                                }
                            }
                            if (!found)
                            {
                                writer.WriteLine("FALSE");
                                writer.Flush();
                            }
                        }
                        break;

                    // Move a chess piece
                    // Expecting string "MOVE x1 y1 x2 y2"
                    case "MOVE":
                        if (isActive)
                        {
                            // Add moves to last played structure for other player to use
                            myGame.lastPlayed[0].xOrigin = Convert.ToInt32(command[1]);
                            myGame.lastPlayed[0].yOrigin = Convert.ToInt32(command[2]);
                            myGame.lastPlayed[0].xMoved  = Convert.ToInt32(command[3]);
                            myGame.lastPlayed[0].yMoved  = Convert.ToInt32(command[4]);
                            // flag that I'm the last player
                            myGame.lastPlayed[0].lastPlayer = username;
                            // flag the state as readable by other player
                            myGame.lastPlayed[0].recievedMove = false;
                            // update the game state
                            // move the piece
                            myGame.boardGame[myGame.lastPlayed[0].xMoved, myGame.lastPlayed[0].yMoved]
                                = myGame.boardGame[myGame.lastPlayed[0].xOrigin, myGame.lastPlayed[0].yOrigin];
                            // clear old square
                            myGame.boardGame[myGame.lastPlayed[0].xOrigin, myGame.lastPlayed[0].yOrigin]
                                = new gameSquare {
                                colour = chessmanColour.empty, piece = chessman.empty
                                };
                        }
                        break;

                    // Get new moves that have been made
                    case "GETMOVE":
                        if (isActive)
                        {
                            if (myGame.lastPlayed[0].lastPlayer != username && !myGame.lastPlayed[0].recievedMove)
                            {
                                // flag the state as unreadable by the player
                                myGame.lastPlayed[0].recievedMove = true;
                                writer.WriteLine("MOVE " + myGame.lastPlayed[0].xOrigin.ToString() + " "
                                                 + myGame.lastPlayed[0].yOrigin.ToString() + " "
                                                 + myGame.lastPlayed[0].xMoved.ToString() + " "
                                                 + myGame.lastPlayed[0].yMoved.ToString());
                                writer.Flush();
                            }
                            else
                            {
                                writer.WriteLine("NOMOVE");
                                writer.Flush();
                            }
                        }
                        break;

                    // logout from the server
                    case "LOGOUT":
                        if (loggedIn)
                        {
                            Console.WriteLine("Logging out " + username);

                            // logout
                            loggedIn = false;
                            // remove username from list of active users
                            userNames.Remove(username);
                            //Clear the game
                            foreach (gameObject game in gamesInPlay)
                            {
                                // if game I'm looking for
                                if (game.playerOne == username && game.playerTwo == usernameOpponent)
                                {
                                    gamesInPlay.Remove(game);
                                    break;
                                }
                            }
                        }
                        else
                        {
                            loggedIn = false;
                        }
                        break;

                    // print gamestate to console. It's really more of a debug option
                    case "PRINT":
                        if (isActive)
                        {
                            for (int i = 0; i < 8; i++)
                            {
                                for (int j = 0; j < 8; j++)
                                {
                                    switch (myGame.boardGame[i, j].piece)
                                    {
                                    case chessman.Bishop:
                                        Console.Write("B ");
                                        break;

                                    case chessman.King:
                                        Console.Write("K ");
                                        break;

                                    case chessman.Knight:
                                        Console.Write("N ");
                                        break;

                                    case chessman.Pawn:
                                        Console.Write("P ");
                                        break;

                                    case chessman.Queen:
                                        Console.Write("Q ");
                                        break;

                                    case chessman.Rook:
                                        Console.Write("R ");
                                        break;

                                    default:
                                        Console.Write("  ");
                                        break;
                                    }
                                }
                                Console.WriteLine("");
                            }
                        }
                        break;

                    // Get new messages that are in the chatroom
                    case "GET":
                        if (isActive)
                        {
                            if (lastLine < myGame.chatRoom.Count)
                            {
                                // send all unread messages
                                writer.WriteLine(myGame.chatRoom[lastLine]);
                                lastLine++;
                                writer.Flush();
                            }
                            else
                            {
                                writer.WriteLine("");
                                writer.Flush();
                            }
                        }

                        break;

                    // default, any other string sent will be posted to the chatroom
                    default:
                        if (isActive)
                        {
                            string connectedString = "";
                            for (int i = 0; i < command.Length; i++)
                            {
                                // catnate the command string to allow spaces to reform
                                connectedString = connectedString + " " + command[i];
                            }
                            // add line to chatroom
                            myGame.chatRoom.Add(username + ": " + connectedString);
                        }
                        break;
                    }
                } while (loggedIn);
            }
            catch (Exception E) {
                Console.WriteLine("Exception " + E.GetType());
                Console.WriteLine("Removing  " + username + " from active users.");

                // remove username from list of active users
                userNames.Remove(username);
                foreach (gameObject game in gamesInPlay)
                {
                    // if game I'm looking for
                    if (game.playerOne == username && game.playerTwo == usernameOpponent)
                    {
                        gamesInPlay.Remove(game);
                        break;
                    }
                }
            }
        }
 public override void OnCollision(gameObject ObjectCollidedWith)
 {
 }
    static void Main(string[] args)
    {
        byte gameFieldWidth = 30;
        uint livesCount = 10; // This is the lives we have in the game.
        uint liveScore = 0; // This keeps the score.
        string[] randomColor = { "Gray", "Blue", "Green", "Cyan", "Red", "Magenta", "Yellow", "White",
        "DarkBlue","DarkGreen","DarkMagenta","DarkCyan","DarkRed","DarkYellow"};
        // An array of strings used to select a Random color further in the program.

        Console.BufferHeight = Console.WindowHeight = 20;
        Console.BufferWidth = Console.WindowWidth = gameFieldWidth;
        // This sets the game area. Height and Width.

        // Initialize and define the Dwarf
        gameObject playerDwarf = new gameObject();
        playerDwarf.x = 14; // This is the starting position of the Dwarf
        playerDwarf.y = Console.WindowHeight - 1;
        playerDwarf.shape = "<O>"; // Get the shape of the Dwarf
        playerDwarf.width = playerDwarf.shape.Length; // Get the width of the Dwarf

        Random randomRockGen = new Random(); // Initialize a random generator
        List<gameObject> rocks = new List<gameObject>();
        // Initialize a list to hold the information about all of the falling rocks.

        while(true)
        // To ensure that the game never ends as long as the player plays without loosing all
        // of his lives, a while cycle is implemented.
        {
            {
                // Create a rock, set it's properties and add it to the List of falling rocks.
                gameObject newRock = new gameObject();
                liveScore++;
                newRock.color = (ConsoleColor)Enum.Parse(typeof(ConsoleColor), randomColor[randomRockGen.Next(0, 13)]);
                // Randomly pick a color for the new rock!
                newRock.x = randomRockGen.Next(1, gameFieldWidth);
                // It generates the rock a random position depending within the game field.
                newRock.y = 1; // It's starts falling from the top, as it should.
                newRock.shape = GetRandomString(randomRockGen.Next(1, 4)) ; // This is what it looks like.
                newRock.width = newRock.shape.Length; // The width of the rock.
                rocks.Add(newRock); // It adds the newly created rock to the list "rocks".
            }

            Console.Clear(); // Clear the console, so it can be filled again.

            PrintOnPosition(0, 0, "Lives: " + livesCount, ConsoleColor.Cyan);
            PrintOnPosition(15, 0, "Score: " + liveScore, ConsoleColor.Cyan);
            // Display how many lives we have.

            foreach (gameObject rock in rocks)
            {
                PrintOnPosition(rock.x, rock.y, rock.shape, rock.color);
                // The cycle foreach draws every rock in the list of rocks.
            }

            while (Console.KeyAvailable)
            {
                ConsoleKeyInfo pressedKey = Console.ReadKey(true); // Gets which key is pressed, if any.
                while (Console.KeyAvailable) Console.ReadKey(true); // Ensures the smoothens of the game.
                if (pressedKey.Key == ConsoleKey.LeftArrow)
                {
                    if (playerDwarf.x - 1 >= 0)
                    {
                        playerDwarf.x = playerDwarf.x - 1;
                    }
                }
                else if (pressedKey.Key == ConsoleKey.RightArrow)
                {
                    if (playerDwarf.x + 1 < gameFieldWidth - (playerDwarf.width))
                    {
                        playerDwarf.x = playerDwarf.x + 1;
                    }
                // This ensures the player stays within the confines of the playing field.
                }
            }

            PrintOnPosition(playerDwarf.x, playerDwarf.y, playerDwarf.shape);
            // This draws the Dwarf.

            List<gameObject> newList = new List<gameObject>();
            for (int i = 0; i < rocks.Count; i++)
            {
                gameObject oldRock = rocks[i]; // It gets the "i" rock from the list of rocks.
                // Then assigns it to the oldRock object (structure).
                gameObject newRock = new gameObject();
                newRock.x = oldRock.x;
                newRock.y = oldRock.y + 1; // The rock has moved down.
                newRock.shape = oldRock.shape;
                newRock.color = oldRock.color;
                newRock.width = oldRock.width;
                // After all of the rocks are moved down and saved in the "NewList"
                // the new list becomes the old list and it's ready for the next cycle.

                if (((oldRock.y == playerDwarf.y) &&
                        !((playerDwarf.x + (playerDwarf.width - 1)) < (newRock.x)) ^
                        ((playerDwarf.x) > (newRock.x + (newRock.width - 1)))) && (oldRock.shape == "+"))
                // This checks if the Dwarf and the Rock crash
                {
                     livesCount++;
                    // If the crash is with a "+" rock then it gives you an additional life.
                }
                else if (((oldRock.y == playerDwarf.y) &&
                       !((playerDwarf.x + (playerDwarf.width - 1)) < (newRock.x)) ^
                       ((playerDwarf.x) > (newRock.x + (newRock.width - 1)))) && (oldRock.shape == "$"))
                {
                    // If you catch a dollar sign you'll get 100 points.
                    liveScore = liveScore + 100;

                }
                else if ((oldRock.y == playerDwarf.y) &&
                        !((playerDwarf.x + (playerDwarf.width - 1)) < (newRock.x)) ^
                        ((playerDwarf.x) > (newRock.x + (newRock.width - 1))))
                {
                    // If you crash with anything other then a "+" or "$" rock it takes one life.
                    livesCount--;
                    if (livesCount == 0)
                    {
                        // If your lives run out,the program stops it's execution.
                        PrintOnPosition(10, 15, "GAME OVER!", ConsoleColor.Red);
                        Console.ReadLine();
                        return;
                    }
                }

                if (newRock.y < Console.WindowHeight) // Check if the new rock is within the game field.
                {
                    newList.Add(newRock); // add the new rock to the new list
                }

            }
            rocks = newList; // It gets the data from the new list of rocks after they've been moved.
            // Draw score
            Thread.Sleep(200); // Sets the game speed
        }
    }
예제 #21
0
        private static void HandleCmd(Socket handler, String userId, String userCmd, String userArg)
        {
            String resp = "UNKN";

            switch (userCmd)
            {
            case "UREG":
            {
                if (players.Any(u => u.Equals(userId, StringComparison.OrdinalIgnoreCase)))
                {
                    resp = "USER EXISTS";
                }
                else
                {
                    players.Add(userId);
                    resp = "OKAY";
                }
            } break;

            case "EXIT":
            {
                gameObject jGame;

                try {
                    jGame = games.Single(g => g.gameState.IndexOf(userId) >= 0);

                    string[] frags = jGame.gameState.Split("|");

                    if (frags[2].Equals(userId))
                    {
                        frags[2] = "";
                    }
                    if (frags[1].Equals(userId))
                    {
                        frags[1] = "";
                    }
                    if (frags[0].Equals(userId))
                    {
                        frags[0] = "";
                    }

                    if (string.IsNullOrWhiteSpace(frags[1]) && string.IsNullOrWhiteSpace(frags[2]))
                    {
                        games.Remove(jGame);
                    }
                    else
                    {
                        jGame.gameState = string.Join("|", frags);
                    }

                    inGame.Remove(userId);
                } catch (Exception) { }

                players.Remove(userId);

                resp = "OKAY";
            } break;

            case "LSPL":
            {
                resp = "OKAY " + string.Join('~', players);
            } break;

            case "LSGS":
            {
                resp = "OKAY " + string.Join('~', games.Select(g => g.gameState));
            } break;

            case "NEWG":
            {
                UInt64     gId   = gIndex++;
                gameObject nGame = new gameObject(gId, userArg);

                games.Add(nGame);
                inGame.Add(userId, gId);

                resp = "OKAY";
            } break;

            case "JOIN":
            {
                string[]   frags;
                gameObject jGame;

                // Remove this user from any currently in progress games before we let them join any other game
                try {
                    jGame = games.Single(g => g.gameState.IndexOf(userId) >= 0);
                    frags = jGame.gameState.Split("|");

                    if (frags[0].Equals(userId))
                    {
                        frags[0] = "";
                    }
                    if (frags[1].Equals(userId))
                    {
                        frags[1] = "";
                    }
                    if (frags[2].Equals(userId))
                    {
                        frags[2] = "";
                    }

                    if (string.IsNullOrWhiteSpace(frags[1]) && string.IsNullOrWhiteSpace(frags[2]))
                    {
                        games.Remove(jGame);
                    }
                    else
                    {
                        jGame.gameState = string.Join("|", frags);
                    }

                    inGame.Remove(userId);
                }
                catch (Exception) { }


                try {
                    jGame = games.Single(g => g.gameState.IndexOf(userArg) >= 0);
                } catch (Exception e) { resp = "E: Failed to find game " + e.ToString(); break; }

                frags = jGame.gameState.Split("|");

                if (string.IsNullOrEmpty(frags[0]))
                {
                    frags[0] = userId;
                }
                if (string.IsNullOrEmpty(frags[1]))
                {
                    frags[1] = userId;
                    inGame.Add(userId, jGame.gameId);
                    resp = "OKAY " + jGame.gameState;
                }
                else if (string.IsNullOrEmpty(frags[2]))
                {
                    frags[2] = userId;
                    inGame.Add(userId, jGame.gameId);
                    resp = "OKAY " + jGame.gameState;
                }
                else
                {
                    resp = "WARN Game is full";
                }

                jGame.gameState = string.Join("|", frags);
            } break;

            case "QUIT":
            {
                gameObject jGame;

                try {
                    jGame = games.Single(g => g.gameState.IndexOf(userId) >= 0);
                } catch (Exception e) { resp = "E: Failed to find game " + e.ToString(); break; }

                string[] frags = jGame.gameState.Split("|");

                if (frags[0].Equals(userId))
                {
                    frags[0] = "";
                }
                if (frags[1].Equals(userId))
                {
                    frags[1] = "";
                }
                if (frags[2].Equals(userId))
                {
                    frags[2] = "";
                }

                if (string.IsNullOrWhiteSpace(frags[1]) && string.IsNullOrWhiteSpace(frags[2]))
                {
                    games.Remove(jGame);
                }
                else
                {
                    jGame.gameState = string.Join("|", frags);
                }

                inGame.Remove(userId);

                resp = "OKAY";
            } break;

            case "SEND":
            {
                UInt64     iGameIdx = inGame[userId];
                gameObject iGame;

                try {
                    iGame = games.Single(g => g.gameId == iGameIdx);
                } catch (Exception e) { resp = "E: Failed to find game " + e.ToString(); break; }

                string[] fragsCur = iGame.gameState.Split("|");
                string[] fragsNew = userArg.Split("|");

                if (string.IsNullOrEmpty(fragsCur[1]))
                {
                    if (fragsNew[0].Equals(fragsNew[1]))
                    {
                        fragsNew[0] = "";
                    }
                    fragsNew[1] = "";
                }
                else if (string.IsNullOrEmpty(fragsCur[2]))
                {
                    if (fragsNew[0].Equals(fragsNew[2]))
                    {
                        fragsNew[0] = "";
                    }
                    fragsNew[2] = "";
                }

                iGame.gameState = string.Join("|", fragsNew);

                resp = "OKAY";
            } break;

            case "RECV":
            {
                UInt64     iGameIdx = inGame[userId];
                gameObject iGame;

                try {
                    iGame = games.Single(g => g.gameId == iGameIdx);
                } catch (Exception e) { resp = "E: Failed to find game " + e.ToString(); break; }

                resp = "OKAY " + iGame.gameState;
            } break;
            }

            switch (userCmd)
            {
            case "RECV":
            case "LSPL":
            case "LSGS":
            {
            } break;

            default:
            {
                Console.WriteLine($"{userId}: {userCmd} {userArg}");
                Console.WriteLine($"SERV: {userCmd} for {userId}: {resp}");
            } break;
            }

            Send(handler, resp);
        }