跳转至内容

02. 暂停,随机,三个奖牌

2.26,完成 Week1 的作业。

添加暂停功能

lua
function PlayState:update(dt)
    if love.keyboard.wasPressed('p') then
        self.isPaused = not self.isPaused
        scrolling = not self.isPaused

        if self.isPaused then
            sounds['pause']:play()
            sounds['music']:pause()
        else
            sounds['music']:play()
        end
    end

    if self.isPaused then
        return
    end

    -- ...
end

管道生成随机化

lua
if self.timer > self.spawnInterval then
    local gapHeight = math.random(80, 110)

    -- 保证生成的管道不会太高或太低
    local y = math.max(
        -PIPE_HEIGHT + 10,
        math.min(
            self.lastY + math.random(-20, 20),
            VIRTUAL_HEIGHT - gapHeight - PIPE_HEIGHT
        )
    )
    -- 加到管道 table 中统一渲染
    table.insert(self.pipePairs, PipePair(y, gapHeight))

    self.lastY = y
    self.timer = 0
    self.spawnInterval = math.random(140, 220) / 100
end
lua
function PipePair:init(y, gapHeight)
    self.x = VIRTUAL_WIDTH + 32
    self.y = y
    self.gapHeight = gapHeight or 90
    self.pipes = {
        ['upper'] = Pipe('top', self.y),
        ['lower'] = Pipe('bottom', self.y + PIPE_HEIGHT + self.gapHeight)
    }
    self.remove = false
    self.scored = false
end

根据分数发放奖牌

lua
function ScoreState:init()
    self.medals = {
        {
            name = 'Gold Medal',
            minScore = GOLD_MIN_SCORE,
            image = love.graphics.newImage('1st-medal.png')
        },
        {
            name = 'Silver Medal',
            minScore = SILVER_MIN_SCORE,
            image = love.graphics.newImage('2nd-medal.png')
        },
        {
            name = 'Bronze Medal',
            minScore = BRONZE_MIN_SCORE,
            image = love.graphics.newImage('3rd-medal.png')
        }
    }
end

function ScoreState:enter(params)
    self.score = params.score
    self.awardedMedal = nil

    for _, medal in ipairs(self.medals) do
        if self.score >= medal.minScore then
            self.awardedMedal = medal
            break
        end
    end
end