server_labytint/Program.cs
2025-09-22 12:19:54 +02:00

126 lines
3.8 KiB
C#

using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
class Player
{
public int Id;
public int Row;
public int Col;
public ConsoleColor Color;
public TcpClient Client;
}
class Server
{
static int[,] maze = new int[,]
{
{ 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },
{ 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1 },
{ 1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1 },
{ 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1 },
{ 1, 0, 1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1 },
{ 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1 },
{ 1, 1, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1 },
{ 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1 },
{ 1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1 },
{ 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 },
{ 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },
};
static List<Player> players = new List<Player>();
static Random rand = new Random();
static void Main()
{
TcpListener listener = new TcpListener(IPAddress.Any, 65500);
listener.Start();
Console.WriteLine("Server running...");
while (true)
{
TcpClient client = listener.AcceptTcpClient();
Thread t = new Thread(() => HandleClient(client));
t.Start();
}
}
static void HandleClient(TcpClient client)
{
Player player = new Player
{
Id = rand.Next(1000, 9999),
Row = 1,
Col = 5,
Color = (ConsoleColor)rand.Next(1, 15),
Client = client
};
lock (players) { players.Add(player); }
NetworkStream stream = client.GetStream();
byte[] buffer = new byte[1024];
while (true)
{
try
{
int read = stream.Read(buffer, 0, buffer.Length);
if (read == 0) break;
string move = Encoding.UTF8.GetString(buffer, 0, read);
int newRow = player.Row;
int newCol = player.Col;
if (move == "W") newRow--;
if (move == "S") newRow++;
if (move == "A") newCol--;
if (move == "D") newCol++;
if (maze[newRow, newCol] != 1)
{
player.Row = newRow;
player.Col = newCol;
}
SendMapToAll();
}
catch { break; }
}
lock (players) { players.Remove(player); }
client.Close();
}
static void SendMapToAll()
{
lock (players)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < maze.GetLength(0); i++)
{
for (int j = 0; j < maze.GetLength(1); j++)
{
var playerHere = players.Find(p => p.Row == i && p.Col == j);
if (playerHere != null)
sb.Append("00");
else if (maze[i, j] == 1)
sb.Append("██");
else if (maze[i, j] == 2)
sb.Append("XX");
else
sb.Append(" ");
}
sb.AppendLine();
}
byte[] data = Encoding.UTF8.GetBytes(sb.ToString());
foreach (var p in players)
{
try { p.Client.GetStream().Write(data, 0, data.Length); } catch { }
}
}
}
}