Skip to content

Commit 6877e94

Browse files
committed
Improve client template
1 parent 1e8f7b9 commit 6877e94

File tree

6 files changed

+157
-41
lines changed

6 files changed

+157
-41
lines changed

new/client/client.go

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,12 @@ var wrapperGameTemplate string
2727
//go:embed templates/wrappers/events.go.tmpl
2828
var wrapperEventsTemplate string
2929

30+
//go:embed templates/wrappers/game.go.init-dev.tmpl
31+
var wrapperGameInitDevTemplate string
32+
33+
//go:embed templates/wrappers/game.go.init-build.tmpl
34+
var wrapperGameInitBuildTemplate string
35+
3036
func CreateNewClient(projectName, gameName, serverURL, libraryVersion string, generateWrappers bool) error {
3137
module, err := cli.Input("Project module path:")
3238
if err != nil {
@@ -140,12 +146,14 @@ func execClientWrappersTemplate(projectName, modulePath, gameName, serverURL, li
140146
PackageName string
141147
ModulePath string
142148
Events []event
149+
InitFunc string
143150
}{
144151
URL: serverURL,
145152
LibraryURL: libraryURL,
146153
PackageName: gamePackageName,
147154
ModulePath: modulePath,
148155
Events: events,
156+
InitFunc: wrapperGameInitDevTemplate,
149157
}
150158

151159
err := new.ExecTemplate(wrapperMainTemplate, filepath.Join("main.go"), data)

new/client/templates/wrappers/events.go.tmpl

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,12 @@
11
package {{.PackageName}}
22

3+
/*
4+
This code was generated by codegame-cli-go.
5+
6+
CHANGES TO THIS FILE MAY CAUSE INCORRECT BEHAVIOR AND WILL BE LOST IF
7+
THE CODE IS REGENERATED.
8+
*/
9+
310
import "{{.LibraryURL}}"
411

512
{{range .Events}}
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
func init() {
2+
URL = "{{.URL}}"
3+
if os.Getenv("CG_GAME_URL") != "" {
4+
URL = os.Getenv("CG_GAME_URL")
5+
}
6+
}
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
func init() {
2+
URL = os.Getenv("CG_GAME_URL")
3+
}

new/client/templates/wrappers/game.go.tmpl

Lines changed: 127 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,119 @@
11
package {{.PackageName}}
22

3+
/*
4+
This code was generated by codegame-cli-go.
5+
6+
CHANGES TO THIS FILE MAY CAUSE INCORRECT BEHAVIOR AND WILL BE LOST IF
7+
THE CODE IS REGENERATED.
8+
*/
9+
310
import (
11+
"errors"
412
"fmt"
13+
"os"
14+
"strings"
515

6-
"{{.LibraryURL}}"
16+
"github.com/code-game-project/go-client/cg"
17+
"github.com/spf13/pflag"
718
)
819

20+
var URL string
21+
22+
{{.InitFunc}}
23+
924
type Game struct {
10-
Id string
11-
socket *cg.Socket
25+
Id string
26+
socket *cg.Socket
27+
spectating bool
28+
}
29+
30+
// If IsSpectating returns true, the session of this game will be empty and no events can be sent.
31+
func (g *Game) IsSpectating() bool {
32+
return g.spectating
1233
}
1334

1435
type Player struct {
1536
Id string
1637
Username string
1738
}
1839

40+
// Init parses command line arguments with pflag and calls either CreateAndJoinGame, CreateAndSpectateGame, JoinGame, SpectateGame or ReconnectGame depending on the provided commands:
41+
//
42+
// Operations:\n")
43+
// create <username> Create a new game.
44+
// join <game_id> <username> Join an existing game.
45+
// reconnect <username> Reconnect to a previous session.
46+
// Flags:
47+
// --public Make the created game public.
48+
// --spectate Spectate the created/joined game. The username is not neccessary if this flag is set.
49+
//
50+
// This function calls pflag.Parse() internally. If you want to add your own flags, you will need to register them with pflag *before* calling this function.
51+
func Init() (*Game, error) {
52+
pflag.Usage = func() {
53+
fmt.Fprintf(os.Stderr, "USAGE: %s [OPTIONS] <operation>\n", os.Args[0])
54+
fmt.Fprintf(os.Stderr, "\nOperations:\n")
55+
fmt.Fprintf(os.Stderr, " create <username> Create a new game.\n")
56+
fmt.Fprintf(os.Stderr, " join <game_id> <username> Join an existing game.\n")
57+
fmt.Fprintf(os.Stderr, " reconnect <username> Reconnect to a previous session.\n")
58+
fmt.Fprintf(os.Stderr, "\nFlags:\n")
59+
pflag.PrintDefaults()
60+
}
61+
62+
var public bool
63+
pflag.BoolVarP(&public, "public", "p", false, "Make the created game public.")
64+
var spectate bool
65+
pflag.BoolVarP(&spectate, "spectate", "s", false, "Spectate the created/joined game. The username is not neccessary if this flag is set.")
66+
pflag.Parse()
67+
68+
var operation string
69+
if pflag.NArg() > 1 || (spectate && pflag.NArg() > 0) {
70+
operation = strings.ToLower(pflag.Arg(0))
71+
} else {
72+
pflag.Usage()
73+
os.Exit(1)
74+
}
75+
76+
if URL == "" {
77+
return nil, errors.New("CG_GAME_URL is empty.")
78+
}
79+
80+
var game *Game
81+
var err error
82+
switch operation {
83+
case "create":
84+
if spectate {
85+
game, err = CreateAndSpectateGame(public)
86+
} else {
87+
game, err = CreateAndJoinGame(public, pflag.Arg(1))
88+
}
89+
case "join":
90+
if (!spectate && pflag.NArg() < 3) || (spectate && pflag.NArg() < 2) {
91+
fmt.Fprintln(os.Stderr, "No game_id specified!")
92+
pflag.Usage()
93+
os.Exit(1)
94+
}
95+
if spectate {
96+
game, err = SpectateGame(pflag.Arg(1))
97+
} else {
98+
game, err = JoinGame(pflag.Arg(1), pflag.Arg(2))
99+
}
100+
case "reconnect":
101+
game, err = ReconnectGame(pflag.Arg(1))
102+
default:
103+
fmt.Fprintf(os.Stderr, "Invalid operation '%s'!\n", operation)
104+
pflag.Usage()
105+
os.Exit(1)
106+
}
107+
if err != nil {
108+
return nil, err
109+
}
110+
111+
return game, nil
112+
}
113+
19114
// CreateAndJoinGame creates a new game and joins it immediately after.
20115
func CreateAndJoinGame(public bool, username string) (*Game, error) {
21-
socket, err := cg.NewSocket("{{.URL}}")
116+
socket, err := cg.NewSocket(URL)
22117
if err != nil {
23118
return nil, fmt.Errorf("failed to connect to server: %s", err)
24119
}
@@ -39,9 +134,32 @@ func CreateAndJoinGame(public bool, username string) (*Game, error) {
39134
}, nil
40135
}
41136

137+
// CreateAndSpectateGame creates a new game and spectates it immediately after.
138+
func CreateAndSpectateGame(public bool) (*Game, error) {
139+
socket, err := cg.NewSocket(URL)
140+
if err != nil {
141+
return nil, fmt.Errorf("failed to connect to server: %s", err)
142+
}
143+
144+
gameId, err := socket.Create(public)
145+
if err != nil {
146+
return nil, fmt.Errorf("failed to create game: %s", err)
147+
}
148+
149+
err = socket.Spectate(gameId)
150+
if err != nil {
151+
return nil, fmt.Errorf("failed to spectate game: %s", err)
152+
}
153+
154+
return &Game{
155+
Id: gameId,
156+
socket: socket,
157+
}, nil
158+
}
159+
42160
// JoinGame joins the game with the specified id.
43161
func JoinGame(gameId, username string) (*Game, error) {
44-
socket, err := cg.NewSocket("{{.URL}}")
162+
socket, err := cg.NewSocket(URL)
45163
if err != nil {
46164
return nil, fmt.Errorf("failed to connect to server: %s", err)
47165
}
@@ -59,7 +177,7 @@ func JoinGame(gameId, username string) (*Game, error) {
59177

60178
// ReconnectGame joins a previous session from the session store.
61179
func ReconnectGame(username string) (*Game, error) {
62-
socket, err := cg.NewSocket("{{.URL}}")
180+
socket, err := cg.NewSocket(URL)
63181
if err != nil {
64182
return nil, fmt.Errorf("failed to connect to server: %s", err)
65183
}
@@ -75,9 +193,9 @@ func ReconnectGame(username string) (*Game, error) {
75193
}, nil
76194
}
77195

78-
// Spectate joins a game as a spectator.
79-
func Spectate(gameId string) (*Game, error) {
80-
socket, err := cg.NewSocket("{{.URL}}")
196+
// SpectateGame joins a game as a spectator.
197+
func SpectateGame(gameId string) (*Game, error) {
198+
socket, err := cg.NewSocket(URL)
81199
if err != nil {
82200
return nil, fmt.Errorf("failed to connect to server: %s", err)
83201
}

new/client/templates/wrappers/main.go.tmpl

Lines changed: 6 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -2,50 +2,24 @@ package main
22

33
import (
44
"fmt"
5-
"os"
65
"{{.ModulePath}}/{{.PackageName}}"
6+
"log"
77

88
"{{.LibraryURL}}"
9-
"github.com/spf13/pflag"
109
)
1110

1211
func main() {
13-
var create bool
14-
pflag.BoolVarP(&create, "create", "c", false, "Create a new game.")
15-
var public bool
16-
pflag.BoolVarP(&public, "public", "p", false, "Make the created game public.")
17-
var gameId string
18-
pflag.StringVarP(&gameId, "join", "j", "", "Join a game.")
19-
pflag.Parse()
20-
21-
if pflag.NArg() != 1 {
22-
fmt.Fprintf(os.Stderr, "USAGE: %s [OPTIONS] <username>\n", os.Args[0])
23-
fmt.Fprintf(os.Stderr, "For help use --help.\n")
24-
os.Exit(1)
25-
}
26-
username := pflag.Arg(0)
27-
28-
var game *{{.PackageName}}.Game
29-
var err error
30-
31-
if create {
32-
game, err = {{.PackageName}}.CreateAndJoinGame(public, username)
33-
} else if gameId != "" {
34-
game, err = {{.PackageName}}.JoinGame(gameId, username)
35-
} else {
36-
game, err = {{.PackageName}}.ReconnectGame(username)
37-
}
38-
12+
game, err := {{.PackageName}}.Init()
3913
if err != nil {
40-
fmt.Println("Couldn't join game:", err)
41-
os.Exit(1)
14+
log.Fatal(err)
4215
}
43-
44-
fmt.Println("GameID:", game.Id)
16+
fmt.Println("Game ID:", game.Id)
4517

4618
game.OnCGErrorEvent(func(origin {{.PackageName}}.Player, data cg.ErrorEventData) {
4719
fmt.Println("error:", data.Message)
4820
})
4921

22+
// TODO: register event listeners
23+
5024
game.Run()
5125
}

0 commit comments

Comments
 (0)