-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathguiGame.go
469 lines (410 loc) · 11.7 KB
/
guiGame.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
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
package graphics
import (
"bytes"
"github.com/TeodorDyakov/spooky-connect4/client/game"
"github.com/TeodorDyakov/spooky-connect4/client/resources"
"github.com/hajimehoshi/ebiten/v2"
"github.com/hajimehoshi/ebiten/v2/inpututil"
"github.com/hajimehoshi/ebiten/v2/text"
"golang.org/x/image/font"
"golang.org/x/image/font/opentype"
"image"
"image/color"
_ "image/jpeg"
_ "image/png"
"log"
"os"
"strconv"
"time"
)
var backgroundImage,
owl,
redBallImage,
dot,
ghost,
greenBallImage,
boardImage,
bats *ebiten.Image
func byteSliceToEbitenImage(arr []byte) *ebiten.Image {
img, _, err := image.Decode(bytes.NewReader(arr))
if err != nil {
log.Fatal(err)
}
return ebiten.NewImageFromImage(img)
}
func init() {
ghost = byteSliceToEbitenImage(resources.Ghost_png)
backgroundImage = byteSliceToEbitenImage(resources.Background_png)
redBallImage = byteSliceToEbitenImage(resources.Red_png)
greenBallImage = byteSliceToEbitenImage(resources.Green_png)
owl = byteSliceToEbitenImage(resources.Owl_png)
dot = byteSliceToEbitenImage(resources.Dot_png)
bats = byteSliceToEbitenImage(resources.Bats_png)
boardImage = byteSliceToEbitenImage(resources.Board_png)
tt, _ := opentype.Parse(resources.MPlus1pRegular_ttf)
mplusNormalFont, _ = opentype.NewFace(tt, &opentype.FaceOptions{
Size: 20,
DPI: 72,
Hinting: font.HintingFull,
})
initBallYCoords()
}
type Game struct{}
type GameState int
func initBallYCoords() {
for i := 0; i < 7; i++ {
for j := 0; j < 6; j++ {
ballYcoords[i][j] = -tileHeight
}
}
}
const (
yourTurn GameState = iota
opponentTurn
win
lose
tie
animation
opponentAnimation
menu
waitingForConnect
waitingForToken
connectToRoomWithToken
cantConnectToServer
enterAIdifficulty
wrongToken
)
const (
batsX = 440
batsY = 200
secondsToMakeTurn = 59
fps = 60
tileHeight = 65
tileOffset = 10
boardX = 84
boardY = 130
gravity = 0.5
)
//the column the opponent has chosen last
var opponentLastCol int
var frameCount int
var gameState GameState = menu
var ballYcoords [7][6]float64
var ballFallSpeed [7][6]float64
var mplusNormalFont font.Face
//this is used to receive information for setting up an online game
var serverCommunicationChannel chan gameLogic.ServerMessage = make(chan gameLogic.ServerMessage)
//messages shown during a match of the game
var messages [7]string = [7]string{"Your turn", "Other's turn", "You win!", "You lost.", "Tie.", "...", "..."}
//the token with which a user connects or the token received by server
var token string
var gm gameLogic.GameManager
func changeGameStateBasedOnGameManagerState(gmState int) {
if gmState != 0 {
if gmState == gameLogic.Win {
gameState = win
}
if gmState == gameLogic.Lose {
gameState = lose
}
if gmState == gameLogic.Tie {
gameState = tie
}
}
}
func updateBallPos(){
for i := 0; i < 6; i++ {
for j := 0; j < 7; j++ {
if gm.GetHoleColor(i, j) == gameLogic.PlayerTwoColor ||
gm.GetHoleColor(i, j) == gameLogic.PlayerOneColor {
y, x := i, j
destY := float64(y) * tileHeight
fallY := &ballYcoords[x][y]
fallSpeed := &ballFallSpeed[x][y]
*fallY += *fallSpeed
*fallSpeed += gravity
if *fallY > destY {
*fallY = destY
*fallSpeed = 0
}
}
}
}
}
//the main logic of the game, changing game state moving between menus and starting a match of the game
func (g *Game) Update() error {
press := inpututil.IsMouseButtonJustReleased(ebiten.MouseButtonLeft)
if gameState == yourTurn || gameState == opponentTurn {
frameCount++
}
if gameState == animation || gameState == opponentAnimation {
frameCount = 0
updateBallPos();
}
if frameCount == fps*secondsToMakeTurn {
os.Exit(1)
}
// updateBallPos();
if gameState == yourTurn && press {
mouseX, _ := ebiten.CursorPosition()
if gm.MakePlayerTurn(xcoordToColumn(mouseX)) {
gameState = animation
go func() {
gmState := gm.GetState()
time.Sleep(1 * time.Second)
if gmState == gameLogic.Running {
gameState = opponentTurn
} else {
changeGameStateBasedOnGameManagerState(gmState)
}
}()
}
}
if gameState == opponentTurn {
gameState = animation
go func() {
opponentLastCol = gm.MakeOpponentTurn()
gameState = opponentAnimation
time.Sleep(1 * time.Second)
gmState := gm.GetState()
if gmState == gameLogic.Running {
gameState = yourTurn
} else {
changeGameStateBasedOnGameManagerState(gmState)
}
}()
}
if gameState == menu && ebiten.IsKeyPressed(ebiten.KeyA) {
gameState = enterAIdifficulty
}
if gameState == enterAIdifficulty {
diff := string(ebiten.InputChars())
if len(diff) == 1 {
difficulty, err := strconv.Atoi(diff)
if err == nil {
gameState = yourTurn
gm = gameLogic.NewGameManager(nil, true, difficulty+3)
}
}
}
if gameState == menu && ebiten.IsKeyPressed(ebiten.KeyO) {
gameState = waitingForConnect
go gameLogic.QuickplayLobby(serverCommunicationChannel)
}
if gameState == menu && ebiten.IsKeyPressed(ebiten.KeyR) {
gameState = waitingForToken
go gameLogic.CreateRoom(serverCommunicationChannel)
}
if gameState == menu && inpututil.IsKeyJustReleased(ebiten.KeyC) {
gameState = connectToRoomWithToken
}
if gameState == connectToRoomWithToken {
token += string(ebiten.InputChars())
if len(token) == 5 {
gameState = waitingForConnect
go gameLogic.ConnectToRoom(token, serverCommunicationChannel)
}
}
if gameState == waitingForToken {
select {
case gameInfo := <-serverCommunicationChannel:
if gameInfo.Conn == nil {
gameState = cantConnectToServer
} else {
token = gameInfo.Token
gameState = waitingForConnect
}
default:
}
}
if gameState == waitingForConnect {
select {
case gameInfo := <-serverCommunicationChannel:
if gameInfo.Conn == nil {
token = ""
gameState = cantConnectToServer
} else if gameInfo.Status == "wrong_token" {
token = ""
gameState = wrongToken
} else {
if gameInfo.IsSecond {
gameState = opponentTurn
} else {
gameState = yourTurn
}
gm = gameLogic.NewGameManager(gameInfo.Conn, false, 0)
}
default:
}
}
if gameState == cantConnectToServer || gameState == wrongToken {
frameCount++
if frameCount == 2*fps {
frameCount = 0
gameState = menu
}
}
if isGameOver() && press {
mouseX, mouseY := ebiten.CursorPosition()
/*check if mouse is in play again area
*/
if mouseX >= 230 && mouseX <= 600 && mouseY >= 500 {
gmState := gm.GetState()
gm.ResetGame()
var s [7][6]float64
ballFallSpeed = s
initBallYCoords()
if gmState == gameLogic.Win {
gameState = opponentTurn
} else {
gameState = yourTurn
}
}
}
return nil
}
//isGameOver returns whether the game is over
func isGameOver() bool {
return gameState == tie || gameState == win || gameState == lose
}
//this fucntion draws the graphic of the game based on the gameState
func (g *Game) Draw(screen *ebiten.Image) {
screen.DrawImage(backgroundImage, nil)
op := &ebiten.DrawImageOptions{}
op.GeoM.Translate(batsX, batsY)
screen.DrawImage(bats, op)
op.GeoM.Reset()
op.GeoM.Translate(boardX, boardY)
if gameState == menu || gameState == cantConnectToServer || gameState == wrongToken {
screen.DrawImage(boardImage, op)
text.Draw(screen, "[A] - play against AI", mplusNormalFont, boardX, boardY-30, color.White)
text.Draw(screen, "[R] - create a room", mplusNormalFont, boardX, 570, color.White)
text.Draw(screen, "[C] - connect to a room", mplusNormalFont, boardX+250, 570, color.White)
text.Draw(screen, "[O] - play online (quick play)", mplusNormalFont, boardX+250, boardY-30, color.White)
if gameState == cantConnectToServer {
text.Draw(screen, "Can't connect to server!", mplusNormalFont, 200, 200, color.White)
}
if gameState == wrongToken {
text.Draw(screen, "There is no room with this token!", mplusNormalFont, 200, 200, color.White)
}
return
}
if gameState == connectToRoomWithToken {
screen.DrawImage(boardImage, op)
text.Draw(screen, "Enter the code for room:\n"+token, mplusNormalFont, 200, 50, color.White)
return
}
if gameState == enterAIdifficulty {
screen.DrawImage(boardImage, op)
text.Draw(screen, "Enter difficulty (1-9)\n"+token, mplusNormalFont, 200, 50, color.White)
return
}
if gameState == waitingForConnect || gameState == waitingForToken {
screen.DrawImage(boardImage, op)
text.Draw(screen, "waiting for opponent...", mplusNormalFont, 200, 50, color.White)
if token != "" {
text.Draw(screen, "Your token is: "+token, mplusNormalFont, 200, 80, color.White)
}
return
}
var msg string = messages[gameState]
text.Draw(screen, "W "+strconv.Itoa(gm.GetWonGames())+":"+strconv.Itoa(gm.GetLostGames())+" L", mplusNormalFont, boardX, 50, color.White)
text.Draw(screen, msg, mplusNormalFont, boardX, 580, color.White)
text.Draw(screen, "00:"+strconv.Itoa(secondsToMakeTurn-frameCount/fps), mplusNormalFont, 500, 580, color.White)
drawOwl(screen)
if gameState == opponentAnimation {
drawGhost(screen)
}
drawBalls(screen)
screen.DrawImage(boardImage, op)
if isGameOver() {
text.Draw(screen, "Click here\nto play again", mplusNormalFont, 250, 580, color.White)
if gameState != tie {
drawWinnerDots(screen)
}
}
}
//drawBalls draws all the balls to the screen
func drawBalls(screen *ebiten.Image) {
for i := 0; i < 6; i++ {
for j := 0; j < 7; j++ {
if gm.GetHoleColor(i, j) == gameLogic.PlayerTwoColor {
drawBall(j, i, gameLogic.PlayerTwoColor, screen)
} else if gm.GetHoleColor(i, j) == gameLogic.PlayerOneColor {
drawBall(j, i, gameLogic.PlayerOneColor, screen)
}
}
}
}
//drawWinnerDors draws the dots indicating where the winner has four connected balls
func drawWinnerDots(screen *ebiten.Image) {
win, dotsY, dotsX := gm.WhereConnected()
if !win {
return
}
for i := 0; i < 4; i++ {
op := &ebiten.DrawImageOptions{}
op.GeoM.Translate(boardX+tileOffset, boardY+tileOffset)
op.GeoM.Translate(float64(dotsX[i])*tileHeight+25, float64(dotsY[i])*tileHeight+25)
screen.DrawImage(dot, op)
}
}
//drawGhost draws the ghost image to the screen
func drawGhost(screen *ebiten.Image) {
op := &ebiten.DrawImageOptions{}
op.GeoM.Translate(float64(opponentLastCol)*tileHeight+boardX+10, boardY-75)
screen.DrawImage(ghost, op)
}
//drawOwl draws the owl image to the screen
func drawOwl(screen *ebiten.Image) {
op := &ebiten.DrawImageOptions{}
mouseX, _ := ebiten.CursorPosition()
if mouseX < boardX {
mouseX = boardX
}
if mouseX > boardX+7*tileHeight {
mouseX = boardX + 7*tileHeight
}
owlX := xcoordToColumn(mouseX)*tileHeight + boardX
op.GeoM.Translate(float64(owlX), boardY-80)
screen.DrawImage(owl, op)
}
//drawBall draws the ball to the screen
func drawBall(x, y int, player string, screen *ebiten.Image) {
op := &ebiten.DrawImageOptions{}
op.GeoM.Translate(boardX+tileOffset, boardY+tileOffset)
op.GeoM.Translate(float64(x)*tileHeight, ballYcoords[x][y]);
if player == gameLogic.PlayerTwoColor {
screen.DrawImage(redBallImage, op)
} else {
screen.DrawImage(greenBallImage, op)
}
}
func updateBallsPos(x, y int){
// for y := 0; y < 6; y++ {
// for x := 0; x < 7; x++ {
destY := float64(y) * tileHeight
fallY := &ballYcoords[x][y]
fallSpeed := &ballFallSpeed[x][y]
*fallY += *fallSpeed
*fallSpeed += gravity
if *fallY > destY {
*fallY = destY
*fallSpeed = 0
}
// }
// }
}
func (g *Game) Layout(outsideWidth, outsideHeight int) (screenWidth, screenHeight int) {
return 640, 640
}
//xcoordToColumn returns the column correspondidng which contains the x coordinate
func xcoordToColumn(x int) int {
return int(float64(x-tileOffset-boardX) / tileHeight)
}
//StartGuiGame initializes the game and the gui, this is the entry point for the whole game
func StartGuiGame() {
ebiten.SetWindowSize(640, 640)
ebiten.SetWindowTitle("Connect four")
ebiten.RunGame(&Game{})
}