MainScene = class("MainScene", function()
    return display.newScene("MainScene")
end)


function MainScene:ctor()
-- 两全局变量实现统计分数和米数
meterNum = 0
scoreNum = 0
mapNum = 1


      --当前瓦片地图序数
    numMap = 0
    posMap = 0
    speed = 6
    maptype = 0
    
    CCUserDefault:sharedUserDefault():setIntegerForKey("score", scoreNum)


    --背景图片的加载(两张实现背景图片循环滚动)
  bg1 = display.newSprite("BG2.png")
bg1:setAnchorPoint(ccp(0, 0))
bg1:setPosition(ccp(0, 0))
bg1:setScaleY(0.5)
self:addChild(bg1, 0)


bg2 = display.newSprite("BG2.png")
bg2:setAnchorPoint(ccp(0, 0))
bg2:setPosition(ccp(bg1:getContentSize().width, 0))
bg2:setScaleY(0.5)
self:addChild(bg2, 0)
    
    -- 英雄图片的加载
hero = Hero.new()
hero:setPosition(ccp(50, 50))
hero:setAnchorPoint(ccp(0.5, 0.5))
hero:setScale(0.5)
self:addChild(hero, 1)
hero:StartRun()


    -- 加载触摸层
touchlayer = TouchLayer.new(hero)
self:addChild(touchlayer, 0)
    
    -- 显示分数的图片的加载
    local score1 = display.newSprite("scoreBg3.png")
    score1:setPosition(ccp(55, 310))
    score1:setScale(0.4)
    self:addChild(score1, 2)
    
    -- 显示米数的图片加载
    local score2 = display.newSprite("scoreBg4.png")
    score2:setPosition(ccp(155, 310))
    score2:setScale(0.4)
    self:addChild(score2, 2)
    
    -- 用label来接米数
    meter = ui.newTTFLabel({
    text = "0",
font = "Arial",
size = 12,
align = ui.TEXT_ALIGN_CENTER,
x = 160,
y = 310,
--color = ccc3(0, 0, 255)
    })
    self:addChild(meter, 2)
    
    -- 用label来接分数
    score = ui.newTTFLabel({
    text = "0",
font = "Arial",
size = 12,
align = ui.TEXT_ALIGN_CENTER,
x = 60,
y = 310,
--color = ccc3(0, 0, 255)
    })
    self:addChild(score, 2)
    
    -- 加载飞龙
    dragon = Dragon.new()
dragon:setPosition(ccp(450, 250))
self:addChild(dragon, 1)
dragon:StartRun()
  
    -- 通过时间调度来实现计算英雄所跑米数和所得分数
    local sharedScheduler = CCDirector:sharedDirector():getScheduler()
self._schedule1 = sharedScheduler:scheduleScriptFunc(countMeter, 0.1, false)
    
    -- 暂停按钮
    pauseBtn = cc.ui.UIPushButton.new({normal = "pause.png"},{scale9 = true})
pauseBtn:setPosition(ccp(display.width - 10, display.height - 10))
pauseBtn:setScale(0.5)
self:addChild(pauseBtn, 1)
    
    -- 暂停按钮的点击事件
pauseBtn:onButtonClicked(function( event )


local sharedScheduler = CCDirector:sharedDirector():getScheduler()
   sharedScheduler:unscheduleScriptEntry(self._schedule)
   sharedScheduler:unscheduleScriptEntry(self._schedule1)
   hero:StopRun()
   hero._Flag = false
        
pausePic = display.newSprite("reBG.png")
pausePic:setScale(0.4)
pausePic:setPosition(ccp(display.cx, display.cy))
self:addChild(pausePic,1)


local okBtn = cc.ui.UIPushButton.new({normal = "reStart1.png"},{scale9 = true})
local continueBtn = cc.ui.UIPushButton.new({normal = "continueGame1.png"},{scale9 = true})
okBtn:setScale(0.3)
   okBtn:setPosition(ccp(pausePic:getPositionX(), pausePic:getPositionY() - 70))
   self:addChild(okBtn, 1)
        
   okBtn:onButtonClicked(function( event )
    okBtn:removeFromParent()
    pausePic:removeFromParent()
    continueBtn:removeFromParent()


       
   end)


continueBtn:setScale(0.3)
   continueBtn:setPosition(ccp(pausePic:getPositionX(), pausePic:getPositionY() - 20))
   self:addChild(continueBtn, 1)


   continueBtn:onButtonClicked(function( event )
    okBtn:removeFromParent()
    pausePic:removeFromParent()
    continueBtn:removeFromParent()


    hero._Flag = true


    local sharedScheduler = CCDirector:sharedDirector():getScheduler()
self._schedule = sharedScheduler:scheduleScriptFunc(function ()
self:ScrollBG()
end, 0.04, false)
            self._schedule1 = sharedScheduler:scheduleScriptFunc(countMeter, 0.1, false)
hero:StartRun()


   end)
end)
    
    -- 瓦片地图
    self:SetMap1()
    self:SetMap2()
        
    -- 通过时间调度实现背景滚动
sharedScheduler = CCDirector:sharedDirector():getScheduler()
self._schedule = sharedScheduler:scheduleScriptFunc(function ()
self:ScrollBG()
end, 0.04, false)




end




-- 两背景图片循环滚动
function MainScene:ScrollBG()
-- 地图滚动
local move1 = cc.MoveBy:create(0.001,ccp(-3, 0))
local move2 = cc.MoveBy:create(0.001,ccp(-3, 0))
bg1:runAction(move1)
bg2:runAction(move2)
if bg1:getPositionX() <= -bg1:getContentSize().width then
bg1:setPositionX(bg2:getPositionX() + bg1:getContentSize().width)
end


if bg2:getPositionX() <= -bg2:getContentSize().width then
bg2:setPositionX(bg1:getPositionX() + bg2:getContentSize().width)
end


    -- 瓦片地图滚动
    self:ScrollMap()


    local moveDra = cc.MoveTo:create(100,ccp(hero:getPositionX(), hero:getPositionY() + 40))
    local moveDra1 = cc.MoveTo:create(100,ccp(display.width, display.height))
    local seq = CCSequence:createWithTwoActions(moveDra, moveDra1)
    local rep = CCRepeatForever:create(seq)
dragon:runAction(seq)
    if hero:getPositionY() >= 45 then
    hero:setPosition(ccp(hero:getPositionX(), hero:getPositionY() - 1))
    end
    


    if maptype == 0 then
    self:collision1(map1, coin, daoju)
    self:collision_floor(map1, floor)
    elseif maptype == 1 then
    self:collision1(map2, coin1, daoju1)
    self:collision_floor(map2, floor1)
    end
        
end


--创建瓦片地图
--1
function MainScene:SetMap1()
  ---添加瓦片地图
  numMap = MainScene:GetnumMap(numMap)
  --print("···11:..." .. numMap)
  map1 = CCTMXTiledMap:create("tiledmap/" .. tostring(numMap)..".tmx")
  map1:setAnchorPoint(ccp(0,0))
  map1:setPosition(ccp(posMap, 0))
  self:addChild(map1,0) 
        
  coin = map1:layerNamed("coin")
  floor = map1:layerNamed("floor")
  daoju = map1:layerNamed("daoju")
  posMap = 960


  
end
--2
function MainScene:SetMap2()
  ---添加瓦片地图
  numMap = MainScene:GetnumMap(numMap)
  --print("···22:..." .. numMap)
  map2 = CCTMXTiledMap:create("tiledmap/" .. tostring(numMap) .. ".tmx")
  map2:setAnchorPoint(ccp(0, 0))
  map2:setPosition(ccp(posMap, 0))
  self:addChild(map2, 0)
        
  coin1 = map2:layerNamed("coin")
  floor1 = map2:layerNamed("floor")
  daoju1 = map2:layerNamed("daoju")


end




--瓦片地图的移动
function MainScene:ScrollMap()
  if map1:getPositionX() <= -960 then
    posMap = 960*2+map1:getPositionX()
    map1:removeFromParentAndCleanup(true)
    self:SetMap1()
    maptype = 1
  end
  if map2:getPositionX() <= -960 then
    posMap = 960*2+map2:getPositionX()
    map2:removeFromParentAndCleanup(true)
    self:SetMap2()
    maptype = 0
  end
  if map2:getPositionX()<=50 and -910<map2:getPositionX() then
  maptype = 1
  else
  maptype = 0
  end


  map1:setPositionX(map1:getPositionX() - speed)
  map2:setPositionX(map2:getPositionX() - speed)
  -- self:Impact()




end


function MainScene:collision1(map1, coin, daoju)


local x1=checkint((math.abs(hero:getPositionX() - map1:getPositionX())/(map1:getTileSize().width))-0.5) 
local y1=checkint(((map1:getMapSize().height * map1:getTileSize().height) - hero:getPositionY())/map1:getTileSize().height) 
local tileCoin =ccp(x1,y1)
-- if assert(coin:tileGIDAt(tileCoin))  then
local tilegidCoin = coin:tileGIDAt(tileCoin)
-- else
-- printf("zzzzz")
-- return
-- end




-- coin:removeTileAt(tileCoin)
if tilegidCoin then
local propertiess = map1:propertiesForGID(tilegidCoin)
if propertiess then
local collCoin = propertiess:objectForKey("coinType")
if collCoin and collCoin:compare("1") == 0 then
scoreNum = scoreNum + 5
                score:setString(scoreNum)
                local scoreH = CCUserDefault:sharedUserDefault():getIntegerForKey("score")
                if scoreNum > scoreH then
                CCUserDefault:sharedUserDefault():setIntegerForKey("score", scoreNum)
                CCUserDefault:sharedUserDefault():flush()
                print(scoreH)
                end
local ccoin = coin:tileAt(tileCoin)
ccoin:removeFromParent()
print("吃了")
end
end
end


local tilegiddaoju = daoju:tileGIDAt(tileCoin)
if tilegiddaoju then
local propertiess = map1:propertiesForGID(tilegiddaoju)
if propertiess then
local colldaoju = propertiess:objectForKey("daojuType")
if colldaoju and colldaoju:compare("1") == 0 then
self:stopAllActions()
print("死了")


self:deadMenu()
end
if colldaoju and colldaoju:compare("2") == 0 then
self:secondGame()
end
end
end
end


function MainScene:collision_floor(map1, floor)
local x1=checkint((math.abs(hero:getPositionX() - map1:getPositionX())/(map1:getTileSize().width))-0.5) 
local y1=checkint(((map1:getMapSize().height * map1:getTileSize().height) - hero:getPositionY())/map1:getTileSize().height) 
local tilefloor =ccp(x1,y1)




local tilegidfloor = floor:tileGIDAt(tilefloor)
-- coin:removeTileAt(tileCoin)
if tilegidfloor then
local propertiess = map1:propertiesForGID(tilegidfloor)
if propertiess then
local collfloor = propertiess:objectForKey("floorType")
if collfloor and collfloor:compare("1") == 0 then
hero:setPositionY(32*(10.5 - y1))
--hero:setPosition(ccp(50, 50))
print("踩地面了")
end
end
end
end


--获取加载的瓦片地图的序数
function MainScene:GetnumMap(map_Num)
if speed >= 10 then
speed = 10
else
   speed = speed + 0.5
end


  map_Num = map_Num%10 + 1
  return map_Num
end


function MainScene:deadMenu( )
-- hero:stopAllActions()
-- self._schedule:unscheduleAll()
hero._Flag = false
self:setTouchEnabled(false)
sharedScheduler = CCDirector:sharedDirector():getScheduler()
sharedScheduler:unscheduleScriptEntry(self._schedule)
sharedScheduler:unscheduleScriptEntry(self._schedule1)
hero:StopRun()




deadBG = display.newSprite("seg.png")
deadBG:setPosition(ccp(display.cx, display.cy))
deadBG:setScale(0.5)
deadBG:setScaleY(0.25)
self:addChild(deadBG,10)


local okBtn = cc.ui.UIPushButton.new({normal = "reStart1.png"},{scale9 = true})
    --local continueBtn = cc.ui.UIPushButton.new({normal = "continueGame1.png"},{scale9 = true})
okBtn:setScale(0.3)
okBtn:setPosition(ccp(deadBG:getPositionX(), deadBG:getPositionY() - 40))
self:addChild(okBtn, 10)
        
okBtn:onButtonClicked(function( event )
   okBtn:removeFromParent()
   deadBG:removeFromParent()
   hero._Flag = true
   local restart = MainScene.new()
   CCDirector:sharedDirector():replaceScene(CCTransitionFade:create(1, restart))
end)
end


-- 计算米数和所得分数
function countMeter()


meterNum = meterNum + 1
meter:setString(meterNum)
end


-- 检测碰撞
function iscollision(sprite1, sprite2)
    if sprite1 and sprite2 then
    local rect1 = sprite1:boundingBox()
   local rect2 = sprite2:boundingBox()
   return CCRect.intersectsRect(rect1,rect2)
else
return false
    end



end


-- 获取精灵的Rect
function MainScene:getRected( sprite)
local s = sprite:getContentSize()
local px = sprite:getPositionX()
local py = sprite:getPositionY()
local ap = sprite:getAnchorPoint()
rect = cc.RectMake( px - ap.x * s.width , py - ap.y * s.height,s.width, s.height )
return rect
end


function MainScene:secondGame()
local movefirstHero = cc.MoveTo:create(1,ccp(-10, 320))
hero:runAction(movefirstHero)
    --hero:setZOrder(-1)


-- 关闭时间调度和英雄动作
    sharedScheduler = CCDirector:sharedDirector():getScheduler()
sharedScheduler:unscheduleScriptEntry(self._schedule)
sharedScheduler:unscheduleScriptEntry(self._schedule1)
hero:StopRun()


    -- 加载第二游戏界面的背景
secondbg = display.newSprite("BG2.png")
secondbg:setAnchorPoint(ccp(0, 0))
secondbg:setPosition(ccp(480, 0))
secondbg:setScaleY(0.5)
self:addChild(secondbg, 5)




local move = cc.MoveBy:create(1,ccp(-480, 0))
secondbg:runAction(CCSequence:createWithTwoActions(move, CCCallFunc:create(function ( )
-- 加载英雄到第二游戏界面
   secondhero = Hero.new()
   secondhero:setPosition(ccp(0, 320))
   secondhero:setAnchorPoint(ccp(0.5, 0.5))
   secondhero:setScale(0.5)
   self:addChild(secondhero, 6)


        local movehero = cc.MoveTo:create(1,ccp(50, 50))
        secondhero:runAction(CCSequence:createWithTwoActions(movehero, CCCallFunc:create(function ( )
        secondhero:setPosition(ccp(50, 50))


            -- 加载飞龙到第二游戏界面
            seconddragon = Dragon.new()
       seconddragon:setPosition(ccp(450, 250))
       self:addChild(seconddragon, 6)
       seconddragon:StartRun()


            local movedragon = cc.MoveTo:create(4,ccp(secondhero:getPositionX(), secondhero:getPositionY()))
       seconddragon:runAction(movedragon)
        end)))
end)))
    


local sharedScheduler = CCDirector:sharedDirector():getScheduler()
self._schedule2 = sharedScheduler:scheduleScriptFunc(function ()
self:panduan()
end, 0.04, false)


-- --添加时间调度延迟加载
 --      local handle=sharedScheduler.performWithDelayGlobal(function ()
--     self:addChild(secondhero, 6)
 --      end, 1)
end


function MainScene:panduan()


if iscollision(secondhero, seconddragon) then
secondhero:removeFromParent()
seconddragon:removeFromParent()
        
        --hero:setZOrder(1)
        local movefirstHero = cc.MoveTo:create(1,ccp(50, 50))
   hero:runAction(movefirstHero)
   local move = cc.MoveBy:create(1,ccp(480, 0))
   secondbg:runAction(move)
        


  local sharedScheduler = CCDirector:sharedDirector():getScheduler()
  sharedScheduler:unscheduleScriptEntry(self._schedule2)
   self._schedule = sharedScheduler:scheduleScriptFunc(function ()
self:ScrollBG()
end, 0.04, false)
        self._schedule1 = sharedScheduler:scheduleScriptFunc(countMeter, 0.1, false)
hero:StartRun()
end
end


function MainScene:onEnter()
end


function MainScene:onExit()
end


return MainScene