public void Play()
        {
            Console.WriteLine($"Battleships board: A1:{(char)('A' + Grid.Size - 1)}{Grid.Size}");
            while (Grid.AnyShipAlive())
            {
                Console.Write("Shot:");
                string pos = Console.ReadLine().ToUpper();
                if (pos.Length >= 2)
                {
                    char col = pos[0];
                    Int32.TryParse(pos.Substring(1), out int row);

                    int x = col - 'A';
                    int y = row - 1;
                    if (x >= 0 && x < Grid.Size && y >= 0 && y < Grid.Size)
                    {
                        ShotResult shotResult = Grid.Shot(x, y);
                        Console.WriteLine(shotResult);
                    }
                    else
                    {
                        Console.WriteLine("Point outside of the Battleship board.");
                    }
                }
                else
                {
                    Console.WriteLine("Invalid input.");
                }
            }
            Console.WriteLine("Game Over. All Battleships sinked!");
        }
        public String getXMLString()
        {
            String result = "<gamePacket type=\"" + type;

            switch (type)
            {
            case TYPE.GAME_RESULT:
                result += "\">" + GameResult.ToXMLString(gameResult);
                break;

            case TYPE.RESULT:
                result += "\">" + ShotResult.ToXMLString(shotResult);
                break;

            case TYPE.SHOT:
                result += "\">" + Coordinates.ToXMLString(coordinates);
                break;

            case TYPE.TEXT_MESSAGE:
                result += "\" message=\"" + message + "\"/>";
                return(result);

            case TYPE.WHO_STARTS:
                result += "\" whoStarts=\"" + (whoStarts == Global.HOST_FIRST ? "host" : "client") + "\"/>";
                return(result);

            default:
                result += "\"/>";
                return(result);
            }

            result += "</gamePacket>";

            return(result);
        }
Example #3
0
        private static string GetMessageBasedOnResult(ShotResult shotResult)
        {
            switch (shotResult)
            {
            case ShotResult.Hit: return("A ship was hit!");

            case ShotResult.Miss: return("That was a miss");

            case ShotResult.Sink: return("A ship has sunk!");
            }

            return("No idea about the result..");
        }
Example #4
0
        private static string GetShotResult(ShotResult result)
        {
            switch (result)
            {
                case ShotResult.Miss:
                    return ".";
                case ShotResult.Hit:
                    return "x";
                case ShotResult.HitAndSunk:
                    return "X";
            }

            return " ";
        }
Example #5
0
        public void ShotResult(ShotResult shotResult)
        {
            int  x      = shotResult.getCoordinates().X;
            int  y      = shotResult.getCoordinates().Y;
            bool result = shotResult.isHit();

            if (result)
            {
                ships[x, y].State = Ship.ShipState.HIT;
            }
            else
            {
                ships[x, y].State = Ship.ShipState.MISSED;
            }
        }
        public static String ToXMLString(ShotResult shotResult)
        {
            String result = "<shotResult isNull=\"";
            if (shotResult == null)
                result += "true\"";
            else
            {
                result += "false\"";
                result += " isHit=\"" + (shotResult.isHit() ? "true" : "false") + "\"";
                result += " isSunk=\"" + (shotResult.isSunk() ? "true" : "false") + "\"";
                result += " isGameEnded=\"" + (shotResult.isGameEnded() ? "true" : "false") + "\"";
                result += " matrix=\"";
                result += ((shotResult.getMatrix() == null) ? "null" : Global.boolArrayToString(shotResult.getMatrix())) + "\"";
            }

            result += ">" + Coordinates.ToXMLString(shotResult.getCoordinates()) + "</shotResult>";
            return result;
        }
Example #7
0
        public static String ToXMLString(ShotResult shotResult)
        {
            String result = "<shotResult isNull=\"";

            if (shotResult == null)
            {
                result += "true\"";
            }
            else
            {
                result += "false\"";
                result += " isHit=\"" + (shotResult.isHit() ? "true" : "false") + "\"";
                result += " isSunk=\"" + (shotResult.isSunk() ? "true" : "false") + "\"";
                result += " isGameEnded=\"" + (shotResult.isGameEnded() ? "true" : "false") + "\"";
                result += " matrix=\"";
                result += ((shotResult.getMatrix() == null) ? "null" : Global.boolArrayToString(shotResult.getMatrix())) + "\"";
            }

            result += ">" + Coordinates.ToXMLString(shotResult.getCoordinates()) + "</shotResult>";
            return(result);
        }
        /// <summary>
        /// Starts the game loop.
        /// </summary>
        /// <param name="gridManager">The <see cref="GridManager" /> which handles the game.</param>
        /// <param name="ioManager">An object specifying how the I/O should be handled.</param>
        public static void Run(GridManager gridManager, IIOManager ioManager)
        {
            ioManager.WriteLine(
                "\t\tBATTLESHIP by ANONYMOUS SOLUTIONS INC.{0}{0}" +
                "You are given a square {1}x{1} grid. The individual squares in the grid{0}" +
                "are identified by letter and number, e.g. A5. Several ships have been{0}" +
                "secretly arranged. Each ship occupies a number of consecutive squares{0}" +
                "on the grid, arranged either horizontally or vertically. The ships can{0}" +
                "touch each other and cannot overlap. The fleet consists of {2} ship(s).{0}" +
                "Your task is to sink them all.{0}",
                Environment.NewLine,
                GridManager.GridSize,
                gridManager.ShipsCount);

            ioManager.WriteLine(gridManager.DisplayShips(false));

            while (true)
            {
                ioManager.Write("Enter target square to shoot at: ");

                string command = ioManager.ReadLine();
                if (command == GridManager.BackdoorCommand)
                {
                    ioManager.WriteLine(gridManager.DisplayShips(true));
                }
                else
                {
                    ShotResult shotResult = gridManager.ShootTarget(command);

                    DisplayShotResult(gridManager, ioManager, shotResult);
                    if (shotResult == ShotResult.AllShipsSunk)
                    {
                        return;
                    }

                    ioManager.WriteLine(gridManager.DisplayShips(false));
                }
            }
        }
        public static GamePacket deserialize(String packetString)
        {
            GamePacket packet = null;

            GamePacket.TYPE type        = GamePacket.TYPE.UNDEFINED;
            String          message     = null;
            Coordinates     coordinates = null;
            bool            whoStarts   = false;
            ShotResult      shotResult  = null;
            GameResult      gameResult  = null;

            bool[,] matrix = null;
            bool isHit       = false;
            bool isSunk      = false;
            bool isGameEnded = false;

            XmlTextReader textReader = new XmlTextReader(new StringReader(packetString));

            textReader.Read();
            //Console.WriteLine("deserialization is ready to start:\n" + packetString);
            while (textReader.Read())
            {
                if (textReader.NodeType == XmlNodeType.Element)
                {
                    if (textReader.Name.Equals("gamePacket"))
                    {
                        String typeString = textReader.GetAttribute("type");
                        if (typeString.Equals("WHO_STARTS"))
                        {
                            type      = GamePacket.TYPE.WHO_STARTS;
                            whoStarts = textReader.GetAttribute("whoStarts").Equals("host") ? Global.HOST_FIRST : Global.CLIENT_FIRST;
                            packet    = new GamePacket(whoStarts);
                        }
                        else if (typeString.Equals("TEXT_MESSAGE"))
                        {
                            type    = GamePacket.TYPE.TEXT_MESSAGE;
                            message = textReader.GetAttribute("message");
                            packet  = new GamePacket(message);
                        }
                        else if (typeString.Equals("SHOT"))
                        {
                            type = GamePacket.TYPE.SHOT;
                        }
                        else if (typeString.Equals("RESULT"))
                        {
                            type = GamePacket.TYPE.RESULT;
                        }
                        else if (typeString.Equals("GAME_RESULT"))
                        {
                            type = GamePacket.TYPE.GAME_RESULT;
                        }
                    }
                    else if (textReader.Name.Equals("shotResult") && textReader.GetAttribute("isNull").Equals("false"))
                    {
                        isHit       = Boolean.Parse(textReader.GetAttribute("isHit"));
                        isSunk      = Boolean.Parse(textReader.GetAttribute("isSunk"));
                        isGameEnded = Boolean.Parse(textReader.GetAttribute("isGameEnded"));
                        String matrixStr = textReader.GetAttribute("matrix");
                        if (!matrixStr.Equals("null"))
                        {
                            matrix = Global.stringToBoolArray(matrixStr);
                        }
                    }
                    else if (textReader.Name.Equals("coordinates") && textReader.GetAttribute("isNull").Equals("false"))
                    {
                        int x = Int32.Parse(textReader.GetAttribute("x"));
                        int y = Int32.Parse(textReader.GetAttribute("y"));
                        coordinates = Coordinates.Get(x, y);
                    }
                    else if (textReader.Name.Equals("gameResult") && textReader.GetAttribute("isNull").Equals("false"))
                    {
                        gameResult = new GameResult(textReader.GetAttribute("result").Equals("winner") ? Global.GAME_RESULT_WINNER : Global.GAME_RESULT_LOOSER);
                    }
                }
                else if (textReader.NodeType == XmlNodeType.EndElement)
                {
                    if (textReader.Name.Equals("gamePacket"))
                    {
                        switch (type)
                        {
                        case GamePacket.TYPE.GAME_RESULT:
                            packet = new GamePacket(gameResult);
                            break;

                        case GamePacket.TYPE.RESULT:
                            packet = new GamePacket(shotResult);
                            break;

                        case GamePacket.TYPE.SHOT:
                            packet = new GamePacket(coordinates);
                            break;

                        case GamePacket.TYPE.TEXT_MESSAGE:
                            packet = new GamePacket(message);
                            break;

                        case GamePacket.TYPE.WHO_STARTS:
                            packet = new GamePacket(whoStarts);
                            break;

                        default:
                            break;
                        }
                    }
                    else if (textReader.Name.Equals("shotResult"))
                    {
                        shotResult = new ShotResult(isHit, isSunk, isGameEnded, coordinates, matrix);
                    }
                }
            }

            return(packet);
        }
Example #10
0
 /// <summary>
 /// Displays a string depending on the specified ShotResult.
 /// </summary>
 /// <param name="gridManager">The <see cref="GridManager" /> which handles the game.</param>
 /// <param name="ioManager">An object specifying how the I/O should be handled.</param>
 /// <param name="value">The value to display.</param>
 public static void DisplayShotResult(GridManager gridManager, IIOManager ioManager, ShotResult value)
 {
     switch (value)
     {
         case ShotResult.Hit:
             {
                 ioManager.WriteLine("\t*** Hit ***");
                 break;
             }
         case ShotResult.ShipSunk:
             {
                 ioManager.WriteLine("\t*** Sunk ***");
                 break;
             }
         case ShotResult.AllShipsSunk:
             {
                 ioManager.WriteLine("Well done! You completed the game in {0} shots.", gridManager.ShotsCount);
                 break;
             }
         case ShotResult.Miss:
             {
                 ioManager.WriteLine("\t*** Miss ***");
                 break;
             }
         case ShotResult.Error:
             {
                 ioManager.WriteLine("\t*** Error ***");
                 break;
             }
         default:
             {
                 throw new BattleshipException("Unknown ShotResult.");
             }
     }
 }
        public static GamePacket deserialize(String packetString)
        {
            GamePacket packet = null;
            GamePacket.TYPE type = GamePacket.TYPE.UNDEFINED;
            String message = null;
            Coordinates coordinates = null;
            bool whoStarts = false;
            ShotResult shotResult = null;
            GameResult gameResult = null;
            bool[,] matrix = null;
            bool isHit = false;
            bool isSunk = false;
            bool isGameEnded = false;

            XmlTextReader textReader = new XmlTextReader(new StringReader(packetString));
            textReader.Read();
            //Console.WriteLine("deserialization is ready to start:\n" + packetString);
            while (textReader.Read())
            {
                if (textReader.NodeType == XmlNodeType.Element)
                {
                    if (textReader.Name.Equals("gamePacket"))
                    {
                        String typeString = textReader.GetAttribute("type");
                        if (typeString.Equals("WHO_STARTS"))
                        {
                            type = GamePacket.TYPE.WHO_STARTS;
                            whoStarts = textReader.GetAttribute("whoStarts").Equals("host") ? Global.HOST_FIRST : Global.CLIENT_FIRST;
                            packet = new GamePacket(whoStarts);
                        }
                        else if (typeString.Equals("TEXT_MESSAGE"))
                        {
                            type = GamePacket.TYPE.TEXT_MESSAGE;
                            message = textReader.GetAttribute("message");
                            packet = new GamePacket(message);
                        }
                        else if (typeString.Equals("SHOT"))
                        {
                            type = GamePacket.TYPE.SHOT;
                        }
                        else if (typeString.Equals("RESULT"))
                        {
                            type = GamePacket.TYPE.RESULT;
                        }
                        else if (typeString.Equals("GAME_RESULT"))
                        {
                            type = GamePacket.TYPE.GAME_RESULT;
                        }
                    }
                    else if (textReader.Name.Equals("shotResult") && textReader.GetAttribute("isNull").Equals("false"))
                    {
                        isHit = Boolean.Parse(textReader.GetAttribute("isHit"));
                        isSunk = Boolean.Parse(textReader.GetAttribute("isSunk"));
                        isGameEnded = Boolean.Parse(textReader.GetAttribute("isGameEnded"));
                        String matrixStr = textReader.GetAttribute("matrix");
                        if (!matrixStr.Equals("null"))
                            matrix = Global.stringToBoolArray(matrixStr);
                    }
                    else if (textReader.Name.Equals("coordinates") && textReader.GetAttribute("isNull").Equals("false"))
                    {
                        int x = Int32.Parse(textReader.GetAttribute("x"));
                        int y = Int32.Parse(textReader.GetAttribute("y"));
                        coordinates = Coordinates.Get(x, y);
                    }
                    else if (textReader.Name.Equals("gameResult") && textReader.GetAttribute("isNull").Equals("false"))
                    {
                        gameResult = new GameResult(textReader.GetAttribute("result").Equals("winner") ? Global.GAME_RESULT_WINNER : Global.GAME_RESULT_LOOSER);
                    }
                }
                else if (textReader.NodeType == XmlNodeType.EndElement)
                {
                    if (textReader.Name.Equals("gamePacket"))
                    {
                        switch (type)
                        {
                            case GamePacket.TYPE.GAME_RESULT:
                                packet = new GamePacket(gameResult);
                                break;
                            case GamePacket.TYPE.RESULT:
                                packet = new GamePacket(shotResult);
                                break;
                            case GamePacket.TYPE.SHOT:
                                packet = new GamePacket(coordinates);
                                break;
                            case GamePacket.TYPE.TEXT_MESSAGE:
                                packet = new GamePacket(message);
                                break;
                            case GamePacket.TYPE.WHO_STARTS:
                                packet = new GamePacket(whoStarts);
                                break;
                            default:
                                break;
                        }
                    }
                    else if (textReader.Name.Equals("shotResult"))
                    {
                        shotResult = new ShotResult(isHit, isSunk, isGameEnded, coordinates, matrix);
                    }
                }
            }

            return packet;
        }
Example #12
0
 public GamePacket(ShotResult result)
 {
     this.shotResult = result;
     type = TYPE.RESULT;
 }
Example #13
0
 public GamePacket(ShotResult result)
 {
     this.shotResult = result;
     type            = TYPE.RESULT;
 }
Example #14
0
 public void AddShot(CellCoords cell, ShotResult result)
 {
     //Console.Write("[{0}, {1}]:{2} ", cell.x, cell.y, GetShotResult(result));
     Console.Write(GetShotResult(result));
 }
Example #15
0
        private void ReceivingThreadStart()
        {
            System.Diagnostics.Debug.WriteLine("ReceivingThread started");
            GamePacket packet;

            gameIsEnded = false;
            while (!gameIsEnded)
            {
                Thread.Sleep(250);

                packet = wifiService.receive();
                if (packet != null)
                {
                    System.Diagnostics.Debug.WriteLine(packet.GetType() + " packt received:" + System.Environment.NewLine + GamePacketSerialization.serialize(packet));

                    if (packet.Type == GamePacket.TYPE.WHO_STARTS)
                    {
                        meStartFirst = packet.getWhoStarts() == Global.CLIENT_FIRST;
                        BeginInvoke(new MethodInvoker(delegate() { mainBoard.setShootable(meStartFirst); }));
                    }
                    else if (packet.Type == GamePacket.TYPE.USER_NAME)
                    {
                    }
                    else if (packet.Type == GamePacket.TYPE.SHOT)
                    {
                        BeginInvoke(new MethodInvoker(delegate()
                        {
                            ShotResult result = prevBoard.Shoot(packet.getCoordinates());
                            if (prevBoard.isGameEnded())
                            {
                                wifiService.send(new GamePacket(new GameResult(Global.GAME_RESULT_WINNER)));    // opponent is winner because he sunk all of my ships
                                EndGame(false);
                            }
                            else
                            {
                                wifiService.send(new GamePacket(result));
                                if (!result.isHit() || result.isSunk())
                                {
                                    BeginInvoke(new MethodInvoker(delegate() { mainBoard.setShootable(true); }));
                                }
                            }
                        }));
                    }
                    else if (packet.Type == GamePacket.TYPE.RESULT)
                    {
                        bool result = packet.getShotResult().isHit();
                        BeginInvoke(new MethodInvoker(delegate()
                        {
                            mainBoard.ShotResult(packet.getShotResult());
                            mainBoard.setShootable(result && !packet.getShotResult().isSunk());
                        }));

                        currentTarget = null;
                        if (packet.getShotResult().isSunk())
                        {
                            BeginInvoke(new MethodInvoker(delegate() { mainBoard.setShipSunk(packet.getShotResult().getMatrix()); }));
                        }
                    }
                    else if (packet.Type == GamePacket.TYPE.GAME_RESULT)
                    {
                        BeginInvoke(new MethodInvoker(delegate() { EndGame(packet.getGameResult().isWinner()); }));
                    }
                }
            }
        }
Example #16
0
        public void ShotResult(ShotResult shotResult)
        {
            int x = shotResult.getCoordinates().X;
            int y = shotResult.getCoordinates().Y;
            bool result = shotResult.isHit();

            if (result)
                ships[x, y].State = Ship.ShipState.HIT;
            else
                ships[x, y].State = Ship.ShipState.MISSED;
        }
        /// <summary>
        /// Displays a string depending on the specified ShotResult.
        /// </summary>
        /// <param name="gridManager">The <see cref="GridManager" /> which handles the game.</param>
        /// <param name="ioManager">An object specifying how the I/O should be handled.</param>
        /// <param name="value">The value to display.</param>
        public static void DisplayShotResult(GridManager gridManager, IIOManager ioManager, ShotResult value)
        {
            switch (value)
            {
            case ShotResult.Hit:
            {
                ioManager.WriteLine("\t*** Hit ***");
                break;
            }

            case ShotResult.ShipSunk:
            {
                ioManager.WriteLine("\t*** Sunk ***");
                break;
            }

            case ShotResult.AllShipsSunk:
            {
                ioManager.WriteLine("Well done! You completed the game in {0} shots.", gridManager.ShotsCount);
                break;
            }

            case ShotResult.Miss:
            {
                ioManager.WriteLine("\t*** Miss ***");
                break;
            }

            case ShotResult.Error:
            {
                ioManager.WriteLine("\t*** Error ***");
                break;
            }

            default:
            {
                throw new BattleshipException("Unknown ShotResult.");
            }
            }
        }