您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

1368 行
37 KiB

  1. -- 游戏逻辑相关的全局函数
  2. local DownloaderHeadManager=require("luaScript.Tools.DownloaderHeadManager")
  3. -- 滚动提示
  4. -- items:滚动的Ui节点
  5. -- speedTime:滚动速度
  6. -- text: 文本显示内容
  7. -- parentNode: 裁剪的父节点
  8. function startScrollTips(items, speedTime, text, parentNode)
  9. local html = items;
  10. local parent = parentNode;
  11. html:setText(text);
  12. html:setPositionType(0);
  13. local winSize = parent:getSize();
  14. local size = html:getSize();
  15. local speed = speedTime;
  16. html:runAction(cc.RepeatForever:create(createActionArray(function()html:setPosition(cc.p(winSize.width , html:getPositionY()));end
  17. , cc.MoveTo:create((size.width + winSize.width) / speed , cc.p(-size.width , html:getPositionY()))
  18. )));
  19. end
  20. -- 数字增长动画
  21. --@curValue 当前值
  22. --@desValue 终值
  23. --@time 增长动画时长
  24. function numIncAnime(node, curValue, desValue, time)
  25. node:setText(curValue);
  26. if curValue == desValue then
  27. return
  28. end
  29. time = time or 2
  30. local function setNum(sum)
  31. if sum > time then
  32. sum = time
  33. end
  34. local showNum = math.ceil(curValue +(desValue - curValue) * sum / time)
  35. node:setText(tostring(showNum));
  36. end
  37. scheduleUpdateScriptFunc(node, time, setNum)
  38. end
  39. -------------------------- dingding game --------------------------
  40. -- 是否正在显示总结算界面
  41. g_isShowCountAll = false
  42. function setShowCountAll(bVisible)
  43. g_isShowCountAll = bVisible
  44. end
  45. function isShowCountAll()
  46. return g_isShowCountAll;
  47. end
  48. --是否在俱乐部和房间里面
  49. g_bInClubRoom = false
  50. function setInClubRoom(bVisible)
  51. g_bInClubRoom = bVisible
  52. end
  53. function getInClubRoom()
  54. return g_bInClubRoom;
  55. end
  56. -- 亲友圈是否退出房间继续进入房间游戏
  57. g_isContinueRoomGamebol = false
  58. function setisContinueRoomGamebol(bVisible)
  59. g_isContinueRoomGamebol = bVisible
  60. end
  61. function isContinueRoomGamebol()
  62. return g_isContinueRoomGamebol;
  63. end
  64. -- 亲友圈重新进入其他房间数据
  65. g_isContinueRoomGamedata = nil
  66. function setisContinueRoomGamedata(data)
  67. g_isContinueRoomGamedata = data
  68. end
  69. function isContinueRoomGamedata()
  70. return g_isContinueRoomGamedata;
  71. end
  72. -- 单个茶馆数据
  73. g_isRoomGamedata = nil
  74. function setIsRoomGamedata(data)
  75. g_isRoomGamedata = data
  76. end
  77. function getIsRoomGamedata()
  78. return g_isRoomGamedata;
  79. end
  80. --自己是否处于游戏中
  81. g_mygamestatus = false
  82. function setMyGameStatus(bol)
  83. g_mygamestatus = bol
  84. end
  85. function getMyGameStatus()
  86. return g_mygamestatus;
  87. end
  88. --------------再来一局start-----------------
  89. ---
  90. -- 设置是否再来一局
  91. --(再来一局加新接口请移步luaScript.Interface.IPlayGameAgain)
  92. -- @param bol 是否再来一局
  93. -- @param wanfadata 子游戏玩法
  94. -- @param uidList 待邀请玩家列表
  95. -- @return
  96. --
  97. function setIsAgainGamebol(bol,wanfadata,uidList)
  98. dd.IPlayGameAgain.setIsAgainGamebol(bol, wanfadata, uidList)
  99. end
  100. ---
  101. -- 是否再来一局
  102. --(再来一局加新接口请移步luaScript.Interface.IPlayGameAgain)
  103. -- @return
  104. --
  105. function getIsAgainGamebol()
  106. return dd.IPlayGameAgain.getIsAgainGamebol()
  107. end
  108. ---
  109. -- 再来一局包间id
  110. --(再来一局加新接口请移步luaScript.Interface.IPlayGameAgain)
  111. -- @param idx
  112. -- @return
  113. --
  114. function setAgainGameBaoJianId(idx)
  115. dd.IPlayGameAgain.setAgainGameBaoJianId(idx)
  116. end
  117. ---
  118. -- 获取再来一局包间id
  119. --(再来一局加新接口请移步luaScript.Interface.IPlayGameAgain)
  120. -- @return
  121. --
  122. function getAgainGameBaoJianId()
  123. return dd.IPlayGameAgain.getAgainGameBaoJianId()
  124. end
  125. ---
  126. -- 保存再来一局接受邀请数据
  127. --(再来一局加新接口请移步luaScript.Interface.IPlayGameAgain)
  128. -- @param data
  129. -- @return
  130. --
  131. function setAgainGameInvitedata(data)
  132. dd.IPlayGameAgain.setAgainGameInvitedata(data)
  133. end
  134. ---
  135. -- 获取再来一局接受邀请数据
  136. --(再来一局加新接口请移步luaScript.Interface.IPlayGameAgain)
  137. -- @return
  138. --
  139. function getAgainGameInvitedata()
  140. return dd.IPlayGameAgain.getAgainGameInvitedata()
  141. end
  142. ---
  143. -- 保存再来一局玩法状态
  144. -- 检测点再来一局的时候,玩法是否被修改。如果是修改那么提示创建失败。
  145. --(再来一局加新接口请移步luaScript.Interface.IPlayGameAgain)
  146. -- @param bol
  147. -- @return
  148. --
  149. function setRuleChangeStatus(bol)
  150. dd.IPlayGameAgain.setRuleChangeStatus(bol)
  151. end
  152. ---
  153. -- 获取再来一局玩法状态
  154. -- 检测点再来一局的时候,玩法是否被修改。如果是修改那么提示创建失败。
  155. --(再来一局加新接口请移步luaScript.Interface.IPlayGameAgain)
  156. -- @return
  157. --
  158. function getRuleChangeStatus()
  159. return dd.IPlayGameAgain.getRuleChangeStatus()
  160. end
  161. ---
  162. -- 保存房间id
  163. -- 邀请的时候需要用到数据
  164. --(再来一局加新接口请移步luaScript.Interface.IPlayGameAgain)
  165. -- @param idx
  166. -- @return
  167. --
  168. function setGameRoomId(idx)
  169. dd.IPlayGameAgain.setGameRoomId(idx)
  170. end
  171. ---
  172. -- 获取房间id
  173. --(再来一局加新接口请移步luaScript.Interface.IPlayGameAgain)
  174. -- @return
  175. --
  176. function getGameRoomId()
  177. return dd.IPlayGameAgain.getGameRoomId()
  178. end
  179. ---
  180. -- 保存玩家是否创建过房间
  181. --(再来一局加新接口请移步luaScript.Interface.IPlayGameAgain)
  182. -- @param bol
  183. -- @return
  184. --
  185. function setMyGameCreateStatus(bol)
  186. dd.IPlayGameAgain.setMyGameCreateStatus(bol)
  187. end
  188. ---
  189. -- 获取玩家是否创建过房间
  190. --(再来一局加新接口请移步luaScript.Interface.IPlayGameAgain)
  191. -- @return
  192. --
  193. function getMyGameCreateStatus()
  194. return dd.IPlayGameAgain.getMyGameCreateStatus()
  195. end
  196. --------------再来一局end-----------------
  197. ----------------------------即将弃用的接口-----------------------------------------
  198. ----------------------------即将弃用的接口-----------------------------------------
  199. ---
  200. -- !!!
  201. -- 亲友圈当前邀请游戏规则数据
  202. -- 子游戏发布后,这个接口setisAgainGamebol可以删掉
  203. -- @param data
  204. -- @return
  205. --
  206. g_RoomGameRuledata = nil
  207. function setRoomGameRuledata(data)
  208. g_RoomGameRuledata = data
  209. end
  210. function getRoomGameRuledata()
  211. return g_RoomGameRuledata;
  212. end
  213. ---
  214. -- !!!
  215. -- 子游戏发布后,这个接口setisAgainGamebol可以删掉
  216. -- @param bol
  217. -- @param wanfadata
  218. -- @return
  219. --
  220. function setisAgainGamebol(bol,wanfadata)
  221. dd.IPlayGameAgain.isAgainGameBol = bol
  222. if wanfadata ~= nil then
  223. dd.IPlayGameAgain.wanfa = wanfadata
  224. end
  225. end
  226. ---
  227. -- !!!
  228. -- 子游戏发布后,这个接口setisAgainGamebol可以删掉
  229. -- @return
  230. --
  231. function isAgainGameide()
  232. return dd.IPlayGameAgain.getAgainGameBaoJianId()
  233. end
  234. ---
  235. -- !!!
  236. -- 子游戏发布后,这个接口setisAgainGamebol可以删掉
  237. -- @param idx
  238. -- @return
  239. --
  240. function setisAgainGameide(idx)
  241. dd.IPlayGameAgain.setAgainGameBaoJianId(idx)
  242. end
  243. -------------------------------------------------------------------
  244. -------------------------------------------------------------------
  245. local _ImageTimes;
  246. local _ImageTimesFile = "ImageTimes.data"
  247. local function loadImageTimesFromFile()
  248. if not _ImageTimes then
  249. local fileString = loadStringFromFile(_ImageTimesFile)
  250. if fileString then
  251. _ImageTimes = json.decode(fileString) or {}
  252. else
  253. _ImageTimes = {}
  254. end
  255. end
  256. end
  257. local function saveImageTimesToFile()
  258. _ImageTimes = _ImageTimes or {}
  259. local fileString = json.encode(_ImageTimes)
  260. saveStringToFile(fileString, _ImageTimesFile)
  261. end
  262. local function loadImageTime(imageName)
  263. loadImageTimesFromFile()
  264. return _ImageTimes[imageName]
  265. end
  266. local function saveImageTime(imageName, timeNew)
  267. loadImageTimesFromFile()
  268. _ImageTimes[imageName] = timeNew
  269. saveImageTimesToFile();
  270. end
  271. -------------------------------------------------------------------
  272. -------------------------------------------------------------------
  273. -- 加载单个图片到缓存
  274. function loadSpriteFile(fileName)
  275. cc.TextureCache:getInstance():addImage(fileName);
  276. end
  277. -- 加载纹理合集
  278. function loadSpriteFrameFile(fileName)
  279. cc.SpriteFrameCache:getInstance():addSpriteFramesWithFile(fileName);
  280. end
  281. function dowloadImageFile(imageUrl,fileName,callback)
  282. -- 地址是否有效
  283. if not imageUrl or string.len(imageUrl) < 10 then
  284. if callback then
  285. callback()
  286. end
  287. return
  288. end
  289. local fullPath = cc.FileUtils:getInstance():getWritablePath()..fileName
  290. if isWin32Platform() then -- or isAndroidPlatform()
  291. getImageFromUrlWithTime(imageUrl, fileName, nil, callback)
  292. else
  293. local function onFinish(result)
  294. local resultJson = json.decode(result)
  295. dump(resultJson,"dowloadFile onFinish")
  296. local code = tonumber(resultJson.code)
  297. local msg = resultJson.message
  298. if callback then
  299. callback()
  300. end
  301. local isExist = cc.FileSystem:fileExists(fullPath)
  302. if isExist then
  303. saveImageTime(fileName, os.time())
  304. end
  305. end
  306. app.plugin:createTask(imageUrl,fullPath,onFinish,-1)
  307. end
  308. end
  309. -- 从网络上下载一张图片到本地
  310. -- imageUrl : 图片链接
  311. -- filename :保存到本地的文件名
  312. -- time :图片时间戳
  313. -- callback :完成后回调,如果本地有这个文件,则直接回调
  314. -- 时间戳的作用:
  315. -- 如果有值,则和本地记录的时间进行比较,不一致就需要重新下载
  316. -- 如果无值,则使用上次更新的时间很当前时间进行比较,大于一定的时间才重新下载
  317. function getImageFromUrlWithTime(imageUrl, fileName, time, onEnd)
  318. logD("getImageFromUrlWithTime()", imageUrl, fileName, time)
  319. local fullPath = cc.FileUtils:getInstance():getWritablePath()..fileName;
  320. local timeNow = os.time()
  321. local timeOld = loadImageTime(fileName) or 0
  322. -- 执行回调
  323. local function doCallback(ret)
  324. if onEnd then
  325. onEnd(ret);
  326. end
  327. end
  328. -- 从网络下载这个图片
  329. local function downloadImageFromUrl()
  330. local function onUpdate(status , info)
  331. -- status = progress,successed,failed
  332. logD("getImageFromUrlWithTime() downloadImageFromUrl()", tostring(status))
  333. if status ~= "successed" then
  334. doCallback(false)
  335. -- showTooltip(string.format("下载update.json文件失败 (%d) ", self.gameId))
  336. return
  337. end
  338. local targetFile = io.open(fullPath, "wb")
  339. if targetFile == nil then
  340. doCallback(false)
  341. print("写入文件:" ..fullPath .."时磁盘创建文件失败")
  342. return
  343. end
  344. targetFile:write(info)
  345. targetFile:close()
  346. -- logD("getImageFromUrlWithTime() downloadImageFromUrl()", tostring(status))
  347. local timeNew = 0;
  348. if time and time > 0 then
  349. timeNew = time
  350. else
  351. timeNew = timeNow;
  352. end
  353. --确保使用时间戳的时候,我才去保存图片,不然过了7天又重新下载。
  354. -- if time then
  355. saveImageTime(fileName, timeNew)
  356. -- end
  357. doCallback(true)
  358. -- if status == "successed" then
  359. -- logD("getImageFromUrlWithTime() downloadImageFromUrl()", tostring(status))
  360. -- local timeNew = 0;
  361. -- if time and time > 0 then
  362. -- timeNew = time
  363. -- else
  364. -- timeNew = timeNow;
  365. -- end
  366. -- saveImageTime(fileName, timeNew)
  367. -- -- fullPath
  368. -- doCallback(true)
  369. -- elseif status == "failed" then
  370. -- logD("getImageFromUrlWithTime() downloadImageFromUrl()", tostring(status))
  371. -- doCallback(false)
  372. -- else
  373. -- end
  374. end
  375. logD("getImageFromUrlWithTime() 请求的图片路径", imageUrl)
  376. downloadFileByUrls(imageUrl, onUpdate)
  377. end
  378. -- 地址是否有效
  379. if not imageUrl or string.len(imageUrl) < 10 then
  380. doCallback(false)
  381. return
  382. end
  383. -- 检查本地是否有这个图片
  384. local isExist = cc.FileSystem:fileExists(fullPath)
  385. if not isExist then
  386. -- 本地没有这个图片,直接下载
  387. logD("getImageFromUrl() file not exist")
  388. downloadImageFromUrl()
  389. return
  390. end
  391. logD("getImageFromUrl() file exist")
  392. -- 本地已有这个文件,则需要检测时间戳
  393. if time and time > 0 then
  394. -- 已使用时间戳
  395. if (time) == (timeOld) then
  396. -- 执行回调
  397. doCallback(true)
  398. else
  399. -- 重新下载
  400. os.remove(fullPath)
  401. downloadImageFromUrl()
  402. end
  403. else
  404. -- 未使用时间戳
  405. if timeNow - timeOld <= 7 * 24 * 3600 then
  406. logD("图片小于7天")
  407. -- 距离上次更新少于7天,不下载,执行回调
  408. doCallback(true)
  409. else
  410. -- 重新下载
  411. os.remove(fullPath)
  412. downloadImageFromUrl()
  413. end
  414. end
  415. end
  416. -- 从网络加载一张图片纹理
  417. -- image : ImageView节点
  418. -- url : 下载地址
  419. function setImageFromUrl(image,url)
  420. local iconUrl, iconTime = convertIconUrl(url)
  421. local pngName = getImageNameFromUrl(iconUrl)
  422. getImageFromUrlWithTime(iconUrl, pngName, tonumber(iconTime), function(ret)
  423. if ret then
  424. local texture = loadTextureFromFile(pngName)
  425. if not texture then
  426. return
  427. end
  428. if not image or tolua.isnull(image) then
  429. return
  430. end
  431. image:setTexture2(texture)
  432. end
  433. end)
  434. end
  435. -- 从本地加载一张图片纹理
  436. -- fileName : 文件名字,不带路径
  437. -- return : texture
  438. function loadTextureFromFile(fileName,isCircle)
  439. print("loadTextureFromFile() ", tostring(fileName))
  440. if not fileName then
  441. return
  442. end
  443. local fullPath = cc.FileUtils:getInstance():getWritablePath()..fileName;
  444. if cc.FileSystem:fileExists(fullPath) then
  445. log("loadTextureFromFile() file exist")
  446. local imageData = cc.FileSystem:readData(fullPath);
  447. if not imageData then
  448. log("loadTextureFromFile() imageData is null ")
  449. return nil
  450. end
  451. local image = cc.Image:createWithDataLua(imageData, string.len(imageData));
  452. if tolua.isnull(image) then
  453. log("loadTextureFromFile() image is null ")
  454. return nil
  455. end
  456. if isCircle then
  457. image = image:convertToCircleImage()
  458. if tolua.isnull(image) then
  459. log("getUserHeadImageWithUrl() image is null ")
  460. return
  461. end
  462. end
  463. local texture = cc.Texture:createWithImage(image);
  464. if tolua.isnull(texture) then
  465. log("loadTextureFromFile() texture is null ")
  466. return nil
  467. end
  468. return texture
  469. else
  470. return nil
  471. end
  472. end
  473. -- 给一个 ImageView 节点设置玩家头像
  474. -- nUserId :用户ID
  475. -- imageUrl :头像地址
  476. -- nodeImage:头像节点
  477. function setPlayerHeadImage(nUserId, imageUrl, nodeImage,isCircle)
  478. --A玩家下载成功出去,B玩家进来坐了A的位置,假设B的头像也失败了,B就用了A的头像。A再进来,就会重复头像
  479. setDefaultHeadImg(nil,nUserId,nodeImage,nodeImage:getContentSize().width,isCircle)
  480. local fileName = "HeadImage_"..tostring(nUserId)..".png";
  481. local fullPath = cc.FileUtils:getInstance():getWritablePath()..fileName;
  482. --uid的引进是为了防止:假设A进来,头像没下载完,不是失败,A出去了。B进来,B下载失败,A这个时候又成功。
  483. nodeImage.uid = nUserId
  484. -- 更新头像
  485. local function updateHeadImage()
  486. -- 从本地文件读取纹理
  487. local texture = loadTextureFromFile(fileName,isCircle)
  488. if not texture then
  489. return
  490. end
  491. -- 判断头像节点是否还有效
  492. if tolua.isnull(nodeImage) then
  493. return
  494. end
  495. --
  496. if nodeImage.uid == nUserId then
  497. -- 设置头像
  498. nodeImage:setTexture2(texture)
  499. texture = nil
  500. end
  501. end
  502. local timeNow = os.time()
  503. local timeOld = loadImageTime(fileName) or 0 --tonumber(loadUserInfo(fileName)) or 0
  504. local timeDelta = 14 * 24 * 60 * 60
  505. local isExist = cc.FileSystem:fileExists(fullPath)
  506. dump(isExist,"setPlayerHeadImage timeNow:"..timeNow.." timeOld:"..timeOld)
  507. -- 文件不存在,或者离上次更新的时间很长了,才需要下载
  508. if not isExist or timeNow >= timeOld + timeDelta then
  509. logD("头像不存在")
  510. if cc.Application:getInstance():getTargetPlatform() == 3 then
  511. logD("------android shi yong curl xiazai------")
  512. getImageFromUrlWithTime(imageUrl, fileName, nil, updateHeadImage)
  513. else
  514. logD("------zheng chang xia zai--------")
  515. DownloaderHeadManager.addTask(nodeImage,imageUrl, fileName, updateHeadImage)
  516. end
  517. else
  518. logD("头像存在,使用已经缓存的头像!")
  519. updateHeadImage()
  520. end
  521. end
  522. -- 删除玩家头像
  523. function updatePlayerHeadImage(nUserId, url)
  524. local fileName = "HeadImage_"..tostring(nUserId)..".png";
  525. local fullPath = cc.FileUtils:getInstance():getWritablePath()..fileName;
  526. os.remove(fullPath)
  527. getImageFromUrlWithTime(url, fileName)
  528. end
  529. ------------------------------------------------------------------------------
  530. --[[
  531. %a 一星期中天数的简写 (Wed)
  532. %A 一星期中天数的全称 (Wednesday)
  533. %b 月份的简写 (Sep)
  534. %B 月份的全称 (September)
  535. %c 日期和时间 (09/16/98 23:48:10)
  536. %d 一个月中的第几天 (16)[0 ~ 31]
  537. %H 24小时制中的小时数 (23)[00 ~ 23]
  538. %I 12小时制中的小时数 (11)[01 ~ 12]
  539. %j 一年中的第几天 (259)[01 ~ 366]
  540. %M 分钟数 (48)[00 ~ 59]
  541. %m 月份数 (09)[01 ~ 12]
  542. %P "上午(am)" 或 "下午(pm)" (pm)
  543. %S 秒数 (10)[00 ~ 59]
  544. %w 一星期中的第几天 (3)[0 ~ 6 = 星期天 ~ 星期六]
  545. %W  一年中的第几个星期        0 ~ 52
  546. %x 日期 (09/16/98)
  547. %X 时间 (23:48:10)
  548. %y 两位数的年份 (90)[00 ~ 99]
  549. %Y 完整的年份 (2009)
  550. %% 字符串'%'
  551. ]]
  552. -- 月-日 时:分:秒
  553. function getTimeString()
  554. return os.date("%Y-%m-%d %X")
  555. end
  556. function getTimeString2()
  557. return os.date("%X")
  558. end
  559. --- 月-日 时:分:秒
  560. function getTimeString3()
  561. return os.date("%m-%d %X")
  562. end
  563. --深度拷贝
  564. function DeepCopy(object)
  565. local SearchTable = {}
  566. local function Func(object)
  567. if type(object) ~= "table" then
  568. return object
  569. end
  570. local NewTable = {}
  571. SearchTable[object] = NewTable
  572. for k, v in pairs(object) do
  573. NewTable[Func(k)] = Func(v)
  574. end
  575. return setmetatable(NewTable, getmetatable(object))
  576. end
  577. return Func(object)
  578. end
  579. --获取两点间距离
  580. function getDistance(x1,y1,x2,y2)
  581. -- local x = x1 - x2
  582. -- local y = y1 - y2
  583. -- local dis = math.sqrt( x * x + y * y)
  584. -- print("getDistance() x1 = "..x1)
  585. -- print("getDistance() y1 = "..y1)
  586. -- print("getDistance() x2 = "..x2)
  587. -- print("getDistance() y2 = "..y2)
  588. -- print("getDistance() x = "..x)
  589. -- print("getDistance() y = "..y)
  590. -- print("getDistance() dis = "..dis)
  591. -- return dis
  592. if type(x1) == "number" and type(y1) == "number" and type(x2) == "number" and type(y2) == "number" then
  593. local pk = 180 / 3.14169;
  594. local a1 = x1 / pk;
  595. local a2 = y1 / pk;
  596. local b1 = x2 / pk;
  597. local b2 = y2 / pk;
  598. local t1 = math.cos(a1) * math.cos(a2) * math.cos(b1) * math.cos(b2);
  599. local t2 = math.cos(a1) * math.sin(a2) * math.cos(b1) * math.sin(b2);
  600. local t3 = math.sin(a1) * math.sin(b1);
  601. local tt = math.acos(t1 + t2 + t3);
  602. return 6371000 * tt;
  603. end
  604. return -1;
  605. end
  606. -- 获得距离的描述,
  607. -- 传入参数单位米
  608. function getDistanceDesc(num)
  609. if num < 1000 then
  610. return string.format("%d米", math.floor(num))
  611. else
  612. return string.format("%0.1f公里", num / 1000)
  613. end
  614. end
  615. -- 获取默认头像
  616. function getDefaultAvatar(sex, uid,isCircle)
  617. if isCircle then
  618. return "res/ui/zy_dating/dating/icon_default_head_circle.png"
  619. else
  620. return "res/ui/zy_dating/dating/icon_default_head.png"
  621. end
  622. end
  623. --设置默认头像
  624. function setDefaultHeadImg(sex, uid, nodeHead, curHeadWidth,isCircle)
  625. -- cc.SpriteFrameCache:getInstance():addSpriteFramesWithFile("res/ui/zy_dating/dating/dating.plist")
  626. -- 先设置成默认头像
  627. local imageFile = getDefaultAvatar(sex, uid,isCircle)
  628. nodeHead:loadTexture(imageFile)
  629. nodeHead:setScale(1.0);
  630. local head = {}
  631. head.width = nodeHead:getContentSize().width
  632. nodeHead:setScale(curHeadWidth / head.width)
  633. end
  634. --获取裁剪后的昵称
  635. function getSubStringNickname(nickname)
  636. if cc.Application:getInstance():getTargetPlatform() == 0 then
  637. return nickname
  638. end
  639. if not nickname then
  640. return "未知昵称"
  641. end
  642. -- 裁剪4个字(4指名称前4个字,并非长度)
  643. nickname = string.getShortName(nickname, 4)
  644. return nickname
  645. end
  646. function getShortName(name)
  647. return getSubStringNickname(name)
  648. end
  649. --第二种方式截取名字(过滤掉所有特殊字符)
  650. function getShortName2(name)
  651. if not name then
  652. return "未知昵称"
  653. end
  654. -- 裁剪4个字(4指名称前4个字,并非长度)
  655. nickname = string.getShortName2(name, 4)
  656. return nickname
  657. end
  658. --裁剪
  659. function getShortNameByLength(name,lens)
  660. if not name then
  661. return "未知昵称"
  662. end
  663. -- 裁剪lens个字(lens指名称前lens个字,并非长度)
  664. nickname = string.getShortName(name, lens)
  665. return nickname
  666. end
  667. function downloadSubGame(gameId, endCallback)
  668. local view = import("luaScript.SubGame.SubGameLoadView"):new(gameId, endCallback)
  669. -- view:setAnchorPoint(cc.p(0.5, 0.5))
  670. app:showSytemDialog(view)
  671. -- app:showWaitDialog(view,0)
  672. end
  673. function requestDownloadSubGame(gameId, endCallback)
  674. logD("GameGlobalFunctions::requestDownloadSubGame() gameId = ", gameId)
  675. local function onOk()
  676. downloadSubGame(gameId, endCallback)
  677. end
  678. local function onCancel()
  679. end
  680. local subGameName = getSubGameName(gameId)
  681. if gameId == 2 then
  682. subGameName = "游戏资源"
  683. end
  684. local versionInfo = app.serverConfigs:getSubGameVersionInfo(gameId)
  685. logD("GameGlobalFunctions::requestDownloadSubGame()", table.tostring(versionInfo))
  686. if versionInfo then
  687. local zipSize = 3
  688. if versionInfo.size and tonumber(versionInfo.size) > 0 then
  689. zipSize = math.ceil(tonumber(versionInfo.size) / 1024 / 1024)
  690. end
  691. local strContent = string.format("是否下载[%s], 文件大小约%sM", subGameName or "", zipSize)
  692. showConfirmDialog(strContent, onOk, onCancel)
  693. else
  694. if endCallback then
  695. endCallback();
  696. end
  697. end
  698. end
  699. --game --
  700. --[[
  701. CARD_VALUE =
  702. {
  703. 0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0a,0x0b,0x0c,0x0d, --//方块 A - K
  704. 0x11,0x12,0x13,0x14,0x15,0x16,0x17,0x18,0x19,0x1a,0x1b,0x1c,0x1d, --//梅花 A - K
  705. 0x21,0x22,0x23,0x24,0x25,0x26,0x27,0x28,0x29,0x2a,0x2b,0x2c,0x2d, --//红桃 A - K
  706. 0x31,0x32,0x33,0x34,0x35,0x36,0x37,0x38,0x39,0x3a,0x3b,0x3c,0x3d, --//黑桃 A - K
  707. }
  708. ]]
  709. function getCardImage(nValue)
  710. local nColor = math.ceil(nValue / 16)
  711. local nValue = math.floor(nValue % 16)
  712. local strValue = "" -- 牌值
  713. local strImage = "" -- 图案
  714. local strColor = "red"
  715. if nColor == 2 or nColor == 4 then
  716. strColor = "black"
  717. end
  718. strValue = string.format("num_%s_%02d.png", strColor, nValue)
  719. if nValue > 10 then
  720. strImage = string.format("di_%02d_%02d.png",nValue, nColor)
  721. else
  722. strImage = string.format("color_%02d.png",nColor)
  723. end
  724. log(string.format("getCardImage() nColor = %d, nValue = %d, strValue = %s, strImage = %s", nColor, nValue, strValue, strImage))
  725. return nColor, nValue, strValue, strImage
  726. end
  727. --[[是否是特殊牌型]]
  728. function getIsSpecialCard(cardType)
  729. return CONST_GAME_CARDTYPE.ETYPE_NIU_NIU < cardType
  730. end
  731. function getVisibleSize()
  732. return cc.Director:getInstance():getVisibleSize()
  733. end
  734. function getWinSize()
  735. return cc.Director:getInstance():getWinSize()
  736. end
  737. function autoAdapt(node)
  738. local glview = cc.Director:getInstance():getOpenGLView();
  739. local finalResourceSize = glview:getDesignResolutionSize();
  740. local resourceSize = {width = 1280 ; height = 720};
  741. -- 宽高比例单独计算
  742. local g_radio_x = finalResourceSize.width / resourceSize.width
  743. local g_radio_y = finalResourceSize.height / resourceSize.height
  744. local uiSize = node:getSize()
  745. local realSize = {width = uiSize.width * g_radio_x, height = uiSize.height * g_radio_y}
  746. node:setSize(realSize)
  747. end
  748. function autoAdaptWidth(node)
  749. local glview = cc.Director:getInstance():getOpenGLView();
  750. local finalResourceSize = glview:getDesignResolutionSize();
  751. local resourceSize = {width = 1280 ; height = 720};
  752. -- 宽高比例单独计算
  753. local g_radio_x = finalResourceSize.width / resourceSize.width
  754. local g_radio_y = finalResourceSize.height / resourceSize.height
  755. -- 适配
  756. local uiSize = node:getSize()
  757. local realSize = {width = uiSize.width * g_radio_x, height = uiSize.height}
  758. node:setSize(realSize)
  759. end
  760. function autoAdaptHeight(node)
  761. local glview = cc.Director:getInstance():getOpenGLView();
  762. local finalResourceSize = glview:getDesignResolutionSize();
  763. local resourceSize = {width = 1280 ; height = 720};
  764. -- 宽高比例单独计算
  765. local g_radio_x = finalResourceSize.width / resourceSize.width
  766. local g_radio_y = finalResourceSize.height / resourceSize.height
  767. -- 适配
  768. local uiSize = node:getSize()
  769. local realSize = {width = uiSize.width, height = uiSize.height * g_radio_y}
  770. node:setSize(realSize)
  771. end
  772. function showPHPFailedResult(content)
  773. if not content then
  774. return
  775. end
  776. local timeStr = getTimeString()
  777. local uid = app.user.loginInfo.uid or "0"
  778. local message = string.format("[%s]%s,%s", timeStr, uid, content)
  779. --showConfirmDialog(message, function() end,nil)
  780. showTooltip(message)
  781. --上传日志,便于查找错误问题
  782. uploadLogs(GAME_ERROR_TYPE.HTTP)
  783. end
  784. function showPHPSuccessResult(content)
  785. if not content then
  786. return
  787. end
  788. showConfirmDialog(content,nil,nil);
  789. end
  790. function showPHPError(content)
  791. if not content then
  792. return
  793. end
  794. local uid = app.user.loginInfo.uid or "null"
  795. local userID = " 用户ID:"..uid
  796. local timeStr = " 时间:"..getTimeString()
  797. --local str = "PHP Error :"..content..userID
  798. local str = "接口异常,请重新登陆再试。"..userID
  799. showConfirmDialog(str,function() end,nil)
  800. --上传日志,便于查找错误问题
  801. --uploadLogs(GAME_ERROR_TYPE.AUTO)
  802. end
  803. -- 检查PHP返回结果是否有效
  804. -- 会检查status、response、response.code、response.result的有效性
  805. -- 失败会返回false及对应的描述
  806. -- 成功会返回true及response.result(jsonData)
  807. function checkPhpResponse(status, response)
  808. if status ~= "successed" then
  809. return false, "status = "..tostring(status)
  810. end
  811. local ttResposne = json.decode(response)
  812. if not ttResposne then
  813. return false, "ttResposne is nil"
  814. end
  815. if ttResposne.code ~= 200 then
  816. return false, "code is "..ttResposne.code
  817. end
  818. if not ttResposne.result then
  819. return false, "result is nil"
  820. end
  821. return true, ttResposne.result
  822. end
  823. --[[
  824. 将带有时间戳的图片地址,转换为图片地址和时间戳
  825. input : "http://www.dingdingqipai.com/doudizhu.png?v=100086"
  826. output : "http://www.dingdingqipai.com/doudizhu.png", "100086"
  827. -- ]]
  828. function convertIconUrl(url)
  829. local iconUrl;
  830. local iconTime;
  831. local arr = toStringArray("?")(url)
  832. if table.nums(arr) > 0 then
  833. iconUrl = arr[1]
  834. end
  835. if table.nums(arr) > 1 then
  836. local arr2 = toStringArray("=")(arr[2])
  837. if table.nums(arr2) > 1 then
  838. iconTime = arr2[2]
  839. end
  840. end
  841. return iconUrl,iconTime;
  842. end
  843. --[[
  844. 获取一个网络图片的图片文件名
  845. input : "http://www.dingdingqipai.com/doudizhu.png"
  846. output : "doudizhu.png"
  847. --]]
  848. function getImageNameFromUrl(url)
  849. local arr = toStringArray("/")(url)
  850. local num = table.nums(arr)
  851. if (num) > 0 then
  852. return arr[num]
  853. end
  854. return nil
  855. end
  856. --[[
  857. 播放金币动画
  858. nodeBegin : 起始点
  859. nodeEnd : 结束点
  860. goldNum : 金币数量
  861. goldIcon : 金币图标
  862. endCallback : 动画完成后的回调
  863. sizeRange : 范围大小,如果金币是点对点,则不传此参数
  864. 测试用例: MainView:testCoinAnimation()
  865. --]]
  866. function playCoinAnimation(nodeBegin, nodeEnd, goldNum, goldIcon, endCallback, sizeRange)
  867. local coinPlayer = import("luaScript.Tools.CoinAniPlayer"):new()
  868. if coinPlayer then
  869. coinPlayer:playAnimation(nodeBegin, nodeEnd, goldNum, goldIcon, endCallback, sizeRange);
  870. end
  871. end
  872. --[[
  873. 播放道具动画
  874. nodeBegin : 起始点
  875. nodeEnd : 结束点
  876. propId : 道具ID
  877. 测试用例: MainView:testPropAnimation()
  878. --]]
  879. function playPropAnimation(nodeBegin, nodeEnd, propId)
  880. local propPlayer = import("luaScript.Tools.PropAniPlayer"):new()
  881. if propPlayer then
  882. propPlayer:playAnimation(nodeBegin, nodeEnd, propId);
  883. end
  884. end
  885. --[[
  886. 播放plist帧动画
  887. plist : plist 文件路径
  888. imgName : 对应的plist图片名字 例如animation_%d.png
  889. startIndex : startIndex 开始帧
  890. endIndex : endIndex 结束帧
  891. 测试用例: MainView:testPropAnimation()
  892. ]]--
  893. function createAnimationByPlist(plist,imgName,startIndex,endIndex,delayTime)
  894. cc.SpriteFrameCache:getInstance():addSpriteFramesWithFile(plist)
  895. local sprite = cc.Sprite:createWithSpriteFrameName(string.format(imgName,startIndex))
  896. local animation = cc.SpriteAnimation:create()
  897. for i = startIndex,endIndex do
  898. local frame = cc.SpriteFrameCache:getInstance():getSpriteFrameByName(string.format(imgName,i))
  899. animation:addSpriteFrame(frame)
  900. end
  901. animation:setDelayPerUnit(1/20)
  902. if delayTime then
  903. if delayTime == -1 then
  904. sprite:runAction(
  905. cc.Sequence:create(
  906. cc.SpriteAnimate:create(animation),
  907. cc.CallFunc:create(function()
  908. sprite:removeFromParent()
  909. end)
  910. )
  911. )
  912. else
  913. sprite:runAction(
  914. cc.RepeatForever:create(
  915. cc.Sequence:create(
  916. cc.SpriteAnimate:create(animation),
  917. cc.DelayTime:create(delayTime)
  918. )
  919. )
  920. )
  921. end
  922. else
  923. sprite:runAction(
  924. cc.RepeatForever:create(
  925. cc.SpriteAnimate:create(animation)
  926. )
  927. )
  928. end
  929. return sprite
  930. end
  931. -- 从一段文本中检测出房间号,只针对全文只有一组六位数数据
  932. function getRoomIdFromString(str)
  933. logD("getRoomIdFromString() str = ", str);
  934. local roomId;
  935. local nums = {}
  936. for w in string.gmatch(str, "%d+") do
  937. local ww = tostring(w)
  938. logD("getRoomIdFromString()", ww);
  939. local sw = string.len(ww)
  940. if sw == 6 then
  941. roomId = ww
  942. end
  943. end
  944. return roomId;
  945. end
  946. -- 从复制文本中检测出房间号
  947. function getRoomIdFromCopyString(str)
  948. logD("getRoomIdFromCopyString() str = ", str);
  949. local roomId;
  950. local nums = {}
  951. --只读取此格式中的数字"[123456]"
  952. for w in string.gmatch(str, "%[%d+%]") do
  953. local ww = string.sub(w, 2, -2)
  954. logD("getRoomIdFromCopyString()", ww);
  955. local sw = string.len(ww)
  956. if sw == 6 then
  957. roomId = ww
  958. break;
  959. end
  960. end
  961. return roomId;
  962. end
  963. function checkIsNumberString(str)
  964. local n = #str
  965. local isNumber = true
  966. for i = 1,n do
  967. local c = string.byte(str, i)
  968. if c < 48 or c > 57 then
  969. isNumber = false
  970. break
  971. end
  972. end
  973. return isNumber
  974. end
  975. --密码只能是大小写字母加数字
  976. function checkIsPasswordString(str)
  977. local n = #str
  978. local isValid = false
  979. for i = 1,n do
  980. local c = string.byte(str, i)
  981. if c >= 48 and c <= 122 and not (c >= 58 and c <= 64) and not (c >= 91 and c <= 96) then
  982. isValid = true
  983. break
  984. end
  985. end
  986. return isValid
  987. end
  988. --过滤特殊字符,保留中文、英文和数字
  989. function filter_spec_chars(s)
  990. local ss = {}
  991. local k = 1
  992. while true do
  993. if k > #s then
  994. break
  995. end
  996. --获取字符ASCII码
  997. local c = string.byte(s,k)
  998. if not c then
  999. break
  1000. end
  1001. if c<192 then
  1002. if (c>=48 and c<=57) or (c>= 65 and c<=90) or (c>=97 and c<=122) then
  1003. --转化字节流为字符串
  1004. local st = string.char(c)
  1005. table.insert(ss, st)
  1006. end
  1007. k = k + 1
  1008. elseif c<224 then
  1009. k = k + 2
  1010. elseif c<240 then
  1011. if c>=228 and c<=233 then
  1012. local c1 = string.byte(s,k+1)
  1013. local c2 = string.byte(s,k+2)
  1014. if c1 and c2 then
  1015. local a1,a2,a3,a4 = 128,191,128,191
  1016. if c == 228 then
  1017. a1 = 184
  1018. elseif c == 233 then
  1019. a2,a4 = 190,c1 ~= 190 and 191 or 165
  1020. end
  1021. if c1>=a1 and c1<=a2 and c2>=a3 and c2<=a4 then
  1022. table.insert(ss, string.char(c,c1,c2))
  1023. end
  1024. end
  1025. end
  1026. k = k + 3
  1027. elseif c<248 then
  1028. k = k + 4
  1029. elseif c<252 then
  1030. k = k + 5
  1031. elseif c<254 then
  1032. k = k + 6
  1033. end
  1034. end
  1035. return table.concat(ss)
  1036. end
  1037. --解码URL
  1038. function decodeURI(s)
  1039. s = string.gsub(s, '%%(%x%x)', function(h) return string.char(tonumber(h, 16)) end)
  1040. return s
  1041. end
  1042. function openClub()
  1043. local function open()
  1044. app.waitDialogManager:closeWaitNetworkDialog()
  1045. if app.club_php.clubList[app.club_php.clubID] then
  1046. local clubView = import("luaScript.Views.Club.ClubTable"):new(app.club_php.clubID)
  1047. clubView:setAnchorPoint(cc.p(0.5, 0.5))
  1048. app:showWaitDialog(clubView)
  1049. else
  1050. showTooltip((app.club_php:getCestIsOpen(app.club_php.clubID) and PLN.CLUB_CEST_NAME or PLN.CLUB_NAME).."不存在或已经解散!")
  1051. end
  1052. end
  1053. if table.nums(app.club_php.clubList)>0 then
  1054. open()
  1055. else
  1056. app.waitDialogManager:showWaitNetworkDialog("请稍等...")
  1057. app.club_php:requestClubList(open)
  1058. end
  1059. end
  1060. function showFuLiConfirm(info)
  1061. local view = import("luaScript.Views.Main.JiangLi"):new(info);
  1062. view:setAnchorPoint(cc.p(0.5, 0.5))
  1063. app:showWaitDialog(view)
  1064. end
  1065. function showFuLiConfirmForCoin(info)
  1066. local view = import("luaScript.Views.Coin.RoomJiangLi"):new(info);
  1067. view:setAnchorPoint(cc.p(0.5, 0.5))
  1068. app:showWaitDialog(view)
  1069. end
  1070. --[[比较两个时间,返回相差多少时间]]
  1071. function timediff(long_time,short_time)
  1072. local n_short_time,n_long_time,carry,diff = os.date('*t',short_time),os.date('*t',long_time),false,{}
  1073. local colMax = {60,60,24,os.date('*t',os.time{year=n_short_time.year,month=n_short_time.month+1,day=0}).day,12,0}
  1074. n_long_time.hour = n_long_time.hour - (n_long_time.isdst and 1 or 0) + (n_short_time.isdst and 1 or 0) -- handle dst
  1075. for i,v in ipairs({'sec','min','hour','day','month','year'}) do
  1076. diff[v] = n_long_time[v] - n_short_time[v] + (carry and -1 or 0)
  1077. carry = diff[v] < 0
  1078. if carry then
  1079. diff[v] = diff[v] + colMax[i]
  1080. end
  1081. end
  1082. return diff
  1083. end
  1084. function addUIEventListener(data)
  1085. if not data or not data.node then
  1086. return
  1087. end
  1088. --注册触摸事件
  1089. local listener = cc.EventListenerTouchOneByOne:create()
  1090. --设置穿透属性
  1091. if data.swallow ~= false or data.swallow ~= true then
  1092. data.swallow = true
  1093. end
  1094. listener:setSwallowTouches(data.swallow)
  1095. --注册
  1096. function onTouchBegan(touch, event)
  1097. if data.node:isVisible() then
  1098. if data.beGanCallback then
  1099. data.beGanCallback(touch, event)
  1100. end
  1101. return true
  1102. else
  1103. return false
  1104. end
  1105. end
  1106. function onTouchMoved(touch, event)
  1107. if data.moveCallback then
  1108. data.moveCallback(touch, event)
  1109. end
  1110. end
  1111. function onTouchEnded(touch, event)
  1112. if data.endCallback then
  1113. data.endCallback(touch, event)
  1114. end
  1115. end
  1116. --添加事件和回调
  1117. listener:registerScriptHandler(onTouchBegan, cc.Handler.EVENT_TOUCH_BEGAN)
  1118. listener:registerScriptHandler(onTouchMoved, cc.Handler.EVENT_TOUCH_MOVED)
  1119. listener:registerScriptHandler(onTouchEnded, cc.Handler.EVENT_TOUCH_ENDED)
  1120. --得到事件派发器
  1121. local eventDispatcher = data.node:getEventDispatcher()
  1122. --将监听器注册到派发器中
  1123. eventDispatcher:addEventListenerWithSceneGraphPriority(listener, data.node)
  1124. end
  1125. -- gameId : 需要检测的子游戏ID
  1126. -- endCallback : 完成后的回调
  1127. function checkSubGameFiles(gameId, endCallback)
  1128. local function doCallback()
  1129. if endCallback then
  1130. endCallback()
  1131. end
  1132. end
  1133. local result, subGameId, missingFiles = app.subGameManager:checkGameFiles(gameId)
  1134. if not result then
  1135. logD("checkSubGameFiles() 发现子游戏文件缺失,gameId = "..subGameId)
  1136. for k,v in pairs(missingFiles) do
  1137. logD(v);
  1138. end
  1139. local function onOk()
  1140. downloadSubGame(subGameId, doCallback);
  1141. end
  1142. app.subGameManager:clearGame(subGameId);
  1143. showConfirmDialog("发现文件缺失,点击确定开始修复", onOk);
  1144. else
  1145. doCallback();
  1146. end
  1147. end
  1148. function getCurrentPlatform()
  1149. local RomSetting = loadRomSettingScript()
  1150. if RomSetting.Platform then
  1151. return RomSetting.Platform
  1152. end
  1153. end
  1154. function getGpsOpen()
  1155. local isOpen = false
  1156. local gpsInfo = app.user.gpsInfo
  1157. if gpsInfo then
  1158. --测试发现Gps关了,返回的gpsStatus是2(已开启),数据xy为0
  1159. if gpsInfo.gpsStatus == GpsStatus.enable and gpsInfo.x ~= 0 and gpsInfo.y ~= 0 then
  1160. isOpen = true
  1161. end
  1162. end
  1163. return isOpen
  1164. end
  1165. function isEnableEnterRoom()
  1166. if not app.club_php.clubID or app.club_php.clubID == 0 or not app.club_php.clubList[app.club_php.clubID] then
  1167. logD("isEnableEnterRoom club php is not exist!")
  1168. return true
  1169. end
  1170. local clubInfo = app.club_php.clubList[app.club_php.clubID]
  1171. --is_gps :1开启强制定位 0 未开启
  1172. if clubInfo and clubInfo.groupext and not (clubInfo.groupext.is_gps == 1) then
  1173. return true
  1174. end
  1175. local bEnter = getGpsOpen()
  1176. if not bEnter then
  1177. showTooltip("GPS未开启,无法加入房间,请开启后再加入!!")
  1178. setIsAgainGamebol(false,"")
  1179. end
  1180. return bEnter
  1181. end
  1182. function getGpsDistance()
  1183. if not app.club_php.clubID or app.club_php.clubID == 0 or not app.club_php.clubList[app.club_php.clubID] then
  1184. logD("getGpsDistance club php is not exist!")
  1185. return 500
  1186. end
  1187. local clubInfo = app.club_php.clubList[tonumber(app.club_php.clubID)]
  1188. local distance = tonumber(clubInfo.groupext.gps_limit) or -1
  1189. return distance
  1190. end
  1191. -- 顺序执行大厅里面的任务
  1192. -- 主要用于有多个弹框需要逐个打开的时候。先加入队列的活动优先执行
  1193. -- 注意:在这里打开的界面,在关闭的时候一定要执行回调,不然后面的界面会打不开
  1194. -- 例如:我要先打开A绑定界面,
  1195. -- 关闭A界面之后,再打开活动弹框界面
  1196. -- 关闭活动弹框之后,再打开红包卡界面
  1197. local g_MainViewExecList = {}
  1198. local g_MainViewExecRunning = false
  1199. function execInMainViewQueue(callback)
  1200. table.insert(g_MainViewExecList, callback)
  1201. local function runFunc()
  1202. if #g_MainViewExecList <= 0 then
  1203. g_MainViewExecRunning = false
  1204. return
  1205. end
  1206. local func = g_MainViewExecList[1]
  1207. table.remove(g_MainViewExecList,1)
  1208. g_MainViewExecRunning = true
  1209. func(function()
  1210. g_MainViewExecRunning = false
  1211. runFunc()
  1212. end)
  1213. end
  1214. log("g_MainViewExecRunning:",g_MainViewExecRunning)
  1215. if not g_MainViewExecRunning then
  1216. runFunc()
  1217. end
  1218. end