Advertisement
Old_But_Gold

Battleship logic

Jan 5th, 2025 (edited)
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.91 KB | None | 0 0
  1. using System.Text;
  2.  
  3. namespace AaDS.Games;
  4.  
  5. public class BattleShip
  6. {
  7.     private readonly ulong _ships;
  8.     private ulong _shots;
  9.  
  10.     //bit mask of ships location like 0b11110000_00000111_00000000_00110000_00000010_01000000_00000000_00000000
  11.     public BattleShip(ulong ships) => _ships = ships;
  12.    
  13.     public bool Shoot(string shot)
  14.     {
  15.         int index = ConvertShotToIndex();
  16.  
  17.         ulong shotBit = (ulong) 1L << index;
  18.         _shots |= shotBit;
  19.  
  20.         return (_ships & shotBit) != 0;
  21.        
  22.         int ConvertShotToIndex()
  23.         {
  24.             if (shot is not { Length: 2 })
  25.             {
  26.                 throw new ArgumentException("Invalid shot format");
  27.             }
  28.  
  29.             char row = shot[0];
  30.             char column = shot[1];
  31.  
  32.             int rowIndex = 7 - (row - 'A'); // инверсия
  33.             int colIndex = 7 - (column - '1'); // инверсия
  34.  
  35.             if (rowIndex < 0 || rowIndex > 7 || colIndex < 0 || colIndex > 7)
  36.             {
  37.                 throw new ArgumentException("Invalid shot format");
  38.             }
  39.  
  40.             return rowIndex + colIndex * 8;
  41.         }
  42.     }
  43.  
  44.     public string State()
  45.     {
  46.         StringBuilder result = new();
  47.  
  48.         for (int i = 0; i < 64; i++)
  49.         {
  50.             var cell = GetCellState(i);
  51.  
  52.             result.Append(cell);
  53.  
  54.             if (i % 8 == 7)
  55.             {
  56.                 result.Append('\n');
  57.             }
  58.         }
  59.  
  60.         return result.ToString();
  61.        
  62.         char GetCellState(int index)
  63.         {
  64.             ulong mask = (ulong) 1L << (63 - index); // инверсия
  65.  
  66.             bool hasShip = (_ships & mask) != 0;
  67.             bool hasShot = (_shots & mask) != 0;
  68.  
  69.             return hasShip switch
  70.             {
  71.                 true when hasShot => '☒',
  72.                 true => '☐',
  73.                 _ => hasShot ? '×' : '.'
  74.             };
  75.         }
  76.     }
  77. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement