Merge pull request #9 from SemvdH/feature/playerList

Feature/player list
This commit is contained in:
SemvdH
2020-10-23 12:53:43 +02:00
committed by GitHub
7 changed files with 65 additions and 21 deletions

View File

@@ -13,9 +13,14 @@ using static SharedClientServer.JSONConvert;
namespace Client namespace Client
{ {
public delegate void LobbyJoinCallback(bool isHost); 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 CanvasDataReceived(double[][] coordinates, Color color);
public delegate void CanvasReset(); public delegate void CanvasReset();
public delegate void LobbyCallback(int id); public delegate void LobbyCallback(int id);
class Client : ObservableObject class Client : ObservableObject
{ {
@@ -34,8 +39,12 @@ namespace Client
public LobbyJoinCallback OnLobbyJoinSuccess; public LobbyJoinCallback OnLobbyJoinSuccess;
public Callback OnLobbiesReceivedAndWaitingForHost; public Callback OnLobbiesReceivedAndWaitingForHost;
public Callback OnServerDisconnect; public Callback OnServerDisconnect;
public Callback OnLobbyUpdate;
public LobbyCallback OnLobbyCreated; public LobbyCallback OnLobbyCreated;
public LobbyCallback OnLobbyLeave; public LobbyCallback OnLobbyLeave;
public RandomWord RandomWord;
public HandleIncomingMsg IncomingMsg;
public HandleIncomingPlayer IncomingPlayer;
private ClientData data = ClientData.Instance; private ClientData data = ClientData.Instance;
public CanvasDataReceived CanvasDataReceived; public CanvasDataReceived CanvasDataReceived;
public CanvasReset CReset; public CanvasReset CReset;
@@ -57,6 +66,7 @@ namespace Client
this.tcpClient.EndConnect(ar); this.tcpClient.EndConnect(ar);
this.stream = tcpClient.GetStream(); this.stream = tcpClient.GetStream();
OnSuccessfullConnect?.Invoke(); OnSuccessfullConnect?.Invoke();
OnLobbyUpdate = updateGameLobby;
SendMessage(JSONConvert.ConstructUsernameMessage(username)); 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);
@@ -72,6 +82,7 @@ namespace Client
if (ar == null || (!ar.IsCompleted) || (!this.stream.CanRead) || !this.tcpClient.Client.Connected) if (ar == null || (!ar.IsCompleted) || (!this.stream.CanRead) || !this.tcpClient.Client.Connected)
return; return;
try try
{ {
int amountReceived = stream.EndRead(ar); int amountReceived = stream.EndRead(ar);
@@ -129,7 +140,7 @@ namespace Client
if(textUsername != data.User.Username) if(textUsername != data.User.Username)
{ {
ViewModels.ViewModelGame.HandleIncomingMsg(textUsername, textMsg); IncomingMsg?.Invoke(textUsername, textMsg);
} }
//TODO display username and message in chat window //TODO display username and message in chat window
@@ -147,6 +158,7 @@ namespace Client
Lobbies = JSONConvert.GetLobbiesFromMessage(payload); Lobbies = JSONConvert.GetLobbiesFromMessage(payload);
OnLobbiesListReceived?.Invoke(); OnLobbiesListReceived?.Invoke();
OnLobbiesReceivedAndWaitingForHost?.Invoke(); OnLobbiesReceivedAndWaitingForHost?.Invoke();
OnLobbyUpdate?.Invoke();
break; break;
case LobbyIdentifier.HOST: case LobbyIdentifier.HOST:
// we receive this when the server has made us a host of a new lobby // we receive this when the server has made us a host of a new lobby
@@ -156,7 +168,6 @@ namespace Client
OnLobbyCreated?.Invoke(lobbyCreatedID); OnLobbyCreated?.Invoke(lobbyCreatedID);
break; break;
case LobbyIdentifier.JOIN_SUCCESS: case LobbyIdentifier.JOIN_SUCCESS:
OnLobbyJoinSuccess?.Invoke(JSONConvert.GetLobbyJoinIsHost(payload)); OnLobbyJoinSuccess?.Invoke(JSONConvert.GetLobbyJoinIsHost(payload));
break; break;
case LobbyIdentifier.LEAVE: case LobbyIdentifier.LEAVE:
@@ -189,9 +200,11 @@ namespace Client
case JSONConvert.RANDOMWORD: case JSONConvert.RANDOMWORD:
//Flag byte for receiving the random word. //Flag byte for receiving the random word.
int lobbyId = JSONConvert.GetLobbyID(payload); int lobbyId = JSONConvert.GetLobbyID(payload);
string randomWord = JSONConvert.GetRandomWord(payload);
if (data.Lobby?.ID == lobbyId) if (data.Lobby?.ID == lobbyId)
ViewModels.ViewModelGame.HandleRandomWord(JSONConvert.GetRandomWord(payload)); RandomWord?.Invoke(randomWord);
break; break;
default: default:
Debug.WriteLine("[CLIENT] Received weird identifier: " + id); Debug.WriteLine("[CLIENT] Received weird identifier: " + id);
@@ -201,11 +214,20 @@ namespace Client
} }
private void updateGameLobby()
{
foreach (var item in Lobbies)
{
Debug.WriteLine("[CLIENT] lobby data: {0}", item.Users.Count);
if (item.ID == data.Lobby?.ID)
IncomingPlayer?.Invoke(item);
}
}
public void SendMessage(byte[] message) public void SendMessage(byte[] message)
{ {
Debug.WriteLine("[CLIENT] sending message " + Encoding.ASCII.GetString(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)

View File

@@ -1,4 +1,3 @@
using Client.Views; using Client.Views;
using GalaSoft.MvvmLight.Command; using GalaSoft.MvvmLight.Command;
using SharedClientServer; using SharedClientServer;
@@ -29,6 +28,7 @@ namespace Client.ViewModels
private Timer queueTimer; private Timer queueTimer;
public static 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 dynamic _payload;
@@ -47,6 +47,14 @@ namespace Client.ViewModels
} }
} }
private string _randomWord;
public string RandomWord
{
get { return _randomWord; }
set { _randomWord = value; }
}
public static string Word public static string Word
{ {
get; get;
@@ -80,6 +88,9 @@ namespace Client.ViewModels
ButtonResetCanvas = new RelayCommand(CanvasResetLocal); ButtonResetCanvas = new RelayCommand(CanvasResetLocal);
data.Client.CanvasDataReceived = UpdateCanvasWithNewData; data.Client.CanvasDataReceived = UpdateCanvasWithNewData;
data.Client.CReset = CanvasResetData; data.Client.CReset = CanvasResetData;
data.Client.RandomWord = HandleRandomWord;
data.Client.IncomingMsg = HandleIncomingMsg;
data.Client.IncomingPlayer = HandleIncomingPlayer;
} }
public ICommand OnKeyDown { get; set; } public ICommand OnKeyDown { get; set; }
@@ -237,6 +248,16 @@ namespace Client.ViewModels
Word = randomWord; Word = randomWord;
}); });
} }
public void HandleIncomingPlayer(Lobby lobby)
{
Application.Current.Dispatcher.Invoke(delegate
{
Players.Clear();
foreach (var item in lobby.Users)
{
Players.Add(item.Username);
}
});
}
} }
} }

View File

@@ -22,16 +22,9 @@
<Grid Grid.Column="0" Grid.Row="1"> <Grid Grid.Column="0" Grid.Row="1">
<Grid.RowDefinitions> <Grid.RowDefinitions>
<RowDefinition/> <RowDefinition/>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions> </Grid.RowDefinitions>
<ListBox Name="PlayerList" ItemsSource="{Binding Path=Players}" Margin="10,0,0,10" FontSize="20"/>
</Grid> </Grid>
<Grid Grid.Row="0" Grid.Column="1"> <Grid Grid.Row="0" Grid.Column="1">
@@ -44,13 +37,15 @@
<Label Grid.Row="0" Grid.Column="0" VerticalAlignment="Center" FontSize="20" Content="Pick a color -->"/> <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"/> <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"/>
<Label Grid.Row="0" Grid.Column="2" FontSize="20" Content="" VerticalAlignment="Center" HorizontalAlignment="Center"/> <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"/> <Button Name="CanvasReset" Click="CanvasReset_Click" Grid.Row="0" Grid.Column="3" Content="RESET"/>
</Grid> </Grid>
<Button Name="StartGame" Grid.Row="0" Grid.Column="2" Content="Start Game" FontSize="20" Command="{Binding ButtonStartGame}" IsEnabled="{Binding IsHost}"/> <Button Name="StartGame" Grid.Row="0" Grid.Column="2" Content="Start Game" FontSize="20" Command="{Binding ButtonStartGame}" IsEnabled="{Binding IsHost}"/>
<Label Name="GuessWord" Grid.Row="0" Grid.Column="1" Content="{Binding Path=Word, UpdateSourceTrigger=PropertyChanged}" Margin="418,-5,103,5"/>
<Border Grid.Row="1" Grid.Column="1" Margin ="10,10,10,10" BorderBrush="Black" BorderThickness ="2.5"> <Border Grid.Row="1" Grid.Column="1" Margin ="10,10,10,10" BorderBrush="Black" BorderThickness ="2.5">
@@ -62,9 +57,9 @@
</Border> </Border>
<Grid Grid.Column="2" Grid.Row="1"> <Grid Grid.Column="2" Grid.Row="1">
<ListBox Name ="TextBox" ItemsSource="{Binding Path=Messages}" Margin="0,0,0,69"/> <ListBox Name ="TextBox" ItemsSource="{Binding Path=Messages}" Margin="0,0,10,69" />
<TextBox Name="ChatBox" Text="{Binding Message, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Margin="0,465,0,0"> <TextBox Name="ChatBox" Text="{Binding Message, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Margin="0,465,10,0">
<TextBox.InputBindings> <TextBox.InputBindings>
<KeyBinding Key="Return" Command="{Binding OnKeyDown}"/> <KeyBinding Key="Return" Command="{Binding OnKeyDown}"/>
</TextBox.InputBindings> </TextBox.InputBindings>

View File

@@ -11,6 +11,7 @@
<RowDefinition Height="60"/> <RowDefinition Height="60"/>
<RowDefinition Height="50"/> <RowDefinition Height="50"/>
<RowDefinition Height="30"/> <RowDefinition Height="30"/>
<RowDefinition Height="100"/>
</Grid.RowDefinitions> </Grid.RowDefinitions>
<Grid.ColumnDefinitions> <Grid.ColumnDefinitions>
@@ -22,8 +23,9 @@
<Label Grid.Row="1" FontSize="30" Content="Enter a username:"/> <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)"/> <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"/> <TextBox Name="usernameTextbox" Grid.Row="1" Grid.Column="1" MaxLength="69" 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"/> <Button Content="ENTER" Grid.Column="1" Grid.Row="1" VerticalAlignment="Center" HorizontalAlignment="Right" Width="100" Height="40" Click="Button_EnterUsername"/>
<Label Grid.Row="3" Grid.Column="0" Content="Tip of the century: base64 != UTF8!" FontSize="20" FontWeight="Bold"/>
</Grid> </Grid>
</Window> </Window>

View File

@@ -1,4 +1,5 @@
using SharedClientServer; using Client.ViewModels;
using SharedClientServer;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Text; using System.Text;

View File

@@ -59,6 +59,7 @@ namespace Server.Models
throw new OutOfMemoryException("buffer is too small!"); throw new OutOfMemoryException("buffer is too small!");
} }
// copy the received bytes into the buffer // copy the received bytes into the buffer
Array.Copy(buffer, 0, totalBuffer, totalBufferReceived, bytesReceived); Array.Copy(buffer, 0, totalBuffer, totalBufferReceived, bytesReceived);
// add the bytes we received to the total amount // add the bytes we received to the total amount
@@ -90,6 +91,7 @@ namespace Server.Models
} }
ar.AsyncWaitHandle.WaitOne(); ar.AsyncWaitHandle.WaitOne();
// 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);
@@ -232,6 +234,7 @@ namespace Server.Models
ServerCommunication.INSTANCE.sendToAll(JSONConvert.ConstructLobbyListMessage(ServerCommunication.INSTANCE.lobbies.ToArray())); ServerCommunication.INSTANCE.sendToAll(JSONConvert.ConstructLobbyListMessage(ServerCommunication.INSTANCE.lobbies.ToArray()));
OnMessageReceivedOk = () => OnMessageReceivedOk = () =>
{ {
serverCom.sendToAll(JSONConvert.GetMessageToSend(JSONConvert.RANDOMWORD, new serverCom.sendToAll(JSONConvert.GetMessageToSend(JSONConvert.RANDOMWORD, new
{ {
id = serverCom.GetLobbyForUser(User).ID, id = serverCom.GetLobbyForUser(User).ID,

View File

@@ -6,7 +6,7 @@ using System.Text;
namespace Client namespace Client
{ {
class Lobby : INotifyPropertyChanged internal class Lobby : INotifyPropertyChanged
{ {
public event PropertyChangedEventHandler PropertyChanged; public event PropertyChangedEventHandler PropertyChanged;