-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathball.go
133 lines (101 loc) · 2.13 KB
/
ball.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
package main
import (
"github.com/gdamore/tcell/v2"
"time"
)
// Ball entity which implements the GameObject interface
type Ball struct{
X int
Y int
SpeedX int
SpeedY int
Active bool
Screen tcell.Screen
}
func (ball Ball) GetX() int{
return ball.X
}
func (ball Ball) GetY() int{
return ball.Y
}
func (ball Ball) GetHeight() int{
return ball.GetY()
}
func (ball Ball) GetWidth() int{
return ball.GetX()
}
func (ball Ball) GetActiveState() bool{
return ball.Active
}
func (ball Ball) Display(engine *Engine) {
shape := "\u26AA"
renderGameObject(
engine.Screen,
ball.GetX(),
ball.GetY(),
ball.GetX(),
ball.GetY(),
engine.Style,
shape,
)
}
func resetPosition(ball *Ball){
width,height := ball.Screen.Size()
ball.X = width / 2
ball.Y = height / 2
}
func (ball *Ball) Update(engine Engine){
if(ball.Active){
ball.X+=ball.SpeedX
ball.Y+=ball.SpeedY
return
}
if (engine.Player.Life == 0){
GameStateMessages <- "game-over"
return
}
//makes ball active again after a small pause
time.Sleep(2 * time.Second)
ball.Active = true
}
func (ball *Ball) CheckCollision(g GameObject){
if(!ball.Active){
return
}
_, isBlock := g.(*Block)
hasCollision :=
ball.GetX() >= g.GetX() &&
ball.GetX() <= g.GetX() + g.GetWidth() &&
ball.GetY() >= g.GetY() &&
ball.GetY() <= g.GetY() + g.GetHeight()
if (hasCollision && !isBlock){
reflect(ball,g)
}
if (hasCollision && isBlock && g.GetActiveState()){
reflect(ball,g)
}
}
func (ball *Ball) CheckEdges(screenWidth int, screenHeight int){
if(!ball.Active){
return
}
if ball.X <= 0 || ball.X >= screenWidth {
ball.SpeedX *= -1
}
if (ball.Y >= screenHeight) {
ball.Active = false
resetPosition(ball)
GameStateMessages <- "ball-droped"
}else if (ball.Y <= 0){
ball.SpeedY *= -1
}
}
func reflect (ball *Ball, g GameObject){
// Determine which side of the block the collision occurred
if ball.GetX() <= g.GetX() || ball.GetX() >= g.GetX()+g.GetWidth() {
ball.SpeedX *= -1 //Reflect X direction
}
if ball.GetY() <= g.GetY() || ball.GetY() >= g.GetY()+g.GetHeight() {
ball.SpeedY *= -1 //Reflect Y direction
}
}