42 Commits

Author SHA1 Message Date
Lars
35ded2b5ea Merge branch 'master' into feature/sendingCanvasData 2020-10-21 21:01:58 +02:00
SemvdH
0f01354b72 Merge pull request #1 from SemvdH/setupBranch
merge Setup branch into develop
2020-10-21 20:59:02 +02:00
Sem van der Hoeven
61577e0df7 [FIX] fixed merge conflicts 2020-10-21 20:56:38 +02:00
Sem van der Hoeven
298bd760e5 Merge remote-tracking branch 'origin/feature/sendingCanvasData' into setupBranch 2020-10-21 20:45:51 +02:00
Sem van der Hoeven
c4c97a3fbe Merge branch 'lobbies' into setupBranch 2020-10-21 20:44:11 +02:00
Dogukan
a4e45b1a6b [MISC] tried to send the message to the current lobby, didn't work. 2020-10-21 20:43:28 +02:00
Sem van der Hoeven
95448832c3 [ADD] added get lobby for users method 2020-10-21 20:42:00 +02:00
Sem van der Hoeven
3a13314519 [FIX] fixed showing of players in lobbies when joining and hosting 2020-10-21 20:34:11 +02:00
Lars
4f07eeb95a useless 2020-10-21 20:24:26 +02:00
Sem van der Hoeven
fc5d51a876 [FIX] made user host when hosting a lobby 2020-10-21 19:38:40 +02:00
Sem van der Hoeven
24701f8bb3 [FIX] fix users not being sent with lobbies 2020-10-21 19:35:52 +02:00
Dogukan
74f8e868f6 [ADDITION] servercommunication towards the client.
Still in progress not functional because of a null exception when receiving the broadcast message.
2020-10-21 17:47:48 +02:00
Dogukan
381c142eaa [ADDITION] Added databinding to the chatbox function.
Tried to broadcast the message, doesn't work yet.
2020-10-20 23:54:29 +02:00
Lars
2aeca40aa4 its not working yet, its getting a System.OutOfMemoryException, needs to be fixed 2020-10-20 23:52:10 +02:00
Sem van der Hoeven
76cd392525 [ADD] added joining lobbies 2020-10-20 22:49:25 +02:00
Sem van der Hoeven
7b30911cd7 [ADD] added hosting a lobby 2020-10-20 22:16:19 +02:00
Sem van der Hoeven
671951c35b [ADD] added sending the lobbies data from the server to the clients on startup 2020-10-20 21:12:31 +02:00
Sem van der Hoeven
ba1b71d870 [AD
D] added lobby add methods
2020-10-20 19:55:36 +02:00
Dogukan
4d161391b1 Merge remote-tracking branch 'origin/setupBranch' into setupBranch 2020-10-20 19:53:35 +02:00
Dogukan
7dbdcc8bcc [ADDITION] fixed the chatbox size 2020-10-20 19:53:28 +02:00
Sem van der Hoeven
3255ae885b [ADD] added lobby identifier enum 2020-10-20 19:40:10 +02:00
Sem van der Hoeven
b1237e53a2 [EDIT] made method for getting in lobby 2020-10-20 19:34:24 +02:00
Sem van der Hoeven
a837611317 [ADD] made join buttons disabled when starting a game 2020-10-20 19:26:11 +02:00
Sem van der Hoeven
1552479f4d [FIX] made mainwindow MVVM 2020-10-20 19:25:56 +02:00
Sem van der Hoeven
f1a47b509d [ADD] added mvvm button commands for host and join 2020-10-20 18:55:12 +02:00
Sem van der Hoeven
73dc0b94de [EDIT] made main window open only when the client has connected 2020-10-20 18:27:53 +02:00
Sem van der Hoeven
f6c70bc717 [FIX] message can now be 4 bytes long 2020-10-20 18:17:42 +02:00
Sem van der Hoeven
33574a7b23 [FIX] fixed server client message structure 2020-10-20 17:43:28 +02:00
Lars
1a539efdd1 Merge remote-tracking branch 'origin/setupBranch' into setupBranch 2020-10-20 16:38:59 +02:00
Lars
84bf1b3e64 [ADDED] the inlog screen and a data singleton for the client 2020-10-20 16:36:34 +02:00
Sem van der Hoeven
e90d782887 [EDIT] edited servercommunication methods to use serverclient users 2020-10-20 16:34:29 +02:00
Sem van der Hoeven
0009393960 [ADD] added username handling sending with json convert 2020-10-20 16:31:59 +02:00
Sem van der Hoeven
5732f0b31d [ADD] add constant identifiers to JSONConvert and made serverclient and client use them 2020-10-20 15:50:26 +02:00
Sem van der Hoeven
d9f2b97d3e [ADD] added method for generating a message 2020-10-20 15:46:28 +02:00
Sem van der Hoeven
78c1aad696 [ADD] new constructor for user 2020-10-20 15:32:50 +02:00
Sem van der Hoeven
1e11bc5416 [FIX] removed bad getter for model 2020-10-20 15:21:11 +02:00
Sem van der Hoeven
3aaff90178 [EDIT] fixed some user stuff 2020-10-20 15:14:48 +02:00
Lars
55425bbec4 for some reason, didnt added this stuff-_- 2020-10-20 13:03:04 +02:00
Lars
f1901f0c35 added something to the user 2020-10-19 23:07:48 +02:00
Dogukan
f5c67fc2da Merge branch 'feature/addChatBoxToGameWindow' into setupBranch 2020-10-19 22:41:54 +02:00
Sem van der Hoeven
d41a2d2668 [EDIT] smol line edit 2020-10-19 22:41:15 +02:00
Lars
0b12e530aa [ADDED] User the shared project + integrated it with the other classes 2020-10-19 22:32:50 +02:00
19 changed files with 886 additions and 218 deletions

View File

@@ -1,4 +1,5 @@
using System; using Client.Views;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Configuration; using System.Configuration;
using System.Data; using System.Data;
@@ -17,9 +18,9 @@ namespace Client
protected override void OnStartup(StartupEventArgs e) protected override void OnStartup(StartupEventArgs e)
{ {
base.OnStartup(e); base.OnStartup(e);
MainWindow startWindow = new MainWindow(); LoginScreen startWindow = new LoginScreen();
ViewModel VM = new ViewModel(); //ViewModel VM = new ViewModel();
startWindow.DataContext = VM; //startWindow.DataContext = VM;
startWindow.Show(); startWindow.Show();
} }

View File

@@ -4,9 +4,11 @@ using System.Collections.Generic;
using System.Diagnostics; using System.Diagnostics;
using System.Net.Sockets; using System.Net.Sockets;
using System.Text; using System.Text;
using static SharedClientServer.JSONConvert;
namespace Client namespace Client
{ {
public delegate void OnLobbyCreated(int id);
class Client : ObservableObject class Client : ObservableObject
{ {
private TcpClient tcpClient; private TcpClient tcpClient;
@@ -16,11 +18,17 @@ namespace Client
private int totalBufferReceived = 0; private int totalBufferReceived = 0;
public int Port = 5555; public int Port = 5555;
public bool Connected = false; public bool Connected = false;
//TODO send login packet to server with ClientServerUtil.createpayload(0x01,dynamic json with username) private string username;
public string Username { get; } public Callback OnSuccessfullConnect;
public Callback OnLobbiesListReceived;
public Callback OnLobbyJoinSuccess;
public Callback OnLobbiesReceivedAndWaitingForHost;
public OnLobbyCreated OnLobbyCreated;
public Lobby[] Lobbies { get; set; }
public Client() public Client(string username)
{ {
this.username = username;
this.tcpClient = new TcpClient(); this.tcpClient = new TcpClient();
Debug.WriteLine("Starting connect to server"); Debug.WriteLine("Starting connect to server");
tcpClient.BeginConnect("localhost", Port, new AsyncCallback(OnConnect), null); tcpClient.BeginConnect("localhost", Port, new AsyncCallback(OnConnect), null);
@@ -31,6 +39,8 @@ namespace Client
Debug.Write("finished connecting to server"); Debug.Write("finished connecting to server");
this.tcpClient.EndConnect(ar); this.tcpClient.EndConnect(ar);
this.stream = tcpClient.GetStream(); this.stream = tcpClient.GetStream();
OnSuccessfullConnect?.Invoke();
SendMessage(JSONConvert.ConstructUsernameMessage(username));
this.stream.BeginRead(buffer, 0, buffer.Length, new AsyncCallback(OnReadComplete),null); this.stream.BeginRead(buffer, 0, buffer.Length, new AsyncCallback(OnReadComplete),null);
} }
@@ -62,35 +72,60 @@ namespace Client
} }
stream.BeginRead(buffer, 0, buffer.Length, new AsyncCallback(OnReadComplete), null); stream.BeginRead(buffer, 0, buffer.Length, new AsyncCallback(OnReadComplete), null);
} }
private void handleData(byte[] message) private void handleData(byte[] message)
{ {
byte id = message[0]; byte id = message[4];
byte[] payload = new byte[message.Length - 1];
Array.Copy(message, 1, payload, 0, message.Length - 1); byte[] payload = new byte[message.Length - 5];
Array.Copy(message, 5, payload, 0, message.Length - 5);
switch (id) switch (id)
{ {
case 0x01: case JSONConvert.LOGIN:
// json log in username data // json log in username data
break; break;
case 0x02: case JSONConvert.MESSAGE:
// json message data // json message data
(string, string) combo = JSONConvert.GetUsernameAndMessage(payload); (string, string) combo = JSONConvert.GetUsernameAndMessage(payload);
string textUsername = combo.Item1; string textUsername = combo.Item1;
string textMsg = combo.Item2; string textMsg = combo.Item2;
//TODO display username and message in chat window
//TODO display username and message in chat window
Debug.WriteLine("[CLIENT] INCOMING MESSAGE!");
Debug.WriteLine("[CLIENT] User name: {0}\t User message: {1}", textUsername, textMsg);
break; break;
case 0x03: case JSONConvert.LOBBY:
// lobby data // lobby data
LobbyIdentifier lobbyIdentifier = JSONConvert.GetLobbyIdentifier(payload);
switch (lobbyIdentifier)
{
case LobbyIdentifier.LIST:
Debug.WriteLine("got lobbies list");
Lobbies = JSONConvert.GetLobbiesFromMessage(payload);
OnLobbiesListReceived?.Invoke();
OnLobbiesReceivedAndWaitingForHost?.Invoke();
break;
case LobbyIdentifier.HOST:
// we receive this when the server has made us a host of a new lobby
// TODO get lobby id
Debug.WriteLine("[CLIENT] got lobby object");
int lobbyCreatedID = JSONConvert.GetLobbyID(payload);
OnLobbyCreated?.Invoke(lobbyCreatedID);
break;
case LobbyIdentifier.JOIN_SUCCESS:
OnLobbyJoinSuccess?.Invoke();
break;
}
//TODO fill lobby with the data received //TODO fill lobby with the data received
break; break;
case 0x04:
case JSONConvert.CANVAS:
// canvas data // canvas data
break; break;
default: default:
Debug.WriteLine("[CLIENT] Received weird identifier: " + id); Debug.WriteLine("[CLIENT] Received weird identifier: " + id);
break; break;
@@ -100,11 +135,13 @@ namespace Client
public void SendMessage(byte[] message) public void SendMessage(byte[] message)
{ {
Debug.WriteLine("[CLIENT] sending message " + Encoding.ASCII.GetString(message));
stream.BeginWrite(message, 0, message.Length, new AsyncCallback(OnWriteComplete), null); stream.BeginWrite(message, 0, message.Length, new AsyncCallback(OnWriteComplete), null);
} }
private void OnWriteComplete(IAsyncResult ar) private void OnWriteComplete(IAsyncResult ar)
{ {
Debug.WriteLine("[CLIENT] finished writing");
stream.EndWrite(ar); stream.EndWrite(ar);
} }
} }

72
Client/ClientData.cs Normal file
View File

@@ -0,0 +1,72 @@
using SharedClientServer;
using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
namespace Client
{
class ClientData
{
private static ClientData _instance;
private static readonly object padlock = new object();
public static ClientData Instance
{
get
{
lock (padlock)
{
if (_instance == null)
{
_instance = new ClientData();
}
return _instance;
}
}
}
private User _user;
private Client _client;
private Lobby _lobby;
private string _message;
private ClientData()
{
}
public User User
{
get { return _user; }
set { _user = value; }
}
public Client Client
{
get { return _client; }
set { _client = value; }
}
public Lobby Lobby
{
get { return _lobby; }
set { _lobby = value; }
}
public String Message
{
get
{
return _message;
}
set
{
_message = value;
}
}
}
}

View File

@@ -11,6 +11,7 @@ namespace Client
private int _numbers; private int _numbers;
private bool _status; private bool _status;
private bool _canStartGame;
//Test code //Test code
public int Numbers public int Numbers
@@ -37,11 +38,18 @@ namespace Client
} }
} }
public bool CanStartGame
{
get { return _canStartGame; }
set { _canStartGame = value; }
}
public Model() public Model()
{ {
_status = false; _status = false;
_numbers = 0; _numbers = 0;
_canStartGame = true;
} }
} }

View File

@@ -5,6 +5,12 @@ using System.ComponentModel;
using System.Text; using System.Text;
using System.Windows.Input; using System.Windows.Input;
using SharedClientServer; using SharedClientServer;
using System.Diagnostics;
using System.Windows;
using System.Collections.ObjectModel;
using Client.Views;
using System.Linq;
using System.Windows.Data;
namespace Client namespace Client
{ {
@@ -12,19 +18,125 @@ namespace Client
{ {
public event PropertyChangedEventHandler PropertyChanged; public event PropertyChangedEventHandler PropertyChanged;
public ICommand OnHostButtonClick { get; set; }
public ICommand JoinSelectedLobby { get; set; }
public Lobby SelectedLobby { get; set; }
private Client client;
private bool wantToBeHost = false;
private int wantToBeHostId = 0;
public ViewModel() public ViewModel()
{ {
_model = new Model(); _model = new Model();
ButtonCommand = new RelayCommand(() => _lobbies = new ObservableCollection<Lobby>();
client = ClientData.Instance.Client;
client.OnLobbiesListReceived = updateLobbies;
OnHostButtonClick = new RelayCommand(hostGame);
JoinSelectedLobby = new RelayCommand(joinLobby, true);
}
private void hostGame()
{
Debug.WriteLine("attempting to host game for " + ClientData.Instance.User.Username);
client.SendMessage(JSONConvert.ConstructLobbyHostMessage());
client.OnLobbyCreated = becomeHostForLobby;
}
private void becomeHostForLobby(int id)
{
Debug.WriteLine($"got host succes with data {id} ");
wantToBeHost = true;
wantToBeHostId = id;
client.OnLobbiesReceivedAndWaitingForHost = hostLobbiesReceived;
}
private void hostLobbiesReceived()
{
if (wantToBeHost)
foreach (Lobby l in Lobbies)
{
if (l.ID == wantToBeHostId)
{
Debug.WriteLine("found lobby that we want to be host of: " + l.ID + ", joining..");
SelectedLobby = l;
startGameInLobby();
wantToBeHost = false;
client.OnLobbiesReceivedAndWaitingForHost = null;
break;
}
}
}
private void joinLobby()
{
// lobby die je wilt joinen verwijderen
// nieuwe binnengekregen lobby toevoegen
client.OnLobbyJoinSuccess = OnLobbyJoinSuccess;
client.SendMessage(JSONConvert.ConstructLobbyJoinMessage(SelectedLobby.ID));
}
private void OnLobbyJoinSuccess()
{
startGameInLobby();
}
private void updateLobbies()
{
Debug.WriteLine("updating lobbies...");
Lobby[] lobbiesArr = client.Lobbies;
Application.Current.Dispatcher.Invoke(delegate
{ {
Client client = new Client();
//for (int i = 0; i < lobbiesArr.Length; i++)
//{
// Lobby lobby = lobbiesArr[i];
// Debug.WriteLine(lobby.PlayersIn);
// if (i < _lobbies.Count && _lobbies[i].ID == lobby.ID)
// {
// _lobbies[i].Set(lobby);
// } else
// {
// _lobbies.Add(lobbiesArr[i]);
// }
//}
_lobbies.Clear();
foreach (Lobby l in lobbiesArr)
{
_lobbies.Add(l);
}
}); });
}
_lobbies = new List<Lobby>(); private void startGameInLobby()
{
if (SelectedLobby != null)
{
ClientData.Instance.Lobby = SelectedLobby;
startGameWindow();
}
}
_lobbies.Add(new Lobby(50, 3, 8)); private void startGameWindow()
_lobbies.Add(new Lobby(69, 1, 9)); {
_lobbies.Add(new Lobby(420, 7, 7)); _model.CanStartGame = false;
Application.Current.Dispatcher.Invoke(delegate
{
GameWindow window = new GameWindow();
window.Show();
});
} }
private void ClickCheck() private void ClickCheck()
@@ -35,17 +147,12 @@ namespace Client
_model.Numbers = _model.Numbers + 5; _model.Numbers = _model.Numbers + 5;
} }
public ICommand ButtonCommand { get; set; }
private Model _model; private Model _model;
public Model Model public Model Model
{ {
get get
{ {
if (_model == null)
_model = new Model();
return _model; return _model;
} }
@@ -55,8 +162,8 @@ namespace Client
} }
} }
private List<Lobby> _lobbies; private ObservableCollection<Lobby> _lobbies;
public List<Lobby> Lobbies public ObservableCollection<Lobby> Lobbies
{ {
get { return _lobbies; } get { return _lobbies; }
set { _lobbies = value; } set { _lobbies = value; }

View File

@@ -1,10 +1,126 @@
using System.Collections.ObjectModel;
using Client.Views;
using GalaSoft.MvvmLight.Command;
using SharedClientServer;
using System.Collections.ObjectModel;
using System.ComponentModel; using System.ComponentModel;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Shapes;
namespace Client.ViewModels namespace Client.ViewModels
{ {
class ViewModelGame : INotifyPropertyChanged class ViewModelGame : INotifyPropertyChanged
{ {
private ClientData data = ClientData.Instance;
public event PropertyChangedEventHandler PropertyChanged; public event PropertyChangedEventHandler PropertyChanged;
private Point currentPoint = new Point();
private Color color;
public ObservableCollection<string> Messages { get; } = new ObservableCollection<string>();
private dynamic _payload;
private string _username;
private string _message;
public string Message
{
get
{
return _message;
}
set
{
_message = value;
}
}
public ICommand OnKeyDown { get; set; }
public void Canvas_MouseDown(MouseButtonEventArgs e, GameWindow window)
{
if (e.ButtonState == MouseButtonState.Pressed)
{
currentPoint = e.GetPosition(window.CanvasForPaint);
}
}
public void Canvas_MouseMove(MouseEventArgs e, GameWindow window)
{
if (e.LeftButton == MouseButtonState.Pressed)
{
double[] coordinates = new double[4];
Line line = new Line();
line.Stroke = new SolidColorBrush(color);
//line.Stroke = SystemColors.WindowFrameBrush;
line.X1 = currentPoint.X;
line.Y1 = currentPoint.Y;
line.X2 = e.GetPosition(window.CanvasForPaint).X;
line.Y2 = e.GetPosition(window.CanvasForPaint).Y;
coordinates[0] = line.X1;
coordinates[1] = line.Y1;
coordinates[2] = line.X2;
coordinates[3] = line.Y2;
currentPoint = e.GetPosition(window.CanvasForPaint);
window.CanvasForPaint.Children.Add(line);
data.Client.SendMessage(JSONConvert.GetMessageToSend(0x04, coordinates));
}
}
public void Color_Picker(RoutedPropertyChangedEventArgs<Color?> e, GameWindow window)
{
Color colorSelected = new Color();
colorSelected.A = 255;
colorSelected.R = window.ClrPcker_Background.SelectedColor.Value.R;
colorSelected.G = window.ClrPcker_Background.SelectedColor.Value.G;
colorSelected.B = window.ClrPcker_Background.SelectedColor.Value.B;
color = colorSelected;
}
public ViewModelGame()
{
if (_payload == null)
{
_message = "";
}
else
{
//_message = data.Message;
//_username = data.User.Username;
//Messages.Add($"{data.User.Username}: {Message}");
}
OnKeyDown = new RelayCommand(ChatBox_KeyDown);
}
private void ChatBox_KeyDown()
{
//if enter then clear textbox and send message.
if (Message != string.Empty) AddMessage(Message);
Message = string.Empty;
}
internal void AddMessage(string message)
{
Messages.Add($"{data.User.Username}: {message}");
_payload = new
{
username = data.User.Username,
message = message
};
//Broadcast the message after adding it to the list!
data.Client.SendMessage(JSONConvert.GetMessageToSend(JSONConvert.MESSAGE, _payload));
}
} }
} }

View File

@@ -48,8 +48,13 @@
</Border> </Border>
<Grid Grid.Column="2" Grid.Row="1"> <Grid Grid.Column="2" Grid.Row="1">
<TextBox Name="SentMessage" IsReadOnly="True"/> <ListBox Name ="TextBox" ItemsSource="{Binding Path=Messages}" Margin="0,0,0,69"/>
<TextBox x:Name="ChatBox" Keyboard.KeyDown="ChatBox_KeyDown" Width="200" Height="50" ToolTip="Message goes here" ToolTipService.IsEnabled="True" VerticalAlignment="Bottom" HorizontalAlignment="Left"/>
<TextBox Name="ChatBox" Text="{Binding Message, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Margin="0,465,0,0">
<TextBox.InputBindings>
<KeyBinding Key="Return" Command="{Binding OnKeyDown}"/>
</TextBox.InputBindings>
</TextBox>
</Grid> </Grid>
</Grid> </Grid>

View File

@@ -18,55 +18,25 @@ namespace Client.Views
/// </summary> /// </summary>
public partial class GameWindow : Window public partial class GameWindow : Window
{ {
ClientData data = ClientData.Instance;
private ViewModelGame viewModel;
public GameWindow() public GameWindow()
{ {
DataContext = new ViewModelGame(); this.viewModel = new ViewModelGame();
DataContext = this.viewModel;
InitializeComponent(); InitializeComponent();
} }
Point currentPoint = new Point();
private void CanvasForPaint_MouseDown(object sender, MouseButtonEventArgs e) private void CanvasForPaint_MouseDown(object sender, MouseButtonEventArgs e)
{ {
if (e.ButtonState == MouseButtonState.Pressed) this.viewModel.Canvas_MouseDown(e, this);
{
currentPoint = e.GetPosition(CanvasForPaint);
}
} }
private void CanvasForPaint_MouseMove(object sender, MouseEventArgs e) private void CanvasForPaint_MouseMove(object sender, MouseEventArgs e)
{ {
if (e.LeftButton == MouseButtonState.Pressed) viewModel.Canvas_MouseMove(e, this);
{
Line line = new Line();
line.Stroke = new SolidColorBrush(color);
//line.Stroke = SystemColors.WindowFrameBrush;
line.X1 = currentPoint.X;
line.Y1 = currentPoint.Y;
line.X2 = e.GetPosition(CanvasForPaint).X;
line.Y2 = e.GetPosition(CanvasForPaint).Y;
currentPoint = e.GetPosition(CanvasForPaint);
CanvasForPaint.Children.Add(line);
}
}
private Color color;
private void ClrPcker_Background_SelectedColorChanged(object sender, RoutedPropertyChangedEventArgs<Color> e)
{
Color colorSelected = new Color();
colorSelected.A = 255;
colorSelected.R = ClrPcker_Background.SelectedColor.Value.R;
colorSelected.G = ClrPcker_Background.SelectedColor.Value.G;
colorSelected.B = ClrPcker_Background.SelectedColor.Value.B;
color = colorSelected;
} }
private void CanvasReset_Click(object sender, RoutedEventArgs e) private void CanvasReset_Click(object sender, RoutedEventArgs e)
@@ -82,36 +52,11 @@ namespace Client.Views
// var deepCopy = System.Windows.Markup.XamlReader.Parse(xaml) as UIElement; // var deepCopy = System.Windows.Markup.XamlReader.Parse(xaml) as UIElement;
// TEST.Children.Add(deepCopy); // TEST.Children.Add(deepCopy);
//} //}
} }
private void ClrPcker_Background_SelectedColorChanged_1(object sender, RoutedPropertyChangedEventArgs<Color?> e) private void ClrPcker_Background_SelectedColorChanged_1(object sender, RoutedPropertyChangedEventArgs<Color?> e)
{ {
Color colorSelected = new Color(); viewModel.Color_Picker(e, this);
colorSelected.A = 255;
colorSelected.R = ClrPcker_Background.SelectedColor.Value.R;
colorSelected.G = ClrPcker_Background.SelectedColor.Value.G;
colorSelected.B = ClrPcker_Background.SelectedColor.Value.B;
color = colorSelected;
}
private void ChatBox_KeyDown(object sender, KeyEventArgs e)
{
//if enter then clear textbox and send message.
if (e.Key.Equals(Key.Enter))
{
WriteToChat(ChatBox.Text);
ChatBox.Clear();
}
}
/*
* Writes the current client's message to the chatbox.
*/
private void WriteToChat(string message)
{
string user = "Monkey";
SentMessage.AppendText($"{user}: {message}\n");
} }
} }
} }

View File

@@ -0,0 +1,29 @@
<Window x:Class="Client.Views.LoginScreen"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:Client.Views"
mc:Ignorable="d"
Title="LoginScreen" Height="450" Width="800">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="60"/>
<RowDefinition Height="50"/>
<RowDefinition Height="30"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<Label Grid.Row="0" FontSize="40" Content="Welcome to Scrubl.io"/>
<Label Grid.Row="1" FontSize="30" Content="Enter a username:"/>
<Label Grid.Row="2" FontSize="15" Content="(max amount of characters for the username is 10)"/>
<TextBox Name="usernameTextbox" Grid.Row="1" Grid.Column="1" MaxLength="10" FontSize="30" VerticalAlignment="Center" HorizontalAlignment="Left" Width="250"/>
<Button Content="ENTER" Grid.Column="1" Grid.Row="1" VerticalAlignment="Center" HorizontalAlignment="Right" Width="100" Height="40" Click="Button_EnterUsername"/>
</Grid>
</Window>

View File

@@ -0,0 +1,46 @@
using SharedClientServer;
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace Client.Views
{
/// <summary>
/// Interaction logic for LoginScreen.xaml
/// </summary>
public partial class LoginScreen : Window
{
ClientData data = ClientData.Instance;
public LoginScreen()
{
InitializeComponent();
}
private void Button_EnterUsername(object sender, RoutedEventArgs e)
{
User user = new User(usernameTextbox.Text);
Client client = new Client(user.Username);
client.OnSuccessfullConnect = () =>
{
// because we need to start the main window on a UI thread, we need to let the dispatcher handle it, which will execute the code on the ui thread
Application.Current.Dispatcher.Invoke(delegate {
data.User = user;
data.Client = client;
client.SendMessage(JSONConvert.ConstructLobbyRequestMessage());
MainWindow startWindow = new MainWindow();
startWindow.Show();
this.Close();
});
};
}
}
}

View File

@@ -34,9 +34,8 @@
<Label Grid.Row="0" Content="This client information:" FontSize="17"/> <Label Grid.Row="0" Content="This client information:" FontSize="17"/>
<Label Grid.Row="1" Grid.Column="0" Content="Your username:" FontSize="15" VerticalAlignment="Center"/> <Label Grid.Row="1" Grid.Column="0" Content="Your username:" FontSize="15" VerticalAlignment="Center"/>
<TextBox Name="usernameTextbox" Grid.Row="1" Grid.Column="1" MaxLength="10" FontSize="15" VerticalAlignment="Center"/>
<Label Grid.Row="2" Grid.Column="0" Content="Which color you want to be:" FontSize="15" VerticalAlignment="Center"/> <Label Grid.Row="2" Grid.Column="0" Content="Select your color:" FontSize="15" VerticalAlignment="Center"/>
<ComboBox Name="colorSelection" Grid.Row="2" Grid.Column="1" VerticalAlignment="Center" FontSize="15"> <ComboBox Name="colorSelection" Grid.Row="2" Grid.Column="1" VerticalAlignment="Center" FontSize="15">
<ComboBoxItem Content="BLUE"/> <ComboBoxItem Content="BLUE"/>
<ComboBoxItem Content="RED"/> <ComboBoxItem Content="RED"/>
@@ -48,11 +47,12 @@
</ComboBox> </ComboBox>
<Label Grid.Row="3" Name="testLabel" FontSize="15" VerticalAlignment="Center"/> <Label Grid.Row="3" Name="testLabel" FontSize="15" VerticalAlignment="Center"/>
<Label Name="usernameLabel" Content="place username here" Grid.Column="1" HorizontalAlignment="Center" Margin="0,12,0,0" VerticalAlignment="Top" Grid.Row="1"/>
</Grid> </Grid>
<ListView Name="LobbyList" Grid.Row="1" Grid.Column="0" Margin="10, 10, 10, 10" ItemsSource="{Binding Path=Lobbies}"> <ListView Name="LobbyList" Grid.Row="1" Grid.Column="0" SelectedItem="{Binding SelectedLobby}" Margin="10, 10, 10, 10" ItemsSource="{Binding Path=Lobbies}">
<ListView.View> <ListView.View>
<GridView x:Name="grdList"> <GridView x:Name="grdList">
<GridViewColumn Header="Lobby ID" DisplayMemberBinding="{Binding ID}" Width="70"/> <GridViewColumn Header="Lobby ID" DisplayMemberBinding="{Binding ID}" Width="70"/>
@@ -67,8 +67,8 @@
<RowDefinition Height="50"/> <RowDefinition Height="50"/>
<RowDefinition Height="50"/> <RowDefinition Height="50"/>
</Grid.RowDefinitions> </Grid.RowDefinitions>
<Button Name="joinButton" Grid.Row="0" Content="join a selected lobby" Click="Button_Click" Width="200" Height="40" HorizontalAlignment="Left" Margin="10, 0, 0, 0"/> <Button Name="joinButton" Grid.Row="0" Content="join a selected lobby" Command="{Binding JoinSelectedLobby}" IsEnabled="{Binding Model.CanStartGame}" Width="200" Height="40" HorizontalAlignment="Left" Margin="10, 0, 0, 0"/>
<Button Name="hostButton" Grid.Row="1" Content="host a new lobby" Command="{Binding ...}" Width="200" Height="40" HorizontalAlignment="left" Margin="10, 0, 0, 0"/> <Button Name="hostButton" Grid.Row="1" Content="host a new lobby" Command="{Binding OnHostButtonClick}" IsEnabled="{Binding Model.CanStartGame}" Width="200" Height="40" HorizontalAlignment="left" Margin="10, 0, 0, 0"/>
</Grid> </Grid>
</Grid> </Grid>

View File

@@ -21,26 +21,17 @@ namespace Client
/// </summary> /// </summary>
public partial class MainWindow : Window public partial class MainWindow : Window
{ {
ClientData data = ClientData.Instance;
public MainWindow() public MainWindow()
{ {
this.DataContext = new ViewModel();
InitializeComponent(); InitializeComponent();
usernameLabel.Content = data.User.Username;
} }
private void Button_Click(object sender, RoutedEventArgs e) private void Button_Click(object sender, RoutedEventArgs e)
{ {
Lobby lobbySelected = LobbyList.SelectedItem as Lobby;
if(lobbySelected != null)
{
testLabel.Content = lobbySelected.ID;
usernameTextbox.IsEnabled = false;
colorSelection.IsEnabled = false;
joinButton.IsEnabled = false;
hostButton.IsEnabled = false;
GameWindow window = new GameWindow();
window.Show();
}
} }
} }
} }

View File

@@ -1,21 +1,26 @@
 
using Client;
using Newtonsoft.Json.Linq;
using SharedClientServer; using SharedClientServer;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics; using System.Diagnostics;
using System.Net.Sockets; using System.Net.Sockets;
using System.Text; using System.Text;
using static SharedClientServer.JSONConvert;
namespace Server.Models namespace Server.Models
{ {
class ServerClient : ObservableObject class ServerClient : ObservableObject
{ {
public string Username { get; set; }
private TcpClient tcpClient; private TcpClient tcpClient;
private NetworkStream stream; private NetworkStream stream;
private byte[] buffer = new byte[1024]; private byte[] buffer = new byte[1024];
private byte[] totalBuffer = new byte[1024]; private byte[] totalBuffer = new byte[1024];
private int totalBufferReceived = 0; private int totalBufferReceived = 0;
public User User { get; set; }
private ServerCommunication serverCom = ServerCommunication.INSTANCE;
/// <summary> /// <summary>
@@ -24,8 +29,10 @@ namespace Server.Models
/// <param name="client">the TcpClient object to use</param> /// <param name="client">the TcpClient object to use</param>
public ServerClient(TcpClient client) public ServerClient(TcpClient client)
{ {
Debug.WriteLine("[SERVERCLIENT] making new instance and starting");
tcpClient = client; tcpClient = client;
stream = tcpClient.GetStream(); stream = tcpClient.GetStream();
Debug.WriteLine("[SERVERCLIENT] starting read");
stream.BeginRead(buffer, 0, buffer.Length, new AsyncCallback(OnRead), null); stream.BeginRead(buffer, 0, buffer.Length, new AsyncCallback(OnRead), null);
} }
@@ -35,6 +42,10 @@ namespace Server.Models
/// <param name="ar">the async result status</param> /// <param name="ar">the async result status</param>
private void OnRead(IAsyncResult ar) private void OnRead(IAsyncResult ar)
{ {
if (ar == null || (!ar.IsCompleted) || (!this.stream.CanRead) || !this.tcpClient.Client.Connected)
return;
int bytesReceived = this.stream.EndRead(ar); int bytesReceived = this.stream.EndRead(ar);
if (totalBufferReceived + bytesReceived > 1024) if (totalBufferReceived + bytesReceived > 1024)
@@ -76,6 +87,7 @@ namespace Server.Models
// start reading for a new message // start reading for a new message
stream.BeginRead(buffer, 0, buffer.Length, new AsyncCallback(OnRead), null); stream.BeginRead(buffer, 0, buffer.Length, new AsyncCallback(OnRead), null);
} }
/// <summary> /// <summary>
@@ -84,36 +96,46 @@ namespace Server.Models
/// <param name="message">the incoming message</param> /// <param name="message">the incoming message</param>
private void HandleIncomingMessage(byte[] message) private void HandleIncomingMessage(byte[] message)
{ {
Debug.WriteLine($"Got message from {Username} : {message}"); Debug.WriteLine($"Got message : {Encoding.ASCII.GetString(message)}");
byte id = message[0]; byte id = message[4];
byte[] payload = new byte[message.Length - 1]; byte[] payload = new byte[message.Length - 5];
Array.Copy(message,1,payload,0,message.Length-1); Array.Copy(message,5,payload,0,message.Length-5);
Debug.WriteLine("[SERVERCLIENT] GOT STRING" + Encoding.ASCII.GetString(payload));
switch(id) switch(id)
{ {
case 0x01: case JSONConvert.LOGIN:
// json log in username data // json log in username data
string uName = JSONConvert.GetUsernameLogin(message); string uName = JSONConvert.GetUsernameLogin(payload);
if (uName != null) if (uName != null)
{ {
Username = uName; User = new User(uName);
Debug.WriteLine("[SERVERCLIENT] set username to " + Username); User.Username = uName;
Debug.WriteLine("[SERVERCLIENT] set username to " + uName);
} }
break; break;
case 0x02: case JSONConvert.MESSAGE:
// json message data // json message data
(string, string) combo = JSONConvert.GetUsernameAndMessage(payload); (string, string) combo = JSONConvert.GetUsernameAndMessage(payload);
string textUsername = combo.Item1; string textUsername = combo.Item1;
string textMsg = combo.Item2; string textMsg = combo.Item2;
Debug.WriteLine("[SERVERCLIENT] User name: {0}\t User message: {1}", textUsername, textMsg);
// todo handle sending to all except this user the username and message to display in chat // todo handle sending to all except this user the username and message to display in chat
serverCom.SendToLobby(ServerCommunication.INSTANCE.GetLobbyForUser(User),payload);
Debug.WriteLine("Payload has been sent!");
break; break;
case 0x03: case JSONConvert.LOBBY:
// lobby data // lobby data
LobbyIdentifier l = JSONConvert.GetLobbyIdentifier(payload);
handleLobbyMessage(payload,l);
break; break;
case 0x04: case JSONConvert.CANVAS:
Debug.WriteLine("GOT A MESSAGE FROM THE CLIENT ABOUT THE CANVAS!!!");
// canvas data // canvas data
// todo send canvas data to all other serverclients in lobby // todo send canvas data to all other serverclients in lobby
break; break;
@@ -121,7 +143,30 @@ namespace Server.Models
Debug.WriteLine("[SERVER] Received weird identifier: " + id); Debug.WriteLine("[SERVER] Received weird identifier: " + id);
break; break;
} }
//TODO implement ways to handle the message }
private void handleLobbyMessage(byte[] payload, LobbyIdentifier l)
{
switch (l)
{
case LobbyIdentifier.REQUEST:
Debug.WriteLine("[SERVERCLIENT] got lobby request message, sending lobbies...");
sendMessage(JSONConvert.ConstructLobbyListMessage(ServerCommunication.INSTANCE.lobbies.ToArray()));
break;
case LobbyIdentifier.HOST:
// add new lobby and add this serverclient to it
int createdLobbyID = ServerCommunication.INSTANCE.HostForLobby(this.User);
Debug.WriteLine("[SERVERCLIENT] created lobby");
sendMessage(JSONConvert.ConstructLobbyHostCreatedMessage(createdLobbyID));
ServerCommunication.INSTANCE.sendToAll(JSONConvert.ConstructLobbyListMessage(ServerCommunication.INSTANCE.lobbies.ToArray()));
break;
case LobbyIdentifier.JOIN:
int id = JSONConvert.GetLobbyID(payload);
ServerCommunication.INSTANCE.JoinLobby(this.User,id);
sendMessage(JSONConvert.ConstructLobbyJoinSuccessMessage());
ServerCommunication.INSTANCE.sendToAll(JSONConvert.ConstructLobbyListMessage(ServerCommunication.INSTANCE.lobbies.ToArray()));
break;
}
} }
/// <summary> /// <summary>

View File

@@ -1,5 +1,4 @@
 using Client;
using Client;
using SharedClientServer; using SharedClientServer;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
@@ -19,6 +18,7 @@ namespace Server.Models
private Dictionary<Lobby, List<ServerClient>> serverClientsInlobbies; private Dictionary<Lobby, List<ServerClient>> serverClientsInlobbies;
public Action newClientAction; public Action newClientAction;
/// <summary> /// <summary>
/// use a padlock object to make sure the singleton is thread-safe /// use a padlock object to make sure the singleton is thread-safe
/// </summary> /// </summary>
@@ -32,7 +32,10 @@ namespace Server.Models
listener = new TcpListener(IPAddress.Any, port); listener = new TcpListener(IPAddress.Any, port);
serverClients = new List<ServerClient>(); serverClients = new List<ServerClient>();
lobbies = new List<Lobby>(); lobbies = new List<Lobby>();
Lobby temp = new Lobby(1, 7, 8);
lobbies.Add(temp);
serverClientsInlobbies = new Dictionary<Lobby, List<ServerClient>>(); serverClientsInlobbies = new Dictionary<Lobby, List<ServerClient>>();
serverClientsInlobbies.Add(temp, new List<ServerClient>());
} }
/// <summary> /// <summary>
@@ -98,7 +101,7 @@ namespace Server.Models
{ {
foreach (ServerClient sc in serverClients) foreach (ServerClient sc in serverClients)
{ {
if (sc.Username != username) sc.sendMessage(message); if (sc.User.Username != username) sc.sendMessage(message);
} }
} }
@@ -117,14 +120,27 @@ namespace Server.Models
} }
} }
public void AddToLobby(Lobby lobby, string username) public Lobby GetLobbyForUser(User user)
{
foreach (Lobby l in lobbies)
{
if (l.Users.Contains(user))
{
return l;
}
}
return null;
}
public void AddToLobby(Lobby lobby, User user)
{ {
foreach (Lobby l in lobbies) foreach (Lobby l in lobbies)
{ {
if (l == lobby) if (l == lobby)
{ {
bool succ; bool succ;
l.AddUsername(username, out succ); l.AddUser(user, out succ);
Debug.WriteLine("[SERVERCOMM] added user to lobby, now contains " + l.PlayersIn);
if (!succ) if (!succ)
{ {
// TODO send lobby full message // TODO send lobby full message
@@ -132,7 +148,7 @@ namespace Server.Models
{ {
foreach(ServerClient sc in serverClients) foreach(ServerClient sc in serverClients)
{ {
if (sc.Username == username) if (sc.User.Username == user.Username)
{ {
serverClientsInlobbies[l].Add(sc); serverClientsInlobbies[l].Add(sc);
break; break;
@@ -144,5 +160,28 @@ namespace Server.Models
} }
} }
} }
public int HostForLobby(User user)
{
Lobby lobby = new Lobby( lobbies.Count + 1,0, 8);
lobbies.Add(lobby);
serverClientsInlobbies.Add(lobby, new List<ServerClient>());
user.Host = true;
AddToLobby(lobby, user);
return lobby.ID;
}
public void JoinLobby(User user, int id)
{
foreach (Lobby l in lobbies)
{
if (l.ID == id)
{
AddToLobby(l, user);
Debug.WriteLine($"{user.Username} joined lobby with id {id}");
break;
}
}
}
} }
} }

View File

@@ -6,6 +6,7 @@ using System.Text;
namespace SharedClientServer namespace SharedClientServer
{ {
public delegate void Callback();
class ClientServerUtil class ClientServerUtil
{ {
// creates a message array to send to the server or to clients // creates a message array to send to the server or to clients
@@ -17,6 +18,5 @@ namespace SharedClientServer
Array.Copy(stringAsBytes, 0, res, 1, stringAsBytes.Length); Array.Copy(stringAsBytes, 0, res, 1, stringAsBytes.Length);
return res; return res;
} }
} }
} }

View File

@@ -1,24 +1,166 @@
using Newtonsoft.Json; using Client;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text; using System.Text;
namespace SharedClientServer namespace SharedClientServer
{ {
class JSONConvert class JSONConvert
{ {
public const byte LOGIN = 0x01;
public const byte MESSAGE = 0x02;
public const byte LOBBY = 0x03;
public const byte CANVAS = 0x04;
public enum LobbyIdentifier
{
HOST,
JOIN,
JOIN_SUCCESS,
LEAVE,
LIST,
REQUEST
}
public static (string,string) GetUsernameAndMessage(byte[] json) public static (string,string) GetUsernameAndMessage(byte[] json)
{ {
string msg = Encoding.ASCII.GetString(json); string msg = Encoding.ASCII.GetString(json);
dynamic payload = JsonConvert.DeserializeObject(msg); dynamic payload = JsonConvert.DeserializeObject(msg);
return (payload.username, payload.message); return (payload.username, payload.message);
} }
public static string GetUsernameLogin(byte[] json) public static string GetUsernameLogin(byte[] json)
{ {
string msg = Encoding.ASCII.GetString(json); dynamic payload = JsonConvert.DeserializeObject(Encoding.ASCII.GetString(json));
dynamic payload = JsonConvert.DeserializeObject(msg);
return payload.username; return payload.username;
} }
public static byte[] ConstructUsernameMessage(string uName)
{
return GetMessageToSend(LOGIN, new
{
username = uName
});
}
#region lobby messages
public static byte[] ConstructLobbyHostMessage()
{
return GetMessageToSend(LOBBY, new
{
identifier = LobbyIdentifier.HOST
});
}
public static byte[] ConstructLobbyHostCreatedMessage(int lobbyID)
{
return GetMessageToSend(LOBBY, new
{
identifier = LobbyIdentifier.HOST,
id = lobbyID
}) ;
}
public static byte[] ConstructLobbyRequestMessage()
{
return GetMessageToSend(LOBBY, new
{
identifier = LobbyIdentifier.REQUEST
});
}
public static byte[] ConstructLobbyListMessage(Lobby[] lobbiesList)
{
return GetMessageToSend(LOBBY, new
{
identifier = LobbyIdentifier.LIST,
lobbies = lobbiesList
});
}
public static byte[] ConstructLobbyJoinMessage(int lobbyID)
{
return GetMessageToSend(LOBBY, new
{
identifier = LobbyIdentifier.JOIN,
id = lobbyID
});
}
public static byte[] ConstructLobbyLeaveMessage(int lobbyID)
{
return GetMessageToSend(LOBBY, new
{
identifier = LobbyIdentifier.LEAVE,
id = lobbyID
});
}
public static LobbyIdentifier GetLobbyIdentifier(byte[] json)
{
dynamic payload = JsonConvert.DeserializeObject(Encoding.ASCII.GetString(json));
return payload.identifier;
}
public static Lobby[] GetLobbiesFromMessage(byte[] json)
{
dynamic payload = JsonConvert.DeserializeObject(Encoding.ASCII.GetString(json));
JArray lobbiesArray = payload.lobbies;
Debug.WriteLine("[JSONCONVERT] got lobbies from message" + lobbiesArray.ToString());
Lobby[] lobbiesTemp = lobbiesArray.ToObject<Lobby[]>();
Debug.WriteLine("lobbies in array: ");
foreach (Lobby l in lobbiesTemp)
{
Debug.WriteLine("players: " + l.PlayersIn);
}
return lobbiesTemp;
}
public static int GetLobbyID(byte[] json)
{
dynamic payload = JsonConvert.DeserializeObject(Encoding.ASCII.GetString(json));
return payload.id;
}
public static Lobby GetLobby(byte[] json)
{
dynamic payload = JsonConvert.DeserializeObject(Encoding.ASCII.GetString(json));
JObject dynamicAsObject = payload.lobby;
return dynamicAsObject.ToObject<Lobby>();
}
public static byte[] ConstructLobbyJoinSuccessMessage()
{
return GetMessageToSend(LOBBY, new { identifier = LobbyIdentifier.JOIN_SUCCESS});
}
#endregion
/// <summary>
/// constructs a message that can be sent to the clients or server
/// </summary>
/// <param name="identifier">the identifier for what kind of message it is</param>
/// <param name="payload">the json payload</param>
/// <returns>a byte array containing a message that can be sent to clients or server</returns>
public static byte[] GetMessageToSend(byte identifier, dynamic payload)
{
// convert the dynamic to bytes
byte[] payloadBytes = Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(payload));
// 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
Array.Copy(payloadBytes, 0, res, 5, payloadBytes.Length);
// put the identifier at the start of the payload part
res[4] = identifier;
// put the length of the payload at the start of the res array
Array.Copy(BitConverter.GetBytes(payloadBytes.Length+5),0,res,0,4);
return res;
}
} }
} }

View File

@@ -1,4 +1,5 @@
using System; using SharedClientServer;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
using System.Text; using System.Text;
@@ -13,24 +14,46 @@ namespace Client
private int _id; private int _id;
private int _playersIn; private int _playersIn;
private int _maxPlayers; private int _maxPlayers;
private List<string> _usernames; //private List<string> _usernames;
private List<User> _users;
public void AddUsername(string username, out bool success) //public void AddUsername(string username, out bool success)
{ //{
success = false; // success = false;
if (_usernames.Count < _maxPlayers) // if (_usernames.Count < _maxPlayers)
{ // {
_usernames.Add(username); // _usernames.Add(username);
success = true; // success = true;
} // }
} //}
public Lobby(int id, int playersIn, int maxPlayers) public Lobby(int id, int playersIn, int maxPlayers)
{ {
_id = id; _id = id;
_playersIn = playersIn; _playersIn = playersIn;
_maxPlayers = maxPlayers; _maxPlayers = maxPlayers;
_usernames = new List<string>(); //_usernames = new List<string>();
_users = new List<User>();
}
public void AddUser(string username, out bool succes)
{
succes = false;
if (_users.Count < _maxPlayers)
{
_users.Add(new User(username, 0, false));
succes = true;
}
}
public void AddUser(User user, out bool succes)
{
succes = false;
if (_users.Count < _maxPlayers)
{
_users.Add(user);
succes = true;
}
} }
public int ID public int ID
@@ -41,16 +64,29 @@ namespace Client
public int PlayersIn public int PlayersIn
{ {
get { return _playersIn; } get { return _users.Count; }
set { _playersIn = value; } set { _playersIn = value; }
} }
public void Set(Lobby lobby)
{
this._id = lobby._id;
this._users = lobby._users;
this._maxPlayers = lobby._maxPlayers;
}
public int MaxPlayers public int MaxPlayers
{ {
get { return _maxPlayers; } get { return _maxPlayers; }
set { _maxPlayers = value; } set { _maxPlayers = value; }
} }
public List<User> Users
{
get { return _users; }
set { _users = value; }
}
} }
} }

View File

@@ -13,5 +13,6 @@
<Compile Include="$(MSBuildThisFileDirectory)JSONConvert.cs" /> <Compile Include="$(MSBuildThisFileDirectory)JSONConvert.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Lobby.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Lobby.cs" />
<Compile Include="$(MSBuildThisFileDirectory)ObservableObject.cs" /> <Compile Include="$(MSBuildThisFileDirectory)ObservableObject.cs" />
<Compile Include="$(MSBuildThisFileDirectory)User.cs" />
</ItemGroup> </ItemGroup>
</Project> </Project>

View File

@@ -0,0 +1,48 @@
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Text;
namespace SharedClientServer
{
class User
{
private string _username;
private int _score;
private bool _host;
private string _message;
[JsonConstructor]
public User(string username, int score, bool host)
{
_username = username;
_score = score;
_host = host;
}
public User(string username)
{
_username = username;
_score = 0;
_host = false;
}
public string Username
{
get { return _username; }
set { _username = value; }
}
public int Score
{
get { return _score; }
set { _score = value; }
}
public bool Host
{
get { return _host; }
set { _host = value; }
}
}
}