12 Commits

Author SHA1 Message Date
Sem van der Hoeven
7ce04447d0 [FIX] fixed canvas data being sent to person drawing 2020-10-23 17:44:39 +02:00
Sem van der Hoeven
2d64accf09 [EDIT] made loginviewmodel kinda mvvm 2020-10-23 17:35:33 +02:00
Sem van der Hoeven
1d8963ec60 [REMOVE] removed the checks for who is host 2020-10-23 17:27:43 +02:00
Lars
13cf0e44ee [ADDED] a begin for the turn base 2020-10-23 16:46:29 +02:00
Lars
eee4f0347f Merge branch 'master' into setupBranch 2020-10-23 15:54:21 +02:00
SemvdH
9558c75eab Merge pull request #14 from SemvdH/feature/guesedWord
[ADDITION] added a new property to the user (may be removed later on)…
2020-10-23 15:51:30 +02:00
Dogukan
ec08fbfced [ADDITION] added a new property to the user (may be removed later on), and made a check for the random word 2020-10-23 15:47:52 +02:00
SemvdH
87ebdeef58 Merge pull request #13 from SemvdH/feature/timer
Feature/timer
2020-10-23 15:45:12 +02:00
Sem van der Hoeven
bf09dba850 [ADD] added timer start on next round message receive 2020-10-23 15:44:18 +02:00
Lars
fd59368c03 Merge branch 'master' into setupBranch 2020-10-23 14:59:41 +02:00
SemvdH
b14a7691b5 Merge pull request #12 from SemvdH/hotfix/fixClientServerComms
[FIX] Callbacks weren't properly called
2020-10-23 14:56:45 +02:00
Sem van der Hoeven
6512518fb7 [FIX] made first user in lobby a host if the host leaves 2020-10-23 14:30:16 +02:00
10 changed files with 225 additions and 48 deletions

View File

@@ -72,7 +72,8 @@ namespace Client
SendMessage(JSONConvert.ConstructUsernameMessage(username));
this.stream.BeginRead(buffer, 0, buffer.Length, new AsyncCallback(OnReadComplete), null);
} catch (Exception e)
}
catch (Exception e)
{
Debug.WriteLine("Can't connect, retrying...");
tcpClient.BeginConnect("localhost", Port, new AsyncCallback(OnConnect), null);
@@ -113,7 +114,8 @@ namespace Client
ar.AsyncWaitHandle.WaitOne();
stream.BeginRead(buffer, 0, buffer.Length, new AsyncCallback(OnReadComplete), null);
} catch (IOException e)
}
catch (IOException e)
{
Debug.WriteLine("[CLIENT] server not responding! got error: " + e.Message);
OnServerDisconnect?.Invoke();
@@ -144,6 +146,11 @@ namespace Client
IncomingMsg?.Invoke(textUsername, textMsg);
}
if (textMsg == data.User.RandomWord && !string.IsNullOrEmpty(data.User.RandomWord))
{
Debug.WriteLine($"[CLIENT] word has been guessed! {data.User.Username} + Word: {data.User.RandomWord}");
}
//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);
@@ -191,29 +198,59 @@ namespace Client
case JSONConvert.CANVAS_WRITING:
CanvasDataReceived?.Invoke(JSONConvert.getCoordinates(payload), JSONConvert.getCanvasDrawingColor(payload));
break;
}
break;
case JSONConvert.RANDOMWORD:
//Flag byte for receiving the random word.
int lobbyId = JSONConvert.GetLobbyID(payload);
string randomWord = JSONConvert.GetRandomWord(payload);
if (data.Lobby?.ID == lobbyId)
RandomWord?.Invoke(randomWord);
data.User.RandomWord = JSONConvert.GetRandomWord(payload);
data.User.TurnToDraw = true; // Dit is test code, dit kan weg zodra alles lopende is.
if (data.Lobby?.ID == lobbyId && data.User.TurnToDraw)
RandomWord?.Invoke(data.User.RandomWord);
break;
default:
Debug.WriteLine("[CLIENT] Received weird identifier: " + id);
break;
case JSONConvert.GAME:
switch (JSONConvert.GetGameCommand(payload))
{
case JSONConvert.GameCommand.TIMER_ELAPSED:
int lobbyElapsedID = JSONConvert.GetLobbyID(payload);
//todo set next round
break;
case JSONConvert.GameCommand.INITIALIZE:
int lobbyID = JSONConvert.GetLobbyID(payload);
string userName = JSONConvert.GetUsernameLogin(payload);
if (lobbyID == clientData.Lobby.ID)
{
if (userName == clientData.User.Username)
{
clientData.User.TurnToDraw = true;
Debug.WriteLine("[CLIENT] Setting a player's turnToDraw to true");
}
clientData.Client.UpdateUserScores?.Invoke(clientData.Lobby);
}
break;
}
break;
}
SendMessage(JSONConvert.GetMessageToSend(JSONConvert.MESSAGE_RECEIVED, null));
}
/*
* Updates the current lobby with the joining players,
* their player score is also tracked and should always be zero.
*/
private void updateGameLobby()
{
Debug.WriteLine("[CLIENT] updating game lobby");

View File

@@ -121,13 +121,18 @@ namespace Client
_lobbies.Clear();
Lobby clientLobby = ClientData.Instance.Lobby;
foreach (Lobby l in lobbiesArr)
{
_lobbies.Add(l);
Lobby clientLobby = ClientData.Instance.Lobby;
if (l.ID == clientLobby?.ID)
{
clientLobby = l;
clientLobby.Users.Clear();
foreach (User user in l.Users)
{
clientLobby.Users.Add(user);
}
}
}

View File

@@ -27,6 +27,8 @@ namespace Client.ViewModels
public Queue<double[][]> linesQueue;
private Timer queueTimer;
private bool wordGuessed = false;
public static ObservableCollection<string> Messages { get; } = new ObservableCollection<string>();
public ObservableCollection<string> Players { get; } = new ObservableCollection<string>();
@@ -50,7 +52,23 @@ namespace Client.ViewModels
private string _randomWord;
public string RandomWord
{
get { return _randomWord; }
get {
if (data.User.TurnToDraw)
return _randomWord;
if (!wordGuessed)
{
string hiddenWord = "";
for (int i = 0; i < _randomWord.Length; i++)
{
hiddenWord += "_ ";
}
return hiddenWord;
}
else
return _randomWord;
}
set { _randomWord = value; }
}
@@ -59,10 +77,15 @@ namespace Client.ViewModels
get { return data.User.Host; }
}
public bool UserTurnToDraw
{
get { return data.User.TurnToDraw; }
}
public ViewModelGame(GameWindow window)
{
this.window = window;
_randomWord = "";
buffer = new double[maxLines][];
linesQueue = new Queue<double[][]>();
OnKeyDown = new RelayCommand(ChatBox_KeyDown);
@@ -144,7 +167,9 @@ namespace Client.ViewModels
public void Canvas_MouseUp(object sender, MouseButtonEventArgs e)
{
sendArrayFromQueue(sender, null);
}
private void sendArrayFromQueue(object sender, ElapsedEventArgs e)
@@ -238,7 +263,7 @@ namespace Client.ViewModels
Players.Clear();
foreach (var item in lobby.Users)
{
Players.Add(item.Username + "\n" + item.Score);
Players.Add(item.Username + "\n" + item.Score + "\n" + item.TurnToDraw);
}
});
}

View File

@@ -20,8 +20,10 @@ namespace Client.Views
public partial class LoginScreen : Window
{
ClientData data = ClientData.Instance;
private LoginViewModel loginViewModel;
public LoginScreen()
{
loginViewModel = new LoginViewModel(this);
InitializeComponent();
}
@@ -29,22 +31,8 @@ namespace Client.Views
{
string name = usernameTextbox.Text;
if (name == string.Empty) return;
User user = new User(name);
Client client = new Client(user.Username);
LoginButton.IsEnabled = false;
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();
});
};
loginViewModel.UsernameEntered(name);
}

View File

@@ -11,6 +11,7 @@ using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Timers;
using static SharedClientServer.JSONConvert;
namespace Server.Models
@@ -22,7 +23,9 @@ namespace Server.Models
private NetworkStream stream;
private byte[] buffer = new byte[2048];
private byte[] totalBuffer = new byte[2048];
private string _randomWord = "";
private int totalBufferReceived = 0;
private Dictionary<System.Timers.Timer, int> lobbyTimers;
public User User { get; set; }
private ServerCommunication serverCom = ServerCommunication.INSTANCE;
private Callback OnMessageReceivedOk;
@@ -34,6 +37,7 @@ namespace Server.Models
/// <param name="client">the TcpClient object to use</param>
public ServerClient(TcpClient client)
{
lobbyTimers = new Dictionary<System.Timers.Timer, int>();
Debug.WriteLine("[SERVERCLIENT] making new instance and starting");
tcpClient = client;
stream = tcpClient.GetStream();
@@ -145,6 +149,11 @@ namespace Server.Models
message = textMsg
};
if (textMsg == _randomWord && !string.IsNullOrEmpty(_randomWord))
{
Debug.WriteLine($"[SERVERCLIENT] word has been guessed! {User.Username} + Word: {_randomWord}");
}
//Sends the incomming message to be broadcast to all of the clients inside the current lobby.
serverCom.SendToLobby(serverCom.GetLobbyForUser(User), JSONConvert.GetMessageToSend(JSONConvert.MESSAGE, packet));
break;
@@ -167,7 +176,7 @@ namespace Server.Models
coords = JSONConvert.getCoordinates(payload),
color = JSONConvert.getCanvasDrawingColor(payload)
};
serverCom.SendToLobby(serverCom.GetLobbyForUser(User),JSONConvert.GetMessageToSend(JSONConvert.CANVAS,canvasData));
serverCom.SendCanvasDataToLobby(serverCom.GetLobbyForUser(User),User.Username,JSONConvert.GetMessageToSend(JSONConvert.CANVAS,canvasData));
break;
case JSONConvert.CANVAS_RESET:
@@ -186,13 +195,36 @@ namespace Server.Models
case JSONConvert.GAME:
Debug.WriteLine("[SERVERCLIENT] Got a message about the game logic");
string command = JSONConvert.GetGameCommand(payload);
GameCommand command = JSONConvert.GetGameCommand(payload);
switch (command)
{
case "startGame":
case GameCommand.START_GAME:
int lobbyID = JSONConvert.GetStartGameLobbyID(payload);
serverCom.CloseALobby(lobbyID);
//todo start a timer for this lobby
Debug.WriteLine("[SERVERCLIENT] making timer for lobby " + lobbyID);
System.Timers.Timer lobbyTimer = new System.Timers.Timer(60 * 1000);
this.lobbyTimers.Add(lobbyTimer, lobbyID);
lobbyTimer.Elapsed += LobbyTimer_Elapsed;
lobbyTimer.Start();
ServerCommunication.INSTANCE.sendToAll(JSONConvert.ConstructLobbyListMessage(ServerCommunication.INSTANCE.lobbies.ToArray()));
serverCom.SendToLobby(lobbyID, JSONConvert.ConstructGameInitializeData( serverCom.FindUserNameInLobby(lobbyID),lobbyID));
break;
case GameCommand.TIMER_ELAPSED:
break;
case GameCommand.NEXT_ROUND:
// The next round has been started, so we can start the timer again
lobbyID = JSONConvert.GetLobbyID(payload);
foreach (System.Timers.Timer timer in lobbyTimers.Keys)
{
if (lobbyTimers[timer] == lobbyID)
{
timer.Start();
break;
}
}
break;
}
@@ -211,6 +243,17 @@ namespace Server.Models
}
}
private void LobbyTimer_Elapsed(object sender, ElapsedEventArgs e)
{
System.Timers.Timer timer = sender as System.Timers.Timer;
int lobbyID = lobbyTimers[timer];
Debug.WriteLine("[SERVERCLIENT] timer elapsed for lobby " + lobbyID);
serverCom.SendToLobby(lobbyID, JSONConvert.ConstructGameTimerElapsedMessage(lobbyID));
timer.Stop();
}
private void handleLobbyMessage(byte[] payload, LobbyIdentifier l)
{
switch (l)
@@ -234,11 +277,11 @@ namespace Server.Models
ServerCommunication.INSTANCE.sendToAll(JSONConvert.ConstructLobbyListMessage(ServerCommunication.INSTANCE.lobbies.ToArray()));
OnMessageReceivedOk = () =>
{
_randomWord = JSONConvert.SendRandomWord("WordsForGame.json");
serverCom.sendToAll(JSONConvert.GetMessageToSend(JSONConvert.RANDOMWORD, new
{
id = serverCom.GetLobbyForUser(User).ID,
word = JSONConvert.SendRandomWord("WordsForGame.json")
word = _randomWord
}));
OnMessageReceivedOk = null;
};

View File

@@ -142,7 +142,23 @@ namespace Server.Models
{
foreach (ServerClient sc in serverClientsInlobbies[l])
{
Debug.WriteLine("[SERVERCLIENT] Sending message");
Debug.WriteLine("[SERVERCLIENT] Sending message to lobby");
sc.sendMessage(message);
}
break;
}
}
}
public void SendToLobby(int lobbyID, byte[] message)
{
foreach (Lobby l in lobbies)
{
if (l.ID == lobbyID)
{
foreach (ServerClient sc in serverClientsInlobbies[l])
{
Debug.WriteLine("[SERVERCLIENT] Sending message to lobby");
sc.sendMessage(message);
}
break;
@@ -158,6 +174,7 @@ namespace Server.Models
{
foreach (ServerClient sc in serverClientsInlobbies[l])
{
if (sc.User.Username != username)
sc.sendMessage(message);
}
break;
@@ -261,6 +278,10 @@ namespace Server.Models
break;
}
}
if (l.Users.Count != 0)
{
l.Users[0].Host = true;
}
break;
}
}
@@ -278,8 +299,24 @@ namespace Server.Models
if (lobby.ID == lobbyID)
{
lobby.LobbyJoinable = false;
break;
}
}
}
public string FindUserNameInLobby(int lobbyID)
{
Lobby lobbyFound = null;
foreach (Lobby lobby in lobbies)
{
if (lobby.ID == lobbyID)
{
lobbyFound = lobby;
break;
}
}
return lobbyFound?.Users[lobbyFound.UserDrawing]?.Username;
}
}
}

View File

@@ -35,6 +35,14 @@ namespace SharedClientServer
REQUEST
}
public enum GameCommand
{
START_GAME,
INITIALIZE,
TIMER_ELAPSED,
NEXT_ROUND
}
public static (string,string) GetUsernameAndMessage(byte[] json)
{
string msg = Encoding.UTF8.GetString(json);
@@ -205,15 +213,35 @@ namespace SharedClientServer
public static byte[] ConstructGameStartData(int lobbyID)
{
string startGame = "startGame";
return GetMessageToSend(GAME, new
{
command = startGame,
command = GameCommand.START_GAME,
lobbyToStart = lobbyID
}); ;
}
public static string GetGameCommand(byte[] payload)
public static byte[] ConstructGameInitializeData(string userName, int lobbyID)
{
dynamic payload = new
{
id = lobbyID,
command = GameCommand.INITIALIZE,
username = userName
};
return GetMessageToSend(GAME, payload);
}
public static byte[] ConstructGameTimerElapsedMessage(int lobbyID)
{
return GetMessageToSend(GAME, new
{
command = GameCommand.TIMER_ELAPSED,
id = lobbyID
});
}
public static GameCommand GetGameCommand(byte[] payload)
{
dynamic json = JsonConvert.DeserializeObject(Encoding.UTF8.GetString(payload));
return json.command;

View File

@@ -17,6 +17,7 @@ namespace Client
private bool _lobbyJoinable;
//private List<string> _usernames;
private List<User> _users;
private int _userDrawing;
//public void AddUsername(string username, out bool success)
//{
@@ -36,6 +37,7 @@ namespace Client
//_usernames = new List<string>();
_users = new List<User>();
_lobbyJoinable = true;
_userDrawing = 0;
}
public void AddUser(string username, out bool succes)
@@ -95,5 +97,11 @@ namespace Client
set { _lobbyJoinable = value; }
}
public int UserDrawing
{
get { return _userDrawing; }
set { _userDrawing = value; }
}
}
}

View File

@@ -13,6 +13,7 @@ namespace SharedClientServer
private bool _host;
private bool _turnToDraw;
private string _message;
private string _randomWord;
[JsonConstructor]
public User(string username, int score, bool host, bool turnToDraw)
@@ -90,5 +91,10 @@ namespace SharedClientServer
get { return _turnToDraw; }
set { _turnToDraw = value; }
}
public string RandomWord
{
get { return _randomWord; }
set { _randomWord = value; }
}
}
}