Fix some warnings and typos

This commit is contained in:
Tnze
2021-02-18 14:07:30 +08:00
parent 750f87e780
commit bc9cd93066
23 changed files with 102 additions and 86 deletions

View File

@ -75,7 +75,7 @@ type eventBroker struct {
// The default handler will run only if pass == false.
ReceivePacket func(p pk.Packet) (pass bool, err error)
// PrePhysics will be called before a phyiscs tick.
// PrePhysics will be called before a physics tick.
PrePhysics func() error
}

View File

@ -31,7 +31,7 @@ func ExampleClient_JoinServer_offline() {
}
log.Println("Login success")
// Regist event handlers
// Register event handlers
// c.Events.GameStart = onGameStartFunc
// c.Events.ChatMsg = onChatMsgFunc
// c.Events.Disconnect = onDisconnectFunc
@ -63,7 +63,7 @@ func ExampleClient_JoinServer_online() {
}
log.Println("Login success")
// Regist event handlers
// Register event handlers
// c.Events.GameStart = onGameStartFunc
// c.Events.ChatMsg = onChatMsgFunc
// c.Events.Disconnect = onDisconnectFunc

View File

@ -34,11 +34,11 @@ func OfflineUUID(name string) uuid.UUID {
h.Reset()
h.Write([]byte("OfflinePlayer:" + name))
s := h.Sum(nil)
var uuid uuid.UUID
copy(uuid[:], s)
uuid[6] = (uuid[6] & 0x0f) | uint8((version&0xf)<<4)
uuid[8] = (uuid[8] & 0x3f) | 0x80 // RFC 4122 variant
return uuid
var id uuid.UUID
copy(id[:], s)
id[6] = (id[6] & 0x0f) | uint8((version&0xf)<<4)
id[8] = (id[8] & 0x3f) | 0x80 // RFC 4122 variant
return id
}
// 加密请求
@ -140,7 +140,7 @@ func authDigest(serverID string, sharedSecret, publicKey []byte) string {
func twosComplement(p []byte) []byte {
carry := true
for i := len(p) - 1; i >= 0; i-- {
p[i] = byte(^p[i])
p[i] = ^p[i]
if carry {
carry = p[i] == 0xff
p[i]++
@ -202,7 +202,9 @@ func loginAuth(AsTk, name, UUID string, shareSecret []byte, er encryptionRequest
// AES/CFB8 with random key
func newSymmetricEncryption() (key []byte, encoStream, decoStream cipher.Stream) {
key = make([]byte, 16)
rand.Read(key) //生成密钥
if _, err := rand.Read(key); err != nil {
panic(err)
}
b, err := aes.NewCipher(key)
if err != nil {

View File

@ -202,7 +202,7 @@ func (s *State) applyPosInputs(input path.Inputs, acceleration, inertia float64)
}
func (s *State) tickPosition(w World) {
player, newVel := s.computeCollisionYXZ(s.BB(), s.BB().Offset(s.Vel.X, s.Vel.Y, s.Vel.Z), s.Vel, w)
p, newVel := s.computeCollisionYXZ(s.BB(), s.BB().Offset(s.Vel.X, s.Vel.Y, s.Vel.Z), s.Vel, w)
if s.onGround || (s.Vel.Y != newVel.Y && s.Vel.Y < 0) {
bb := s.BB()
@ -236,15 +236,15 @@ func (s *State) tickPosition(w World) {
if oldMove >= newMove || outVel.Y <= (0.000002-stepHeight) {
// fmt.Println("nope")
} else {
player = bb
p = bb
newVel = outVel
}
}
// Update flags.
s.Pos.X = player.X.Min + playerWidth/2
s.Pos.Y = player.Y.Min
s.Pos.Z = player.Z.Min + playerWidth/2
s.Pos.X = p.X.Min + playerWidth/2
s.Pos.Y = p.Y.Min
s.Pos.Z = p.Z.Min + playerWidth/2
s.collision.horizontal = newVel.X != s.Vel.X || newVel.Z != s.Vel.Z
s.collision.vertical = newVel.Y != s.Vel.Y
s.onGround = s.collision.vertical && s.Vel.Y < 0

View File

@ -5,20 +5,20 @@ package world
// space of a uint64 is unused.
type bitArray struct {
width uint // bit width of each value
valsPerElement uint // number of values which fit into a single uint64.
valuesPerElement uint // number of values which fit into a single uint64.
data []uint64
}
// Size returns the number of elements that can fit into the bit array.
func (b *bitArray) Size() int {
return int(b.valsPerElement) * len(b.data)
return int(b.valuesPerElement) * len(b.data)
}
func (b *bitArray) Set(idx, val uint) {
var (
arrayIdx = idx / b.valsPerElement
startBit = (idx % b.valsPerElement) * b.width
arrayIdx = idx / b.valuesPerElement
startBit = (idx % b.valuesPerElement) * b.width
mask = ^uint64((1<<b.width - 1) << startBit) // set for all bits except target
)
b.data[arrayIdx] = (b.data[arrayIdx] & mask) | uint64(val<<startBit)
@ -26,13 +26,13 @@ func (b *bitArray) Set(idx, val uint) {
func (b *bitArray) Get(idx uint) uint {
var (
arrayIdx = idx / b.valsPerElement
offset = (idx % b.valsPerElement) * b.width
arrayIdx = idx / b.valuesPerElement
offset = (idx % b.valuesPerElement) * b.width
mask = uint64((1<<b.width - 1) << offset) // set for just the target
)
return uint(b.data[arrayIdx]&mask) >> offset
}
func valsPerBitArrayElement(bitsPerValue uint) uint {
func valuesPerBitArrayElement(bitsPerValue uint) uint {
return uint(64 / bitsPerValue)
}

View File

@ -9,7 +9,7 @@ import (
func TestBitArrayBasic(t *testing.T) {
a := bitArray{
width: 5,
valsPerElement: valsPerBitArrayElement(5),
valuesPerElement: valuesPerBitArrayElement(5),
data: make([]uint64, 5),
}
@ -33,7 +33,7 @@ func TestBitArrayHardcoded(t *testing.T) {
a := bitArray{
width: 5,
valsPerElement: valsPerBitArrayElement(5),
valuesPerElement: valuesPerBitArrayElement(5),
data: []uint64{binary.BigEndian.Uint64(d1), binary.BigEndian.Uint64(d2)},
}

View File

@ -93,7 +93,7 @@ func readSection(data pk.DecodeReader) (s Section, err error) {
sec := directSection{
bitArray{
width: width,
valsPerElement: valsPerBitArrayElement(width),
valuesPerElement: valuesPerBitArrayElement(width),
data: dataArray,
},
}
@ -133,12 +133,12 @@ func (d *directSection) clone(bpb uint) *directSection {
}
func newSectionWithSize(bpb uint) *directSection {
valsPerElement := valsPerBitArrayElement(bpb)
valuesPerElement := valuesPerBitArrayElement(bpb)
return &directSection{
bitArray{
width: bpb,
valsPerElement: valsPerElement,
data: make([]uint64, int(math.Ceil(16*16*16/float64(valsPerElement)))),
valuesPerElement: valuesPerElement,
data: make([]uint64, int(math.Ceil(16*16*16/float64(valuesPerElement)))),
},
}
}

View File

@ -84,9 +84,13 @@ func (s Slot) Encode() []byte {
b.Write(pk.Byte(s.Count).Encode())
if s.NBT != nil {
nbt.NewEncoder(&b).Encode(s.NBT)
if err := nbt.NewEncoder(&b).Encode(s.NBT); err != nil {
panic(err)
}
} else {
b.Write([]byte{nbt.TagEnd})
if _, err := b.Write([]byte{nbt.TagEnd}); err != nil {
panic(err)
}
}
return b.Bytes()

View File

@ -24,7 +24,7 @@ func (w *World) PlayerEntities() []entity.Entity {
}
// OnSpawnEntity should be called when a SpawnEntity packet
// is recieved.
// is received.
func (w *World) OnSpawnEntity(pkt ptypes.SpawnEntity) error {
w.entityLock.Lock()
defer w.entityLock.Unlock()
@ -53,7 +53,7 @@ func (w *World) OnSpawnEntity(pkt ptypes.SpawnEntity) error {
}
// OnSpawnLivingEntity should be called when a SpawnLivingEntity packet
// is recieved.
// is received.
func (w *World) OnSpawnLivingEntity(pkt ptypes.SpawnLivingEntity) error {
w.entityLock.Lock()
defer w.entityLock.Unlock()
@ -81,7 +81,7 @@ func (w *World) OnSpawnLivingEntity(pkt ptypes.SpawnLivingEntity) error {
}
// OnSpawnPlayer should be called when a SpawnPlayer packet
// is recieved.
// is received.
func (w *World) OnSpawnPlayer(pkt ptypes.SpawnPlayer) error {
w.entityLock.Lock()
defer w.entityLock.Unlock()
@ -100,7 +100,7 @@ func (w *World) OnSpawnPlayer(pkt ptypes.SpawnPlayer) error {
}
// OnEntityPosUpdate should be called when an EntityPosition packet
// is recieved.
// is received.
func (w *World) OnEntityPosUpdate(pkt ptypes.EntityPosition) error {
w.entityLock.Lock()
defer w.entityLock.Unlock()
@ -118,7 +118,7 @@ func (w *World) OnEntityPosUpdate(pkt ptypes.EntityPosition) error {
}
// OnEntityPosLookUpdate should be called when an EntityPositionLook packet
// is recieved.
// is received.
func (w *World) OnEntityPosLookUpdate(pkt ptypes.EntityPositionLook) error {
w.entityLock.Lock()
defer w.entityLock.Unlock()
@ -137,7 +137,7 @@ func (w *World) OnEntityPosLookUpdate(pkt ptypes.EntityPositionLook) error {
}
// OnEntityLookUpdate should be called when an EntityRotation packet
// is recieved.
// is received.
func (w *World) OnEntityLookUpdate(pkt ptypes.EntityRotation) error {
w.entityLock.Lock()
defer w.entityLock.Unlock()
@ -153,7 +153,7 @@ func (w *World) OnEntityLookUpdate(pkt ptypes.EntityRotation) error {
}
// OnEntityDestroy should be called when a DestroyEntities packet
// is recieved.
// is received.
func (w *World) OnEntityDestroy(eIDs []pk.VarInt) error {
w.entityLock.Lock()
defer w.entityLock.Unlock()

View File

@ -180,7 +180,7 @@ func (m Message) ClearString() string {
// String return the message string with escape sequence for ansi color.
// To convert Translated Message to string, you must set
// On windows, you may want print this string using github.com/mattn/go-colorable.
// On windows, you may want print this string using github.com/matte/go-colorable.
func (m Message) String() string {
var msg, format strings.Builder
if m.Bold {

View File

@ -55,7 +55,7 @@ var texts = []string{
" ",
}
var ctexts = []string{
var clearTexts = []string{
"故我依然™ Kun_QwQ: 为什么想要用炼药锅灭火时总是跳不进去",
"<Xi_Xi_Mi> 好像是这个id。。",
@ -95,7 +95,7 @@ func TestChatMsgClearString(t *testing.T) {
}
str := cm.ClearString()
if str != ctexts[i] {
if str != clearTexts[i] {
t.Errorf("gets %q, wants %q", str, texts[i])
}
}

View File

@ -9,7 +9,7 @@ import (
"github.com/Tnze/go-mc/bot"
"github.com/Tnze/go-mc/chat"
_ "github.com/Tnze/go-mc/data/lang/en-us"
//"github.com/mattn/go-colorable" // this package is nice but cannot get in china mainland because it import golang.org/x/sys
"github.com/mattn/go-colorable"
)
const timeout = 45
@ -20,7 +20,7 @@ var (
)
func main() {
//log.SetOutput(colorable.NewColorableStdout())
log.SetOutput(colorable.NewColorableStdout())
c = bot.NewClient()
//Login
@ -46,8 +46,8 @@ func main() {
func onDeath() error {
log.Println("Died and Respawned")
c.Respawn() // If we exclude Respawn(...) then the player won't press the "Respawn" button upon death
return nil
// If we exclude Respawn(...) then the player won't press the "Respawn" button upon death
return c.Respawn()
}
func onGameStart() error {
@ -59,6 +59,7 @@ func onGameStart() error {
return c.UseItem(0)
}
//goland:noinspection SpellCheckingInspection
func onSound(name string, category int, x, y, z float64, volume, pitch float32) error {
if name == "entity.fishing_bobber.splash" {
if err := c.UseItem(0); err != nil { //retrieve

View File

@ -31,6 +31,7 @@ type Block struct {
EmitLightLevel int
}
//goland:noinspection ALL
var (
Air = Block{ID: 0, DisplayName: "Air", Name: "air", Hardness: 0, Diggable: true, DropIDs: []uint32{0}, NeedsTools: map[uint32]bool{}, MinStateID: 0, MaxStateID: 0, Transparent: true, FilterLightLevel: 0, EmitLightLevel: 0}
Stone = Block{ID: 1, DisplayName: "Stone", Name: "stone", Hardness: 1.5, Diggable: true, DropIDs: []uint32{1}, NeedsTools: map[uint32]bool{585: true, 590: true, 595: true, 600: true, 605: true}, MinStateID: 1, MaxStateID: 1, Transparent: false, FilterLightLevel: 15, EmitLightLevel: 0}

View File

@ -33,6 +33,7 @@ type Entity struct {
Category Category
}
//goland:noinspection ALL
var (
AreaEffectCloud = Entity{ID: 0, InternalID: 0, DisplayName: "Area Effect Cloud", Name: "area_effect_cloud", Width: 6, Height: 0.5, Type: "mob", Category: Immobile}
ArmorStand = Entity{ID: 1, InternalID: 1, DisplayName: "Armor Stand", Name: "armor_stand", Width: 0.5, Height: 1.975, Type: "mob", Category: Immobile}

View File

@ -12,6 +12,7 @@ type Item struct {
StackSize uint
}
//goland:noinspection GoNameStartsWithPackageName
var (
Air = Item{ID: 0, DisplayName: "Air", Name: "air", StackSize: 0}
Stone = Item{ID: 1, DisplayName: "Stone", Name: "stone", StackSize: 64}

2
go.mod
View File

@ -5,5 +5,5 @@ go 1.13
require (
github.com/beefsack/go-astar v0.0.0-20200827232313-4ecf9e304482
github.com/google/uuid v1.1.1
github.com/iancoleman/strcase v0.1.1 // indirect
github.com/mattn/go-colorable v0.1.8
)

9
go.sum
View File

@ -2,5 +2,10 @@ github.com/beefsack/go-astar v0.0.0-20200827232313-4ecf9e304482 h1:p4g4uok3+r6Tg
github.com/beefsack/go-astar v0.0.0-20200827232313-4ecf9e304482/go.mod h1:Cu3t5VeqE8kXjUBeNXWQprfuaP5UCIc5ggGjgMx9KFc=
github.com/google/uuid v1.1.1 h1:Gkbcsh/GbpXz7lPftLA3P6TYMwjCLYm83jiFQZF/3gY=
github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/iancoleman/strcase v0.1.1 h1:2I+LRClyCYB7JgZb9U0k75VHUiQe9RfknRqDyUfzp7k=
github.com/iancoleman/strcase v0.1.1/go.mod h1:SK73tn/9oHe+/Y0h39VT4UCxmurVJkR5NA7kMEAOgSE=
github.com/mattn/go-colorable v0.1.8 h1:c1ghPdyEDarC70ftn0y+A/Ee++9zz8ljHG1b13eJ0s8=
github.com/mattn/go-colorable v0.1.8/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc=
github.com/mattn/go-isatty v0.0.12 h1:wuysRhFDzyxgEmMf5xjvJ2M9dZoWAXNNr5LSBS7uHXY=
github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=
golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae h1:/WDfKMnPU+m5M4xB+6x4kaepxRw6jWvR5iDRdvjHgy8=
golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=

View File

@ -5,6 +5,7 @@ import (
"fmt"
)
//goland:noinspection SpellCheckingInspection
func ExampleUnmarshal() {
var data = []byte{
0x08, 0x00, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x00, 0x09,

View File

@ -4,6 +4,6 @@ type Unmarshaler interface {
Unmarshal(tagType byte, tagName string, r DecoderReader) error
}
//type Marshaler interface{
//type Marshaller interface{
// Marshal()
//}

View File

@ -40,24 +40,24 @@ func (p Packet) Scan(fields ...FieldDecoder) error {
// Pack 打包一个数据包
func (p *Packet) Pack(threshold int) (pack []byte) {
data := append(VarInt(p.ID).Encode(), p.Data...)
d := append(VarInt(p.ID).Encode(), p.Data...)
if threshold > 0 { //是否启用了压缩
if len(data) > threshold { //是否需要压缩
Len := len(data)
if len(d) > threshold { //是否需要压缩
Len := len(d)
VarLen := VarInt(Len).Encode()
data = Compress(data)
d = Compress(d)
pack = append(pack, VarInt(len(VarLen)+len(data)).Encode()...)
pack = append(pack, VarInt(len(VarLen)+len(d)).Encode()...)
pack = append(pack, VarLen...)
pack = append(pack, data...)
pack = append(pack, d...)
} else {
pack = append(pack, VarInt(int32(len(data)+1)).Encode()...)
pack = append(pack, VarInt(int32(len(d)+1)).Encode()...)
pack = append(pack, 0x00)
pack = append(pack, data...)
pack = append(pack, d...)
}
} else {
pack = append(pack, VarInt(int32(len(data))).Encode()...) //len
pack = append(pack, data...)
pack = append(pack, VarInt(int32(len(d))).Encode()...) //len
pack = append(pack, d...)
}
return
@ -73,17 +73,17 @@ func RecvPacket(r DecodeReader, useZlib bool) (*Packet, error) {
return nil, fmt.Errorf("packet length too short")
}
data := make([]byte, length) // read packet content
if _, err := io.ReadFull(r, data); err != nil {
d := make([]byte, length) // read packet content
if _, err := io.ReadFull(r, d); err != nil {
return nil, fmt.Errorf("read content of packet fail: %v", err)
}
//解压数据
if useZlib {
return UnCompress(data)
return UnCompress(d)
}
buf := bytes.NewBuffer(data)
buf := bytes.NewBuffer(d)
var packetID VarInt
if err := packetID.Decode(buf); err != nil {
return nil, fmt.Errorf("read packet id fail: %v", err)

View File

@ -10,7 +10,7 @@ import (
pk "github.com/Tnze/go-mc/net/packet"
)
// ChunkData is a clientbound packet which describes a chunk.
// ChunkData is a client-bound packet which describes a chunk.
type ChunkData struct {
X, Z pk.Int
FullChunk pk.Boolean
@ -24,10 +24,10 @@ type ChunkData struct {
func (p *ChunkData) Decode(pkt pk.Packet) error {
r := bytes.NewReader(pkt.Data)
if err := p.X.Decode(r); err != nil {
return fmt.Errorf("X: %v", err)
return fmt.Errorf("decode X: %v", err)
}
if err := p.Z.Decode(r); err != nil {
return fmt.Errorf("Z: %v", err)
return fmt.Errorf("decode Z: %v", err)
}
if err := p.FullChunk.Decode(r); err != nil {
return fmt.Errorf("full chunk: %v", err)
@ -39,7 +39,7 @@ func (p *ChunkData) Decode(pkt pk.Packet) error {
return fmt.Errorf("heightmaps: %v", err)
}
// Biome data is only present for full chunks.
// Biomes data is only present for full chunks.
if p.FullChunk {
if err := p.Biomes.Decode(r); err != nil {
return fmt.Errorf("heightmaps: %v", err)
@ -60,13 +60,13 @@ type biomesData struct {
}
func (b *biomesData) Decode(r pk.DecodeReader) error {
var nobd pk.VarInt // Number of Biome Datums
if err := nobd.Decode(r); err != nil {
var BiomesDataNums pk.VarInt // Number of Biomes Data
if err := BiomesDataNums.Decode(r); err != nil {
return err
}
b.data = make([]pk.VarInt, nobd)
b.data = make([]pk.VarInt, BiomesDataNums)
for i := 0; i < int(nobd); i++ {
for i := 0; i < int(BiomesDataNums); i++ {
var d pk.VarInt
if err := d.Decode(r); err != nil {
return err

View File

@ -2,7 +2,7 @@ package ptypes
import pk "github.com/Tnze/go-mc/net/packet"
// SpawnEntity is a clientbound packet used to spawn a non-mob entity.
// SpawnEntity is a client-bound packet used to spawn a non-mob entity.
type SpawnEntity struct {
ID pk.VarInt
UUID pk.UUID
@ -19,7 +19,7 @@ func (p *SpawnEntity) Decode(pkt pk.Packet) error {
&p.Data, &p.VelX, &p.VelY, &p.VelZ)
}
// SpawnPlayer is a clientbound packet used to describe a player entering
// SpawnPlayer is a client-bound packet used to describe a player entering
// visible range.
type SpawnPlayer struct {
ID pk.VarInt
@ -32,7 +32,7 @@ func (p *SpawnPlayer) Decode(pkt pk.Packet) error {
return pkt.Scan(&p.ID, &p.UUID, &p.X, &p.Y, &p.Z, &p.Yaw, &p.Pitch)
}
// SpawnLivingEntity is a clientbound packet used to spawn a mob.
// SpawnLivingEntity is a client-bound packet used to spawn a mob.
type SpawnLivingEntity struct {
ID pk.VarInt
UUID pk.UUID
@ -49,7 +49,7 @@ func (p *SpawnLivingEntity) Decode(pkt pk.Packet) error {
&p.HeadPitch, &p.VelX, &p.VelY, &p.VelZ)
}
// EntityAnimationClientbound updates the animationf state of an entity.
// EntityAnimationClientbound updates the animation state of an entity.
type EntityAnimationClientbound struct {
ID pk.VarInt
Animation pk.UnsignedByte

View File

@ -8,7 +8,7 @@ import (
pk "github.com/Tnze/go-mc/net/packet"
)
// SoundEffect is a clientbound packet used to play a specific sound ID
// SoundEffect is a client-bound packet used to play a specific sound ID
// on the client.
type SoundEffect struct {
Sound pk.VarInt
@ -21,7 +21,7 @@ func (p *SoundEffect) Decode(pkt pk.Packet) error {
return pkt.Scan(&p.Sound, &p.Category, &p.X, &p.Y, &p.Z, &p.Volume, &p.Pitch)
}
// NamedSoundEffect is a clientbound packet used to play a sound with the
// NamedSoundEffect is a client-bound packet used to play a sound with the
// specified name on the client.
type NamedSoundEffect struct {
Sound pk.String
@ -64,11 +64,11 @@ func (p PluginData) Encode() []byte {
}
func (p *PluginData) Decode(r pk.DecodeReader) error {
data, err := ioutil.ReadAll(r)
d, err := ioutil.ReadAll(r)
if err != nil {
return err
}
*p = data
*p = d
return nil
}