forked from Tnze/go-mc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
basic.go
87 lines (76 loc) · 2.41 KB
/
basic.go
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
// Package basic provides some basic packet handler which client needs.
//
// # [Player]
//
// The [Player] is attached to a [Client] by calling [NewPlayer] before the client joins a server.
//
// There is 4 kinds of clientbound packet is handled by this package.
// - LoginPacket, for cache player info. The player info will be stored in [Player.PlayerInfo].
// - KeepAlivePacket, for avoid the client to be kicked by the server.
// - PlayerPosition, is only received when server teleporting the player.
// - Respawn, for updating player info, which may change when player respawned.
//
// # [EventsListener]
//
// Handles some basic event you probably need.
// - GameStart
// - Disconnect
// - HealthChange
// - Death
package basic
import (
"github.com/SkyVillageMC/go-mc/bot"
"github.com/SkyVillageMC/go-mc/data/packetid"
pk "github.com/SkyVillageMC/go-mc/net/packet"
)
type Player struct {
c *bot.Client
Settings Settings
PlayerInfo
WorldInfo
}
// NewPlayer create a new Player manager.
func NewPlayer(c *bot.Client, settings Settings, events EventsListener) *Player {
p := &Player{c: c, Settings: settings}
c.Events.AddListener(
bot.PacketHandler{Priority: 0, ID: packetid.ClientboundLogin, F: p.handleLoginPacket},
bot.PacketHandler{Priority: 0, ID: packetid.ClientboundKeepAlive, F: p.handleKeepAlivePacket},
bot.PacketHandler{Priority: 0, ID: packetid.ClientboundRespawn, F: p.handleRespawnPacket},
)
events.attach(p)
return p
}
// Respawn is used to send a respawn packet to the server.
// Typically, you should call this method when the player is dead (in the [Death] event handler).
func (p *Player) Respawn() error {
const PerformRespawn = 0
err := p.c.Conn.WritePacket(pk.Marshal(
int32(packetid.ServerboundClientCommand),
pk.VarInt(PerformRespawn),
))
if err != nil {
return Error{err}
}
return nil
}
// AcceptTeleportation is used to send a teleport confirmation packet to the server.
// Typically, you should call this method when received a ClientboundPlayerPosition packet (in the [Teleported] event handler).
func (p *Player) AcceptTeleportation(teleportID pk.VarInt) error {
err := p.c.Conn.WritePacket(pk.Marshal(
packetid.ServerboundAcceptTeleportation,
teleportID,
))
if err != nil {
return Error{err}
}
return nil
}
type Error struct {
Err error
}
func (e Error) Error() string {
return "bot/basic: " + e.Err.Error()
}
func (e Error) Unwrap() error {
return e.Err
}