Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Net;
- using System.Net.Sockets;
- using System.Text;
- using System.Text.Json;
- using System.Threading;
- using Microsoft.Xna.Framework;
- using Microsoft.Xna.Framework.Graphics;
- using Microsoft.Xna.Framework.Input;
- namespace BuildingMultiplayer;
- public class Game1 : Game
- {
- private GraphicsDeviceManager _graphics;
- private SpriteBatch _spriteBatch;
- Point placeholderPos;
- Point blockSize = new(24, 24);
- Dictionary<Point, Texture2D> blocks = new();
- Texture2D tileTexture;
- Texture2D andreyTexture;
- Texture2D currentTexture;
- Texture2D[] textures;
- public TcpClient client;
- public NetworkStream onlStr;
- const int PORT = 14092;
- const string IP = "127.0.0.1";
- bool existsAt = false;
- bool paused = false;
- bool online = false;
- public Game1()
- {
- _graphics = new GraphicsDeviceManager(this);
- Content.RootDirectory = "Content";
- IsMouseVisible = true;
- Deactivated += (sender, ev) =>
- {
- paused = true;
- };
- Activated += (sender, ev) =>
- {
- paused = false;
- };
- }
- protected override void Initialize()
- {
- // TODO: Add your initialization logic here
- placeholderPos = new(-blockSize.X, -blockSize.Y);
- try
- {
- client = new(IP, PORT);
- client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
- onlStr = client.GetStream();
- Thread receiveThread = new(ReceiveThread);
- receiveThread.Start();
- online = true;
- }
- catch (Exception ex)
- {
- System.Windows.Forms.MessageBox.Show("Unable to connect to server.\nException: \n" + ex.ToString() + "\nGame will be offline");
- }
- base.Initialize();
- }
- protected override void LoadContent()
- {
- _spriteBatch = new SpriteBatch(GraphicsDevice);
- // TODO: use this.Content to load your game content here
- tileTexture = Content.Load<Texture2D>("Tile");
- andreyTexture = Content.Load<Texture2D>("Tile2");
- currentTexture = tileTexture;
- textures = new Texture2D[]
- {
- tileTexture,
- andreyTexture
- };
- }
- protected override void UnloadContent()
- {
- base.UnloadContent();
- }
- protected override void Update(GameTime gameTime)
- {
- if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
- Exit();
- if (paused)
- return;
- // TODO: Add your update logic here
- float x = MathF.Round(Mouse.GetState().X / blockSize.X) * blockSize.X;
- float y = MathF.Round(Mouse.GetState().Y / blockSize.Y) * blockSize.Y;
- placeholderPos = new Vector2(x, y).ToPoint();
- if (blocks.ContainsKey(placeholderPos))
- {
- existsAt = true;
- }
- else
- {
- existsAt = false;
- }
- if (Keyboard.GetState().IsKeyDown(Keys.D1))
- currentTexture = textures[0];
- else if (Keyboard.GetState().IsKeyDown(Keys.D2))
- currentTexture = textures[1];
- if (Keyboard.GetState().IsKeyDown(Keys.LeftControl) && Keyboard.GetState().IsKeyDown(Keys.S))
- {
- ExportMap();
- }
- else if (Keyboard.GetState().IsKeyDown(Keys.LeftControl) && Keyboard.GetState().IsKeyDown(Keys.O))
- {
- LoadMap();
- }
- if (Keyboard.GetState().IsKeyDown(Keys.Back))
- {
- blocks.Clear();
- }
- if (Mouse.GetState().LeftButton == ButtonState.Pressed && !existsAt)
- {
- blocks.Add(placeholderPos, currentTexture);
- if (online)
- {
- try
- {
- string data = string.Format("set {0} {1}", StringFromPoint(placeholderPos), currentTexture);
- byte[] byteData = Encoding.UTF8.GetBytes(data);
- onlStr.Write(byteData, 0, byteData.Length);
- }
- catch (Exception ex)
- {
- System.Windows.Forms.MessageBox.Show("Unable to send request.\nException:\n" + ex.ToString());
- }
- }
- }
- else if (Mouse.GetState().LeftButton == ButtonState.Pressed && existsAt && blocks[placeholderPos] != currentTexture)
- {
- blocks[placeholderPos] = currentTexture;
- }
- if (Mouse.GetState().RightButton == ButtonState.Pressed && existsAt)
- {
- if (blocks.ContainsKey(placeholderPos))
- blocks.Remove(placeholderPos);
- }
- base.Update(gameTime);
- }
- protected override void Draw(GameTime gameTime)
- {
- GraphicsDevice.Clear(Color.CornflowerBlue);
- // TODO: Add your drawing code here
- _spriteBatch.Begin();
- foreach (var block in blocks.Keys)
- {
- _spriteBatch.Draw(blocks[block], new Rectangle(block, blockSize), null, Color.White, 0, Vector2.Zero, SpriteEffects.None, 1);
- }
- Color placeholderColor = new(0, 0, 255, 50);
- if (existsAt && blocks.ContainsKey(placeholderPos))
- {
- if (blocks[placeholderPos] != currentTexture)
- placeholderColor = new((int) Color.Yellow.R, Color.Yellow.G, Color.Yellow.B, 50);
- else
- placeholderColor = new(255, 0, 0, 50);
- }
- else if (existsAt)
- placeholderColor = new(255, 0, 0, 50);
- _spriteBatch.Draw(currentTexture, new Rectangle(placeholderPos, blockSize), null, placeholderColor, 0, Vector2.Zero, SpriteEffects.None, 1);
- _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);
- _spriteBatch.End();
- base.Draw(gameTime);
- }
- void ProcessMessage(string msg)
- {
- string[] split = msg.Split(' ');
- if (split[0] == "msg" && split.Length >= 4)
- {
- Point pos = PointFromString(string.Format("{0} {1}", split[1], split[2]));
- if (int.TryParse(split[3], out int id))
- {
- if (id < 0 || id > textures.Length - 1)
- return;
- if (!blocks.ContainsKey(pos))
- {
- blocks.Add(pos, textures[id]);
- }
- else if (blocks[pos] != textures[id])
- {
- blocks[pos] = textures[id];
- }
- }
- }
- else if (split[0] == "rem" && split.Length >= 3)
- {
- Point pos = PointFromString(string.Format("{0} {1}", split[1], split[2]));
- if (blocks.ContainsKey(pos))
- blocks.Remove(pos);
- }
- }
- void ExportMap()
- {
- using System.Windows.Forms.SaveFileDialog saveFileDialog = new()
- {
- Filter = "JSON Map Document|*.json",
- Title = "Export map"
- };
- if (saveFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
- {
- try
- {
- Map map = new();
- foreach (var block in blocks.Keys)
- {
- map.Blocks.Add(StringFromPoint(block), Array.IndexOf(textures, blocks[block]));
- }
- File.WriteAllText(saveFileDialog.FileName, JsonSerializer.Serialize(map));
- }
- catch (Exception ex)
- {
- System.Windows.Forms.MessageBox.Show(ex.ToString());
- }
- }
- }
- void LoadMap()
- {
- using System.Windows.Forms.OpenFileDialog openFileDialog = new()
- {
- Filter = "JSON Map Document|*.json",
- Title = "Load map"
- };
- if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
- {
- try
- {
- blocks.Clear();
- Map map = JsonSerializer.Deserialize<Map>(File.ReadAllText(openFileDialog.FileName));
- foreach (var block in map.Blocks.Keys)
- {
- blocks.Add(PointFromString(block), textures[map.Blocks[block]]);
- }
- }
- catch (Exception ex)
- {
- System.Windows.Forms.MessageBox.Show(ex.ToString());
- }
- }
- }
- string StringFromPoint(Point point)
- {
- return string.Format("{0} {1}", point.X, point.Y);
- }
- Point PointFromString(string str)
- {
- string[] xyPos = str.Split(' ');
- if (int.TryParse(xyPos[0], out int x) && int.TryParse(xyPos[1], out int y))
- {
- return new(x, y);
- }
- return Point.Zero;
- }
- void ReceiveThread()
- {
- try
- {
- do
- {
- byte[] bytes = new byte[256];
- onlStr.Read(bytes, 0, bytes.Length);
- string data = Encoding.UTF8.GetString(bytes, 0, bytes.Length);
- ProcessMessage(data);
- byte[] anotherBytes = Encoding.UTF8.GetBytes(data);
- onlStr.Write(anotherBytes, 0, anotherBytes.Length);
- }
- while (onlStr.DataAvailable);
- }
- catch (Exception)
- {
- Exit();
- }
- }
- class Map
- {
- public Dictionary<string, int> Blocks { get; set; } = new();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment