-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrain.go
More file actions
73 lines (64 loc) · 1.45 KB
/
rain.go
File metadata and controls
73 lines (64 loc) · 1.45 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
package main
import (
"log"
)
// RainDrop holds the state of a single raindrop
type RainDrop struct {
char rune
x int
y int
}
// Rain holds the state of all raindrops
// Density detemines number of raindrops created for a rain
// For a rain with 50w and 20h, the area is 50 * 20 = 1000
// Density of 0.5 means 0.5 * 1000 = 500 raindrops
type Rain struct {
w int
h int
density float64
drops []*RainDrop
}
// NewRain creates a new rain
func NewRain(w, h int, density float64) *Rain {
log.Println("create new rain...")
// Create rain
rain := &Rain{w: w, h: h, density: density}
// Create raindrops
area := rain.w * rain.h
totalDrops := int(rain.density * float64(area))
drops := make([]*RainDrop, totalDrops)
for i := range drops {
// We want more heavy drops than light drops
// To create the illusion of depth
var char rune
switch RandInt(0, 5) {
case 0, 1, 2:
char = '|'
case 3, 4:
char = ':'
case 5:
char = '.'
}
drop := &RainDrop{
char: char,
x: RandInt(0, rain.w-1),
y: RandInt(-rain.h, -1),
}
drops[i] = drop
}
rain.drops = drops
log.Printf("rain = {drops:[%d], w:%d, h:%d}", len(rain.drops), rain.w, rain.h)
return rain
}
// Fall updates the state of rainfall by one tick
func (r *Rain) Fall() {
for _, drop := range r.drops {
if drop.y+1 < r.h {
drop.y++
} else {
// If a raindrop has reached the ground, reset its position
drop.x = RandInt(0, r.w-1)
drop.y = 0
}
}
}