-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcoverage.html
More file actions
6534 lines (5535 loc) · 250 KB
/
Copy pathcoverage.html
File metadata and controls
6534 lines (5535 loc) · 250 KB
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>client: Go Coverage Report</title>
<style>
body {
background: black;
color: rgb(80, 80, 80);
}
body, pre, #legend span {
font-family: Menlo, monospace;
font-weight: bold;
}
#topbar {
background: black;
position: fixed;
top: 0; left: 0; right: 0;
height: 42px;
border-bottom: 1px solid rgb(80, 80, 80);
}
#content {
margin-top: 50px;
}
#nav, #legend {
float: left;
margin-left: 10px;
}
#legend {
margin-top: 12px;
}
#nav {
margin-top: 10px;
}
#legend span {
margin: 0 5px;
}
.cov0 { color: rgb(192, 0, 0) }
.cov1 { color: rgb(128, 128, 128) }
.cov2 { color: rgb(116, 140, 131) }
.cov3 { color: rgb(104, 152, 134) }
.cov4 { color: rgb(92, 164, 137) }
.cov5 { color: rgb(80, 176, 140) }
.cov6 { color: rgb(68, 188, 143) }
.cov7 { color: rgb(56, 200, 146) }
.cov8 { color: rgb(44, 212, 149) }
.cov9 { color: rgb(32, 224, 152) }
.cov10 { color: rgb(20, 236, 155) }
</style>
</head>
<body>
<div id="topbar">
<div id="nav">
<select id="files">
<option value="file0">github.com/opd-ai/go-netrek/cmd/client/main.go (0.0%)</option>
<option value="file1">github.com/opd-ai/go-netrek/cmd/server/main.go (0.0%)</option>
<option value="file2">github.com/opd-ai/go-netrek/examples/ai_client/main.go (0.0%)</option>
<option value="file3">github.com/opd-ai/go-netrek/examples/simple_server/main.go (0.0%)</option>
<option value="file4">github.com/opd-ai/go-netrek/pkg/config/config.go (96.0%)</option>
<option value="file5">github.com/opd-ai/go-netrek/pkg/engine/game.go (71.7%)</option>
<option value="file6">github.com/opd-ai/go-netrek/pkg/entity/entity.go (62.5%)</option>
<option value="file7">github.com/opd-ai/go-netrek/pkg/entity/planet.go (96.2%)</option>
<option value="file8">github.com/opd-ai/go-netrek/pkg/entity/ship.go (96.3%)</option>
<option value="file9">github.com/opd-ai/go-netrek/pkg/entity/weapon.go (100.0%)</option>
<option value="file10">github.com/opd-ai/go-netrek/pkg/event/event.go (96.8%)</option>
<option value="file11">github.com/opd-ai/go-netrek/pkg/network/client.go (24.5%)</option>
<option value="file12">github.com/opd-ai/go-netrek/pkg/network/server.go (1.0%)</option>
<option value="file13">github.com/opd-ai/go-netrek/pkg/physics/collision.go (87.0%)</option>
<option value="file14">github.com/opd-ai/go-netrek/pkg/physics/ship.go (100.0%)</option>
<option value="file15">github.com/opd-ai/go-netrek/pkg/physics/vector.go (100.0%)</option>
<option value="file16">github.com/opd-ai/go-netrek/pkg/render/engo/assets.go (13.1%)</option>
<option value="file17">github.com/opd-ai/go-netrek/pkg/render/engo/camera.go (71.4%)</option>
<option value="file18">github.com/opd-ai/go-netrek/pkg/render/engo/hud.go (0.0%)</option>
<option value="file19">github.com/opd-ai/go-netrek/pkg/render/engo/input.go (0.0%)</option>
<option value="file20">github.com/opd-ai/go-netrek/pkg/render/engo/renderer.go (0.0%)</option>
<option value="file21">github.com/opd-ai/go-netrek/pkg/render/engo/scene.go (15.4%)</option>
<option value="file22">github.com/opd-ai/go-netrek/pkg/render/renderer.go (100.0%)</option>
<option value="file23">github.com/opd-ai/go-netrek/pkg/render/terminal.go (100.0%)</option>
</select>
</div>
<div id="legend">
<span>not tracked</span>
<span class="cov0">not covered</span>
<span class="cov8">covered</span>
</div>
</div>
<div id="content">
<pre class="file" id="file0" style="display: none">// cmd/client/main.go
package main
import (
"flag"
"fmt"
"log"
"os"
"os/signal"
"syscall"
"time"
"github.com/EngoEngine/engo"
"github.com/opd-ai/go-netrek/pkg/config"
"github.com/opd-ai/go-netrek/pkg/event"
"github.com/opd-ai/go-netrek/pkg/network"
engorender "github.com/opd-ai/go-netrek/pkg/render/engo"
)
func main() <span class="cov0" title="0">{
args := parseCommandLineArguments()
gameConfig := loadGameConfiguration(args.configPath)
serverAddr := resolveServerAddress(args.serverAddr, gameConfig)
eventBus := event.NewEventBus()
client := initializeGameClient(eventBus, serverAddr, args.playerName, args.teamID)
setupEventSubscriptions(eventBus)
startSelectedRenderer(args.renderer, client, eventBus, args.teamID, args.width, args.height, args.fullscreen)
}</span>
// clientArgs holds parsed command line arguments for the client application.
type clientArgs struct {
configPath string
serverAddr string
playerName string
teamID int
renderer string
fullscreen bool
width int
height int
}
// parseCommandLineArguments parses and returns command line arguments for the client.
func parseCommandLineArguments() *clientArgs <span class="cov0" title="0">{
args := &clientArgs{}
flag.StringVar(&args.configPath, "config", "config.json", "Path to configuration file")
flag.StringVar(&args.serverAddr, "server", "", "Server address (overrides config)")
flag.StringVar(&args.playerName, "name", "Player", "Player name")
flag.IntVar(&args.teamID, "team", 0, "Team ID")
flag.StringVar(&args.renderer, "renderer", "terminal", "Renderer type: 'terminal' or 'engo'")
flag.BoolVar(&args.fullscreen, "fullscreen", false, "Run in fullscreen mode (Engo only)")
flag.IntVar(&args.width, "width", 1024, "Window width (Engo only)")
flag.IntVar(&args.height, "height", 768, "Window height (Engo only)")
flag.Parse()
return args
}</span>
// loadGameConfiguration loads the game configuration from file or returns default configuration.
func loadGameConfiguration(configPath string) *config.GameConfig <span class="cov0" title="0">{
if _, err := os.Stat(configPath); os.IsNotExist(err) </span><span class="cov0" title="0">{
log.Printf("Configuration file not found, using default configuration")
return config.DefaultConfig()
}</span>
<span class="cov0" title="0">gameConfig, err := config.LoadConfig(configPath)
if err != nil </span><span class="cov0" title="0">{
log.Fatalf("Failed to load configuration: %v", err)
}</span>
<span class="cov0" title="0">return gameConfig</span>
}
// resolveServerAddress determines the final server address to use for connection.
func resolveServerAddress(cmdLineAddr string, gameConfig *config.GameConfig) string <span class="cov0" title="0">{
if cmdLineAddr == "" </span><span class="cov0" title="0">{
return gameConfig.NetworkConfig.ServerAddress
}</span>
<span class="cov0" title="0">return cmdLineAddr</span>
}
// initializeGameClient creates and connects a new game client to the server.
func initializeGameClient(eventBus *event.Bus, serverAddr, playerName string, teamID int) *network.GameClient <span class="cov0" title="0">{
client := network.NewGameClient(eventBus)
log.Printf("Connecting to server at %s", serverAddr)
if err := client.Connect(serverAddr, playerName, teamID); err != nil </span><span class="cov0" title="0">{
log.Fatalf("Failed to connect to server: %v", err)
}</span>
<span class="cov0" title="0">log.Printf("Connected to server")
return client</span>
}
// setupEventSubscriptions configures all event handlers for client-server communication.
func setupEventSubscriptions(eventBus *event.Bus) <span class="cov0" title="0">{
eventBus.Subscribe(network.ChatMessageReceived, func(e event.Event) </span><span class="cov0" title="0">{
if chatEvent, ok := e.(*network.ChatEvent); ok </span><span class="cov0" title="0">{
fmt.Printf("[%s]: %s\n", chatEvent.SenderName, chatEvent.Message)
}</span>
})
<span class="cov0" title="0">eventBus.Subscribe(network.ClientDisconnected, func(e event.Event) </span><span class="cov0" title="0">{
log.Printf("Disconnected from server")
}</span>)
<span class="cov0" title="0">eventBus.Subscribe(network.ClientReconnected, func(e event.Event) </span><span class="cov0" title="0">{
log.Printf("Reconnected to server")
}</span>)
<span class="cov0" title="0">eventBus.Subscribe(network.ClientReconnectFailed, func(e event.Event) </span><span class="cov0" title="0">{
log.Printf("Failed to reconnect to server")
os.Exit(1)
}</span>)
}
// startSelectedRenderer launches the appropriate renderer based on user selection.
func startSelectedRenderer(renderer string, client *network.GameClient, eventBus *event.Bus, teamID, width, height int, fullscreen bool) <span class="cov0" title="0">{
switch renderer </span>{
case "engo":<span class="cov0" title="0">
startEngoRenderer(client, eventBus, uint64(teamID), width, height, fullscreen)</span>
case "terminal":<span class="cov0" title="0">
fallthrough</span>
default:<span class="cov0" title="0">
startTerminalRenderer(client, eventBus)</span>
}
}
// startEngoRenderer starts the Engo GUI client
func startEngoRenderer(client *network.GameClient, eventBus *event.Bus, playerID uint64, width, height int, fullscreen bool) <span class="cov0" title="0">{
// Create the game scene
scene := engorender.NewGameScene(client, eventBus, playerID)
// Configure Engo options
opts := engo.RunOptions{
Title: "Go Netrek",
Width: width,
Height: height,
Fullscreen: fullscreen,
VSync: true,
}
// Run Engo with the game scene
engo.Run(opts, scene)
}</span>
// startTerminalRenderer starts the terminal-based client (existing implementation)
func startTerminalRenderer(client *network.GameClient, eventBus *event.Bus) <span class="cov0" title="0">{
// Handle game state updates
go func() </span><span class="cov0" title="0">{
for gameState := range client.GetGameStateChannel() </span><span class="cov0" title="0">{
// Process game state
// In a real client, this would update the game view
log.Printf("Received game state update: tick=%d ships=%d planets=%d",
gameState.Tick, len(gameState.Ships), len(gameState.Planets))
}</span>
}()
// Example input simulation (in a real client, this would be based on user input)
<span class="cov0" title="0">go func() </span><span class="cov0" title="0">{
for </span><span class="cov0" title="0">{
// Send input every 100ms
time.Sleep(100 * time.Millisecond)
// Example input: thrust, turn right, fire weapon 0
client.SendInput(true, false, true, 0, false, false, 0, 0)
}</span>
}()
// Example chat message
<span class="cov0" title="0">go func() </span><span class="cov0" title="0">{
time.Sleep(3 * time.Second)
log.Printf("Sending chat message")
client.SendChatMessage("Hello, Netrek!")
}</span>()
// Handle graceful shutdown
<span class="cov0" title="0">sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
<-sigChan
log.Println("Disconnecting from server...")
client.Disconnect()</span>
}
</pre>
<pre class="file" id="file1" style="display: none">// cmd/server/main.go
package main
import (
"flag"
"log"
"os"
"os/signal"
"syscall"
"github.com/opd-ai/go-netrek/pkg/config"
"github.com/opd-ai/go-netrek/pkg/engine"
"github.com/opd-ai/go-netrek/pkg/network"
)
func main() <span class="cov0" title="0">{
configPath := flag.String("config", "config.json", "Path to configuration file")
createDefault := flag.Bool("default", false, "Create default configuration file")
flag.Parse()
// Create default configuration file if requested
if *createDefault </span><span class="cov0" title="0">{
defaultConfig := config.DefaultConfig()
if err := config.SaveConfig(defaultConfig, *configPath); err != nil </span><span class="cov0" title="0">{
log.Fatalf("Failed to create default configuration: %v", err)
}</span>
<span class="cov0" title="0">log.Printf("Created default configuration file: %s", *configPath)
return</span>
}
// Load configuration
<span class="cov0" title="0">var gameConfig *config.GameConfig
if _, err := os.Stat(*configPath); os.IsNotExist(err) </span><span class="cov0" title="0">{
log.Printf("Configuration file not found, using default configuration")
gameConfig = config.DefaultConfig()
}</span> else<span class="cov0" title="0"> {
gameConfig, err = config.LoadConfig(*configPath)
if err != nil </span><span class="cov0" title="0">{
log.Fatalf("Failed to load configuration: %v", err)
}</span>
}
// Create game
<span class="cov0" title="0">game := engine.NewGame(gameConfig)
// Create server
server := network.NewGameServer(game, gameConfig.MaxPlayers)
// Start server
serverAddr := gameConfig.NetworkConfig.ServerAddress
if serverAddr == "" </span><span class="cov0" title="0">{
serverAddr = "localhost:4566"
}</span>
<span class="cov0" title="0">log.Printf("Starting server on %s", serverAddr)
if err := server.Start(serverAddr); err != nil </span><span class="cov0" title="0">{
log.Fatalf("Failed to start server: %v", err)
}</span>
// Handle graceful shutdown
<span class="cov0" title="0">sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
<-sigChan
log.Println("Shutting down server...")
server.Stop()</span>
}
</pre>
<pre class="file" id="file2" style="display: none">// examples/ai_client/main.go
// AI-controlled client bot demonstrating different behaviors
package main
import (
"flag"
"log"
"math"
"math/rand/v2"
"os"
"os/signal"
"syscall"
"time"
"github.com/opd-ai/go-netrek/pkg/engine"
"github.com/opd-ai/go-netrek/pkg/entity"
"github.com/opd-ai/go-netrek/pkg/event"
"github.com/opd-ai/go-netrek/pkg/network"
"github.com/opd-ai/go-netrek/pkg/physics"
)
// AIBehavior defines different AI behaviors
type AIBehavior int
const (
BehaviorExplorer AIBehavior = iota // Flies around exploring
BehaviorAggressor // Seeks and attacks enemies
BehaviorDefender // Defends home planets
BehaviorBomber // Attacks enemy planets
)
// AIClient represents an AI-controlled game client
type AIClient struct {
client *network.GameClient
eventBus *event.Bus
behavior AIBehavior
playerName string
teamID int
lastGameState *engine.GameState
myShipID entity.ID
targetPlanetID entity.ID
targetShipID entity.ID
lastActionTime time.Time
actionCooldown time.Duration
random *rand.Rand
}
func main() <span class="cov0" title="0">{
// Command line flags
serverAddr := flag.String("server", "localhost:4566", "Server address")
playerName := flag.String("name", "AIBot", "Player name")
teamID := flag.Int("team", 0, "Team ID (0 or 1)")
behaviorStr := flag.String("behavior", "explorer", "AI behavior (explorer, aggressor, defender, bomber)")
flag.Parse()
// Parse behavior
var behavior AIBehavior
switch *behaviorStr </span>{
case "explorer":<span class="cov0" title="0">
behavior = BehaviorExplorer</span>
case "aggressor":<span class="cov0" title="0">
behavior = BehaviorAggressor</span>
case "defender":<span class="cov0" title="0">
behavior = BehaviorDefender</span>
case "bomber":<span class="cov0" title="0">
behavior = BehaviorBomber</span>
default:<span class="cov0" title="0">
log.Fatalf("Unknown behavior: %s", *behaviorStr)</span>
}
<span class="cov0" title="0">log.Printf("Starting AI Client: %s (Team %d, Behavior: %s)", *playerName, *teamID, *behaviorStr)
// Create AI client
aiClient := NewAIClient(*playerName, *teamID, behavior)
// Connect to server
if err := aiClient.Connect(*serverAddr); err != nil </span><span class="cov0" title="0">{
log.Fatalf("Failed to connect to server: %v", err)
}</span>
<span class="cov0" title="0">log.Printf("Connected to server at %s", *serverAddr)
log.Printf("AI behavior: %s", getBehaviorDescription(behavior))
// Handle graceful shutdown
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
<-sigChan
log.Println("Shutting down AI client...")
aiClient.Disconnect()</span>
}
// NewAIClient creates a new AI client
func NewAIClient(playerName string, teamID int, behavior AIBehavior) *AIClient <span class="cov0" title="0">{
eventBus := event.NewEventBus()
ai := &AIClient{
client: network.NewGameClient(eventBus),
eventBus: eventBus,
behavior: behavior,
playerName: playerName,
teamID: teamID,
actionCooldown: time.Millisecond * 200, // Act every 200ms
random: rand.New(rand.NewPCG(uint64(time.Now().UnixNano()), uint64(teamID))),
}
// Subscribe to events
ai.setupEventHandlers()
return ai
}</span>
// Connect connects to the game server
func (ai *AIClient) Connect(serverAddr string) error <span class="cov0" title="0">{
if err := ai.client.Connect(serverAddr, ai.playerName, ai.teamID); err != nil </span><span class="cov0" title="0">{
return err
}</span>
// Start AI behavior loop
<span class="cov0" title="0">go ai.behaviorLoop()
return nil</span>
}
// Disconnect disconnects from the server
func (ai *AIClient) Disconnect() <span class="cov0" title="0">{
ai.client.Disconnect()
}</span>
// setupEventHandlers sets up event handling
func (ai *AIClient) setupEventHandlers() <span class="cov0" title="0">{
ai.eventBus.Subscribe(network.ChatMessageReceived, func(e event.Event) </span><span class="cov0" title="0">{
if chatEvent, ok := e.(*network.ChatEvent); ok </span><span class="cov0" title="0">{
log.Printf("[Chat] %s: %s", chatEvent.SenderName, chatEvent.Message)
}</span>
})
<span class="cov0" title="0">ai.eventBus.Subscribe(network.ClientDisconnected, func(e event.Event) </span><span class="cov0" title="0">{
log.Printf("Disconnected from server")
os.Exit(0)
}</span>)
}
// behaviorLoop runs the main AI behavior loop
func (ai *AIClient) behaviorLoop() <span class="cov0" title="0">{
// Game state processing
go func() </span><span class="cov0" title="0">{
for gameState := range ai.client.GetGameStateChannel() </span><span class="cov0" title="0">{
ai.lastGameState = gameState
ai.updateMyShipID(gameState)
}</span>
}()
// Main behavior loop
<span class="cov0" title="0">for </span><span class="cov0" title="0">{
time.Sleep(ai.actionCooldown)
if ai.lastGameState == nil </span><span class="cov0" title="0">{
continue</span>
}
// Execute behavior based on type
<span class="cov0" title="0">ai.executeBehavior()
ai.lastActionTime = time.Now()</span>
}
}
// updateMyShipID finds and updates the AI's ship ID
func (ai *AIClient) updateMyShipID(gameState *engine.GameState) <span class="cov0" title="0">{
// Find our ship by looking for ships belonging to our team
for shipID, shipState := range gameState.Ships </span><span class="cov0" title="0">{
if shipState.TeamID == ai.teamID </span><span class="cov0" title="0">{
// For simplicity, assume first ship found is ours
// In a real implementation, we'd track player-to-ship mapping
ai.myShipID = shipID
break</span>
}
}
}
// executeBehavior executes the AI's current behavior
func (ai *AIClient) executeBehavior() <span class="cov0" title="0">{
if ai.myShipID == 0 </span><span class="cov0" title="0">{
return // Don't have a ship yet
}</span>
<span class="cov0" title="0">myShip, exists := ai.lastGameState.Ships[ai.myShipID]
if !exists </span><span class="cov0" title="0">{
return // Ship doesn't exist
}</span>
<span class="cov0" title="0">switch ai.behavior </span>{
case BehaviorExplorer:<span class="cov0" title="0">
ai.executeExplorerBehavior(myShip)</span>
case BehaviorAggressor:<span class="cov0" title="0">
ai.executeAggressorBehavior(myShip)</span>
case BehaviorDefender:<span class="cov0" title="0">
ai.executeDefenderBehavior(myShip)</span>
case BehaviorBomber:<span class="cov0" title="0">
ai.executeBomberBehavior(myShip)</span>
}
}
// executeExplorerBehavior makes the AI explore the galaxy
func (ai *AIClient) executeExplorerBehavior(myShip engine.ShipState) <span class="cov0" title="0">{
// Simple exploration: move in random directions, occasionally change course
thrust := true
turnLeft := false
turnRight := false
// Randomly change direction
if ai.random.Float64() < 0.1 </span><span class="cov0" title="0">{ // 10% chance to turn
if ai.random.Float64() < 0.5 </span><span class="cov0" title="0">{
turnLeft = true
}</span> else<span class="cov0" title="0"> {
turnRight = true
}</span>
}
// Send input
<span class="cov0" title="0">ai.client.SendInput(thrust, turnLeft, turnRight, -1, false, false, 0, 0)
// Occasionally send a friendly message
if ai.random.Float64() < 0.005 </span><span class="cov0" title="0">{ // 0.5% chance
messages := []string{
"Exploring the galaxy!",
"Beautiful stars out here",
"Anyone seen any interesting planets?",
"The universe is vast",
}
msg := messages[ai.random.IntN(len(messages))]
ai.client.SendChatMessage(msg)
}</span>
}
// executeAggressorBehavior makes the AI seek and attack enemies
func (ai *AIClient) executeAggressorBehavior(myShip engine.ShipState) <span class="cov0" title="0">{
// Find the nearest enemy ship
nearestEnemy := ai.findNearestEnemyShip(myShip.Position)
thrust := true
turnLeft := false
turnRight := false
fireWeapon := -1
if nearestEnemy != nil </span><span class="cov0" title="0">{
// Calculate angle to enemy
targetVector := nearestEnemy.Position.Sub(myShip.Position)
targetAngle := targetVector.Angle()
// Calculate angle difference
angleDiff := targetAngle - myShip.Rotation
// Normalize angle difference to [-π, π]
for angleDiff > math.Pi </span><span class="cov0" title="0">{
angleDiff -= 2 * math.Pi
}</span>
<span class="cov0" title="0">for angleDiff < -math.Pi </span><span class="cov0" title="0">{
angleDiff += 2 * math.Pi
}</span>
// Turn towards enemy
<span class="cov0" title="0">if math.Abs(angleDiff) > 0.1 </span><span class="cov0" title="0">{
if angleDiff > 0 </span><span class="cov0" title="0">{
turnLeft = true
}</span> else<span class="cov0" title="0"> {
turnRight = true
}</span>
}
// Fire if pointing roughly at enemy
<span class="cov0" title="0">distance := targetVector.Length()
if math.Abs(angleDiff) < 0.3 && distance < 1000 </span><span class="cov0" title="0">{
fireWeapon = 0 // Fire first weapon
}</span>
// Taunt enemies occasionally
<span class="cov0" title="0">if ai.random.Float64() < 0.01 </span><span class="cov0" title="0">{
ai.client.SendChatMessage("Prepare for battle!")
}</span>
}
<span class="cov0" title="0">ai.client.SendInput(thrust, turnLeft, turnRight, fireWeapon, false, false, 0, 0)</span>
}
// executeDefenderBehavior makes the AI defend home planets
func (ai *AIClient) executeDefenderBehavior(myShip engine.ShipState) <span class="cov0" title="0">{
homePlanet := ai.findHomePlanet()
thrust, turnLeft, turnRight := ai.initializeDefenseInputs()
if homePlanet != nil </span><span class="cov0" title="0">{
distance := ai.calculateDistanceToHome(myShip.Position, homePlanet.Position)
if distance > 500 </span><span class="cov0" title="0">{
turnLeft, turnRight = ai.calculateNavigationToHome(myShip, homePlanet)
}</span> else<span class="cov0" title="0"> {
turnLeft, turnRight = ai.executePatrolBehavior()
}</span>
}
<span class="cov0" title="0">ai.client.SendInput(thrust, turnLeft, turnRight, -1, false, false, 0, 0)</span>
}
// initializeDefenseInputs sets up the default input state for defensive behavior.
func (ai *AIClient) initializeDefenseInputs() (thrust bool, turnLeft bool, turnRight bool) <span class="cov0" title="0">{
return true, false, false
}</span>
// calculateDistanceToHome computes the distance between the ship and home planet.
func (ai *AIClient) calculateDistanceToHome(shipPosition, homePosition physics.Vector2D) float64 <span class="cov0" title="0">{
homeVector := homePosition.Sub(shipPosition)
return homeVector.Length()
}</span>
// calculateNavigationToHome determines turn direction to navigate toward the home planet.
func (ai *AIClient) calculateNavigationToHome(myShip engine.ShipState, homePlanet *engine.PlanetState) (turnLeft bool, turnRight bool) <span class="cov0" title="0">{
homeVector := homePlanet.Position.Sub(myShip.Position)
targetAngle := homeVector.Angle()
angleDiff := ai.normalizeAngleDifference(targetAngle - myShip.Rotation)
return ai.determineTurnDirection(angleDiff)
}</span>
// normalizeAngleDifference normalizes angle difference to the range [-π, π].
func (ai *AIClient) normalizeAngleDifference(angleDiff float64) float64 <span class="cov0" title="0">{
for angleDiff > math.Pi </span><span class="cov0" title="0">{
angleDiff -= 2 * math.Pi
}</span>
<span class="cov0" title="0">for angleDiff < -math.Pi </span><span class="cov0" title="0">{
angleDiff += 2 * math.Pi
}</span>
<span class="cov0" title="0">return angleDiff</span>
}
// determineTurnDirection decides whether to turn left or right based on angle difference.
func (ai *AIClient) determineTurnDirection(angleDiff float64) (turnLeft bool, turnRight bool) <span class="cov0" title="0">{
if math.Abs(angleDiff) > 0.1 </span><span class="cov0" title="0">{
if angleDiff > 0 </span><span class="cov0" title="0">{
return true, false
}</span>
<span class="cov0" title="0">return false, true</span>
}
<span class="cov0" title="0">return false, false</span>
}
// executePatrolBehavior implements random patrol movement around the home planet.
func (ai *AIClient) executePatrolBehavior() (turnLeft bool, turnRight bool) <span class="cov0" title="0">{
if ai.random.Float64() < 0.2 </span><span class="cov0" title="0">{
if ai.random.Float64() < 0.5 </span><span class="cov0" title="0">{
return true, false
}</span>
<span class="cov0" title="0">return false, true</span>
}
<span class="cov0" title="0">return false, false</span>
}
// executeBomberBehavior makes the AI attack enemy planets
func (ai *AIClient) executeBomberBehavior(myShip engine.ShipState) <span class="cov0" title="0">{
// Find enemy planets to bomb
target := ai.findEnemyPlanet(myShip.Position)
thrust := true
turnLeft := false
turnRight := false
beamDown := false
if target != nil </span><span class="cov0" title="0">{
// Move towards target planet
targetVector := target.Position.Sub(myShip.Position)
distance := targetVector.Length()
targetAngle := targetVector.Angle()
angleDiff := targetAngle - myShip.Rotation
for angleDiff > math.Pi </span><span class="cov0" title="0">{
angleDiff -= 2 * math.Pi
}</span>
<span class="cov0" title="0">for angleDiff < -math.Pi </span><span class="cov0" title="0">{
angleDiff += 2 * math.Pi
}</span>
<span class="cov0" title="0">if math.Abs(angleDiff) > 0.1 </span><span class="cov0" title="0">{
if angleDiff > 0 </span><span class="cov0" title="0">{
turnLeft = true
}</span> else<span class="cov0" title="0"> {
turnRight = true
}</span>
}
// If close to planet, beam down armies (bomb)
<span class="cov0" title="0">if distance < 100 && myShip.Armies > 0 </span><span class="cov0" title="0">{
beamDown = true
}</span>
}
<span class="cov0" title="0">ai.client.SendInput(thrust, turnLeft, turnRight, -1, beamDown, false, 1, 0)</span>
}
// Helper functions for AI decision making
func (ai *AIClient) findNearestEnemyShip(myPos physics.Vector2D) *engine.ShipState <span class="cov0" title="0">{
var nearest *engine.ShipState
var nearestDistance float64 = math.Inf(1)
for _, ship := range ai.lastGameState.Ships </span><span class="cov0" title="0">{
if ship.TeamID != ai.teamID </span><span class="cov0" title="0">{
distance := ship.Position.Distance(myPos)
if distance < nearestDistance </span><span class="cov0" title="0">{
nearest = &ship
nearestDistance = distance
}</span>
}
}
<span class="cov0" title="0">return nearest</span>
}
func (ai *AIClient) findHomePlanet() *engine.PlanetState <span class="cov0" title="0">{
// Look for planets owned by our team - use planet names to identify home planets
for _, planet := range ai.lastGameState.Planets </span><span class="cov0" title="0">{
if planet.TeamID == ai.teamID </span><span class="cov0" title="0">{
// Common home planet names
if planet.Name == "Earth" || planet.Name == "Qo'noS" ||
planet.Name == "Romulus" || planet.Name == "Cardassia" </span><span class="cov0" title="0">{
return &planet
}</span>
}
}
// If no home planet found by name, return any planet owned by our team
<span class="cov0" title="0">for _, planet := range ai.lastGameState.Planets </span><span class="cov0" title="0">{
if planet.TeamID == ai.teamID </span><span class="cov0" title="0">{
return &planet
}</span>
}
<span class="cov0" title="0">return nil</span>
}
func (ai *AIClient) findEnemyPlanet(myPos physics.Vector2D) *engine.PlanetState <span class="cov0" title="0">{
var target *engine.PlanetState
var nearestDistance float64 = math.Inf(1)
for _, planet := range ai.lastGameState.Planets </span><span class="cov0" title="0">{
if planet.TeamID != ai.teamID && planet.TeamID >= 0 </span><span class="cov0" title="0">{
distance := planet.Position.Distance(myPos)
if distance < nearestDistance </span><span class="cov0" title="0">{
target = &planet
nearestDistance = distance
}</span>
}
}
<span class="cov0" title="0">return target</span>
}
func getBehaviorDescription(behavior AIBehavior) string <span class="cov0" title="0">{
switch behavior </span>{
case BehaviorExplorer:<span class="cov0" title="0">
return "Explores the galaxy peacefully"</span>
case BehaviorAggressor:<span class="cov0" title="0">
return "Seeks out and attacks enemy ships"</span>
case BehaviorDefender:<span class="cov0" title="0">
return "Defends team's home planets"</span>
case BehaviorBomber:<span class="cov0" title="0">
return "Attacks enemy planets"</span>
default:<span class="cov0" title="0">
return "Unknown"</span>
}
}
</pre>
<pre class="file" id="file3" style="display: none">// examples/simple_server/main.go
// Simple server example demonstrating basic Netrek server setup
package main
import (
"flag"
"log"
"os"
"os/signal"
"syscall"
"time"
"github.com/opd-ai/go-netrek/pkg/config"
"github.com/opd-ai/go-netrek/pkg/engine"
"github.com/opd-ai/go-netrek/pkg/entity"
"github.com/opd-ai/go-netrek/pkg/network"
)
func main() <span class="cov0" title="0">{
// Command line flags
port := flag.String("port", "4566", "Server port")
maxClients := flag.Int("max-clients", 8, "Maximum number of clients")
flag.Parse()
log.Println("Starting Simple Netrek Server...")
// Create a simple game configuration
gameConfig := createSimpleGameConfig(*port, *maxClients)
// Create game engine
game := engine.NewGame(gameConfig)
log.Printf("Game created with %d teams and %d planets", len(gameConfig.Teams), len(gameConfig.Planets))
// Create and start server
server := network.NewGameServer(game, gameConfig.MaxPlayers)
serverAddr := "localhost:" + *port
log.Printf("Starting server on %s", serverAddr)
if err := server.Start(serverAddr); err != nil </span><span class="cov0" title="0">{
log.Fatalf("Failed to start server: %v", err)
}</span>
// Start game loop in background
<span class="cov0" title="0">go func() </span><span class="cov0" title="0">{
log.Println("Starting game loop...")
for game.Running </span><span class="cov0" title="0">{
game.Update()
time.Sleep(time.Second / 60) // 60 FPS
}</span>
}()
<span class="cov0" title="0">log.Printf("Server is ready! Connect with:")
log.Printf(" go run examples/ai_client/main.go -server=localhost:%s -name=Player1 -team=0", *port)
log.Printf(" go run examples/ai_client/main.go -server=localhost:%s -name=Player2 -team=1", *port)
// Handle graceful shutdown
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
<-sigChan
log.Println("Shutting down server...")
server.Stop()
game.Stop()
log.Println("Server stopped.")</span>
}
// createSimpleGameConfig creates a basic game configuration suitable for testing
func createSimpleGameConfig(port string, maxClients int) *config.GameConfig <span class="cov0" title="0">{
return &config.GameConfig{
WorldSize: 8000,
MaxPlayers: maxClients,
Teams: []config.TeamConfig{
{
Name: "Federation",
Color: "#0066FF",
MaxShips: 4,
StartingShip: "Scout",
},
{
Name: "Klingons",
Color: "#FF6600",
MaxShips: 4,
StartingShip: "Scout",
},
},
Planets: []config.PlanetConfig{
{
Name: "Earth",
X: -2000,
Y: 0,
Type: entity.Homeworld,
HomeWorld: true,
TeamID: 0,
InitialArmies: 25,
},
{
Name: "Qo'noS",
X: 2000,
Y: 0,
Type: entity.Homeworld,
HomeWorld: true,
TeamID: 1,
InitialArmies: 25,
},
{
Name: "Neutral Station",
X: 0,
Y: 1500,
Type: entity.Industrial,
HomeWorld: false,
TeamID: -1, // Neutral
InitialArmies: 15,
},
{
Name: "Mining Colony",
X: 0,
Y: -1500,
Type: entity.Agricultural,
HomeWorld: false,
TeamID: -1, // Neutral
InitialArmies: 10,
},
},
PhysicsConfig: config.PhysicsConfig{
Gravity: 0,
Friction: 0.05,
CollisionDamage: 15,
},
NetworkConfig: config.NetworkConfig{
UpdateRate: 20,
TicksPerState: 2,
UsePartialState: true,
ServerPort: 4566,
ServerAddress: "localhost:" + port,
},
GameRules: config.GameRules{
WinCondition: "conquest",
TimeLimit: 900, // 15 minutes
MaxScore: 50,
RespawnDelay: 3,
FriendlyFire: false,
StartingArmies: 0,
},
}
}</span>
</pre>
<pre class="file" id="file4" style="display: none">// pkg/config/config.go
package config
import (
"encoding/json"
"fmt"
"os"
"github.com/opd-ai/go-netrek/pkg/entity"