-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
126 lines (106 loc) · 2.23 KB
/
main.go
File metadata and controls
126 lines (106 loc) · 2.23 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
package main
import (
"fmt"
"math/rand"
"strings"
"sync"
"time"
)
type Box struct {
x int
y int
}
type Particle struct {
position Box
velocity Box
}
type System struct {
Box
particles []Particle
mutex sync.Mutex
}
func (sys *System) clear_screen() {
fmt.Print("\033[H\033[2J")
}
func (sys *System) draw_box() {
sys.mutex.Lock()
defer sys.mutex.Unlock()
border := strings.Repeat("-", sys.Box.x+2)
fmt.Println(border)
for y := 0; y < sys.Box.y; y++ {
line := strings.Repeat(" ", sys.Box.x)
for _, p := range sys.particles {
if p.position.y == y {
line = line[:p.position.x] + "☺" + line[p.position.x+1:]
}
}
fmt.Println("|" + line + "|")
}
fmt.Println(border)
}
func (sys *System) update_particles() {
sys.mutex.Lock()
defer sys.mutex.Unlock()
for i := range sys.particles {
p := &sys.particles[i]
p.position.x += p.velocity.x
p.position.y += p.velocity.y
if p.position.x <= 0 || p.position.x >= sys.Box.x-1 {
p.velocity.x *= -1
p.position.x += p.velocity.x
}
if p.position.y <= 0 || p.position.y >= sys.Box.y-1 {
p.velocity.y *= -1
p.position.y += p.velocity.y
}
}
handle_collisions(sys.particles)
}
func handle_collisions(particles []Particle) {
for i := 0; i < len(particles); i++ {
for j := i + 1; j < len(particles); j++ {
a := &particles[i]
b := &particles[j]
if a.position == b.position {
a.velocity, b.velocity = b.velocity, a.velocity
}
}
}
}
func (b Box) generate_random_particles(n int) []Particle {
particles := make([]Particle, n)
for i := 0; i < n; i++ {
particles[i] = Particle{
position: Box{
x: rand.Intn(b.x),
y: rand.Intn(b.y),
},
velocity: Box{
x: rand.Intn(2)*2 - 1, // -1 or 1
y: rand.Intn(2)*2 - 1, // -1 or 1
},
}
}
return particles
}
func main() {
box := Box{x: 75, y: 20}
sys := &System{
Box: box,
particles: box.generate_random_particles(10),
}
ticker := time.NewTicker(43 * time.Millisecond)
defer ticker.Stop()
for range ticker.C {
sys.clear_screen()
sys.draw_box()
sys.update_particles()
}
}
// p := Particle{
// position: Box{x: box_size.x / 2, y: box_size.y / 2},
// }
// p2 := Particle{
// Box: box_size,
// position: Box{x: box_size.x / 2, y: box_size.y / 2},
// }