VS2010 + cocos2dx 2.X版本 + python 3

Cocos2dx就不废话介绍了, 非常火的游戏引擎,关键是它开源,可以免费下载、学习、开发,不用搞这么多激活的东西。下面以Cocos2dx 2.x为例说明这个平台的一些基本东西。虽然现在Cocos2dx早已去到3.x的稳定版本,但之所以选用Cocos2dx 2.x版本,主要是这方面的资料比较多,本来搞Cocos2dx的人就不多了,搞了也没几个人写写编程记录,再去毫无资料只有一堆难以看懂的官方文档的Cocos2dx 3.x,基本上等于瞎整。

首先,由于这引擎在Windows的主流平台是通过大家熟悉的C++写出来的,所以Cocos2dx 2.x的开发,你首先要准备Visual Studio 2010以上的版本。如果你选用Cocos2dx 3.x还要支持准备Visual Studio 2012以上的版本。已经不支持Visual Studio 2008了,这就没办法了,怪怪下载一个完整安装。网上一搜一堆,不说了。

之后,由于Cocos2dx 2.x在当今网站的最后一版2.2.6不再提供InstallWizardForVS2010.js这鬼东西,需要用Python语言创建新的工程,因此你可以参看我之前的《【Python】Windows版本的Python开发环境的配置,Helloworld,Python中文问题,输入输出、条件、循环、数组、类》(点击打开链接)先配好Python2.x的环境。

然后,你才在Cocos2dx的中文官网(点击打开链接),如下图,拉到最下面,下载Cocos2dx 2.x版本。

具体下载地址为:http://54.192.159.100/cocos2d-x-2.2.6.zip?fid=D2qKo-*f7vaAbUj7fijGQlgs5hzdkV4YAAAAAOeOX4E0-gk5fRKd*Y-Bb8j7lCvn&mid=666&threshold=150&tid=5D3FD9855047216E67D27C85E859FC2D&srcid=119&verno=1


下载之后,得到一个cocos2d-x-2.2.6.zip,解压,这个解压位置就是你以后cocos2dx的开发环境、工程的所在目录,和PHP是一样的,不好迁移,请小心选择。

在你的cocos2dx的解压目录找到build-win32.bat这东西,双击运行。


经历如下的一个漫长的编译过程:


搞好之后,会出现如下的一个界面,cocos2dx官方提供的一大堆例子,有兴趣看看之后,可以直接关闭。


至此,Cocos2dx的配置完成。

下面创建一个属于我们自己的Helloworld,不要用官方的例子,根本看不出什么端倪。

利用命令行进入.\cocos2d-x-2.2.6\tools\project-creator这个文件夹,利用python命令,如下图,创建一个工程。

  1. create_project.py -project 你的工程文件夹名称 -package 包名 -language 开发语言(基本上为cpp,不排除有大神精通肥猪流的Lua,也不建议使用javascript开发!) 


用python 3的朋友会遇到新的问题:上面py文件出错。

解决方案是。修改之:

  1. #!/usr/bin/python  
  2. #coding=utf-8  
  3. # create_project_v3.py  
  4. # Create cross-platform cocos2d-x project  
  5. # Copyright (c) 2012 cocos2d-x.org  
  6. # Author: WangZhe  
  7.   
  8. # define global variables  
  9.   
  10. context = {  
  11. "language"          : "undefined",  
  12. "src_project_name"  : "undefined",  
  13. "src_package_name"  : "undefined",   
  14. "dst_project_name"  : "undeifned",  
  15. "dst_package_name"  : "undefined",  
  16. "src_project_path"  : "undefined",  
  17. "dst_project_path"  : "undefined",  
  18. "script_dir"        : "undefined",  
  19. }  
  20. platforms_list = []  
  21.   
  22. # begin  
  23. import sys  
  24. import os, os.path  
  25. import json  
  26. import shutil  
  27.   
  28. def dumpUsage():  
  29.     print ("Usage: create_project.py -project PROJECT_NAME -package PACKAGE_NAME -language PROGRAMING_LANGUAGE")  
  30.     print ("Options:")  
  31.     print ("  -project   PROJECT_NAME          Project name, for example: MyGame")  
  32.     print ("  -package   PACKAGE_NAME          Package name, for example: com.MyCompany.MyAwesomeGame")  
  33.     print ("  -language  PROGRAMING_LANGUAGE   Major programing lanauge you want to used, should be [cpp | lua | javascript]")  
  34.     print ("")  
  35.     print ("Sample 1: ./create_project.py -project MyGame -package com.MyCompany.AwesomeGame")  
  36.     print ("Sample 2: ./create_project.py -project MyGame -package com.MyCompany.AwesomeGame -language javascript")  
  37.     print ("")  
  38.   
  39. def checkParams(context):  
  40.     # generate our internal params  
  41.     context["script_dir"] = os.getcwd() + "/"  
  42.     global platforms_list  
  43.       
  44.     # invalid invoke, tell users how to input params  
  45.     if len(sys.argv) < 7:  
  46.         dumpUsage()  
  47.         sys.exit()  
  48.       
  49.     # find our params  
  50.     for i in range(1, len(sys.argv)):  
  51.         if "-project" == sys.argv[i]:  
  52.             # read the next param as project_name  
  53.             context["dst_project_name"] = sys.argv[i+1]  
  54.             context["dst_project_path"] = os.getcwd() + "/../../projects/" + context["dst_project_name"]  
  55.         elif "-package" == sys.argv[i]:  
  56.             # read the next param as g_PackageName  
  57.             context["dst_package_name"] = sys.argv[i+1]  
  58.         elif "-language" == sys.argv[i]:  
  59.             # choose a scripting language  
  60.             context["language"] = sys.argv[i+1]  
  61.       
  62.     # pinrt error log our required paramters are not ready  
  63.     raise_error = False  
  64.     if context["dst_project_name"] == "undefined":  
  65.         print ("Invalid -project parameter")  
  66.         raise_error = True  
  67.     if context["dst_package_name"] == "undefined":  
  68.         print ("Invalid -package parameter")  
  69.         raise_error = True  
  70.     if context["language"] == "undefined":  
  71.         print ("Invalid -language parameter")  
  72.         raise_error = True  
  73.     if raise_error != False:  
  74.         sys.exit()  
  75.                                    
  76.     # fill in src_project_name and src_package_name according to "language"  
  77.     if ("cpp" == context["language"]):  
  78.         context["src_project_name"] = "HelloCpp"  
  79.         context["src_package_name"] = "org.cocos2dx.hellocpp"  
  80.         context["src_project_path"] = os.getcwd() + "/../../template/multi-platform-cpp"  
  81.         platforms_list = ["ios",  
  82.                           "android",  
  83.                           "win32",  
  84.                           "winrt",  
  85.                           "wp8",  
  86.                           "mac",  
  87.                           "blackberry",  
  88.                           "linux",  
  89.                           "marmalade",  
  90.                           "tizen",  
  91.                           "wp8-xaml"]  
  92.     elif ("lua" == context["language"]):  
  93.         context["src_project_name"] = "HelloLua"  
  94.         context["src_package_name"] = "org.cocos2dx.hellolua"  
  95.         context["src_project_path"] = os.getcwd() + "/../../template/multi-platform-lua"  
  96.         platforms_list = ["ios",  
  97.                           "android",  
  98.                           "win32",  
  99.                           "blackberry",  
  100.                           "linux",  
  101.                           "marmalade"]  
  102.     elif ("javascript" == context["language"]):  
  103.         context["src_project_name"] = "HelloJavascript"  
  104.         context["src_package_name"] = "org.cocos2dx.hellojavascript"  
  105.         context["src_project_path"] = os.getcwd() + "/../../template/multi-platform-js"  
  106.         platforms_list = ["ios",  
  107.                           "android",  
  108.                           "win32"]  
  109. # end of checkParams(context) function  
  110.   
  111. def replaceString(filepath, src_string, dst_string):  
  112.     content = ""  
  113.     f1 = open(filepath, "rb")  
  114.     for line in f1:  
  115.         temp_content = line.decode('utf-8')  
  116.         if src_string in temp_content:  
  117.             content += temp_content.replace(src_string, dst_string)  
  118.         else:  
  119.             content += temp_content  
  120.     f1.close()  
  121.     f2 = open(filepath, "wb")  
  122.     f2.write(content.encode(encoding='utf_8', errors='strict'))  
  123.     f2.close()  
  124. # end of replaceString  
  125.   
  126. def replaceLastNameInPath(raw_path):  
  127.     cnt = raw_path.count("PROJECT_NAME")  
  128.     if (cnt > 0):  
  129.         raw_path = raw_path.replace("PROJECT_NAME", context["src_project_name"], cnt - 1)  
  130.         dst = raw_path.replace("PROJECT_NAME", context["dst_project_name"])  
  131.         return dst  
  132.     return ""  
  133. # end of replaceLastNameInPath  
  134.   
  135. def processPlatformProjects(platform):  
  136.     # determine proj_path  
  137.     proj_path = context["dst_project_path"] + "/proj.%s/" % platform  
  138.     java_package_path = ""  
  139.   
  140.     # read josn config file or the current platform  
  141.     f = open("%s.json" % platform)  
  142.     data = json.load(f)  
  143.   
  144.     # rename package path, like "org.cocos2dx.hello" to "com.company.game". This is a special process for android  
  145.     if (platform == "android"):  
  146.         src_pkg = context["src_package_name"].split('.')  
  147.         dst_pkg = context["dst_package_name"].split('.')  
  148.         os.rename(proj_path + "src/" + src_pkg[0],  
  149.                   proj_path + "src/" + dst_pkg[0])  
  150.         os.rename(proj_path + "src/" + dst_pkg[0] + "/" + src_pkg[1],  
  151.                   proj_path + "src/" + dst_pkg[0] + "/" + dst_pkg[1])  
  152.         os.rename(proj_path + "src/" + dst_pkg[0] + "/" + dst_pkg[1] + "/" + src_pkg[2],  
  153.                   proj_path + "src/" + dst_pkg[0] + "/" + dst_pkg[1] + "/" + dst_pkg[2])  
  154.         java_package_path = dst_pkg[0] + "/" + dst_pkg[1] + "/" + dst_pkg[2]  
  155.   
  156.     # rename files and folders  
  157.     for i in range(0, len(data["rename"])):  
  158.         tmp = data["rename"][i].replace("PACKAGE_PATH", java_package_path)  
  159.         src = tmp.replace("PROJECT_NAME", context["src_project_name"])  
  160.         if (platform == "wp8-xaml"):  
  161.             dst = replaceLastNameInPath(tmp)  
  162.         else:  
  163.             dst = tmp.replace("PROJECT_NAME", context["dst_project_name"])  
  164.         if (os.path.exists(proj_path + src) == True):  
  165.             os.rename(proj_path + src, proj_path + dst)  
  166.   
  167.     # remove useless files and folders  
  168.     for i in range(0, len(data["remove"])):  
  169.         dst = data["remove"][i].replace("PROJECT_NAME", context["dst_project_name"])  
  170.         if (os.path.exists(proj_path + dst) == True):  
  171.             shutil.rmtree(proj_path + dst)  
  172.       
  173.     # rename package_name. This should be replaced at first. Don't change this sequence  
  174.     for i in range(0, len(data["replace_package_name"])):  
  175.         tmp = data["replace_package_name"][i].replace("PACKAGE_PATH", java_package_path)  
  176.         dst = tmp.replace("PROJECT_NAME", context["dst_project_name"])  
  177.         if (os.path.exists(proj_path + dst) == True):  
  178.             replaceString(proj_path + dst, context["src_package_name"], context["dst_package_name"])  
  179.       
  180.     # rename project_name  
  181.     for i in range(0, len(data["replace_project_name"])):  
  182.         tmp = data["replace_project_name"][i].replace("PACKAGE_PATH", java_package_path)  
  183.         dst = tmp.replace("PROJECT_NAME", context["dst_project_name"])  
  184.         if (os.path.exists(proj_path + dst) == True):  
  185.             replaceString(proj_path + dst, context["src_project_name"], context["dst_project_name"])  
  186.                     
  187.     # done!  
  188.     print ("proj.%s\t\t: Done!" % platform)  
  189.     # end of processPlatformProjects  
  190.   
  191.   
  192.   
  193. # -------------- main --------------  
  194. # dump argvs  
  195. # print sys.argv  
  196.   
  197. # prepare valid "context" dictionary  
  198. checkParams(context)  
  199. # import pprint  
  200. # pprint.pprint(context)  
  201.   
  202. # copy "lauguage"(cpp/lua/javascript) platform.proj into cocos2d-x/projects/<project_name>/folder  
  203. if (os.path.exists(context["dst_project_path"]) == True):  
  204.     print ("Error:" + context["dst_project_path"] + " folder is already existing")  
  205.     print ("Please remove the old project or choose a new PROJECT_NAME in -project parameter")  
  206.     sys.exit()  
  207. else:  
  208.     shutil.copytree(context["src_project_path"], context["dst_project_path"], True)  
  209.   
  210. # call process_proj from each platform's script folder            
  211. for platform in platforms_list:  
  212.     processPlatformProjects(platform)  
  213. #    exec "import %s.handle_project_files" % (platform)  
  214. #    exec "%s.handle_project_files.handle_project_files(context)" % (platform)  
  215.   
  216. print ("New project has been created in this path: " + context["dst_project_path"].replace("/tools/project-creator/../..", ""))  
  217. print ("Have Fun!"


在创建的过程中,可能会有如上图的报错,不用管,因为你创建的MyDemo工程已经成功出现在.\cocos2d-x-2.2.6\projects文件夹了,进入.\cocos2d-x-2.2.6\projects\MyDemo\proj.win32打开HelloCpp.sln,开始利用Cocos2dx引擎(框架)在Windows上开发游戏。

你可以观察到在.\cocos2d-x-2.2.6\projects\MyDemo,出现proj.Android、proj.iOS等平台的文件夹,这里意味着,你可以在这些平台同样利用Cocos2dx引擎(框架)进行开发。不是说一个平台开发,多平台共同编译……


打开HelloCpp.sln之后,等待Visual Studio 2010加载一大堆外部库之后,你可以看到如下的文件结构:


首先,你要明白一个概念,Cocos2dx中最简单的Helloworld,是由一个叫Helloworld的场景、然后在这个Helloworld场景上放上一个Helloworld字符串所组成的,

官方初始的Helloworld还在Helloworld这个场景中放上背景图片、关闭按钮等杂七杂八的东西,让Helloworld文件看起来比较复杂。

我们先从上图的main.cpp与AppDelegate.cpp入手,先设置好程序的一些基本东西。

首先是main.cpp,这东西的主函数就5行代码,将其关于程序标题与窗口尺寸的18、19行进行修改,如下:

  1. #include "main.h"  
  2. #include "AppDelegate.h"  
  3. #include "CCEGLView.h"  
  4.   
  5. USING_NS_CC;  
  6.   
  7. int APIENTRY _tWinMain(HINSTANCE hInstance,  
  8.                        HINSTANCE hPrevInstance,  
  9.                        LPTSTR    lpCmdLine,  
  10.                        int       nCmdShow)  
  11. {  
  12.     UNREFERENCED_PARAMETER(hPrevInstance);  
  13.     UNREFERENCED_PARAMETER(lpCmdLine);  
  14.   
  15.     // create the application instance  
  16.     AppDelegate app;  
  17.     CCEGLView* eglView = CCEGLView::sharedOpenGLView();  
  18.     eglView->setViewName("HelloWorld");//修改程序运行的标题为Helloworld  
  19.     eglView->setFrameSize(1024, 768);//修成程序运行的尺寸为1024x768  
  20.     return CCApplication::sharedApplication()->run();  
  21. }  

其余代码看不懂暂时先不要管,就像你当初学C语言,不必在乎#include<stdio.h>与void main(){}是什么鬼,你首先要会改printf()中的内容。关于引入、函数这些东西,回头再来学。

之后,还没有改完,对AppDelegate.cpp进行修改,把第22行的帧数调试信息关了,第25行的帧数有兴趣可以改下,不过改了也看不出效果,修改如下:

  1. #include "AppDelegate.h"  
  2. #include "HelloWorldScene.h"  
  3.   
  4. USING_NS_CC;  
  5.   
  6. AppDelegate::AppDelegate() {  
  7.   
  8. }  
  9.   
  10. AppDelegate::~AppDelegate()   
  11. {  
  12. }  
  13.   
  14. bool AppDelegate::applicationDidFinishLaunching() {  
  15.     // initialize director  
  16.     CCDirector* pDirector = CCDirector::sharedDirector();  
  17.     CCEGLView* pEGLView = CCEGLView::sharedOpenGLView();  
  18.   
  19.     pDirector->setOpenGLView(pEGLView);  
  20.       
  21.     // turn on display FPS  
  22.     pDirector->setDisplayStats(false);//关闭调试信息  
  23.   
  24.     // set FPS. the default value is 1.0/60 if you don't call this  
  25.     pDirector->setAnimationInterval(1.0 / 60);//这里是设置游戏运行的帧数锁定为60,一般牛B机器、牛B的游戏都是锁这个帧数,30帧是低配  
  26.   
  27.     // create a scene. it's an autorelease object  
  28.     CCScene *pScene = HelloWorld::scene();  
  29.   
  30.     // run  
  31.     pDirector->runWithScene(pScene);  
  32.   
  33.     return true;  
  34. }  
  35.   
  36. // This function will be called when the app is inactive. When comes a phone call,it's be invoked too  
  37. void AppDelegate::applicationDidEnterBackground() {  
  38.     CCDirector::sharedDirector()->stopAnimation();  
  39.   
  40.     // if you use SimpleAudioEngine, it must be pause  
  41.     // SimpleAudioEngine::sharedEngine()->pauseBackgroundMusic();  
  42. }  
  43.   
  44. // this function will be called when the app is active again  
  45. void AppDelegate::applicationWillEnterForeground() {  
  46.     CCDirector::sharedDirector()->startAnimation();  
  47.   
  48.     // if you use SimpleAudioEngine, it must resume here  
  49.     // SimpleAudioEngine::sharedEngine()->resumeBackgroundMusic();  
  50. }  
其余那些什么初始化代码之类,看不懂,先不要管,也不要改。

之后,对整个程序的核心,管理HelloWorld这个场景的HelloWorldScene.cpp进行修改,放上属于我们自己的东西,去掉官方的东西。主要对HelloWorldScene.cpp中的初始化参数bool HelloWorld::init(){}进行修改,其余不要动,整个HelloWorldScene.cpp修改如下:

  1. #include "HelloWorldScene.h"  
  2.   
  3. USING_NS_CC;  
  4.   
  5. CCScene* HelloWorld::scene()  
  6. {  
  7.     // 'scene' is an autorelease object  
  8.     CCScene *scene = CCScene::create();  
  9.       
  10.     // 'layer' is an autorelease object  
  11.     HelloWorld *layer = HelloWorld::create();  
  12.   
  13.     // add layer as a child to scene  
  14.     scene->addChild(layer);  
  15.   
  16.     // return the scene  
  17.     return scene;  
  18. }  
  19.   
  20. // on "init" you need to initialize your instance  
  21. bool HelloWorld::init()  
  22. {  
  23.     //保留已经存在的初始化部分,不要进行修改,开始  
  24.     if ( !CCLayer::init() )  
  25.     {  
  26.         return false;  
  27.     }  
  28.       
  29.     CCSize visibleSize = CCDirector::sharedDirector()->getVisibleSize();  
  30.     CCPoint origin = CCDirector::sharedDirector()->getVisibleOrigin();  
  31.     //保留已经存在的初始化部分,不要进行修改,结束  
  32.       
  33.       
  34.     CCLabelTTF* pLabel = CCLabelTTF::create("Hello World""Arial", 96);//声明一个标签文本Helloworld,其字体为Arial,字号为96  
  35.     pLabel->setPosition(ccp(origin.x + visibleSize.width/2,//设置标签文本的位置ccp是必须的,visibleSize.width/2为屏幕的中央,前面的origin.x是必须加上,用于多平台固定好位置  
  36.                             origin.y + visibleSize.height/2));//y部分同理  
  37.     this->addChild(pLabel, 1);//把这个标签文本Helloworld放到场景中,层叠关系为1,相当于css中的z-index,这个数字越大,越在上面  
  38.     return true;  
  39. }  
  40.   
  41.   
  42. void HelloWorld::menuCloseCallback(CCObject* pSender)  
  43. {  
  44. #if (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) || (CC_TARGET_PLATFORM == CC_PLATFORM_WP8)  
  45.     CCMessageBox("You pressed the close button. Windows Store Apps do not implement a close button.","Alert");  
  46. #else  
  47.     CCDirector::sharedDirector()->end();  
  48. #if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)  
  49.     exit(0);  
  50. #endif  
  51. #endif  
  52. }  

利用Ctrl+F5运行,或者点击上方的运行按钮则看到如下效果:

如果在编译的时候,遇到如下图的“LINK : fatal error LNK1123: 转换到 COFF 期间失败: 文件无效或损坏”错误:

那不关Cocos2dx的问题,是由于电脑中有多个Visual Studio冲突,或者之前版本的Visual Studio没有卸载干净。当前系统中存在两个cvtres.exe文件,版本不同就会有问题了。我们让VS2010直接使用系统的cvtres.exe程序。重命名或删除:(vs2010安装的位置).\VC\bin\cvtres.exe

如图,我就把cvtres.exe搞成_cvtres.exe完事。


最后总结一下,Cocos2dx的Helloworld比起SSH算是简单多了,代码清晰。关键是注意好版本,正如php5.5之后不支持windows2003这样的问题,你必须搞清楚Visual Studio 2010只能支持Cocos2dx 2.x之类的。就是安装可能有些繁琐,毕竟python环境的安装对于很多人来说比较陌生,Visual Studio 2010的安装的耗时实在是无力吐槽了,再加上Cocos2dx 2.x的编译过程,就是比较久。最主要网上许多蛋疼的资料就不说了……

猜你喜欢

转载自blog.csdn.net/liyaoqing/article/details/60396739
今日推荐