Why use scripts in games?
In some early games, most of the game logic was directly written into the game code, such as calculation formulas and game processes. However, with the continuous development of the game industry, game development itself has become more and more complex. Game planning requires more time to adjust the game. If the game logic is still written in the code, it is planned that every modification to the game should be carried out through the program, and the program needs to be re-compiled and restarted, which greatly reduces the work efficiency.
Using scripts in the game can solve the above problems, from the calculation formula to the control process of the game, in addition, most of the current script systems are interpreted and executed, so they can be dynamically modified at runtime, so that you can immediately see the modification results, which is very convenient.
How to use scripts
There are two main ways to use scripts in a game. One way is that the main program uses a high-level language, such as C ++, to write it, and then embed a script interpreter to dynamically execute some script functions at runtime; another way is to write the entire program using scripts. For example, some mud games are directly written using LPC scripts.
This article mainly studies the use of embedded scripts, because most of the scripts currently do not provide a convenient debugging environment such as VC ++. If all the programs are written in scripts, debugging becomes very painful when the script contains tens of thousands or even tens of thousands of lines. In addition, some very time-consuming code can be written in C ++ for Embedded use to ensure better running efficiency.
The program starts from the main () function of C ++ and then enters the main loop. In some C ++ functions, the script function is called directly. during the running of the script function, it is also possible to call C ++ extension functions. C ++ has two main functions: one is to add functions that cannot be directly written by scripts, and the other is to replace functions that are too slow to run in scripts.
The key aspect of the above process is how C ++ and scripts call functions and how parameters and results are transmitted. The general solution is to register C ++ extension functions with the script API when the program starts, and pass the function pointer to the script system for future calls, when a script function is called, the API of the script system is used to compress the call parameters into the stack and obtain the running result through the API.
Python script Introduction
Currently, many third-party scripting languages are available for direct use, such as TCL and Lua. This article describes Python scripts. Python has more than a decade of history. It is an explanatory and object-oriented scripting language. Python interpreters can run on most operating systems, such as Windows, Linux, Solaris, and Mac.
1. installation and configuration
Python home page in http://www.python.org, the latest version is 2.3.2, this article uses 2.2.2, you can download the installation package on its home page http://www.python.org/ftp/python/2.2.2/python-2.2.2.exe. After running the installer, it will install the python interpreter, documentation, extension module, and so on to your computer.
After the installation is complete, the python Graphical Editor (idle, but Chinese characters are not supported in the current version), Python command line interpreter, and user manual will be displayed in the Start Menu.
To call the python API function in a C ++ program, you need to add the header file and Lib path to the search directory of VC ++, the header file path is the include directory under the Local Python installation directory, and the Lib path is the libs directory under the Local Python installation directory. Note that the installation package only provides the lib and DLL of the release version. If debugging is required, you must download the Python source code to compile the lib and DLL of the debug version, for the source code, download http://www.python.org/ftp/python/2.2.2/python-2.2.2.tgz.
2. Syntax Introduction
For detailed syntax instructions, refer to the documentation that comes with the python installation package. Here I will only introduce some common keywords and precautions.
Python does not include {And} in C ++. It is replaced by indentation. Variables do not need to be declared separately, but cannot reference unassigned variables.
Python introduces the concept of a module, similar to the concept of library in C ++. A module can contain functions, variables, and classes. A script file is a module that needs to be imported before use.
Python does not have a switch. If is used instead:
If (num = 1 ):
Print "1"
Elif (num = 2 ):
Print "2"
Else:
Print "unknown"
While is a loop Statement of Python. In the while loop, you can use continue to jump to the next loop, and use break to jump out of the entire loop:
CNT = 5
While (CNT> 0 ):
Print CNT
CNT-= 1
For Loop:
List = ["test1", "Test2", "test3"]
For STR in list:
Print Str
A dictionary is a type of ing data in Python. It can be mapped from a key to the actual content (value ):
Accounts = {'Tom ': '123', 'Mike': '123 '}
Print accounts ['Tom ']
Print accounts ['Mike ']
3. API Introduction
Python provides a large number of C APIs, through which c ++ interacts with python. The following describes several important API functions:
Void py_initialize ()
Before using the python system, you must use py_initialize to initialize it. It loads Python built-in modules and adds the system path to the module search path. This function has no return value. You need to use py_isinitialized to check whether the system initialization is successful.
Int pyrun_simplestring (char * command)
Run the input string directly as the Python code. If the return value is 0, the input string is successful, and if the return value is-1, the input string is incorrect. Most errors are caused by syntax errors in strings.
Pyobject * py_buildvalue (char * format ,...)
Converts the C ++ variable into a python object. This function is used when a variable needs to be passed from C ++ to Python. This function is a bit similar to C's printf, but the format is different. The commonly used formats include "S", "I", and "F", which indicate a string. "O" indicates a python object.
Pyobject * pyobject_callobject (pyobject * callable_object, pyobject * ARGs)
Call a python function pointing to callable_object. ARGs is the call parameter. Before using this function, you can use pycallable_check to check whether callable_object is a callable Python object.
Pyobject * pyimport_import (pyobject * name)
Load a module specified by n a m e. You can use pystring_fromstring to convert the module name to a python object, and then use pyimport_import to load the module.
Void py_finalize ()
Shut down the python system. This function is generally called when the program exits.
[Knowledge]
More about Python
Python uses an elegant programming syntax that is very similar to a natural language, making it readable.
Python is a flexible programming language that is easy to run. This makes it an idealized language for prototype development and special program design tasks. With p y t h o n for program design, you may not even consider the poor maintainability of your program.
Python is an object-oriented programming that supports classes and multi-inheritance.
Python code can be packaged as templates and packages.
Python supports Exception Handling tracking and can list clear and detailed error prompts.
Python contains some advanced programming features, such as code generators and interpreters. The automatic garbage collection function frees you from the Battle of memory management.
Python's huge Standard Library supports many general programming tasks, such as connecting to a network server, regular expressions, and file operations.
The interactive mode of Python makes debugging of short programs very convenient. In addition, it also has a bundled development environment-idle when processing large programs.
The Python compiler can be easily extended. You can add the C or C ++ compiled template as a new template.
The Python compiler can be embedded into another application to provide a programmable interface.
Python can run on many different types of computers and operating systems, such as Windows, Mac OS, OS/2, UNIX, and Linux.
The Python compiler is an open-source project with copyright, but it can be used and released for free, or even used in commercial projects.
The easiest way to use python in C ++ is to use advanced applications.
Initialize the interpreter of the Python language during use.
Py_initialize ();
Stop the python interpreter after use.
Py_finalize ();
The simplest thing about this application is to directly execute a broken script.
Pyrun_simplestring ("Import sys/N"
"Print 100 + 200/N ");
This is the simplest application.
If you want to execute a script stored in the file, call
Int pyrun_simplefile (File * FP, const char * filename)
This method is the simplest one.
Function call can finally return the value of BCB calling Python a few days ago. It does not directly call the python function in C ++, but simply uses the pyrun_simplestring () function to execute the specified string. This call can still be used when there is no output result, or when the output result is in a file or the like. However, in general, we need to return a result to the called function. In this case, it is not feasible to use the interpreted string method (it can be implemented, and the output stream redirection is used, but the processing is complicated). You can only call the function and then accept the return value of the function.
This call is also relatively simple (because I only need to return a string :)). First, use pyimport_importmodule to initialize the module you want to call (usually the file name ), then use pyobject_callmethod to call your python function. Of course, you need to set the parameters to call the function.
Reference code:
-----------------------------------
Ansistring scriptpath = extractfilepath (Application-> exename) + "script ";
Ansistring pystr;
Pyobject * pname, * POs, * parg, * presult, * pcall;
Py_initialize ();
Initlogger ();
Pos = pyimport_importmodule ("OS. Path ");
Pyobject_callmethod (Pos, "Join", "(s)", scriptpath. c_str ());
Pcall = pyimport_importmodule ("bomandxy ");
Presult = pyobject_callmethod (pcall, "readbom", "(s)", filename. c_str ());
Showmessage (pystring_asstring (presult ));
Py_finalize ();