Fourteen test cases in the Quick-Cocos2D-X learning series
Define variables and create 13 scene names
local items = {
“framework.helper”,
“framework.native”,
“framework.display”,
“framework.crypto”,
“framework.network”,
“framework.luabinding”,
“framework.event”,
“framework.interface”,
“framework.socketTcp”,
“framework.timer”,
“framework.gamestate”,
“framework.transition”,
“framework.nvgdrawnode”
}
The game.createMenu function is used to create a UIListView and add all menus to it (the callback for each menu is Opentest).
Set the variable game.bListViewMove = true when sliding UIListView (reset to false when sliding stops). When this value is true, menu is not called.
Game.createsceneclass (name) is used to create a class.
Each class creates two functions prepare and runTest.
The prepare function creates a Layer, sets the touch, creates a RETURN button, clicks back to the MainScene, and creates a label to display the title. If there are parameters, another label is displayed.
The runtest function calls a function with the same name as its own Memu and with an extra Test word.
1. framework.helper
Call the game.createMenu function to add menu.(this is why this function is in the game.lua file) The callback is the runtest function. This function is consistent across all scenario classes.
This example loads the config.lua file.
2. framework.native
Contains 7 items,
local items = {
“activityIndicator”,
“showAlert”,
“openWebBrowser”,
“callme”,
“sendEmail”,
“getInputText”,
“vibrate”,
}
2.1 activityIndicator
Display display activity indicator, after 2 seconds call function hide display activity indicator, and stop calling function.
2.2 showAlert
The code is as follows:
local function onButtonClicked(event)
if event.buttonIndex == 1 then
Print (” Player selected YES button “)
else
Print (” Player selects NO button “)
end
end
device.showAlert(“Confirm Exit”, “Are you sure exit game ?” , {“YES”, “NO”}, onButtonClicked)
Displays a dialog box.
2.3 openWebBrowser
Open the browser as shown below:
device.openURL(“dualface.github.com”)
2.4 callme
Make a call using the following functions:
device.openURL(“tel:123-456-7890”)
2.5 sendEmail
Use the following code to open the mail program on the device, create a new message, and fill in the recipient address
local subject = string.urlencode(“Hello”)
local body = string.urlencode(“How are you ?” )
device.openURL(string.format(“mailto:[email protected]?subject=%s&body=%s”, subject, body))
2.6 getInputText
Get input information
cc.Native:getInputText(“Information”,”How weight are you (KG)”, “60”)
2.7 Vibrate
Vibrate calls the function cc.native: Vibrate ().
3. framework.display
local items = {
“addImageAsync”,
“scale9Sprite”,
“tilesSprite”,
“tiledBatchNode”,
“drawNode”,
“progress”,
“layerMultiTouch”
}
3.1 addImageAsync
Asynchronously loading images
display.addImageAsync(“Coin0001.png”, function(event, texture)
printf(“display.addImageAsync(\”Coin0001.png\”) – event = %s,texture = %s”, tostring(event), tostring(texture))
self.coin = display.newSprite(“Coin0001.png”, display.left + 100, display.cy)
self:addChild(self.coin)
end)
After loading, call the function to display the image to the scene.
3.2 scale9Sprite
Create the Sprite by using newScale9Sprite to create the image greenbutton. PNG
Set Sprite range and finally set fadeout and Fadein.
3.3 tilesSprite
Create a tilesprite of pictures by using the following command.
self.tilesSprite_ = display.newTilesSprite(“close.png”, cc.rect(10, 10, 100, 100))
:pos(display.left + 10, display.bottom+ 10)
:addTo(self)
3.4 tiledBatchNode
The code is as follows:
local cb = function(plist, image)
self.tiledBatchNode_ = display.newTiledBatchNode(“#blocks9.png”, “blocks9ss.png”, cc.size(170, 170), 10, 10)
:pos(display.left + 10, display.bottom+ 150)
:addTo(self)
end
display.addSpriteFrames(“blocks9ss.plist”, “blocks9ss.png”, cb)
Load the picture into the frame and then call the function cb.
Display.addspriteframes ()
display.addSpriteFrames(plistFilename, image, handler)
Loads the specified Sprite Sheets material file and its data file into the image frame cache.
Format:
Display.addspriteframes (Data file, material file)
12345678 | <br>-- display. AddSpriteFrames (" sprites.plist ", "sprites.png ") Local cb = function(plist, image) -- do something``end``display.addSpriteFrames("Sprites.plist", "Sprites.png", cb) |
---|
Sprite Sheets is simply a collection of multiple images. The Sprite Sheets material file consists of multiple images, while the data file records information such as the position of the image in the material file.
Parameters
· String plistFilename Data file name
· String image Material file name
3.5 drawNode
Initialize a node to draw a graph.
A solid circle, a hollow circle, a square, a straight line, a triangle.
3.6 the progress
Create a progress bar for the prototype
local progress = display.newProgressTimer(“Coin0001.png”, display.PROGRESS_TIMER_RADIAL)
:pos(100, 100)
:addTo(self)
progress:setPercentage(60)
self.progressNode_ = progress
3.7 layerMultiTouch
Create a new Layer. Add a listener to it with the onTouch callback.
The onTouch function implements multi-touch.
4. framework.crypto
local items = {
“AES256”,
“XXTEA”,
“Base64”,
“MD5File”,
“MD5”,
}
4.1 AES256
Perform AES256 encryption and decryption.
4.2 XXTEA
XXTEA encryption, the following code:
local p = “Test123”
local k = “KEYKEY”
local c = crypto.encryptXXTEA(p, k)
printf(“source: %s”, p)
printf(“encrypt XXTEA: %s”, bin2hex(c))
printf(“decrypt XXTEA: %s”, crypto.decryptXXTEA(c, k))
local p = string.rep(“HELLO”, 15)
local k = “keykey”
local c = crypto.encryptXXTEA(p, k)
printf(“source: %s”, p)
printf(“encrypt XXTEA: %s”, bin2hex(c))
printf(“decrypt XXTEA: %s”, crypto.decryptXXTEA(c, k))
4.3 Base64
Base64 encryption and decryption operations. With XXTEA.
4.4 MD5File
MD5 algorithm: Performs MD5 calculation for files. The code is as follows
local file = cc.FileUtils:getInstance():fullPathForFilename(“config.lua”)
printf(“md5 file test: %s -> %s”, file, crypto.md5file(file))
4.5 the MD5
Perform MD5 calculation on the string as follows:
local p = string.rep(“HELLO”, 5)
printf(“md5Test: %s -> %s”, p, crypto.md5(p))
5. framework.network
local items = {
“createHTTPRequest”,
“createHTTPRequestBadDomain”,
“send data to server”,
“isLocalWiFiAvailable”,
“isInternetConnectionAvailable”,
“isHostNameReachable”,
“getInternetConnectionStatus”,
}
The onResponse function handles HTTP-related events.
An error is reported if the event is not progress, the data length is retrieved if competeled, and the String is printed if dumpResponse is true.
For others, print ———————————-.
5.1 createHTTPRequest
local url = “quick-x.com/feed/”
self.requestCount = self.requestCount + 1
local index = self.requestCount
local request = network.createHTTPRequest(function(event)
if tolua.isnull(self) then
printf(“REQUEST %d COMPLETED, BUT SCENE HAS QUIT”, index)
return
end
self:onResponse(event, index)
end, url, “GET”)
printf(“REQUEST START %d”, index)
request:start()
See the createHTTPRequest function explained in 14.3
5.2 createHTTPRequestBadDomain
The code is the same as above, but connects to a non-existent HTTP address.
5.3 senddata publishes the event to the server
To send data to the SERVER, run the POST command.
5.4 isLocalWiFiAvailable
Check whether local WIFI is available.
5.5 isInternetConnectionAvailable
Check whether the network connection is available.
5.6 isHostNameReachable
Determine whether a web address is reachable.
5.7 getInternetConnectionStatus
Through the network. GetInternetConnectionStatus () command, whether Internet, WIFI, 3 g network is available.
6. framework.luabinding
local items = {
“avoidPeertableGC”,
“getCppFunction”,
}
6.1 avoidPeertableGC
local node = display.newNode()
node:addNodeEventListener(cc.NODE_EVENT, function(event)
printf(“node event %s”, event.name)
end)
node.customVar = 1
node:setTag(1)
self:addChild(node)
printf(“1. node.customVar = %s, expected = 1”, tostring(node.customVar)) — 1
collectgarbage()
collectgarbage()
printf(“2. node.customVar = %s, expected = 1”, tostring(node.customVar)) — 1
self:performWithDelay(function()
printf(“3. node.customVar = %s, expected = 1”, tostring(self:getChildByTag(1).customVar)) — 1
local node2 = self:getChildByTag(1)
collectgarbage()
collectgarbage()
printf(“4. node.customVar = %s, expected = 1”, tostring(node2.customVar)) — 1
self:removeChildByTag(1)
printf(“5. node = %s, expected = nil”, tostring(self:getChildByTag(1))) — nil
printf(“6. node.customVar = %s, expected = nil”, tostring(node2.customVar)) — nil
End, 1.0)
6.2 getCppFunction
— override C++ class method
function cc.Node:setPosition(x, y)
Printf (” cc. Node: setPosition (% 0.2 f, % 0.2 f) “, x, y)
— call origin C++ method
local cfunction = tolua.getcfunction(cc.Node, “setPosition”)
cfunction(self, x, y)
end
local node = display.newNode()
self:addChild(node)
Print (” expected ‘cc. Node: setPosition (100.00, 100.00),’ “)
Node: setPosition (100, 100) – cc. The node: setPosition (100.00, 100.00)
local x, y = node:getPosition()
Printf (“x, y = %0.2f, %0.2f, expected 100.00, 100.00”, x, y) printf(“x, y = %0.2f, %0.2f, expected 100.00, 100.00”, y)
— restoreC++ method
cc.Node.setPosition = tolua.getcfunction(cc.Node,”setPosition”)
print(“expected – no output”)
node:setPosition(100, 100)
Rewrite the C++ class function and reload the function.
7. framework.event
local items = {
“addEventListener”,
“removeEventListener”,
“removeAllListener”,
“removeCoin”,
“sendEvent”
}
Create a node and add the image coin0001.png.
Added event listening for EventTest1, EventTest2
7.1 the addEventListener
Added event listener EventTest3, EventTest4 for proxy events.
self.eventProxy:addEventListener(“EventTest3”, function(event) print(“event listener 3”) dump(event) end, “tag3”)
self.eventProxy:addEventListener(“EventTest4”, function(event) print(“event listener 4”) dump(event) end)
7.2 removeEventListener
Remove EventTest1, EventTest2,EventTest3.
Through three different methods as follows:
self.eventProxy:removeEventListener(self.eventHandle2)
local eventHandle1 = self.eventProxy:getEventHandle(“EventTest1”)
self.eventProxy:removeEventListener(eventHandle1)
self.eventProxy:removeAllEventListenersForEvent(“EventTest3”)
7.3 removeAllListener
Remove all listeners.
7.4 removeCoin
Remove the coin Sprite. The event listener added when the coin is removed disappears.
7.5 adds
Distribute EventTest events.
Event name EventTest1, EventTest2, EventTest3, EventTest4.
8. framework.interface
local items = {
“register”,
“modebase”,
“functions”
}
There are three common interfaces.
8.1 the Register
local register =require(“framework.cc.Registry”)
local eventProtocol =register.newObject(“components.behavior.EventProtocol”)
Create an event protocol object.
register.setObject(eventProtocol, “cryptoTest1”)
if not register.isObjectExists(“cryptoTest1”) then
printError(“ERRORsome thing wrong please check Register”)
end
register.getObject(“cryptoTest1”)
register.removeObject(“cryptoTest1”)
if register.isObjectExists(“cryptoTest1”) then
printError(“ERRORsome thing wrong please check Register”)
end
if not register.exists(“components.behavior.EventProtocol”) then
printError(“ERRORsome thing wrong please check Register”)
end
8.2 Modebase
local mvcBase =require(“framework.cc.mvc.ModelBase”)
8.3 functions provides
Create two classes Animal,Duck.
The Iskindof function is used to determine whether an object belongs to the specified class.
Call luA-related functions such as math related functions.
9. framework.socketTcp
local items = {
“Connect”,
“SendData”,
“Close”
}
The Init function creates a SocketTCP object. And add SocketTCP related events
EVENT_DATA
EVENT_CLOSE
EVENT_CLOSED
EVENT_CONNECTED
EVENT_CONNECT_FAILURE
9.1 the Connect
Link 127.0.0.1.
9.2 SendData publishes the event
Sends information to the Socket.
9.3 the Close
Close the Socket object.
10. framework.timer
Create a timer
if self.timer_ then
return
end
local Timer = require(“framework.cc.utils.Timer”)
local appTimer = Timer.new()
— Responds to the CITYHALL_UPGRADE_TIMER event
local function onCityHallUpgradeTimer(event)
if event.countdown > 0 then
— The countdown is not over, update the time displayed on the user interface
print(“timer counting”)
else
— The countdown is over, update the user interface to show the upgraded City Defense Hall
print(“timer over”)
end
end
— Register event
appTimer:addEventListener(“CITYHALL_UPGRADE_TIMER”, onCityHallUpgradeTimer)
– It takes 3600 seconds to upgrade the city Defense Hall, and the interface display is updated every 30 seconds
appTimer:addCountdown(“CITYHALL_UPGRADE_TIMER”, 600, 10)
appTimer:start()
self.timer_ = appTimer
AddCountdown command
11. framework.gamestate
The initialization function is as follows:
local stateListener = function(event)
if event.errorCode then
print(“ERROR,load:” .. event.errorCode)
return
end
if “load” == event.name then
local str = crypto.decryptXXTEA(event.values.data, “scertKey”)
local gameData = json.decode(str)
dump(gameData, “gameData:”)
elseif “save” == event.name then
local str = json.encode(event.values)
if str then
str = crypto.encryptXXTEA(str, “scertKey”)
returnValue = {data = str}
else
print(“ERROR, encode fail”)
return
end
return {data = str}
end
end
gameState.init(stateListener, “gameState.dat”, “keyHTL”)
Save the game state.
Call the gamestate.load () and gamestate.save (data) functions, respectively.
12. framework.transition
Create 10 coins, each performing a different action.
Create two Grossini_blue_, one running once and the other running permanently.
13. framework.nvgdrawnode
— nvgDraw drawing function
local quarLB = cc.p(display.cx/2, display.cy/2)
local quarRT = cc.p(display.width – quarLB.x, display.height- quarLB.y)
local drawNode1 = cc.NVGDrawNode:create()
self:addChild(drawNode1)
drawNode1:drawPoint(cc.p(display.cx – 100, display.cy), cc.c4f(1, 0, 0, 1))
local points = {}
For I = 1, 10 do
points[i] = cc.p(display.width/10*i, 10)
end
local drawNode2 = cc.NVGDrawNode:create():addTo(self)
drawNode2:drawPoints(points, 10, cc.c4f(0, 1, 0, 1))
local drawNode3 = cc.NVGDrawNode:create()
self:addChild(drawNode3)
drawNode3:drawLine(quarLB, quarRT, cc.c4f(0, 0, 1, 1))
local drawNode4 = cc.NVGDrawNode:create()
self:addChild(drawNode4)
drawNode4:drawRect(quarLB, quarRT, cc.c4f(1, 1, 0, 1))
points = {}
points[1] = cc.p(100, 200)
points[2] = cc.p(100, 100)
points[3] = cc.p(200, 100)
points[4] = cc.p(300, 150)
local drawNode5 = cc.NVGDrawNode:create()
self:addChild(drawNode5)
drawNode5:drawPolygon(points, 4, true, cc.c4f(0, 1, 1, 1))
local drawNode6 = cc.NVGDrawNode:create()
self:addChild(drawNode6)
drawNode6:drawCircle(cc.p(display.cx, display.cy), 20, cc.c4f(1, 0, 1, 1))
local drawNode7 = cc.NVGDrawNode:create()
self:addChild(drawNode7)
DrawNode7 :drawQuadBezier(quarLB, cc.p(quarrt. x, quarlb.y), quarRT, cc.c4f(1, 1,1))
local drawNode8 = cc.NVGDrawNode:create()
self:addChild(drawNode8)
DrawNode8: drawCubicBezier (cc) p (300, 400), the cc. P (350, 500), the cc. P (500, 300), the cc. P (600, 400), the cc. C4f (0.5, 0, 0, 1))
local drawNode9 = cc.NVGDrawNode:create()
self:addChild(drawNode9)
Cx, display.cy),5, cc.c4f(0, 0.5, 0, 1))
local drawNode10 = cc.NVGDrawNode:create()
self:addChild(drawNode10)
drawNode10:setColor(cc.c4f(1, 1, 1, 1))
DrawNode10 :drawSolidRect(cc.p(330, 120), cc.p(430, 220), cc.c4f(0, 0, 0.5, 1))
points = {}
points[1] = cc.p(500, 400)
points[2] = cc.p(600, 400)
points[3] = cc.p(550, 500)
local drawNode11 = cc.NVGDrawNode:create()
self:addChild(drawNode11)
DrawNode11: drawSolidPolygon (points, 3 cc. C4f (0.5, 0.5, 0, 1))
local drawNode12 = cc.NVGDrawNode:create()
self:addChild(drawNode12)
drawNode12:setFill(true)
drawNode12:setFillColor(cc.c4f(1, 1, 1, 1))
DrawNode12 :drawArc(cc. P (50, 200), 50, 30, 200, 1, cc. C4f (0, 0.5, 0.5, 1))
local points = {}
points[1] = cc.p(10, 300)
points[2] = cc.p(200, 320)
points[3] = cc.p(180, 350)
points[4] = cc.p(220, 410)
local drawNode13 = cc.NVGDrawNode:create()
self:addChild(drawNode13)
drawNode13:setLineWidth(4)
DrawNode13: setColor (cc) c4f (0, 0.5, 0.5, 1))
DrawNode13: drawSolidPolygon (points, 4, cc c4f (0.5, 0, 0.5, 1))
14. Correlation function
14.1 the device
You can query device properties and access device functions
When the framework is initialized, the device module provides the following properties:
· Device. platform Returns the name of the current running platform. Available value: ios, Android, MAC, Windows.
· Device. model Returns the device model, available value: unknown, iPhone, iPad
· Device. language Returns the language currently used by the device. Available value:
O cn: Chinese
O FR: French
O it: Italian
O GR: German
O sp: Spanish
O ru: Russian
O JP: Japanese
O en: English
· Device. writablePath Returns the preferred path to which data can be written on the device:
O Return to the Documents directory where the application is located on iOS
O Return to the root directory of the memory card on Android
O Return values for other platforms are determined by quick-x-player
· Device. cachePath Returns the cache directory on the device to which data can be written:
O Return to the Library/Caches directory where your app is located on iOS
O Other platforms return the same value as device.writablePath
· device. DirectorySeparator directory separator, is “\” on Windows platforms, other platforms are “/”
· device. PathSeparator pathSeparator, “; “on Windows. , other platforms are “:”
Functions |
---|
device.showActivityIndicator() |
Display activity indicator |
device.hideActivityIndicator() |
Hide the activity indicator that is being displayed |
device.showAlert(title, message, buttonLabels, listener) |
Displays a pop-up dialog box containing the button |
device.cancelAlert() |
Cancels the dialog box being displayed. |
device.getOpenUDID() |
Returns the OpenUDID value of the device |
device.openURL(url) |
Use your browser to open the specified url |
device.showInputBox(title, message, defaultValue) |
Displays an input box and returns what the user entered. |
14.2 the display
Functions associated with displaying images, scenes
The display module encapsulates most of the display-related functions and is responsible for calculating the design resolution of the screen according to the resolution defined in config.lua.
After framework initialization, the display module provides the following properties:
· display. SizeInPixels. Width,
· display. SizeInPixels. Height of the screen pixel resolution
· display. WidthInPixels,
· Display.HeightinPixels Screen pixel resolution
· display. ContentScaleFactor content scaling factor
, the display. The size. The width,
· Display. Size. Height Design resolution of the screen
· display. The width,
· Display. Height Design resolution of the screen
Cx, · the display.
· display. Cy x and Y coordinates in the center of the screen
· display. Left,
Display, a top,
The display, right,
· display. Bottom Coordinates of the four sides of the screen
· display. C_left,
· display. C_top,
· display. C_right,
· display.c_bottom Coordinates of the four sides of the screen when the parent object is in the center of the screen
14.3 network. CreateHTTPRequest ()
network.createHTTPRequest(callback, url, method)
Create an asynchronous HTTP request and return a cc.Httprequest object.
Copy the code
function onRequestFinished(event)
Copy the code
local ok = (event.name == "completed")
Copy the code
local request = event.request
Copy the code
Copy the code
if not ok then
Copy the code
Request failed, error code and error message displayedCopy the code
print(request:getErrorCode(), request:getErrorMessage())
Copy the code
return
Copy the code
end
Copy the code
Copy the code
local code = request:getResponseStatusCode()
Copy the code
if code ~= 200 then
Copy the code
Request complete, but no 200 response code returnedCopy the code
print(code)
Copy the code
return
Copy the code
end
Copy the code
Copy the code
The request is successful, and the server returns the contentCopy the code
local response = request:getResponseString()
Copy the code
print(response)
Copy the code
end
Copy the code
Copy the code
Create a request and POST the data to the serverCopy the code
local url = "http://www.mycompany.com/request.php"
Copy the code
local request = network.createHTTPRequest(onRequestFinished, url, "POST")
Copy the code
request:addPOSTValue("KEY", "VALUE")
Copy the code
Copy the code
-- Start asking. The callback() function is called when the request completesCopy the code
request:start()
Copy the code
Copy the code
Returns
The HTTPRequest results,