Guest User

khjhjk

a guest
Sep 17th, 2022
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 9.71 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Net;
  5. using System.Net.Sockets;
  6. using System.Text;
  7. using System.Text.Json;
  8. using System.Threading;
  9. using Microsoft.Xna.Framework;
  10. using Microsoft.Xna.Framework.Graphics;
  11. using Microsoft.Xna.Framework.Input;
  12.  
  13. namespace BuildingMultiplayer;
  14. public class Game1 : Game
  15. {
  16.     private GraphicsDeviceManager _graphics;
  17.     private SpriteBatch _spriteBatch;
  18.  
  19.     Point placeholderPos;
  20.     Point blockSize = new(24, 24);
  21.     Dictionary<Point, Texture2D> blocks = new();
  22.  
  23.     Texture2D tileTexture;
  24.     Texture2D andreyTexture;
  25.     Texture2D currentTexture;
  26.  
  27.     Texture2D[] textures;
  28.  
  29.     public TcpClient client;
  30.     public NetworkStream onlStr;
  31.     const int PORT = 14092;
  32.     const string IP = "127.0.0.1";
  33.  
  34.     bool existsAt = false;
  35.     bool paused = false;
  36.     bool online = false;
  37.  
  38.     public Game1()
  39.     {
  40.         _graphics = new GraphicsDeviceManager(this);
  41.         Content.RootDirectory = "Content";
  42.         IsMouseVisible = true;
  43.         Deactivated += (sender, ev) =>
  44.         {
  45.             paused = true;
  46.         };
  47.         Activated += (sender, ev) =>
  48.         {
  49.             paused = false;
  50.         };
  51.     }
  52.  
  53.     protected override void Initialize()
  54.     {
  55.         // TODO: Add your initialization logic here
  56.         placeholderPos = new(-blockSize.X, -blockSize.Y);
  57.         try
  58.         {
  59.             client = new(IP, PORT);
  60.             client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
  61.             onlStr = client.GetStream();
  62.  
  63.             Thread receiveThread = new(ReceiveThread);
  64.             receiveThread.Start();
  65.  
  66.             online = true;
  67.         }
  68.         catch (Exception ex)
  69.         {
  70.             System.Windows.Forms.MessageBox.Show("Unable to connect to server.\nException: \n" + ex.ToString() + "\nGame will be offline");
  71.         }
  72.  
  73.         base.Initialize();
  74.     }
  75.  
  76.     protected override void LoadContent()
  77.     {
  78.         _spriteBatch = new SpriteBatch(GraphicsDevice);
  79.  
  80.         // TODO: use this.Content to load your game content here
  81.         tileTexture = Content.Load<Texture2D>("Tile");
  82.         andreyTexture = Content.Load<Texture2D>("Tile2");
  83.         currentTexture = tileTexture;
  84.         textures = new Texture2D[]
  85.         {
  86.             tileTexture,
  87.             andreyTexture
  88.         };
  89.     }
  90.  
  91.     protected override void UnloadContent()
  92.     {
  93.         base.UnloadContent();
  94.     }
  95.  
  96.     protected override void Update(GameTime gameTime)
  97.     {
  98.         if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
  99.             Exit();
  100.  
  101.         if (paused)
  102.             return;
  103.  
  104.         // TODO: Add your update logic here
  105.         float x = MathF.Round(Mouse.GetState().X / blockSize.X) * blockSize.X;
  106.         float y = MathF.Round(Mouse.GetState().Y / blockSize.Y) * blockSize.Y;
  107.  
  108.         placeholderPos = new Vector2(x, y).ToPoint();
  109.  
  110.         if (blocks.ContainsKey(placeholderPos))
  111.         {
  112.             existsAt = true;
  113.         }
  114.         else
  115.         {
  116.             existsAt = false;
  117.         }
  118.  
  119.         if (Keyboard.GetState().IsKeyDown(Keys.D1))
  120.             currentTexture = textures[0];
  121.         else if (Keyboard.GetState().IsKeyDown(Keys.D2))
  122.             currentTexture = textures[1];
  123.  
  124.        
  125.  
  126.         if (Keyboard.GetState().IsKeyDown(Keys.LeftControl) && Keyboard.GetState().IsKeyDown(Keys.S))
  127.         {
  128.             ExportMap();
  129.         }
  130.         else if (Keyboard.GetState().IsKeyDown(Keys.LeftControl) && Keyboard.GetState().IsKeyDown(Keys.O))
  131.         {
  132.             LoadMap();
  133.         }
  134.  
  135.         if (Keyboard.GetState().IsKeyDown(Keys.Back))
  136.         {
  137.             blocks.Clear();
  138.         }
  139.  
  140.         if (Mouse.GetState().LeftButton == ButtonState.Pressed && !existsAt)
  141.         {
  142.             blocks.Add(placeholderPos, currentTexture);
  143.             if (online)
  144.             {
  145.                 try
  146.                 {
  147.                     string data = string.Format("set {0} {1}", StringFromPoint(placeholderPos), currentTexture);
  148.                     byte[] byteData = Encoding.UTF8.GetBytes(data);
  149.                     onlStr.Write(byteData, 0, byteData.Length);
  150.                 }
  151.                 catch (Exception ex)
  152.                 {
  153.                     System.Windows.Forms.MessageBox.Show("Unable to send request.\nException:\n" + ex.ToString());
  154.                 }
  155.             }
  156.         }
  157.         else if (Mouse.GetState().LeftButton == ButtonState.Pressed && existsAt && blocks[placeholderPos] != currentTexture)
  158.         {
  159.             blocks[placeholderPos] = currentTexture;
  160.         }
  161.         if (Mouse.GetState().RightButton == ButtonState.Pressed && existsAt)
  162.         {
  163.             if (blocks.ContainsKey(placeholderPos))
  164.                 blocks.Remove(placeholderPos);
  165.         }
  166.  
  167.         base.Update(gameTime);
  168.     }
  169.  
  170.     protected override void Draw(GameTime gameTime)
  171.     {
  172.         GraphicsDevice.Clear(Color.CornflowerBlue);
  173.  
  174.         // TODO: Add your drawing code here
  175.         _spriteBatch.Begin();
  176.  
  177.         foreach (var block in blocks.Keys)
  178.         {
  179.             _spriteBatch.Draw(blocks[block], new Rectangle(block, blockSize), null, Color.White, 0, Vector2.Zero, SpriteEffects.None, 1);
  180.         }
  181.  
  182.         Color placeholderColor = new(0, 0, 255, 50);
  183.  
  184.         if (existsAt && blocks.ContainsKey(placeholderPos))
  185.         {
  186.             if (blocks[placeholderPos] != currentTexture)
  187.                 placeholderColor = new((int) Color.Yellow.R, Color.Yellow.G, Color.Yellow.B, 50);
  188.             else
  189.                 placeholderColor = new(255, 0, 0, 50);
  190.         }
  191.         else if (existsAt)
  192.             placeholderColor = new(255, 0, 0, 50);
  193.  
  194.         _spriteBatch.Draw(currentTexture, new Rectangle(placeholderPos, blockSize), null, placeholderColor, 0, Vector2.Zero, SpriteEffects.None, 1);
  195.  
  196.         _spriteBatch.Draw(currentTexture, new Rectangle(new Point(Window.ClientBounds.Width - 24, 24), new Point(36, 36)), null, Color.White, 0, new(currentTexture.Width, 0), SpriteEffects.None, 1);
  197.  
  198.         _spriteBatch.End();
  199.  
  200.         base.Draw(gameTime);
  201.     }
  202.     void ProcessMessage(string msg)
  203.     {
  204.         string[] split = msg.Split(' ');
  205.  
  206.         if (split[0] == "msg" && split.Length >= 4)
  207.         {
  208.             Point pos = PointFromString(string.Format("{0} {1}", split[1], split[2]));
  209.             if (int.TryParse(split[3], out int id))
  210.             {
  211.                 if (id < 0 || id > textures.Length - 1)
  212.                     return;
  213.  
  214.                 if (!blocks.ContainsKey(pos))
  215.                 {
  216.                     blocks.Add(pos, textures[id]);
  217.                 }
  218.                 else if (blocks[pos] != textures[id])
  219.                 {
  220.                     blocks[pos] = textures[id];
  221.                 }
  222.             }
  223.         }
  224.         else if (split[0] == "rem" && split.Length >= 3)
  225.         {
  226.             Point pos = PointFromString(string.Format("{0} {1}", split[1], split[2]));
  227.             if (blocks.ContainsKey(pos))
  228.                 blocks.Remove(pos);
  229.         }
  230.     }
  231.  
  232.     void ExportMap()
  233.     {
  234.         using System.Windows.Forms.SaveFileDialog saveFileDialog = new()
  235.         {
  236.             Filter = "JSON Map Document|*.json",
  237.             Title = "Export map"
  238.         };
  239.  
  240.         if (saveFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
  241.         {
  242.             try
  243.             {
  244.                 Map map = new();
  245.                 foreach (var block in blocks.Keys)
  246.                 {
  247.                     map.Blocks.Add(StringFromPoint(block), Array.IndexOf(textures, blocks[block]));
  248.                 }
  249.                 File.WriteAllText(saveFileDialog.FileName, JsonSerializer.Serialize(map));
  250.             }
  251.             catch (Exception ex)
  252.             {
  253.                 System.Windows.Forms.MessageBox.Show(ex.ToString());
  254.             }
  255.         }
  256.     }
  257.     void LoadMap()
  258.     {
  259.         using System.Windows.Forms.OpenFileDialog openFileDialog = new()
  260.         {
  261.             Filter = "JSON Map Document|*.json",
  262.             Title = "Load map"
  263.         };
  264.  
  265.         if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
  266.         {
  267.             try
  268.             {
  269.                 blocks.Clear();
  270.                 Map map = JsonSerializer.Deserialize<Map>(File.ReadAllText(openFileDialog.FileName));
  271.                 foreach (var block in map.Blocks.Keys)
  272.                 {
  273.                     blocks.Add(PointFromString(block), textures[map.Blocks[block]]);
  274.                 }
  275.             }
  276.             catch (Exception ex)
  277.             {
  278.                 System.Windows.Forms.MessageBox.Show(ex.ToString());
  279.             }
  280.         }
  281.     }
  282.  
  283.     string StringFromPoint(Point point)
  284.     {
  285.         return string.Format("{0} {1}", point.X, point.Y);
  286.     }
  287.     Point PointFromString(string str)
  288.     {
  289.         string[] xyPos = str.Split(' ');
  290.  
  291.         if (int.TryParse(xyPos[0], out int x) && int.TryParse(xyPos[1], out int y))
  292.         {
  293.             return new(x, y);
  294.         }
  295.  
  296.         return Point.Zero;
  297.     }
  298.  
  299.     void ReceiveThread()
  300.     {
  301.         try
  302.         {
  303.             do
  304.             {
  305.                 byte[] bytes = new byte[256];
  306.                 onlStr.Read(bytes, 0, bytes.Length);
  307.                 string data = Encoding.UTF8.GetString(bytes, 0, bytes.Length);
  308.                 ProcessMessage(data);
  309.                 byte[] anotherBytes = Encoding.UTF8.GetBytes(data);
  310.                 onlStr.Write(anotherBytes, 0, anotherBytes.Length);
  311.             }
  312.             while (onlStr.DataAvailable);
  313.         }
  314.         catch (Exception)
  315.         {
  316.             Exit();
  317.         }
  318.     }
  319.  
  320.     class Map
  321.     {
  322.         public Dictionary<string, int> Blocks { get; set; } = new();
  323.     }
  324.  
  325.  
  326. }
  327.  
Advertisement
Add Comment
Please, Sign In to add comment