Sobes.tech
Senior

How to add support for time-limited games (3 or 5 minutes) in addition to unlimited games?

sobes.tech AI

Answer from AI

To add support for time-limited games (e.g., 3 or 5 minutes) in Go, you can use timers and contexts to control the game duration.

Main idea:

  • Start a timer for the specified duration when the game begins.
  • Automatically end the game when the time is up.
  • For games without time limits, do not start a timer.

Example implementation using time.Timer and a channel to stop the game:

package main

import (
    "fmt"
    "time"
)

type Game struct {
    duration time.Duration // 0 for unlimited
    done     chan bool
}

func NewGame(duration time.Duration) *Game {
    return &Game{
        duration: duration,
        done:     make(chan bool),
    }
}

func (g *Game) Start() {
    fmt.Println("Game started")
    if g.duration > 0 {
        timer := time.NewTimer(g.duration)
        go func() {
            <-timer.C
            fmt.Println("Time's up! Game over.")
            g.done <- true
        }()
    }
    // Game logic here
}

func (g *Game) Wait() {
    if g.duration > 0 {
        <-g.done
    } else {
        // Unlimited game, wait for user event
    }
}

func main() {
    gameWithLimit := NewGame(3 * time.Minute)
    gameWithLimit.Start()
    gameWithLimit.Wait()

    gameWithoutLimit := NewGame(0)
    gameWithoutLimit.Start()
    // For unlimited game, implement a different termination mechanism
}

Thus, by adding a time parameter, you can flexibly manage time restrictions for different game types.

How to add support for time-limited games (3 or 5… - sobes.tech