forked from castle-games/basic-multiplayer-tutorial
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.lua
100 lines (84 loc) · 2.81 KB
/
client.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
require 'common'
local client = clientServer.client
if USE_LOCAL_SERVER then
client.enabled = true
client.start('127.0.0.1:22122')
else
client.useCastleConfig()
end
local share = client.share
local home = client.home
function client.connect()
print('client: connected to server')
local player = share.players[client.id]
home.x, home.y = player.x, player.y
home.me = castle.user.getMe()
end
function client.disconnect()
print('client: disconnected from server')
end
function client.receive(message, ...)
if message == 'otherClientPressedKey' then
local otherClientId, key = ...
if otherClientId ~= client.id then
print('client: other client ' .. otherClientId .. " pressed key '" .. key .. "'")
end
end
end
local playerImages = {}
function client.draw()
if client.connected then
for clientId, player in pairs(share.players) do
local x, y = player.x, player.y
if clientId == client.id then
x, y = home.x, home.y
end
if not playerImages[clientId] then
playerImages[clientId] = {}
end
if playerImages[clientId].image then
-- Image is loaded, draw it
local image = playerImages[clientId].image
love.graphics.draw(image, x - 20, y - 20, 0,
40 / image:getWidth(), 40 / image:getHeight())
else
-- Image isn't loaded, draw a rectangle for now
love.graphics.rectangle('fill', x - 20, y - 20, 40, 40)
-- If a photo is available and we haven't fetched it yet,
-- start fetching it and then save the image
if player.me and player.me.photoUrl
and not playerImages[clientId].fetched then
playerImages[clientId].fetched = true
network.async(function()
local image = love.graphics.newImage(player.me.photoUrl)
playerImages[clientId].image = image
end)
end
end
end
else
love.graphics.print('connecting...', 20, 20)
end
end
local PLAYER_SPEED = 200
function client.update(dt)
if client.connected then
if love.keyboard.isDown('left') then
home.x = home.x - PLAYER_SPEED * dt
end
if love.keyboard.isDown('right') then
home.x = home.x + PLAYER_SPEED * dt
end
if love.keyboard.isDown('up') then
home.y = home.y - PLAYER_SPEED * dt
end
if love.keyboard.isDown('down') then
home.y = home.y + PLAYER_SPEED * dt
end
end
end
function client.keypressed(key)
if client.connected then
client.send('pressedKey', key)
end
end