天天看点

lua+love2d的小游戏点格子

编辑环境 vsCode + love2D support(vsCode的插件) + love2D(c++写的运行lua游戏的一个引擎)udemy一个课介绍的

function love.load() ---love 的载入
    button = {}
    button.x = 200
    button.y = 200
    button.size = 50
    score = 0
    timer = 10
    gameState = 1 --2 为开始 1 为关闭状态
    myFont = love.graphics.newFont(40)--设置字体
end

function love.update(dt)  --delt  time every frame  --每dt 的更新
    if gameState == 2 then --2 为开始状态
        if timer > 0 then
            timer = timer -dt
        end  
    
        if timer < 0 then --时间为0后状态调整为关闭
            timer = 0
            gameState = 1
        end
    end  
end

function love.draw()  --每帧的画
    -- love.graphics.setColor(0,0,1) --love 11.0
    -- love.graphics.rectangle("fill",200,400,200,100) --draw order
    if gameState == 2 then
        love.graphics.setColor(1,0,0)
        love.graphics.circle("fill",button.x,button.y,button.size)
    end
    love.graphics.setFont(myFont)
    love.graphics.setColor(1,1,1)
    love.graphics.print("Score: " .. score) --打印分数  ..connect the string with the value (combine)
    love.graphics.print("Timer: " .. math.ceil(timer),300,0)  --打印时间  
    if gameState == 1 then
        love.graphics.printf("RightClick anywhere to begin",--打印开始画面
        0,love.graphics.getHeight()/2,love.graphics.getWidth(),"center")  --与print 的区别。
        --在屏幕的中央打印一句话。
    end
end

function love.mousepressed(x,y,b,istouch) --鼠标点击的更新程序
    if b == 1 and gameState == 2 then
        if distanceBetween(love.mouse.getX(),love.mouse.getY(),button.x,button.y) <= button.size then
            score = score + 1
            button.x = math.random(button.size,love.graphics.getWidth() - button.size)
            button.y = math.random(button.size,love.graphics.getHeight() - button.size)
        end
    end
    if b == 2 and gameState == 1 then 
        gameState =2
        timer = 10
    end
end

function distanceBetween(x1,y1,x2,y2) --计算鼠标点距离圆中心的距离
    return math.sqrt((y2 - y1)^2 + (x2 - x1)^2) 
end
           

右键点击任意位置开始,左键点击一下加一分,10秒后结束,计算分数,等待开始。