Skip to content

Commit

Permalink
Limiting the amount of bombs functionality added
Browse files Browse the repository at this point in the history
  • Loading branch information
barisbll committed Sep 30, 2023
1 parent e7bd964 commit 75cb405
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 7 deletions.
12 changes: 6 additions & 6 deletions bomb.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package main

import (
"sync"
"time"

tcell "github.com/gdamore/tcell/v2"
Expand Down Expand Up @@ -101,14 +102,11 @@ func calculateFinalPosition(maxX, maxY, currentX, currentY, distanceX, distanceY
}
}

func (b *Bomb) draw(s tcell.Screen, style tcell.Style) {
ticker := time.NewTicker(20 * time.Millisecond)
bombExploded := make(chan struct{})
explosionComplete := make(chan struct{})
func (b *Bomb) draw(s tcell.Screen, style tcell.Style, ticker *time.Ticker, bombExploded chan string, explosionComplete chan struct{}, explosionWaitGroup *sync.WaitGroup) {
go func() {
time.Sleep(b.explodeIn)
b.isDead = true
close(bombExploded)
bombExploded <- ""
bombExploded <- ""
time.Sleep(1 * time.Second)
close(explosionComplete)
}()
Expand All @@ -134,6 +132,8 @@ func (b *Bomb) draw(s tcell.Screen, style tcell.Style) {
s.SetContent(b.currentX, b.currentY, ExplosionEmoji, nil, style)
b.lastDrawnPosition.x = b.currentX
b.lastDrawnPosition.y = b.currentY
explosionWaitGroup.Done()
explosionWaitGroup.Wait()
case <-explosionComplete:
s.SetContent(b.currentX, b.currentY, ' ', nil, style)
s.Show()
Expand Down
39 changes: 38 additions & 1 deletion hero.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package main

import (
"sync"
"time"

tcell "github.com/gdamore/tcell/v2"
Expand Down Expand Up @@ -69,6 +70,42 @@ func (h *Hero) addBomb(s tcell.Screen, style tcell.Style, clickedX, clickedY int

h.bombIdCounter++
h.bombs = append(h.bombs, bomb)
bomb.draw(s, style)

ticker := time.NewTicker(20 * time.Millisecond)
bombExploded := make(chan string)
explosionComplete := make(chan struct{})

var explosionWaitGroup sync.WaitGroup
explosionWaitGroup.Add(2)

bomb.draw(s, style, ticker, bombExploded, explosionComplete, &explosionWaitGroup)

// TODO: use the waitGroups to be sure that each goroutine are not leaking

go func() {
for {
select {
case <-bombExploded:

var indexToRemove int = -1

for i, heroBomb := range h.bombs {
if heroBomb.bombId == bomb.bombId {
bomb.isDead = true
indexToRemove = i
break
}
}

if indexToRemove != -1 {
// Create a new slice without the element to remove
h.bombs = append(h.bombs[:indexToRemove], h.bombs[indexToRemove+1:]...)
}

explosionWaitGroup.Done()
explosionWaitGroup.Wait()
}
}
}()

}

0 comments on commit 75cb405

Please sign in to comment.