Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for changing nickname #41

Open
wants to merge 1 commit into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 24 additions & 13 deletions client/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,14 +29,13 @@ class Game extends Phaser.Scene {
this.load.image('dirtTile', dirtTileImg);
this.load.image('grassTile', grassTileImg);
this.load.image('background', backgroundImg);
//this.load.image('player', playerImg);

this.load.atlas('player', animationPng, animationJson);
}

create() {
this.background = new Background(this, 0, 0, 0, 0, 'background').setDepth(-100);
this.player = new Player(this, 100, 650, 'player');
this.player = new Player(this, 100, 650, 'player', true);
this.terrain = new Terrain(this.physics.world, this);

this.cameras.main.startFollow(this.player, false, 1, 1, -350, 200);
Expand Down Expand Up @@ -71,7 +70,7 @@ class Game extends Phaser.Scene {
velocity.dx = 0;
}

if (Phaser.Input.Keyboard.JustDown(this.wasd.W) && this.player.body.velocity.y == 0) {
if ((Phaser.Input.Keyboard.JustDown(this.cursors.up) || Phaser.Input.Keyboard.JustDown(this.wasd.W)) && this.player.body.velocity.y === 0) {
velocity.dy = -400;
}

Expand All @@ -87,28 +86,40 @@ class Game extends Phaser.Scene {

handleMessage(msg) {
if (msg.hasJoin()) {
this.joinRecieve(msg.getPlayerId());
const join = msg.getJoin();
this.joinRecieve(msg.getPlayerId(), join.getNickname());
} else if (msg.hasLeave()) {
this.leaveReceive(msg.getPlayerId());
} else if (msg.hasMove()) {
const move = msg.getMove();
this.playerMoveRecieve(msg.getPlayerId(), move.getX(), move.getY(), move.getDx(), move.getDy());
} else if (msg.hasLeave()) {
this.leaveReceive(msg.getPlayerId());
} else if (msg.hasChangeName()) {
const changeName = msg.getChangeName();
this.changeNameReceive(msg.getPlayerId(), changeName.getNickname());
}
}

playerMoveRecieve(player_id, x, y, dx, dy) {
this.players[player_id].move(x, y, dx, dy);
playerMoveRecieve(playerId, x, y, dx, dy) {
this.players[playerId].move(x, y, dx, dy);
}

joinRecieve(player_id) {
joinRecieve(playerId, nickname) {
const player = new Player(this, 100, 650, 'player');
this.players[player_id] = player;
this.players[playerId] = player;
this.physics.add.collider(this.terrain, player);

// TODO: Set player nickname
console.log('Nickname set', playerId, nickname);
}

leaveReceive(playerId) {
this.players[playerId].destroy();
delete this.players[playerId];
}

leaveReceive(player_id) {
this.players[player_id].destroy();
delete this.players[player_id];
changeNameReceive(playerId, nickname) {
// TODO: Change player nickname
console.log('Nickname change', playerId, nickname);
}
}

Expand Down
22 changes: 18 additions & 4 deletions client/src/network/websocket.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,10 @@ export class Websocket {
var message = new messages.Message();
var join = new messages.Join();
message.setJoin(join);
join.setUsername('spela in lara');
join.setNickname(this.getInitialNickname());
this.sendMessage(message);
});



// Listen for messages
this.socket.addEventListener('message', (event) => {
if (this.receiveCallback == null ||
Expand All @@ -30,7 +28,6 @@ export class Websocket {
const message = messages.Message.deserializeBinary(new Uint8Array(event.data));
this.receiveCallback(message);
});

}

sendMessage(message) {
Expand All @@ -48,4 +45,21 @@ export class Websocket {
move.setDy(dy);
this.sendMessage(message);
}

playerNameSend(nickname) {
window.localStorage.setItem('playerName', nickname);

const changeName = new messages.ChangeName();
changeName.setNickname(nickname);
const message = new messages.Message();
message.setChangeName(changeName);
this.sendMessage(message);
}

getInitialNickname() {
const storedName = window.localStorage.getItem('playerName');
if (storedName) return storedName;

return `Player ${Math.floor(Math.random() * 100)}`;
}
}
14 changes: 12 additions & 2 deletions client/src/objects/player.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import Phaser from 'phaser';

export class Player extends Phaser.Physics.Arcade.Sprite {
constructor(scene, x, y, texture) {
constructor(scene, x, y, texture, isMain = false) {
super(scene, x, y, texture);

this.scene.physics.world.enable(this);
Expand All @@ -27,6 +27,8 @@ export class Player extends Phaser.Physics.Arcade.Sprite {
frameRate: 15,
repeat: -1,
});

if (isMain) this.listenForNameChange();
}

move(x, y, dx, dy) {
Expand All @@ -53,5 +55,13 @@ export class Player extends Phaser.Physics.Arcade.Sprite {
this.anims.stop();
}
}
}

listenForNameChange() {
document.addEventListener('keydown', (event) => {
if (event.key === 'n') {
const name = prompt('Enter name');
this.scene.websocket.playerNameSend(name);
}
});
}
}
13 changes: 9 additions & 4 deletions messages/messages.proto
Original file line number Diff line number Diff line change
Expand Up @@ -3,25 +3,30 @@ syntax = "proto3";
option go_package = "./server/internal/messages";

message Join {
string username = 1;
string nickname = 1;
optional bool success = 2;
}

message Leave {}

message Move {
float x = 1;
float y = 2;
float dx = 3;
float dy = 4;
}

message Leave {}
message ChangeName {
string nickname = 1;
}

message Message {
optional string server = 1;
optional int32 player_id = 2;
oneof data {
Join join = 4;
Move move = 5;
Leave leave = 6;
Leave leave = 5;
Move move = 6;
ChangeName change_name = 7;
}
}
28 changes: 20 additions & 8 deletions server/internal/ws/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,10 @@ const (
)

type clientImpl struct {
id int32
addr net.Addr
conn *websocket.Conn
id int32
nickname string
addr net.Addr
conn *websocket.Conn

logger *zap.SugaredLogger

Expand All @@ -36,11 +37,13 @@ type clientImpl struct {
func NewClient(conn *websocket.Conn, serv Server, logger *zap.Logger) Client {
return &clientImpl{
// Just randomly generate
id: rand.Int31(),
addr: conn.RemoteAddr(),
conn: conn,
logger: logger.Sugar(),
server: serv,
id: rand.Int31(),
// Empty nickname, it is set by client on join
nickname: "",
addr: conn.RemoteAddr(),
conn: conn,
logger: logger.Sugar(),
server: serv,

send: make(chan *messages.Message),
}
Expand All @@ -56,6 +59,15 @@ func (c *clientImpl) GetRemoteAddr() net.Addr {
return c.addr
}

func (c *clientImpl) GetNickname() string {
return c.nickname
}

func (c *clientImpl) SetNickname(nickname string) {
// TODO: Validate nickname
c.nickname = nickname
}

//closes the client
func (c *clientImpl) Close() {
close(c.send)
Expand Down
6 changes: 5 additions & 1 deletion server/internal/ws/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,10 @@ func (s *serverImpl) Disconnect(client Client) {
}

func (s *serverImpl) Broadcast(excludeClient int32, msg *messages.Message) {
if join := msg.GetJoin(); join != nil {
s.clients[excludeClient].SetNickname(join.GetNickname())
}

s.broadcast <- broadcastMessage{msg: msg, excludeClient: excludeClient}
}

Expand All @@ -151,7 +155,7 @@ func (s *serverImpl) sendPlayers(client Client) {
PlayerId: &id,
Data: &messages.Message_Join{
Join: &messages.Join{
Username: "",
Nickname: s.clients[id].GetNickname(),
},
},
}
Expand Down
3 changes: 3 additions & 0 deletions server/internal/ws/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@ type Client interface {
GetID() int32
GetRemoteAddr() net.Addr

GetNickname() string
SetNickname(string)

Send(msg *messages.Message)
Close()

Expand Down