Merge branch 'master' into feature/playerList

This commit is contained in:
SemvdH
2020-10-23 12:53:35 +02:00
committed by GitHub
13 changed files with 522 additions and 214 deletions

View File

@@ -5,22 +5,31 @@ using System.Diagnostics;
using System.IO;
using System.Net.Sockets;
using System.Text;
using System.Windows.Media;
using System.Windows;
using static SharedClientServer.JSONConvert;
namespace Client
{
public delegate void LobbyCallback(int id);
public delegate void LobbyJoinCallback(bool isHost);
public delegate void RandomWord(string word);
public delegate void HandleIncomingMsg(string username, string msg);
internal delegate void HandleIncomingPlayer(Lobby lobby);
public delegate void CanvasDataReceived(double[][] coordinates, Color color);
public delegate void CanvasReset();
public delegate void LobbyCallback(int id);
class Client : ObservableObject
{
private ClientData clientData = ClientData.Instance;
private TcpClient tcpClient;
private NetworkStream stream;
private byte[] buffer = new byte[1024];
private byte[] totalBuffer = new byte[1024];
private byte[] buffer = new byte[2048];
private byte[] totalBuffer = new byte[2048];
private int totalBufferReceived = 0;
public int Port = 5555;
public bool Connected = false;
@@ -37,6 +46,8 @@ namespace Client
public HandleIncomingMsg IncomingMsg;
public HandleIncomingPlayer IncomingPlayer;
private ClientData data = ClientData.Instance;
public CanvasDataReceived CanvasDataReceived;
public CanvasReset CReset;
public Lobby[] Lobbies { get; set; }
public Client(string username)
@@ -68,6 +79,7 @@ namespace Client
private void OnReadComplete(IAsyncResult ar)
{
if (ar == null || (!ar.IsCompleted) || (!this.stream.CanRead) || !this.tcpClient.Client.Connected)
return;
@@ -75,11 +87,12 @@ namespace Client
{
int amountReceived = stream.EndRead(ar);
if (totalBufferReceived + amountReceived > 1024)
if (totalBufferReceived + amountReceived > 2048)
{
throw new OutOfMemoryException("buffer too small");
}
Array.Copy(buffer, 0, totalBuffer, totalBufferReceived, amountReceived);
totalBufferReceived += amountReceived;
@@ -91,7 +104,6 @@ namespace Client
byte[] message = new byte[expectedMessageLength];
// put the message received into the message array
Array.Copy(totalBuffer, 0, message, 0, expectedMessageLength);
handleData(message);
totalBufferReceived -= expectedMessageLength;
@@ -105,7 +117,6 @@ namespace Client
Debug.WriteLine("[CLIENT] server not responding! got error: " + e.Message);
OnServerDisconnect?.Invoke();
}
}
private void handleData(byte[] message)
@@ -169,7 +180,22 @@ namespace Client
case JSONConvert.CANVAS:
// canvas data
break;
//clientData.CanvasData = JSONConvert.getCoordinates(payload);
int type = JSONConvert.GetCanvasMessageType(payload);
switch (type)
{
case JSONConvert.CANVAS_RESET:
CReset?.Invoke();
break;
case JSONConvert.CANVAS_WRITING:
CanvasDataReceived?.Invoke(JSONConvert.getCoordinates(payload), JSONConvert.getCanvasDrawingColor(payload));
// we hebben gedrawed, dus stuur dat we weer kunnen drawen
break;
}
break;
case JSONConvert.RANDOMWORD:
//Flag byte for receiving the random word.

View File

@@ -31,6 +31,7 @@ namespace Client
private Client _client;
private Lobby _lobby;
private string _message;
private double[] _canvasData = new double[4];
private ClientData()
{
@@ -68,5 +69,11 @@ namespace Client
}
}
public double[] CanvasData
{
get { return _canvasData; }
set { _canvasData = value; }
}
}
}

View File

@@ -11,6 +11,9 @@ using System.Collections.ObjectModel;
using Client.Views;
using System.Linq;
using System.Windows.Data;
using System.Data;
using System.Windows.Controls.Primitives;
using System.Windows.Controls;
namespace Client
{
@@ -87,10 +90,16 @@ namespace Client
private void joinLobby()
{
// lobby die je wilt joinen verwijderen
// nieuwe binnengekregen lobby toevoegen
client.OnLobbyJoinSuccess = OnLobbyJoinSuccess;
client.SendMessage(JSONConvert.ConstructLobbyJoinMessage(SelectedLobby.ID));
if (SelectedLobby != null)
{
if (SelectedLobby.PlayersIn == SelectedLobby.MaxPlayers || !SelectedLobby.LobbyJoinable)
{
return;
}
client.OnLobbyJoinSuccess = OnLobbyJoinSuccess;
client.SendMessage(JSONConvert.ConstructLobbyJoinMessage(SelectedLobby.ID));
}
}
private void OnLobbyJoinSuccess(bool isHost)
@@ -166,5 +175,7 @@ namespace Client
get { return _lobbies; }
set { _lobbies = value; }
}
}
}

View File

@@ -1,14 +1,13 @@
using Client.Views;
using GalaSoft.MvvmLight;
using Client.Views;
using GalaSoft.MvvmLight.Command;
using SharedClientServer;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Timers;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Shapes;
@@ -17,25 +16,23 @@ namespace Client.ViewModels
{
class ViewModelGame : INotifyPropertyChanged
{
private ClientData data = ClientData.Instance;
public event PropertyChangedEventHandler PropertyChanged;
private ClientData data = ClientData.Instance;
private GameWindow window;
private Point currentPoint = new Point();
private Color color;
public Color color;
public double[][] buffer;
public int pos = 0;
public int maxLines = 50;
public Queue<double[][]> linesQueue;
private Timer queueTimer;
public ObservableCollection<string> Messages { get; } = new ObservableCollection<string>();
public static ObservableCollection<string> Messages { get; } = new ObservableCollection<string>();
public ObservableCollection<string> Players { get; } = new ObservableCollection<string>();
private dynamic _payload;
private string _randomWord;
public string RandomWord
{
get { return _randomWord; }
set { _randomWord = value; }
}
public string _username;
public string _message;
public string Message
@@ -50,7 +47,72 @@ namespace Client.ViewModels
}
}
private string _randomWord;
public string RandomWord
{
get { return _randomWord; }
set { _randomWord = value; }
}
public static string Word
{
get;
set;
}
public bool IsHost
{
get { return data.User.Host; }
}
public ViewModelGame(GameWindow window)
{
this.window = window;
if (_payload == null)
{
_message = "";
}
else
{
//_message = data.Message;
//_username = data.User.Username;
//Messages.Add($"{data.User.Username}: {Message}");
}
buffer = new double[maxLines][];
linesQueue = new Queue<double[][]>();
OnKeyDown = new RelayCommand(ChatBox_KeyDown);
ButtonStartGame = new RelayCommand(BeginGame);
ButtonResetCanvas = new RelayCommand(CanvasResetLocal);
data.Client.CanvasDataReceived = UpdateCanvasWithNewData;
data.Client.CReset = CanvasResetData;
data.Client.RandomWord = HandleRandomWord;
data.Client.IncomingMsg = HandleIncomingMsg;
data.Client.IncomingPlayer = HandleIncomingPlayer;
}
public ICommand OnKeyDown { get; set; }
public ICommand ButtonStartGame { get; set; }
public ICommand ButtonResetCanvas { get; set; }
public void BeginGame()
{
queueTimer = new Timer(50);
queueTimer.Start();
queueTimer.Elapsed += sendArrayFromQueue;
data.Client.SendMessage(JSONConvert.ConstructGameStartData(data.Lobby.ID));
}
private void CanvasResetLocal()
{
this.window.CanvasForPaint.Children.Clear();
data.Client.SendMessage(JSONConvert.GetMessageToSend(JSONConvert.CANVAS, JSONConvert.CANVAS_RESET));
}
public void Canvas_MouseDown(MouseButtonEventArgs e, GameWindow window)
{
@@ -78,9 +140,37 @@ namespace Client.ViewModels
coordinates[2] = line.X2;
coordinates[3] = line.Y2;
currentPoint = e.GetPosition(window.CanvasForPaint);
buffer[pos] = coordinates;
pos++;
window.CanvasForPaint.Children.Add(line);
data.Client.SendMessage(JSONConvert.GetMessageToSend(0x04, coordinates));
if (pos == maxLines)
{
double[][] temp = new double[maxLines][];
for (int i = 0; i < maxLines; i++)
{
temp[i] = buffer[i];
}
linesQueue.Enqueue(temp);
Array.Clear(buffer, 0, buffer.Length);
pos = 0;
}
}
}
public void Canvas_MouseUp(object sender, MouseButtonEventArgs e)
{
sendArrayFromQueue(sender, null);
}
private void sendArrayFromQueue(object sender, ElapsedEventArgs e)
{
if (linesQueue.Count != 0)
{
double[][] temp = linesQueue.Dequeue();
data.Client.SendMessage(JSONConvert.ConstructDrawingCanvasData(temp,color));
}
}
@@ -94,13 +184,26 @@ namespace Client.ViewModels
color = colorSelected;
}
public ViewModelGame()
private void UpdateCanvasWithNewData(double[][] buffer, Color color)
{
OnKeyDown = new RelayCommand(ChatBox_KeyDown);
data.Client.RandomWord = HandleRandomWord;
data.Client.IncomingMsg = HandleIncomingMsg;
data.Client.IncomingPlayer = HandleIncomingPlayer;
Application.Current.Dispatcher.Invoke(delegate
{
foreach (double[] arr in buffer)
{
Line line = new Line();
line.Stroke = new SolidColorBrush(color);
line.X1 = arr[0];
line.Y1 = arr[1];
line.X2 = arr[2];
line.Y2 = arr[3];
this.window.CanvasForPaint.Children.Add(line);
}
});
}
private void CanvasResetData()
{
this.window.CanvasForPaint.Children.Clear();
}
private void ChatBox_KeyDown()
@@ -110,49 +213,41 @@ namespace Client.ViewModels
Message = string.Empty;
}
internal void AddMessage(string incomingMessage)
internal void AddMessage(string message)
{
Messages.Add($"{data.User.Username}: {incomingMessage}");
Messages.Add($"{data.User.Username}: {message}");
_payload = new
{
username = data.User.Username,
message = incomingMessage
message = message
};
//Broadcast the message after adding it to the list!
data.Client.SendMessage(JSONConvert.GetMessageToSend(JSONConvert.MESSAGE, _payload));
}
/*
* MISC make this a callback
* Handles the incoming chat message from another client.
*/
public void HandleIncomingMsg(string username, string message)
public static void HandleIncomingMsg(string username, string message)
{
Application.Current.Dispatcher.Invoke(delegate
{
Messages.Add($"{username}: {message}");
});
}
public void LeaveGame(object sender, CancelEventArgs e)
public void LeaveGame(object sender, System.ComponentModel.CancelEventArgs e)
{
Debug.WriteLine("Leaving...");
Application.Current.Dispatcher.Invoke(delegate
{
Players.Remove(data.User.Username);
});
data.Client.SendMessage(JSONConvert.ConstructLobbyLeaveMessage(data.Lobby.ID));
}
/*
* Handles the random word that has been received from the server.
*/
public void HandleRandomWord(string randomWord)
public static void HandleRandomWord(string randomWord)
{
RandomWord = randomWord;
Debug.WriteLine($"[CLIENT] The random word is: {_randomWord}");
Debug.WriteLine("[CLIENT] Reached the handle random word method!");
Application.Current.Dispatcher.Invoke(delegate
{
Word = randomWord;
});
}
public void HandleIncomingPlayer(Lobby lobby)
{
Application.Current.Dispatcher.Invoke(delegate
@@ -166,4 +261,3 @@ namespace Client.ViewModels
}
}
}

View File

@@ -27,14 +27,29 @@
<ListBox Name="PlayerList" ItemsSource="{Binding Path=Players}" Margin="10,0,0,10" FontSize="20"/>
</Grid>
<Button Name="CanvasReset" Click="CanvasReset_Click" Grid.Row="0" Grid.Column="2" Margin="84,10,10,10" Content="RESET"/>
<Grid Grid.Row="0" Grid.Column="1">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="160"/>
<ColumnDefinition Width="160"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="100"/>
</Grid.ColumnDefinitions>
<Label Grid.Row="0" Grid.Column="0" VerticalAlignment="Center" FontSize="20" Content="Pick a color -->"/>
<xctk:ColorPicker Name="ClrPcker_Background" SelectedColorChanged="ClrPcker_Background_SelectedColorChanged_1" Grid.Column="1" HorizontalAlignment="Left" VerticalAlignment="Center" Height="22" Width="100"/>
<Label Name="GuessWord" Grid.Row="0" Grid.Column="1" Content="{Binding Path=RandomWord, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}" VerticalAlignment="Center" HorizontalAlignment="Center"/>
<xctk:ColorPicker Name="ClrPcker_Background" SelectedColorChanged="ClrPcker_Background_SelectedColorChanged_1" Grid.Column="1" HorizontalAlignment="Left" VerticalAlignment="Center" Height="22" Width="100"/>
<Label Grid.Row="0" Grid.Column="2" FontSize="20" Content="" VerticalAlignment="Center" HorizontalAlignment="Center"/>
<Button Name="CanvasReset" Click="CanvasReset_Click" Grid.Row="0" Grid.Column="3" Content="RESET"/>
</Grid>
<Button Name="StartGame" Grid.Row="0" Grid.Column="2" Content="Start Game" FontSize="20" Command="{Binding ButtonStartGame}" IsEnabled="{Binding IsHost}"/>
<Border Grid.Row="1" Grid.Column="1" Margin ="10,10,10,10" BorderBrush="Black" BorderThickness ="2.5">
<Canvas Name="CanvasForPaint" MouseDown="CanvasForPaint_MouseDown" MouseMove="CanvasForPaint_MouseMove">
<Canvas Name="CanvasForPaint" MouseDown="CanvasForPaint_MouseDown" MouseMove="CanvasForPaint_MouseMove" MouseUp="CanvasForPaint_MouseUp">
<Canvas.Background>
<SolidColorBrush Color="White" Opacity="0"/>
</Canvas.Background>

View File

@@ -15,7 +15,7 @@ namespace Client.Views
private ViewModelGame viewModel;
public GameWindow()
{
this.viewModel = new ViewModelGame();
this.viewModel = new ViewModelGame(this);
DataContext = this.viewModel;
Closing += this.viewModel.LeaveGame;
InitializeComponent();
@@ -36,16 +36,6 @@ namespace Client.Views
private void CanvasReset_Click(object sender, RoutedEventArgs e)
{
CanvasForPaint.Children.Clear();
//FOR FUTURE USE, IF NECCESSARY
//TEST.Children.Clear();
//foreach (UIElement child in CanvasForPaint.Children)
//{
// var xaml = System.Windows.Markup.XamlWriter.Save(child);
// var deepCopy = System.Windows.Markup.XamlReader.Parse(xaml) as UIElement;
// TEST.Children.Add(deepCopy);
//}
}
private void ClrPcker_Background_SelectedColorChanged_1(object sender, RoutedPropertyChangedEventArgs<Color?> e)
@@ -53,5 +43,9 @@ namespace Client.Views
viewModel.Color_Picker(e, this);
}
private void CanvasForPaint_MouseUp(object sender, MouseButtonEventArgs e)
{
viewModel.Canvas_MouseUp(sender, e);
}
}
}

View File

@@ -57,7 +57,8 @@
<GridView x:Name="grdList">
<GridViewColumn Header="Lobby ID" DisplayMemberBinding="{Binding ID}" Width="70"/>
<GridViewColumn Header="Players in" DisplayMemberBinding="{Binding PlayersIn}" Width="70"/>
<GridViewColumn Header="max players available" DisplayMemberBinding="{Binding MaxPlayers}"/>
<GridViewColumn Header="max players available" DisplayMemberBinding="{Binding MaxPlayers}" Width="150"/>
<GridViewColumn Header="joinable" DisplayMemberBinding="{Binding LobbyJoinable}"/>
</GridView>
</ListView.View>
</ListView>

View File

@@ -20,8 +20,8 @@ namespace Server.Models
{
private TcpClient tcpClient;
private NetworkStream stream;
private byte[] buffer = new byte[1024];
private byte[] totalBuffer = new byte[1024];
private byte[] buffer = new byte[2048];
private byte[] totalBuffer = new byte[2048];
private int totalBufferReceived = 0;
public User User { get; set; }
private ServerCommunication serverCom = ServerCommunication.INSTANCE;
@@ -54,7 +54,7 @@ namespace Server.Models
{
int bytesReceived = this.stream.EndRead(ar);
if (totalBufferReceived + bytesReceived > 1024)
if (totalBufferReceived + bytesReceived > 2048)
{
throw new OutOfMemoryException("buffer is too small!");
}
@@ -154,12 +154,49 @@ namespace Server.Models
LobbyIdentifier l = JSONConvert.GetLobbyIdentifier(payload);
handleLobbyMessage(payload, l);
break;
case JSONConvert.CANVAS:
Debug.WriteLine("GOT A MESSAGE FROM THE CLIENT ABOUT THE CANVAS!!!");
int typeToCheck = JSONConvert.GetCanvasMessageType(payload);
switch (typeToCheck)
{
case JSONConvert.CANVAS_WRITING:
dynamic canvasData = new
{
canvasType = typeToCheck,
coords = JSONConvert.getCoordinates(payload),
color = JSONConvert.getCanvasDrawingColor(payload)
};
serverCom.SendToLobby(serverCom.GetLobbyForUser(User),JSONConvert.GetMessageToSend(JSONConvert.CANVAS,canvasData));
break;
case JSONConvert.CANVAS_RESET:
dynamic canvasDataForReset = new
{
type = JSONConvert.GetCanvasMessageType(payload)
};
serverCom.SendToLobby(serverCom.GetLobbyForUser(User), JSONConvert.GetMessageToSend(CANVAS, canvasDataForReset));
break;
}
// canvas data
// todo send canvas data to all other serverclients in lobby
break;
case JSONConvert.GAME:
Debug.WriteLine("[SERVERCLIENT] Got a message about the game logic");
string command = JSONConvert.GetGameCommand(payload);
switch (command)
{
case "startGame":
int lobbyID = JSONConvert.GetStartGameLobbyID(payload);
serverCom.CloseALobby(lobbyID);
ServerCommunication.INSTANCE.sendToAll(JSONConvert.ConstructLobbyListMessage(ServerCommunication.INSTANCE.lobbies.ToArray()));
break;
}
break;
case JSONConvert.RANDOMWORD:
//Flag byte for receiving the random word.
break;
@@ -167,6 +204,7 @@ namespace Server.Models
// we now can send a new message
OnMessageReceivedOk?.Invoke();
break;
default:
Debug.WriteLine("[SERVER] Received weird identifier: " + id);
break;

View File

@@ -150,6 +150,21 @@ namespace Server.Models
}
}
public void SendCanvasDataToLobby(Lobby lobby, string username, byte[] message)
{
foreach (Lobby l in lobbies)
{
if (l == lobby)
{
foreach (ServerClient sc in serverClientsInlobbies[l])
{
sc.sendMessage(message);
}
break;
}
}
}
public Lobby GetLobbyForUser(User user)
{
foreach (Lobby l in lobbies)
@@ -255,5 +270,16 @@ namespace Server.Models
}
}
}
public void CloseALobby(int lobbyID)
{
foreach (Lobby lobby in lobbies)
{
if (lobby.ID == lobbyID)
{
lobby.LobbyJoinable = false;
}
}
}
}
}

View File

@@ -7,6 +7,8 @@ using System.Text;
namespace SharedClientServer
{
public delegate void Callback();
class ClientServerUtil
{
// creates a message array to send to the server or to clients

View File

@@ -1,5 +1,4 @@
using Client;
using Microsoft.VisualBasic.CompilerServices;
using Client;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
@@ -8,6 +7,7 @@ using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Media;
namespace SharedClientServer
{
@@ -17,8 +17,13 @@ namespace SharedClientServer
public const byte MESSAGE = 0x02;
public const byte LOBBY = 0x03;
public const byte CANVAS = 0x04;
public const byte RANDOMWORD = 0x05;
public const byte GAME = 0x05;
public const byte MESSAGE_RECEIVED = 0x06;
public const byte RANDOMWORD = 0x07;
public const int CANVAS_WRITING = 0;
public const int CANVAS_RESET = 1;
public enum LobbyIdentifier
{
@@ -29,9 +34,10 @@ namespace SharedClientServer
LIST,
REQUEST
}
public static (string,string) GetUsernameAndMessage(byte[] json)
{
string msg = Encoding.ASCII.GetString(json);
string msg = Encoding.UTF8.GetString(json);
dynamic payload = JsonConvert.DeserializeObject(msg);
return (payload.username, payload.message);
@@ -39,7 +45,7 @@ namespace SharedClientServer
public static string GetUsernameLogin(byte[] json)
{
dynamic payload = JsonConvert.DeserializeObject(Encoding.ASCII.GetString(json));
dynamic payload = JsonConvert.DeserializeObject(Encoding.UTF8.GetString(json));
return payload.username;
}
@@ -87,6 +93,7 @@ namespace SharedClientServer
});
}
public static byte[] ConstructLobbyJoinMessage(int lobbyID)
{
return GetMessageToSend(LOBBY, new
@@ -106,13 +113,13 @@ namespace SharedClientServer
}
public static LobbyIdentifier GetLobbyIdentifier(byte[] json)
{
dynamic payload = JsonConvert.DeserializeObject(Encoding.ASCII.GetString(json));
dynamic payload = JsonConvert.DeserializeObject(Encoding.UTF8.GetString(json));
return payload.identifier;
}
public static Lobby[] GetLobbiesFromMessage(byte[] json)
{
dynamic payload = JsonConvert.DeserializeObject(Encoding.ASCII.GetString(json));
dynamic payload = JsonConvert.DeserializeObject(Encoding.UTF8.GetString(json));
JArray lobbiesArray = payload.lobbies;
Debug.WriteLine("[JSONCONVERT] got lobbies from message" + lobbiesArray.ToString());
Lobby[] lobbiesTemp = lobbiesArray.ToObject<Lobby[]>();
@@ -126,13 +133,13 @@ namespace SharedClientServer
public static int GetLobbyID(byte[] json)
{
dynamic payload = JsonConvert.DeserializeObject(Encoding.ASCII.GetString(json));
dynamic payload = JsonConvert.DeserializeObject(Encoding.UTF8.GetString(json));
return payload.id;
}
public static Lobby GetLobby(byte[] json)
{
dynamic payload = JsonConvert.DeserializeObject(Encoding.ASCII.GetString(json));
dynamic payload = JsonConvert.DeserializeObject(Encoding.UTF8.GetString(json));
JObject dynamicAsObject = payload.lobby;
return dynamicAsObject.ToObject<Lobby>();
}
@@ -145,11 +152,79 @@ namespace SharedClientServer
public static bool GetLobbyJoinIsHost(byte[] json)
{
dynamic payload = JsonConvert.DeserializeObject(Encoding.ASCII.GetString(json));
dynamic payload = JsonConvert.DeserializeObject(Encoding.UTF8.GetString(json));
return payload.host;
}
#endregion
public static byte[] ConstructCanvasDataSend(int typeToSend, double[][] buffer, Color colorToSend)
{
return GetMessageToSend(CANVAS, new
{
canvasType = typeToSend,
coords = buffer,
color = colorToSend
}); ;
}
public static byte[] ConstructDrawingCanvasData(double[][] buffer, Color colorToSend)
{
return GetMessageToSend(CANVAS, new
{
canvasType = CANVAS_WRITING,
coords = buffer,
color = colorToSend
});
}
public static int GetCanvasMessageType(byte[] json)
{
dynamic d = JsonConvert.DeserializeObject(Encoding.UTF8.GetString(json));
return d.canvasType;
}
public static double[][] getCoordinates(byte[] payload)
{
Debug.WriteLine("got coords " + Encoding.UTF8.GetString(payload));
dynamic json = JsonConvert.DeserializeObject(Encoding.UTF8.GetString(payload));
JArray coordinatesArray = json.coords;
double[][] coordinates = coordinatesArray.ToObject<double[][]>();
return coordinates;
}
public static Color getCanvasDrawingColor(byte[] payload)
{
dynamic json = JsonConvert.DeserializeObject(Encoding.UTF8.GetString(payload));
Color color = json.color;
return color;
}
public static byte[] ConstructGameStartData(int lobbyID)
{
string startGame = "startGame";
return GetMessageToSend(GAME, new
{
command = startGame,
lobbyToStart = lobbyID
}); ;
}
public static string GetGameCommand(byte[] payload)
{
dynamic json = JsonConvert.DeserializeObject(Encoding.UTF8.GetString(payload));
return json.command;
}
public static int GetStartGameLobbyID(byte[] payload)
{
dynamic json = JsonConvert.DeserializeObject(Encoding.UTF8.GetString(payload));
return json.lobbyToStart;
}
/// <summary>
/// constructs a message that can be sent to the clients or server
/// </summary>
@@ -159,7 +234,8 @@ namespace SharedClientServer
public static byte[] GetMessageToSend(byte identifier, dynamic payload)
{
// convert the dynamic to bytes
byte[] payloadBytes = Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(payload));
string json = JsonConvert.SerializeObject(payload);
byte[] payloadBytes = Encoding.UTF8.GetBytes(json);
// make the array that holds the message and copy the payload into it with the first spot containing the identifier
byte[] res = new byte[payloadBytes.Length + 5];
// put the payload in the res array
@@ -171,7 +247,7 @@ namespace SharedClientServer
return res;
}
/*
/*
* This method sends a random word from the json file, this happens when the client joins a lobby.
*/
public static string SendRandomWord(string filename)
@@ -204,5 +280,7 @@ namespace SharedClientServer
dynamic payload = JsonConvert.DeserializeObject(Encoding.ASCII.GetString(json));
return payload.word;
}
}
}

View File

@@ -14,6 +14,7 @@ namespace Client
private int _id;
private int _playersIn;
private int _maxPlayers;
private bool _lobbyJoinable;
//private List<string> _usernames;
private List<User> _users;
@@ -34,6 +35,7 @@ namespace Client
_maxPlayers = maxPlayers;
//_usernames = new List<string>();
_users = new List<User>();
_lobbyJoinable = true;
}
public void AddUser(string username, out bool succes)
@@ -41,7 +43,7 @@ namespace Client
succes = false;
if (_users.Count < _maxPlayers)
{
_users.Add(new User(username, 0, false));
_users.Add(new User(username, 0, false, false));
succes = true;
}
}
@@ -87,6 +89,11 @@ namespace Client
set { _users = value; }
}
public bool LobbyJoinable
{
get { return _lobbyJoinable; }
set { _lobbyJoinable = value; }
}
}
}

View File

@@ -11,14 +11,16 @@ namespace SharedClientServer
private string _username;
private int _score;
private bool _host;
private bool _turnToDraw;
private string _message;
[JsonConstructor]
public User(string username, int score, bool host)
public User(string username, int score, bool host, bool turnToDraw)
{
_username = username;
_score = score;
_host = host;
_turnToDraw = turnToDraw;
}
public User(string username)
@@ -26,6 +28,7 @@ namespace SharedClientServer
_username = username;
_score = 0;
_host = false;
_turnToDraw = false;
}
public static bool operator ==(User u1, User u2)
@@ -81,5 +84,11 @@ namespace SharedClientServer
get { return _host; }
set { _host = value; }
}
public bool TurnToDraw
{
get { return _turnToDraw; }
set { _turnToDraw = value; }
}
}
}