软件开发SoftDev分类
浅谈HOOK技术在VC编程中的应用 [转]
浅谈HOOK技术在VC编程中的应用
作者: 中国电波传播研究所青岛分所郎锐 出处: yesky
摘要: 本文针对HOOK技术在VC编程中的应用进行讨论,并着重对应用比较广泛的全局HOOK做了阐述。
引言
Windows操作系统是建立在事件驱动机制之上的,系统各部分之间的沟通也都是通过消息的相互传递而实现的。但在通常情况下,应用程序只能处理来自进程内部的消息或是从其他进程发过来的消息,如果需要对在进程外传递的消息进行拦截处理就必须采取一种被称为HOOK(钩子)的技术。钩子是Windows操作系统中非常重要的一种系统接口,用它可以轻松截获并处理在其他应用程序之间传递的消息,并由此可以完成一些普通应用程序难以实现的特殊功能。基于钩子在消息拦截处理中的强大功能,本文即以VC++ 6.0为编程背景对钩子的基本概念及其实现过程展开讨论。为方便理解,在文章最后还给出了一个简单的有关鼠标钩子的应用示例。
钩子的基本原理
钩子的本质是一段用以处理系统消息的程序,通过系统调用,将其挂入到系统。钩子的种类有很多,每一种钩子负责截获并处理相应的消息。钩子机制允许应用程序截获并处理发往指定窗口的消息或特定事件,其监视的窗口即可以是本进程内的也可以是由其他进程所创建的。在特定的消息发出,并在到达目的窗口之前,钩子程序先行截获此消息并得到对其的控制权。此时在钩子函数中就可以对截获的消息进行各种修改处理,甚至强行终止该消息的继续传递。
任何一个钩子都由系统来维护一个指针列表(钩子链表),其指针指向钩子的各个处理函数。最近安装的钩子放在链的开始,最早安装的钩子则放在最后,当钩子监视的消息出现时,操作系统调用链表开始处的第一个钩子处理函数进行处理,也就是说最后加入的钩子优先获得控制权。在这里提到的钩子处理函数必须是一个回调函数(callback function),而且不能定义为类成员函数,必须定义为普通的C函数。在使用钩子时可以根据其监视范围的不同将其分为全局钩子和线程钩子两大类,其中线程钩子只能监视某个线程,而全局钩子则可对在当前系统下运行的所有线程进行监视。显然,线程钩子可以看作是全局钩子的一个子集,全局钩子虽然功能强大但同时实现起来也比较烦琐:其钩子函数的实现必须封装在动态链接库中才可以使用。
钩子的安装与卸载
由于全局钩子具有相当的广泛性而且在功能上完全覆盖了线程钩子,因此下面就主要对应用较多的全局钩子的安装与使用进行讨论。前面已经提过,操作系统是通过调用钩子链表开始处的第一个钩子处理函数而进行消息拦截处理的。因此,为了设置钩子,只需将回调函数放置于链首即可,操作系统会使其首先被调用。在具体实现时由函数SetWindowsHookEx()负责将回调函数放置于钩子链表的开始位置。SetWindowsHookEx()函数原型声明如下:
HHOOK SetWindowsHookEx(int idHook;
HOOKPROC lpfn;
HINSTANCE hMod;
DWORD dwThreadId);
其中:参数idHook 指定了钩子的类型,总共有如下13种:
WH_CALLWNDPROC 系统将消息发送到指定窗口之前的”钩子”
WH_CALLWNDPROCRET 消息已经在窗口中处理的”钩子”
WH_CBT 基于计算机培训的”钩子”
WH_DEBUG 差错”钩子”
WH_FOREGROUNDIDLE 前台空闲窗口”钩子”
WH_GETMESSAGE 接收消息投递的”钩子”
WH_JOURNALPLAYBACK 回放以前通过WH_JOURNALRECORD”钩子”记录的输入消息
WH_JOURNALRECORD 输入消息记录”钩子”
WH_KEYBOARD 键盘消息”钩子”
WH_MOUSE 鼠标消息”钩子”
WH_MSGFILTER 对话框、消息框、菜单或滚动条输入消息”钩子”
WH_SHELL 外壳”钩子”
WH_SYSMSGFILTER 系统消息”钩子”
参数lpfn为指向钩子处理函数的指针,即回调函数的首地址;参数hMod则标识了钩子处理函数所处模块的句柄;第四个参数dwThreadId 指定被监视的线程,如果明确指定了某个线程的ID就只监视该线程,此时的钩子即为线程钩子;如果该参数被设置为0,则表示此钩子为监视系统所有线程的全局钩子。此函数在执行完后将返回一个钩子句柄。
虽然对于线程钩子并不要求其象全局钩子一样必须放置于动态链接库中,但是推荐其也在动态链接库中实现。因为这样的处理不仅可使钩子可为系统内的多个进程访问,也可以在系统中被直接调用,而且对于一个只供单进程访问的钩子,还可以将其钩子处理过程放在安装钩子的同一个线程内,此时SetWindowsHookEx()函数的第三个参数也就是该线程的实例句柄。
在SetWindowsHookEx()函数完成对钩子的安装后,如果被监视的事件发生,系统马上会调用位于相应钩子链表开始处的钩子处理函数进行处理,每一个钩子处理函数在进行相应的处理时都要考虑是否需要把事件传递给下一个钩子处理函数。如果要传递,就通过函数CallNestHookEx()来解决。尽管如此,在实际使用时还是强烈推荐无论是否需要事件传递而都在过程的最后调用一次CallNextHookEx( )函数,否则将会引起一些无法预知的系统行为或是系统锁定。该函数将返回位于钩子链表中的下一个钩子处理过程的地址,至于具体的返回值类型则要视所设置的钩子类型而定。该函数的原型声明如下:
LRESULT CallNextHookEx(HHOOK hhk;int nCode;WPARAM wParam;LPARAM lParam);
其中,参数hhk为由SetWindowsHookEx()函数返回的当前钩子句柄;参数nCode为传给钩子过程的事件代码;参数wParam和lParam 则为传给钩子处理函数的参数值,其具体含义同设置的钩子类型有关。
最后,由于安装钩子对系统的性能有一定的影响,所以在钩子使用完毕后应及时将其卸载以释放其所占资源。释放钩子的函数为UnhookWindowsHookEx(),该函数比较简单只有一个参数用于指定此前由SetWindowsHookEx()函数所返回的钩子句柄,原型声明如下:
BOOL UnhookWindowsHookEx(HHOOK hhk);
Flash8API Full !!!
——————————————————————————————-
Download Flash 8 here: http://www.macromedia.com/software/flashplayer/public_beta/
——————————————————————————————-
getVersion() => WIN 8,0,0,434
——————————————————————————————-
BEFORE TESTING ANY NEW FEATURES:
——————————————————————————————-
1) Use Flash MX or MX2004 to create SWF version 6 or 7 !
2) patch the SWF to version 8 (use my tool here: http://www.develotec.com/fto8.exe !!)
(alternatively, use the XML patch for flash MX 2004 publishing profile ‘default.xml’ )
3) now run with flash player beta 8!
cheers,
franky
cacheAsBitmap / Paralax Scrolling example:
——————————————————————————————-
http://www.brokenbutton.com/f8test.html
http://www.margaris.de/flash8/bitmap/cacheboth.html
http://www.margaris.de/flash8/bitmap/cacheboth120.html
bitmap drawing:
——————————————————————————————-
http://www.margaris.de/flash8/bitmap/bitmapdraw.html
bmpData = new flash.display.BitmapData(300, 300, true, 0xFF000000);
_root.attachBitmap(bmpData, 2, “auto”, true);
_root.createEmptyMovieClip(“carrier”, 1);
for (i=0; i<30; i++) {
_root.carrier.attachMovie(“identifier”, “new”+i, i);
_root.carrier["new"+i]._x = random(300);
_root.carrier["new"+i]._y = random(300);
}
bmpData.draw(_root.carrier);
_root.carrier._visible = false;
/*
var fps = 0;
this.createTextField(“tfFPS”, 1000000, 0, 0, 40, 20);
this.tfFPS.background = true;
this.onEnterFrame = function(){
fps++;
}
setInterval(function(){tfFPS.text=fps; fps=0}, 1000);
*/
skewed bitmap fills:
——————————————————————————————-
var bitmap = new flash.display.BitmapData(50, 50, false, 0xFF000000);
var mat2 = { a:1, b:0.1, c:0.1, d:1, tx:0, ty:0 };
for (x=0; x<50; x++) {
for (y=0; y<50; y++) {
bitmap.setPixel(x, y, x*256/50);
}
}
_root.createEmptyMovieClip(“bloop”, 0);
with (_root.bloop) {
beginBitmapFill(bitmap, mat2 );
moveTo(100, 100);
lineTo(300, 100);
lineTo(300, 200);
lineTo(100, 200);
endFill();
}
skewing:
——————————————————————————————-
// *** SKEWING: ***
var trans = new flash.geom.Transform(mc);
var scaleX = 1,
scaleY = 1,
skew0 = 0,
skew1 = 0,
transX = 100,
transY = 0;
trans.matrix = new flash.geom.Matrix(scaleX, skew0, skew1, scaleY, transX, transY);
more filters:
——————————————————————————————-
http://www.waterlijn.info/flash8/ColorMatrixFilter.swf
http://www.waterlijn.info/flash8/ConvolutionFilter.swf
noise:
——————————————————————————————-
var bitmap = new flash.display.BitmapData(500, 500, true, 0xFF000000);
var starter:Number = 0;
this.onEnterFrame = function() {
starter += 1;
bitmap.noise(starter);
_root.attachBitmap(bitmap, 0, “auto”, true);
};
transforms:
——————————————————————————————-
trans=new flash.geom.Transform(anyClip);
mat=new flash.geom.Matrix();
mat.rotate(0.2);
mat.translate(30,30);
trans.matrix=mat;
perlin Noise test:
——————————————————————————————-
_root.createEmptyMovieClip(“mc2″, 2);
canvas.dispose();
canvas = new flash.display.BitmapData(256, 256, true, 0xff000000);
_root.mc2.attachBitmap(canvas, 10, “auto”, true);
for (var x=0; x<50; x++)
{
for (var y=0; y<50; y++)
{
canvas.setPixel32(x, y, 0xff00ff00);
}
}
canvas.floodFill(51,51,0xffff0000);
mc2._x += 256;
canvas.perlinNoise(1000,200,3,4,5,-1); // <— parameter meaning YET unknown, sorry!
useful links:
——————————————————————————————-
http://blog.franto.com/
displacement maps:
——————————————————————————————-
http://www.flashforum.de/forum/showthread.php?t=172204&page=4
http://www.rgblaster.de/ff/f8toys4.html
http://www.kneib.biz/f8files/water_with_f8.html
map=new flash.display.BitmapData(400,400,true,0);
disp= new flash.filters.DisplacementMapFilter();
disp.mapBitmap=map;
disp.mode=”ignore”;
disp.scaleX=-40;
disp.scaleY=-40;
disp.componentX=1;
disp.componentY=1;
disp.alpha=1;
disp.mapPoint=new flash.geom.Point(0,0);
disp.color=0xFF882266;
flt= [disp];
anyClip.filters=flt;
beginBitmapFill: (source: http://www.flashforum.de/forum/showthread.php?t=172204&page=2)
——————————————————————————————-
var bitmap = new flash.display.BitmapData(50, 50, false, 0xFF000000);
for (x=0; x<50; x++) {
for (y=0; y<50; y++) {
bitmap.setPixel(x, y, x*256/50);
}
}
_root.createEmptyMovieClip(“bloop”, 0);
with (_root.bloop) {
beginBitmapFill(bitmap);
moveTo(100, 100);
lineTo(300, 100);
lineTo(300, 200);
lineTo(100, 200);
endFill();
}
lots of collected stuff also here:
——————————————————————————————-
http://osflash.org/doku.php?id=flashcoders:undocumented:flash8
Bitmap Cache:
——————————————————————————————-
try this: mc.cacheAsBitmap = true;
or : component.cacheAsBitmap = true;
eg: trace( some_mc.cacheAsBitmap ); // outputs: false by default !
online example 1: http://www.margaris.de/flash8/bitmap/bitmapcache.html
online example 2: http://www.potapenko.com/tmp/test_8_flash.html
this also rocks: draw movieclips into your bitmap:
——————————————————————————————-
bmpData.draw(_root.irgendeinClip);
flash 8 && ASNative function lists:
——————————————————————————————-
compare this:
flash WIN 7,0,19,0 — 1, 2, 3, 4, 5, 9, 10, 11, 12, 100, 101, 102, 103, 104, 105, 106, 107, 110, 111, 112, 113, 200, 250, 251, 252, 253, 300, 301, 302, 303, 304, 400, 500, 600, 666, 667, 700, 800, 900, 901, 1066, 1067, 1999, 2100, 2101, 2102, 2104, 2106, 2107, 2200, 2201, 2341,
vs:
flash 8 — 1, 2, 3, 4, 5, 9, 11, 12, 13, 14, 100, 101, 102, 103, 104, 105, 106, 107, 110, 111, 112, 113, 200, 250, 251, 252, 253, 300, 301, 400, 500, 600, 666, 667, 700, 800, 900, 901, 1066, 1067, 1100, 1101, 1102, 1103, 1105, 1106, 1107, 1108, 1109, 1110, 1111, 1112, 1999, 2100, 2101, 2102, 2104, 2106, 2107, 2150, 2151, 2198, 2200, 2201, 2202, 2204, 2205,
for(var i:Number=1; i<3000; i++)
{
if(typeof(ASnative(i, 0)) == “function”)
{
txtNative.text += i + “, “;
}
}
file Upload example:
——————————————————————————————-
var fileRef = new flash.net.FileReference();
btBrowse.onRelease = function () {
if (fileRef.browse()) {
txtInfo.text = “File Name:” + fileRef.name;
}
};
view online: http://flash-ripper.com/experiments/browse-for-file/
setPixel EXAMPLE:
——————————————————————————————-
stop();
var bitmap = new flash.display.BitmapData(256,256, true, 0xFF000000);
bitmap.setPixel(5, 5, 0xff0000);
_root.attachBitmap( bitmap, 10, “auto”, true);
view online: www.develotec.com/setpixel.html
download: www.develotec.com/setpixel.fla
some infos on setPixel && bitmaps: (german)
——————————————————————————————-
http://www.flashforum.de/forum/archive/index.php/t-171925.html
——————————————————————————————-
tracing the flash.* object:
——————————————————————————————-
for (var i in flash) {
msg_txt.text += “\nflash.” + i + ” = ” + flash[i] + “\n”;
for (var j in flash[i]) {
msg_txt.text += ” ” + j + ” = ” + flash[i][j] + ” : “;
var obj = new flash[i][j];
for (var k in obj) {
msg_txt.text += k + “, “;
}
msg_txt.text += “\n”;
}
}
——————————————————————————————-
gives following results:
——————————————————————————————-
flash.external = [object Object]
ExternalInterface = [type Function] :
flash.net = [object Object]
FileReferenceList = [type Function] : _listeners, fileList,
FileReference = [type Function] : _listeners, creator, creationDate, modificationDate, size, type, name,
flash.geom = [object Object]
Transform = [type Function] :
ColorTransform = [type Function] : toString, concat, rgb, blueOffset, greenOffset, redOffset, alphaOffset, blueMultiplier, greenMultiplier, redMultiplier, alphaMultiplier,
Matrix = [type Function] : toString, transformPoint, deltaTransformPoint, scale, translate, rotate, identity, clone, createGradientBox, createBox, invert, concat, tx, ty, b, c, a, d,
Point = [type Function] : toString, normalize, add, subtract, equals, offset, clone, length, x, y,
Rectangle = [type Function] : toString, equals, union, intersects, intersection, containsRectangle, containsPoint, contains, offsetPoint, offset, inflatePoint, inflate, size, bottomRight, topLeft, bottom, top, right, left, isEmpty, setEmpty, clone, x, y, width, height,
flash.filters = [object Object]
DisplacementMapFilter = [type Function] : clone, alpha, color, mode, scaleY, scaleX, componentY, componentX, mapPoint, mapBitmap,
ColorMatrixFilter = [type Function] : clone, matrix,
ConvolutionFilter = [type Function] : clone, alpha, color, clamp, preserveAlpha, bias, divisor, matrix, matrixY, matrixX,
GradientBevelFilter = [type Function] : clone, type, knockout, strength, quality, blurY, blurX, ratios, alphas, colors, angle, distance,
GradientGlowFilter = [type Function] : clone, type, knockout, strength, quality, blurY, blurX, ratios, alphas, colors, angle, distance,
BevelFilter = [type Function] : clone, type, blurY, blurX, knockout, strength, quality, shadowAlpha, shadowColor, highlightAlpha, highlightColor, angle, distance,
GlowFilter = [type Function] : clone, strength, blurY, blurX, knockout, inner, quality, alpha, color,
BlurFilter = [type Function] : clone, quality, blurY, blurX,
DropShadowFilter = [type Function] : clone, hideObject, strength, blurY, blurX, knockout, inner, quality, alpha, color, angle, distance,
BitmapFilter = [type Function] : clone,
flash.display = [object Object]
BitmapData = [type Function] :
flash.text = [object Object]
TextRenderer = [type Function] :
you can find an even more detailed list here: http://www.franto.com/blog2/new-features-in-maelstrom-8ball
——————————————————————————————-
FILTER EXAMPLE (yet untested by myself with fp8 beta!):
(coming from http://www.martijndevisser.com/archives/000033.php)
var filterObj = new flash.filters.DropShadowFilter();
filterObj.blury = undefined;
filterObj.blurx = undefined;
filterObj.knockout = false;
filterObj.inner = false;
filterObj.numIterations = 2;
filterObj.blur = 44;
filterObj.alpha = 100;
filterObj.color = 0×00000000;
filterObj.angle = 36;
filterObj.distance = 11;
loaderClip.filterList = [filterObj];
——————————————————————————————-
FULL NEW FILTER EXAMPLE OVER HERE:
——————————————————————————————-
DOWNLOAD: http://www.luminicbox.com/dev/flash/flash8/flash8.zip
HINT:
——
DONT FORGET TO RUN THE FLASH 8 PATCH TOOL BEFORE TESTING RE-COMPILED SWF’s, OTHERWISE
THE NEW FEATURES WONT BE WORKING!!! (use my tool here: http://www.develotec.com/fto8.exe !!)
full post:
http://www.luminicbox.com/blog/default.aspx?page=post&id=49
——————————————————————————————-
FULL API: (source: http://script.com.ua/dev/materials.php?id=11)
——————————————————————————————-
// decoded by MSA [15.07.2005]
function MovieClip(){}
function XMLSocket(){}
function AsBroadcaster(){}
function Color(target){
this.target = target;
ASSetPropFlags(this, null, 7);
}
function NetConnection(){
this.isConnected = false;
ASSetPropFlags(this, null, 7);
ASnative(2100, 200)(this);
}
function NetStream(connection){
function OnCreate(nStream){
this.nStream = nStream;
}
ASnative(2101, 200)(this, connection);
var _l2 = OnCreate.prototype;
_l2.onResult = function (streamId){
ASnative(2101, 201)(this.nStream, streamId);
};
streamId.onStatus = function (info){
this.nStream.onStatus(info);
};
connection.call(“createStream”, new OnCreate(this));
}
function Camera(){}
function Microphone(){}
function SharedObject(){}
function LocalConnection(){}
function ContextMenuItem(capt, cb, sepBefore, enab, vis){
this.caption = capt;
this.onSelect = cb;
this.separatorBefore = sepBefore == undefined ? (false) : (sepBefore);
this.enabled = enab == undefined ? (true) : (enab);
this.visible = vis == undefined ? (true) : (vis);
}
function ContextMenu(cb){
this.onSelect = cb;
this.builtInItems = {save: true, zoom: true, quality: true, play: true, loop: true, rewind: true, forward_back: true, print: true};
this.customItems = new Array();
}
function Error(m){
if (typeof(m) != “undefined”) {
this.message = m;
}
}
function AsSetupError(s) {
var _l6 = s.split(“,”);
var _l3 = 0;
while (_l3 < _l6.length){
var _l4 = _l6[_l3];
var _l5 = function (m)
{
this.message = m;
};
var _l2 = new Error();
_l5.prototype = _l2;
_l2.name = _l4;
_l2.message = _l4;
++_l3;
}
}
function RemoteLSOUsage(){}
ASSetPropFlags = ASnative(1, 0);
ASSetNative = ASnative(4, 0);
ASSetNativeAccessor = ASnative(4, 1);
escape = ASnative(100, 0);
unescape = ASnative(100, 1);
parseInt = ASnative(100, 2);
parseFloat = ASnative(100, 3);
trace = ASnative(100, 4);
updateAfterEvent = ASnative(9, 0);
isNaN = ASnative(200, 18);
isFinite = ASnative(200, 19);
setInterval = ASnative(250, 0);
clearInterval = clearTimeout = ASnative(250, 1);
setTimeout = ASnative(250, 2);
showRedrawRegions = ASnative(1021, 1);
var o = Object.prototype;
ASSetNative(o, 101, “6watch,6unwatch,6addProperty,valueOf,toString,6hasOwnProperty,6isPrototypeOf,6isPropertyEnumerable”);
o.toLocaleString = function (){
return (this.toString());
};
Object.registerClass = ASnative(101, 8);
ASSetPropFlags(o, null, 3);
ASSetPropFlags(Object, null, 7);
var o = Function.prototype;
ASSetNative(o, 101, “6call,6apply”, 10);
ASSetPropFlags(o, null, 3);
Number = ASconstructor(106, 2);
var o = Number.prototype;
ASSetNative(o, 106, “valueOf,toString”);
ASSetPropFlags(o, null, 3);
var o = Number;
o.NaN = NaN;
o.POSITIVE_INFINITY = Infinity;
o.NEGATIVE_INFINITY = -Infinity;
o.MIN_VALUE = 0;
o.MAX_VALUE = Number.MAX_VALUE;
ASSetPropFlags(o, null, 7);
Boolean = ASconstructor(107, 2);
var o = Boolean.prototype;
ASSetNative(o, 107, “valueOf,toString”);
ASSetPropFlags(o, null, 3);
Date = ASconstructor(103, 256);
var o = Date.prototype;
ASSetNative(o, 103,
“getFullYear,getYear,getMonth,getDate,getDay,getHours,getMinutes,getSeconds,getMilliseconds,setFullYear,setMonth,setDate,setHours,setMinutes,setSeconds,setMilliseconds,getTime,setTime,getTimezoneOffset,toString,setYear”);
ASSetNative(o, 103,
“getUTCFullYear,getUTCYear,getUTCMonth,getUTCDate,getUTCDay,getUTCHours,getUTCMinutes,getUTCSeconds,getUTCMilliseconds,setUTCFullYear,setUTCMonth,setUTCDate,setUTCHours,setUTCMinutes,setUTCSeconds,setUTCMilliseconds”,
128);
o.valueOf = o.getTime;
Date.UTC = ASnative(103, 257);
ASSetPropFlags(o, null, 3);
ASSetPropFlags(Date, null, 7);
String = ASconstructor(251, 0);
var o = String.prototype;
ASSetNative(o, 251, “valueOf,toString,toUpperCase,toLowerCase,charAt,charCodeAt,concat,indexOf,lastIndexOf,slice,substring,split,substr”, 1);
String.fromCharCode = ASnative(251, 14);
ASSetPropFlags(o, null, 3);
ASSetPropFlags(String, null, 3);
Array = ASconstructor(252, 0);
var o = Array.prototype;
ASSetNative(o, 252, “push,pop,concat,shift,unshift,slice,join,splice,toString,sort,reverse,sortOn”, 1);
ASSetPropFlags(o, null, 3);
var o = Array;
o.CASEINSENSITIVE = 1;
o.DESCENDING = 2;
o.UNIQUESORT = 4;
o.RETURNINDEXEDARRAY = 8;
o.NUMERIC = 16;
Math = {E: 2.718282, LN10: 2.302585, LN2: 0.693147, LOG10E: 0.434294, LOG2E: 1.442695, PI: 3.141593, SQRT1_2: 0.707107, SQRT2: 1.414214};
ASSetNative(Math, 200, “abs,min,max,sin,cos,atan2,tan,exp,log,sqrt,round,random,floor,ceil,atan,asin,acos,pow”);
ASSetPropFlags(Math, null, 7);
Sound = ASconstructor(500, 16);
var o = Sound.prototype;
ASSetNative(o, 500,
“getPan,getTransform,getVolume,setPan,setTransform,setVolume,stop,attachSound,start,6getDuration,6setDuration,6getPosition,6setPosition,6loadSound,6getBytesLoaded,6getBytesTotal”);
ASSetPropFlags(o, null, 7);
var o = MovieClip;
o.BlendModeType = {};
o.BlendModeType.NORMAL = “normal”;
o.BlendModeType.LAYER = “layer”;
o.BlendModeType.MULTIPLY = “multiply”;
o.BlendModeType.SCREEN = “screen”;
o.BlendModeType.LIGHTEN = “lighten”;
o.BlendModeType.DARKEN = “darken”;
o.BlendModeType.DIFFERENCE = “difference”;
o.BlendModeType.ADD = “add”;
o.BlendModeType.SUBTRACT = “subtract”;
o.BlendModeType.INVERT = “invert”;
o.BlendModeType.ALPHA = “alpha”;
o.BlendModeType.INVERT = “invert”;
o.BlendModeType.OVERLAY = “overlay”;
o.BlendModeType.HARDLIGHT = “hardlight”;
ASSetPropFlag(o, “BlendModeType”, 4096);
var o = MovieClip.prototype;
o.useHandCursor = true;
o.enabled = true;
ASSetNativeAccessor(o, 900, “tabIndex”, 200);
ASSetNativeAccessor(o, 900, “_lockroot”, 300);
ASSetNativeAccessor(o, 900, “8cacheAsBitmap,8opaqueBackground,8scrollRect”, 401);
ASSetNativeAccessor(o, 900, “8filters,8transform”, 417);
ASSetNativeAccessor(o, 900, “8blendMode”, 500);
ASSetNativeAccessor(o, 901, “8scale9Grid”, 12);
o.meth = function (method){
var _l1 = method.toLowerCase();
if (_l1 == “get”) {
return (1);
} else if (_l1 == “post”) {
return (2);
}
return (0);
};
o.getURL = function (url, window, method) {
if (typeof(window) == “undefined”) {
var _l2 = “”;
}
var _l3 = this.meth(method);
tellTarget(this._target) {
if (_l3 == 0) {
getURL(url, _l2);
} else if (_l3 == 1) {
getURL(url, _l2, “GET”);
} else {
getURL(url, _l2, “POST”);
}
}
};
o.unloadMovie = function () {
unloadMovie(this._target);
};
o.loadVariables = function (url, method) {
var _l3 = this.meth(method);
tellTarget(this._target) {
if (_l3 == 0) {
loadVariables(url, _target);
} else if (_l3 == 1) {
loadVariables(url, _target, “GET”);
} else {
loadVariables(url, _target, “POST”);
}
}
};
o.loadMovie = function (url, method) {
var _l3 = this.meth(method);
tellTarget(this._target) {
if (_l3 == 0) {
loadMovie(url, _target);
} else if (_l3 == 1) {
loadMovie(url, _target, “GET”);
} else {
loadMovie(url, _target, “POST”);
}
}
};
ASSetNative(o, 900,
“attachMovie,swapDepths,localToGlobal,globalToLocal,hitTest,getBounds,getBytesTotal,getBytesLoaded,6attachAudio,6attachVideo,6getDepth,6setMask,play,stop,nextFrame,prevFrame,gotoAndPlay,gotoAndStop,duplicateMovieClip,removeMovieClip,startDrag,stopDrag,7getNextHighestDepth,7getInstanceAtDepth,getSWFVersion,8attachBitmap,8getRect”);
ASSetNative(o, 901,
“6createEmptyMovieClip,6beginFill,6beginGradientFill,6moveTo,6lineTo,6curveTo,6lineStyle,6endFill,6clear,8lineGradientStyle,8beginMeshFill,8beginBitmapFill”);
o.createTextField = ASnative(104, 200);
ASSetPropFlags(o, null, 3);
XMLNode = ASconstructor(253, 0);
var o = XMLNode.prototype;
ASSetNative(o, 253, “cloneNode,removeNode,insertBefore,appendChild,hasChildNodes,toString,getNamespaceForPrefix,getPrefixForNamespace”, 1);
XML = ASconstructor(253, 9);
XML.prototype = new XMLNode(1, “”);
var o = XML.prototype;
ASSetNative(o, 253, “createElement,createTextNode,parseXML”, 10);
o.load = ASnative(301, 0);
o.send = ASnative(301, 1);
o.sendAndLoad = ASnative(301, 2);
o.onLoad = function () {};
o.onData = function (src) {
if (src == undefined) {
this.onLoad(false);
} else {
this.parseXML(src);
this.loaded = true;
this.onLoad(true);
}
};
o.getBytesLoaded = function () {
return (this._bytesLoaded);
};
o.getBytesTotal = function () {
return (this._bytesTotal);
};
o.addRequestHeader = function (key, value) {
if (typeof(this._customHeaders) == “undefined”) {
this._customHeaders = new Array();
ASSetPropFlags(this, “_customHeaders”, 131);
}
if (typeof(key) == “string” && typeof(value) == “string”) {
this._customHeaders.push(key, value);
}
else if (key instanceof Array) {
var _l2 = 0;
while (_l2 < key.length) {
if (_l2 + 1 < key.length) {
this.addRequestHeader(key[_l2], key[_l2 + 1]);
}
_l2 = _l2 + 2;
}
}
};
LoadVars = ASconstructor(253, 13);
var o = LoadVars.prototype;
ASSetNative(o, 301, “load,send,sendAndLoad,decode”);
o.getBytesLoaded = function () {
return (this._bytesLoaded);
};
o.getBytesTotal = function () {
return (this._bytesTotal);
};
o.toString = function () {
var _l2 = [];
for (var _l3 in this) {
_l2.push(escape(_l3) + “=” + escape(this[_l3]));
}
return (_l2.join(“&”));
};
o.contentType = “application/x-www-form-urlencoded”;
o.onLoad = function () {};
o.onData = function (src) {
if (src == undefined) {
this.onLoad(false);
} else {
this.decode(src);
this.loaded = true;
this.onLoad(true);
}
};
o.addRequestHeader = function (key, value) {
if (typeof(this._customHeaders) == “undefined”) {
this._customHeaders = new Array();
ASSetPropFlags(this, “_customHeaders”, 131);
}
if (typeof(key) == “string” && typeof(value) == “string”) {
this._customHeaders.push(key, value);
} else if (key instanceof Array) {
var _l2 = 0;
while (_l2 < key.length) {
if (_l2 + 1 < key.length){
this.addRequestHeader(key[_l2], key[_l2 + 1]);
}
_l2 = _l2 + 2;
}
}
};
ASSetPropFlags(o, null, 131);
var o = XMLSocket.prototype;
ASSetNative(o, 400, “connect,send,close”);
o.onData = function (src) {
this.onXML(new XML(src));
};
ASSetPropFlags(o, null, 3);
var o = AsBroadcaster;
o.broadcastMessage = ASnative(101, 12);
o.addListener = function (x) {
this.removeListener(x);
this._listeners.push(x);
return (true);
};
o.removeListener = function (x) {
var _l3 = this._listeners;
var _l2 = 0;
while (_l2 < _l3.length){
if (_l3[_l2] == x){
_l3.splice(_l2, 1);
return (true);
}
++_l2;
}
return (false);
};
o.initialize = function (o) {
o.broadcastMessage = ASnative(101, 12);
o.addListener = AsBroadcaster.addListener;
o.removeListener = AsBroadcaster.removeListener;
o._listeners = [];
ASSetPropFlags(o, “broadcastMessage,addListener,removeListener,_listeners”, 131);
};
ASSetPropFlags(o, null, 131);
Selection = {};
ASSetNative(Selection, 600, “getBeginIndex,getEndIndex,getCaretIndex,getFocus,setFocus,setSelection”);
AsBroadcaster.initialize(Selection);
ASSetPropFlags(Selection, null, 7);
var o = Color.prototype;
ASSetNative(o, 700, “setRGB,setTransform,getRGB,getTransform”);
ASSetPropFlags(o, null, 7);
Mouse = {};
ASSetNative(Mouse, 5, “show,hide”);
AsBroadcaster.initialize(Mouse);
ASSetPropFlags(Mouse, null, 7);
Key = {ALT: 18, ENTER: 13, SPACE: 32, UP: 38, DOWN: 40, LEFT: 37, RIGHT: 39, PGUP: 33, PGDN: 34, HOME: 36, END: 35, TAB: 9, CONTROL: 17, SHIFT: 16, ESCAPE:
27, INSERT: 45, DELETEKEY: 46, BACKSPACE: 8, CAPSLOCK: 20};
ASSetNative(Key, 800, “getAscii,getCode,isDown,isToggled,8isAccessible”);
AsBroadcaster.initialize(Key);
ASSetPropFlags(Key, null, 7);
Button = ASconstructor(105, 0);
var o = Button.prototype;
o.useHandCursor = true;
o.enabled = true;
o.getDepth = ASnative(105, 3);
ASSetNativeAccessor(o, 105, “8scale9Grid,8filters,8cacheAsBitmap,8blendMode”, 4);
TextField = ASconstructor(104, 0);
var o = TextField.prototype;
ASSetNative(o, 104, “6replaceSel,6getTextFormat,6setTextFormat,6removeTextField,6getNewTextFormat,6setNewTextFormat,6getDepth,7replaceText”, 100);
AsBroadcaster.initialize(o);
ASSetPropFlags(o, null, 131);
TextField.getFontList = ASnative(104, 201);
ASSetPropFlags(TextField, null, 131);
ASSetNativeAccessor(o, 104, “8gridFitType,8antiAliasType,8thickness,8sharpness,8filters”, 300);
TextField.StyleSheet = ASconstructor(113, 0);
var o = TextField.StyleSheet.prototype;
o._copy = function (o) {
if (typeof(o) != “object”) {
return (null);
}
var _l2 = {};
for (var _l3 in o) {
_l2[_l3] = o[_l3];
}
return (_l2);
};
o.getStyle = function (n) {
return (this._copy(this._css[n]));
};
o.setStyle = function (n, s) {
if (!this._css) {
this._css = {};
}
var _l2 = typeof(o);
if (_l2 == “object” || _l2 == “null” || _l2 == “undefined”) {
this._css[n] = this._copy(s);
this.doTransform(n);
this.update();
}
};
o.clear = function () {
this._css = {};
this._styles = {};
this.update();
};
o.getStyleNames = function () {
var _l2 = [];
for (var _l3 in this._css) {
_l2.push(_l3);
}
return (_l2);
};
o.doTransform = function (n) {
var _l2 = this.transform(this._css[n]);
if (!this._styles) {
this._styles = {};
}
this._styles[n] = _l2;
};
o.transform = function (o) {
if (o == null) {
return (null);
}
var _l2 = new TextFormat();
var _l4 = o.textAlign;
if (_l4) {
_l2.align = _l4;
}
_l4 = o.fontSize;
if (_l4) {
_l4 = parseInt(_l4);
if (_l4 > 0) {
_l2.size = _l4;
}
}
_l4 = o.textDecoration;
if (_l4 == “none”) {
_l2.underline = false;
}
else if (_l4 == “underline”) {
_l2.underline = true;
}
_l4 = o.marginLeft;
if (_l4) {
_l2.leftMargin = parseInt(_l4);
}
_l4 = o.marginRight;
if (_l4) {
_l2.rightMargin = parseInt(_l4);
}
_l4 = o.leading;
if (_l4) {
_l2.leading = parseInt(_l4);
}
_l4 = o.kerning;
if (_l4 == “true”) {
_l2.kerning = 1;
} else if (_l4 == “false”) {
_l2.kerning = 0;
} else {
_l2.kerning = parseInt(_l4);
}
_l4 = o.letterSpacing;
if (_l4) {
_l2.letterSpacing = parseInt(_l4);
}
_l4 = o.fontFamily;
if (_l4) {
_l2.font = this.parseCSSFontFamily(_l4);
}
_l2.display = o.display;
_l4 = o.fontWeight;
if (_l4 == “bold”) {
_l2.bold = true;
} else if (_l4 == “normal”) {
_l2.bold = false;
}
_l4 = o.fontStyle;
if (_l4 == “italic”) {
_l2.italic = true;
} else if (_l4 == “normal”) {
_l2.italic = false;
}
_l4 = o.textIndent;
if (_l4) {
_l2.indent = parseInt(_l4);
}
_l4 = o.color;
if (_l4) {
_l4 = this.parseColor(_l4);
if (_l4 != null) {
_l2.color = _l4;
}
}
return (_l2);
};
o.parseCSS = function (s) {
var _l2 = this.parseCSSInternal(s);
if (typeof(_l2) == “null”) {
return (false);
}
if (!this._css) {
this._css = {};
}
for (var _l3 in _l2) {
this._css[_l3] = this._copy(_l2[_l3]);
this.doTransform(_l3);
}
this.update();
return (true);
};
o.parse = o.parseCSS;
o.load = ASnative(301, 0);
o.onLoad = function () {};
o.onData = function (src) {
if (src == undefined) {
this.onLoad(false);
} else {
var _l2 = this.parse(src);
this.loaded = _l2;
this.onLoad(_l2);
}
};
ASSetNative(o, 113, “7update,7parseCSSInternal,7parseCSSFontFamily,7parseColor”, 100);
ASSetPropFlags(o, null, 1027);
ASSetPropFlags(TextField, “StyleSheet”, 1027);
TextFormat = ASconstructor(110, 0);
Stage = {width: 0, height: 0, scaleMode: 0, align: “”};
ASSetNativeAccessor(Stage, 666, “scaleMode,align,width,height,showMenu”, 1);
AsBroadcaster.initialize(Stage);
Video = ASconstructor(667, 0);
var o = Video.prototype;
ASSetNative(o, 667, “6attachVideo,6clear”, 1);
ASSetPropFlags(o, null, 3);
Accessibility = {};
ASSetNative(Accessibility, 1999, “6isActive,6sendEvent,6updateProperties”);
ASSetPropFlags(Accessibility, null, 6);
var o = NetConnection.prototype;
ASSetNative(o, 2100, “6connect,6close,6call,6addHeader”);
ASSetPropFlags(o, null, 3);
var o = NetStream.prototype;
o.publish = function (name, type) {
var _l3 = args.length;
if (_l3 == 1) {
ASnative(2101, 202)(this, “publish”, null, name);
} else {
ASnative(2101, 202)(this, “publish”, null, name, type);
}
};
o.play = function (name, start, len, reset) {
var _l3 = args.length;
if (_l3 == 1) {
ASnative(2101, 202)(this, “play”, null, name);
} else if (_l3 == 2) {
ASnative(2101, 202)(this, “play”, null, name, start * 1000);
} else if (_l3 == 3) {
ASnative(2101, 202)(this, “play”, null, name, start * 1000, len * 1000);
} else {
ASnative(2101, 202)(this, “play”, null, name, start * 1000, len * 1000, reset);
}
};
o.receiveAudio = function (flag) {
ASnative(2101, 202)(this, “receiveAudio”, null, flag);
};
o.receiveVideo = function (flag) {
ASnative(2101, 202)(this, “receiveVideo”, null, flag);
};
o.pause = function (flag) {
ASnative(2101, 202)(this, “pause”, null, flag, this.time * 1000);
};
o.seek = function (offset) {
ASnative(2101, 202)(this, “seek”, null, offset * 1000);
};
ASSetNative(o, 2101, “6close,6attachAudio,6attachVideo,6send,6setBufferTime”);
ASSetPropFlags(o, null, 3);
Camera.get = function (index) {
return (ASnative(2102, 200)(index));
};
Camera.addProperty(“names”, ASnative(2102, 201), null);
var o = Camera.prototype;
ASSetNative(o, 2102, “6setMode,6setQuality,6setKeyFrameInterval,6setMotionLevel,6setLoopback,6setCursor”);
ASSetPropFlags(o, null, 3);
Microphone.get = function (index) {
return (ASnative(2104, 200)(index));
};
Microphone.addProperty(“names”, ASnative(2104, 201), null);
var o = Microphone.prototype;
ASSetNative(o, 2104, “6setSilenceLevel,6setRate,6setGain,6setUseEchoSuppression”);
ASSetPropFlags(o, null, 3);
SharedObject.getLocal = function (name, localPath, secure) {
var _l1 = ASnative(2106, 202)(name, localPath, secure);
if (!_l1) {
_l1 = new SharedObject();
if (!ASnative(2106, 204)(_l1, name, localPath, secure)) {
return (null);
}
}
return (_l1);
};
SharedObject.getRemote = function (name, remotePath, options, secure){
var _l1 = ASnative(2106, 203)(name, remotePath, options, secure);
if (!_l1) {
_l1 = new SharedObject();
if (!ASnative(2106, 205)(_l1, name, remotePath, options, secure)) {
return (null);
}
}
return (_l1);
};
SharedObject.deleteAll = function (url) {
return (ASnative(2106, 206)(url));
};
SharedObject.getDiskUsage = function (url) {
return (ASnative(2106, 207)(url));
};
ASSetPropFlags(SharedObject, “deleteAll,getDiskUsage”, 1);
var o = SharedObject.prototype;
ASSetNative(o, 2106, “6connect,6send,6flush,6close,6getSize,6setFps,6clear”);
ASSetPropFlags(o, null, 3);
System = {};
System.capabilities = {hasAudio: true, hasMP3: true, hasAudio: true, hasMP3: true, hasAudioEncoder: true, hasVideoEncoder: true, screenResolutionX: 800,
screenResolutionY: 600, screenDPI: 72, screenColor: “color”, pixelAspectRatio: 1, hasAccessibility: true, Query: ASnative(11, 0)};
System.capabilities.Query();
delete System.capabilities.Query;
System.Product = function (strName) {
this.name = strName;
ASSetPropFlags(this, null, 7);
};
var o = System.Product.prototype;
o.isRunning = function () {
return (ASnative(2201, 0)(this.name));
};
o.isInstalled = function () {
return (ASnative(2201, 1)(this.name));
};
o.launch = function () {
return (ASnative(2201, 2)(this.name));
};
o.download = function () {
if (args.length > 0) {
return (ASnative(2201, 3)(this, this.name, args[0]));
} else {
return (ASnative(2201, 3)(this, this.name));
}
};
o.installedVersion = function () {
return (ASnative(2201, 4)(this.name));
};
ASSetPropFlags(o, null, 3);
System.showSettings = ASnative(2107, 0);
ASSetNativeAccessor(System, 2107, “exactSettings”, 1);
ASSetPropFlags(System, “exactSettings”, 128);
flash = {};
ASSetPropFlags(_global, “flash”, 4096);
flash.text = {};
flash.text.TextRenderer = ASconstructor(2150, 0);
var textRenderer = flash.text.TextRenderer;
textRenderer.AntiAliasType = {};
textRenderer.AntiAliasType.NORMAL = “normal”;
textRenderer.AntiAliasType.ADVANCED = “advanced”;
textRenderer.AntiAliasType.GLOBAL_ADVANCED_ANTIALIASING_OFF = “off”;
textRenderer.AntiAliasType.GLOBAL_ADVANCED_ANTIALIASING_ON = “on”;
textRenderer.AntiAliasType.GLOBAL_ADVANCED_ANTIALIASING_TEXTFIELD_CONTROL = “default”;
textRenderer.GridFitType = {};
textRenderer.GridFitType.NONE = “none”;
textRenderer.GridFitType.PIXEL = “pixel”;
textRenderer.GridFitType.SUBPIXEL = “subpixel”;
textRenderer.ColorType = {};
textRenderer.ColorType.DARK = “dark”;
textRenderer.ColorType.LIGHT = “light”;
textRenderer.FontStyle = {};
textRenderer.FontStyle.NONE = “none”;
textRenderer.FontStyle.BOLD = “bold”;
textRenderer.FontStyle.ITALIC = “italic”;
textRenderer.FontStyle.BOLDITALIC = “bolditalic”;
ASSetNative(textRenderer, 2150, “8setAdvancedAntialiasingTable”, 1);
ASSetNativeAccessor(textRenderer, 2150, “8antiAliasType,8maxLevel”, 2);
var o = new Object();
System.security = o;
ASSetNative(o, 12, “allowDomain,7allowInsecureDomain,loadPolicyFile,chooseLocalSwfPath,escapeDomain”);
System.setClipboard = ASnative(1066, 0);
System.IME = {ALPHANUMERIC_FULL: “ALPHANUMERIC_FULL”, ALPHANUMERIC_HALF: “ALPHANUMERIC_HALF”, CHINESE: “CHINESE”, JAPANESE_HIRAGANA: “JAPANESE_HIRAGANA”,
JAPANESE_KATAKANA_FULL: “JAPANESE_KATAKANA_FULL”, JAPANESE_KATAKANA_HALF: “JAPANESE_KATAKANA_HALF”, KOREAN: “KOREAN”, UNKNOWN: “UNKNOWN”};
ASSetNative(System.IME, 13, “8getEnabled,8setEnabled,8getConversionMode,8setConversionMode,8setCompositionString,8doConversion”);
AsBroadcaster.initialize(System.IME);
ASSetPropFlags(System.IME, null, 7);
var o = LocalConnection.prototype;
ASSetNative(o, 2200, “6connect,6send,6close,6domain”);
ASSetPropFlags(o, null, 3);
var o = ContextMenuItem.prototype;
o.copy = function () {
var _l2 = new ContextMenuItem();
_l2.caption = this.caption;
_l2.onSelect = this.onSelect;
_l2.separatorBefore = this.separatorBefore;
_l2.enabled = this.enabled;
_l2.visible = this.visible;
return (_l2);
};
ASSetPropFlags(o, null, 1027);
var o = ContextMenu.prototype;
o.copy = function () {
var _l3 = new ContextMenu();
_l3.onSelect = this.onSelect;
_l3.builtInItems = this.builtInItems;
_l3.customItems = new Array();
var _l2 = 0;
while (_l2 < this.customItems.length) {
_l3.customItems.push(this.customItems[_l2].copy());
++_l2;
}
return (_l3);
};
o.hideBuiltInItems = function () {
this.builtInItems = {save: false, zoom: false, quality: false, play: false, loop: false, rewind: false, forward_back: false, print: false};
};
ASSetPropFlags(o, null, 1027);
var o = Error.prototype;
o.name = o.message = “Error”;
o.toString = function () {
return (this.message);
};
AsSetupError(“EvalError,ReferenceError,SyntaxError,TypeError,URIError”);
MovieClipLoader = ASconstructor(112, 0);
var o = MovieClipLoader.prototype;
ASSetNative(o, 112, “7loadClip,7getProgress,7unloadClip”, 100);
AsBroadcaster.initialize(o);
ASSetPropFlags(o, null, 1027);
PrintJob = ASconstructor(111, 0);
var o = PrintJob.prototype;
ASSetNative(o, 111, “7start,7addPage,7send”, 100);
ASSetPropFlags(o, null, 1027);
TextSnapshot = ASconstructor(1067, 0);
MovieClip.prototype.getTextSnapshot = function () {
return (new TextSnapshot(this));
};
ASSetPropFlags(MovieClip.prototype, “getTextSnapshot”, 131);
ASSetNative(TextSnapshot.prototype, 1067,
“6getCount,6setSelected,6getSelected,6getText,6getSelectedText,6hitTestTextNearPos,6findText,6setSelectColor,6getTextRunInfo”, 1);
flash.display = {};
flash.display.BitmapData = ASconstructor(1100, 0);
var o = flash.display.BitmapData;
o.Channel = {};
o.Channel.RED = 1;
o.Channel.GREEN = 2;
o.Channel.BLUE = 4;
o.Channel.ALPHA = 8;
ASSetNative(o, 1100, “8loadBitmap”, 40);
var o = flash.display.BitmapData.prototype;
ASSetNativeAccessor(o, 1100, “8width,8height,8rectangle,8transparent”, 100);
ASSetNative(o, 1100,
“8getPixel,8setPixel,8fillRect,8copyPixels,8applyFilter,8scroll,8threshold,8draw,8pixelDissolve,8getPixel32,8setPixel32,8floodFill,8getColorBoundsRect,8perlinNoise,8colorTransform,8hitTest,8paletteMap,8merge,8noise,8copyChannel,8clone,8dispose,8generateFilterRect”,
1);
flash.filters = {};
var o = flash.filters.BitmapFilter = ASconstructor(1112, 0);
o.Quality = {};
o.Quality.LOW = 1;
o.Quality.MEDIUM = 2;
o.Quality.HIGH = 3;
o.Type = {};
o.Type.INNER = “inner”;
o.Type.OUTER = “outer”;
o.Type.FULL = “full”;
ASSetNative(o.prototype, 1112, “8clone”, 1);
flash.filters.DropShadowFilter = ASconstructor(1101, 0);
flash.filters.DropShadowFilter.prototype = o = new flash.filters.BitmapFilter();
ASSetNativeAccessor(o, 1101, “8distance,8angle,8color,8alpha,8quality,8inner,8knockout,8blurX,8blurY,8strength,8hideObject”, 1);
flash.filters.BlurFilter = ASconstructor(1102, 0);
flash.filters.BlurFilter.prototype = o = new flash.filters.BitmapFilter();
ASSetNativeAccessor(o, 1102, “8blurX,8blurY,8quality”, 1);
flash.filters.GlowFilter = ASconstructor(1103, 0);
flash.filters.GlowFilter.prototype = o = new flash.filters.BitmapFilter();
ASSetNativeAccessor(o, 1103, “8color,8alpha,8quality,8inner,8knockout,8blurX,8blurY,8strength”, 1);
flash.filters.BevelFilter = ASconstructor(1107, 0);
flash.filters.BevelFilter.prototype = o = new flash.filters.BitmapFilter();
ASSetNativeAccessor(o, 1107, “8distance,8angle,8highlightColor,8highlightAlpha,8shadowColor,8shadowAlpha,8quality,8strength,8knockout,8blurX,8blurY,8type”,
1);
flash.filters.GradientGlowFilter = ASconstructor(1108, 0);
flash.filters.GradientGlowFilter.prototype = o = new flash.filters.BitmapFilter();
ASSetNativeAccessor(o, 1108, “8distance,8angle,8colors,8alphas,8ratios,8blurX,8blurY,8quality,8strength,8knockout,8type”, 1);
flash.filters.GradientBevelFilter = ASconstructor(1108, 1000);
flash.filters.GradientBevelFilter.prototype = o = new flash.filters.BitmapFilter();
ASSetNativeAccessor(o, 1108, “8distance,8angle,8colors,8alphas,8ratios,8blurX,8blurY,8quality,8strength,8knockout,8type”, 1);
flash.filters.ConvolutionFilter = ASconstructor(1109, 0);
flash.filters.ConvolutionFilter.prototype = o = new flash.filters.BitmapFilter();
ASSetNativeAccessor(o, 1109, “8matrixX,8matrixY,8matrix,8divisor,8bias,8preserveAlpha,8clamp,8color,8alpha”, 1);
flash.filters.ColorMatrixFilter = ASconstructor(1110, 0);
flash.filters.ColorMatrixFilter.prototype = o = new flash.filters.BitmapFilter();
ASSetNativeAccessor(o, 1110, “8matrix”, 1);
var o = flash.filters.DisplacementMapFilter = ASconstructor(1111, 0);
o.Mode = {};
o.Mode.WRAP = “wrap”;
o.Mode.CLAMP = “clamp”;
o.Mode.IGNORE = “ignore”;
o.Mode.COLOR = “color”;
flash.filters.DisplacementMapFilter.prototype = o = new flash.filters.BitmapFilter();
ASSetNativeAccessor(o, 1111, “8mapBitmap,8mapPoint,8componentX,8componentY,8scaleX,8scaleY,8mode,8color,8alpha”, 1);
flash.geom = {};
flash.geom.Rectangle = function (p1, p2, p3, p4) {
var _l3 = args.length;
if (!_l3) {
this.setEmpty();
} else {
this.x = p1;
this.y = p2;
this.width = p3;
this.height = p4;
} // end if
};
var o = flash.geom.Rectangle.prototype;
o.clone = function () {
return (new flash.geom.Rectangle(this.x, this.y, this.width, this.height));
};
o.setEmpty = function () {
this.x = this.y = this.width = this.height = 0;
};
o.isEmpty = function () {
return (this.width <= 0 || this.height <= 0);
};
o.addProperty(“left”, function () {
return (this.x);
}, function (newx) {
this.width = this.width + (this.x – newx);
this.x = newx;
});
o.addProperty(“right”, function () {
return (this.x + this.width);
}, function (newr) {
this.width = newr – this.x;
});
o.addProperty(“top”, function () {
return (this.y);
}, function (newy) {
this.height = this.height + (this.y – newy);
this.y = newy;
});
o.addProperty(“bottom”, function () {
return (this.y + this.height);
}, function (newb) {
this.height = newb – this.y;
});
o.addProperty(“topLeft”, function () {
return (new flash.geom.Point(this.x, this.y));
}, function (value) {
this.width = this.width + (this.x – value.x);
this.height = this.height + (this.y – value.y);
this.x = value.x;
this.y = value.y;
});
o.addProperty(“bottomRight”, function () {
return (new flash.geom.Point(this.x + this.width, this.y + this.height));
}, function (value) {
this.width = value.x – this.x;
this.height = value.y – this.y;
});
o.addProperty(“size”, function () {
return (new flash.geom.Point(this.width, this.height));
}, function (value) {
this.width = value.x;
this.height = value.y;
});
o.inflate = function (dx, dy) {
this.x = this.x – dx;
this.width = this.width + 2 * dx;
this.y = this.y – dy;
this.height = this.height + 2 * dy;
};
o.inflatePoint = function (pt) {
this.x = this.x – pt.x;
this.width = this.width + 2 * pt.x;
this.y = this.y – pt.y;
this.height = this.height + 2 * pt.y;
};
o.offset = function (dx, dy) {
this.x = this.x + dx;
this.y = this.y + dy;
};
o.offsetPoint = function (pt) {
this.x = this.x + pt.x;
this.y = this.y + pt.y;
};
o.contains = function (x, y) {
return (this.x <= x && this.x + this.width > x && this.y <= y && this.y + this.height > y);
};
o.containsPoint = function (pt) {
return (pt.x >= this.x && pt.x < this.x + this.width && pt.y >= this.y && pt.y < this.y + this.height);
};
o.containsRectangle = function (rect) {
var _l4 = rect.x + rect.width;
var _l6 = rect.y + rect.height;
var _l3 = this.x + this.width;
var _l5 = this.y + this.height;
return (rect.x >= this.x && rect.x < _l3 && rect.y >= this.y && rect.y < _l5 && _l4 > this.x && _l4 <= _l3 && _l6 > this.y && _l6 <= _l5);
};
o.intersection = function (toIntersect) {
var _l2 = new flash.geom.Rectangle();
if (this.isEmpty() || toIntersect.isEmpty()) {
_l2.setEmpty();
return (_l2);
}
_l2.x = Math.max(this.x, toIntersect.x);
_l2.y = Math.max(this.y, toIntersect.y);
_l2.width = Math.min(this.x + this.width, toIntersect.x + toIntersect.width) – _l2.x;
_l2.height = Math.min(this.y + this.height, toIntersect.y + toIntersect.height) – _l2.y;
if (_l2.width <= 0 || _l2.height <= 0) {
_l2.setEmpty();
}
return (_l2);
};
o.intersects = function (toIntersect) {
return (!this.intersection(toIntersect).isEmpty());
};
o.union = function (toUnion) {
if (this.isEmpty()) {
return (toUnion.clone());
} else if (toUnion.isEmpty()) {
return (this.clone());
} else {
var _l2 = new flash.geom.Rectangle();
_l2.x = Math.min(this.x, toUnion.x);
_l2.y = Math.min(this.y, toUnion.y);
_l2.width = Math.max(this.x + this.width, toUnion.x + toUnion.width) – _l2.x;
_l2.height = Math.max(this.y + this.height, toUnion.y + toUnion.height) – _l2.y;
return (_l2);
}
};
o.equals = function (toCompare) {
return (toCompare instanceof flash.geom.Rectangle && toCompare.x == this.x && toCompare.y == this.y && toCompare.width == this.width &&
toCompare.height == this.height);
};
o.toString = function () {
return (“(x=” + this.x + “, y=” + this.y + “, w=” + this.width + “, h=” + this.height + “)”);
};
flash.geom.Point = function (p1, p2) {
var _l3 = args.length;
if (!_l3) {
this.x = this.y = 0;
} else {
this.x = p1;
this.y = p2;
}
};
var o = flash.geom.Point;
o.distance = function (pt1, pt2) {
return (pt1.subtract(pt2).length);
};
o.polar = function (len, angle) {
return (new flash.geom.Point(len * Math.cos(angle), len * Math.sin(angle)));
};
o.interpolate = function (pt1, pt2, f) {
return (new flash.geom.Point(pt2.x + f * (pt1.x – pt2.x), pt2.y + f * (pt1.y – pt2.y)));
};
var o = flash.geom.Point.prototype;
o.addProperty(“length”, function () {
return (Math.sqrt(this.x * this.x + this.y * this.y));
}, function (newlen) {});
o.clone = function () {
return (new flash.geom.Point(this.x, this.y));
};
o.offset = function (dx, dy) {
this.x = this.x + dx;
this.y = this.y + dy;
};
o.equals = function (toCompare) {
return (toCompare instanceof flash.geom.Point && toCompare.x == this.x && toCompare.y == this.y);
};
o.subtract = function (v) {
return (new flash.geom.Point(this.x – v.x, this.y – v.y));
};
o.add = function (v) {
return (new flash.geom.Point(this.x + v.x, this.y + v.y));
};
o.normalize = function (thickness) {
var _l2 = this.length;
if (_l2 > 0) {
_l2 = thickness / _l2;
this.x = this.x * _l2;
this.y = this.y * _l2;
}
};
o.toString = function () {
return (“(x=” + this.x + “, y=” + this.y + “)”);
};
flash.geom.Matrix = function (pa, pb, pc, pd, ptx, pty) {
var _l3 = args.length;
if (!_l3) {
this.identity();
} else {
this.a = pa;
this.b = pb;
this.c = pc;
this.d = pd;
this.tx = ptx;
this.ty = pty;
}
};
var o = flash.geom.Matrix.prototype;
o.concat = function (m) {
var _l4;
var _l3;
var _l7;
var _l5;
var _l8;
var _l6;
result_a = this.a * m.a;
result_d = this.d * m.d;
result_b = result_c = 0;
result_tx = this.tx * m.a + m.tx;
result_ty = this.ty * m.d + m.ty;
if (this.b != 0 || this.c != 0 || m.b != 0 || m.c != 0) {
result_a = result_a + this.b * m.c;
result_d = result_d + this.c * m.b;
result_b = result_b + (this.a * m.b + this.b * m.d);
result_c = result_c + (this.c * m.a + this.d * m.c);
result_tx = result_tx + this.ty * m.c;
result_ty = result_ty + this.tx * m.b;
}
this.a = result_a;
this.b = result_b;
this.c = result_c;
this.d = result_d;
this.tx = result_tx;
this.ty = result_ty;
};
o.invert = function () {
if (this.b == 0 && this.c == 0) {
this.a = 1 / this.a;
this.d = 1 / this.d;
this.b = this.c = 0;
this.tx = -this.a * this.tx;
this.ty = -this.d * this.ty;
} else {
var _l6;
var _l5;
var _l4;
var _l3;
var _l7;
a0 = this.a;
a1 = this.b;
a2 = this.c;
a3 = this.d;
det = a0 * a3 – a1 * a2;
if (det == 0) {
this.identity();
return (undefined);
}
det = 1 / det;
this.a = a3 * det;
this.b = -a1 * det;
this.c = -a2 * det;
this.d = a0 * det;
var _l2 = this.deltaTransformPoint(new flash.geom.Point(this.tx, this.ty));
this.tx = -_l2.x;
this.ty = -_l2.y;
}
};
o.createBox = function (scaleX, scaleY, rotation, x, y) {
var _l3 = args.length;
var _l6 = 0;
if (_l3 > 2) {
_l6 = rotation;
}
var _l5 = 0;
if (_l3 > 3) {
_l5 = x;
}
var _l4 = 0;
if (_l3 > 4) {
_l4 = y;
}
this.identity();
this.rotate(rotation);
this.scale(scaleX, scaleY);
this.tx = _l5;
this.ty = _l4;
};
o.createGradientBox = function (width, height, rotation, x, y) {
var _l3 = args.length;
var _l6 = 0;
if (_l3 > 2) {
_l6 = rotation;
}
var _l5 = 0;
if (_l3 > 3) {
_l5 = x;
}
var _l4 = 0;
if (_l3 > 4) {
_l4 = y;
}
this.createBox(width / 1638.400000, height / 1638.400000, _l6, _l5 + width / 2, _l4 + height / 2);
};
o.clone = function () {
return (new flash.geom.Matrix(this.a, this.b, this.c, this.d, this.tx, this.ty));
};
o.identity = function () {
this.a = this.d = 1;
this.b = this.c = 0;
this.tx = this.ty = 0;
};
o.rotate = function (radians) {
var _l3 = Math.cos(radians);
var _l2 = Math.sin(radians);
var _l4 = new flash.geom.Matrix(_l3, _l2, -_l2, _l3, 0, 0);
this.concat(_l4);
};
o.translate = function (dx, dy) {
this.tx = this.tx + dx;
this.ty = this.ty + dy;
};
o.scale = function (sx, sy) {
var _l2 = new flash.geom.Matrix(sx, 0, 0, sy, 0, 0);
this.concat(_l2);
};
o.deltaTransformPoint = function (pt) {
return (new flash.geom.Point(this.a * pt.x + this.c * pt.y, this.d * pt.y + this.b * pt.x));
};
o.transformPoint = function (pt) {
return (new flash.geom.Point(this.a * pt.x + this.c * pt.y + this.tx, this.d * pt.y + this.b * pt.x + this.ty));
};
o.toString = function () {
return (“(a=” + this.a + “, b=” + this.b + “, c=” + this.c + “, d=” + this.d + “, tx=” + this.tx + “, ty=” + this.ty + “)”);
};
flash.geom.ColorTransform = ASconstructor(1105, 0);
var o = flash.geom.ColorTransform.prototype;
ASSetNativeAccessor(o, 1105, “8alphaMultiplier,8redMultiplier,8greenMultiplier,8blueMultiplier,8alphaOffset,8redOffset,8greenOffset,8blueOffset,8rgb”, 101);
ASSetNative(o, 1105, “8concat”, 1);
o.toString = function () {
return (“(redMultiplier=” + this.redMultiplier + “, greenMultiplier=” + this.greenMultiplier + “, blueMultiplier=” + this.blueMultiplier + “,
alphaMultiplier=” + this.alphaMultiplier + “, redOffset=” + this.redOffset + “, greenOffset=” + this.greenOffset + “, blueOffset=” + this.blueOffset + “,
alphaOffset=” + this.alphaOffset + “)”);
};
flash.geom.Transform = ASconstructor(1106, 0);
ASSetNativeAccessor(flash.geom.Transform.prototype, 1106, “8matrix,8concatenatedMatrix,8colorTransform,8concatenatedColorTransform,8pixelBounds”, 101);
RemoteLSOUsage.getURLPageSupport = function () {
return (ASnative(2198, 101)());
};
ASSetPropFlags(RemoteLSOUsage, “getURLPageSupport”, 1);
flash.net = {};
flash.net.FileReference = function () {
ASnative(2204, 200)(this);
this._listeners = [];
};
var o = flash.net.FileReference.prototype;
AsBroadcaster.initialize(o);
ASSetNative(o, 2204, “8browse,8upload,8download,8cancel”);
ASSetPropFlags(o, null, 3);
flash.net.FileReferenceList = function () {
this.fileList = new Array();
this._listeners = [];
};
var o = flash.net.FileReferenceList.prototype;
AsBroadcaster.initialize(o);
ASSetNative(o, 2205, “8browse”);
ASSetPropFlags(o, null, 3);
flash.external = {};
flash.external.ExternalInterface = function () {};
ASSetNative(flash.external.ExternalInterface, 14, “8_initJS,8_objectID,8_addCallback,8_evalJS,8_callOut,8_escapeXML,8_unescapeXML,8_jsQuoteString”);
ASSetNativeAccessor(flash.external.ExternalInterface, 14, “8available”, 100);
flash.external.ExternalInterface.addCallback = function (functionName, instance, method) {
if (method && flash.external.ExternalInterface.available) {
flash.external.ExternalInterface._initJS();
var _l3 = function (request) {
return (flash.external.ExternalInterface._callIn(instance, method, request));
};
var _l1 = flash.external.ExternalInterface._addCallback(functionName, _l3);
if (_l1) {
var _l2 = flash.external.ExternalInterface._objectID();
if (_l2 != null) {
flash.external.ExternalInterface._evalJS(“__flash__addCallback(” + _l2 + “, \”" + functionName + “\”);”);
}
}
return (_l1);
} else {
return (false);
}
};
flash.external.ExternalInterface.call = function (functionName) {
if (flash.external.ExternalInterface.available) {
flash.external.ExternalInterface._initJS();
var _l3 = “try { “;
var _l4 = flash.external.ExternalInterface._objectID();
if (_l4 != null) {
_l3 = _l3 + (_l4 + “.SetReturnValue(“);
} // end if
_l3 = _l3 + (“__flash__toXML(” + functionName + “(“);
var _l2 = 1;
while (_l2 < args.length) {
if (_l2 != 1) {
_l3 = _l3 + “,”;
}
_l3 = _l3 + flash.external.ExternalInterface._toJS(args[_l2]);
++_l2;
}
_l3 = _l3 + “)) “;
if (_l4 != null) {
_l3 = _l3 + “)”;
}
_l3 = _l3 + “; } catch (e) { “;
if (_l4 != null) {
_l3 = _l3 + (_l4 + “.SetReturnValue(\”<undefined/>\”);”);
} else {
_l3 = _l3 + “\”<undefined/>\”;”;
}
_l3 = _l3 + ” }”;
var _l5 = flash.external.ExternalInterface._evalJS(_l3);
if (_l5 == null) {
var _l7 = “<invoke name=\”" + functionName + “\” returntype=\”xml\”>” + flash.external.ExternalInterface._argumentsToXML(args) + “</invoke>”;
_l5 = flash.external.ExternalInterface._callOut(_l7);
}
if (_l5 == null) {
return (null);
} else {
var _l6 = new XML();
_l6.ignoreWhite = true;
_l6.parseXML(_l5);
return (flash.external.ExternalInterface._toAS(_l6.firstChild));
}
} else {
return (null);
}
};
flash.external.ExternalInterface._callIn = function (instance, method, request) {
var _l2 = new XML();
_l2.ignoreWhite = true;
_l2.parseXML(request);
var _l3 = null;
var _l1 = 0;
while (_l1 < _l2.firstChild.childNodes.length) {
if (_l2.firstChild.childNodes[_l1].nodeName == “arguments”) {
_l3 = _l2.firstChild.childNodes[_l1];
break;
}
++_l1;
}
var _l4 = method.apply(instance, flash.external.ExternalInterface._argumentsToAS(_l3));
return (_l2.firstChild.attributes.returntype == “javascript” ? (flash.external.ExternalInterface._toJS(_l4)) :
(flash.external.ExternalInterface._toXML(_l4)));
};
flash.external.ExternalInterface._arrayToXML = function (obj) {
var _l3 = “<array>”;
var _l1 = 0;
while (_l1 < obj.length) {
_l3 = _l3 + (“<property id=\”" + _l1 + “\”>” + flash.external.ExternalInterface._toXML(obj[_l1]) + “</property>”);
++_l1;
}
return (_l3 + “</array>”);
};
flash.external.ExternalInterface._argumentsToXML = function (obj) {
var _l3 = “<arguments>”;
var _l1 = 1;
while (_l1 < obj.length) {
_l3 = _l3 + flash.external.ExternalInterface._toXML(obj[_l1]);
++_l1;
}
return (_l3 + “</arguments>”);
};
flash.external.ExternalInterface._objectToXML = function (obj) {
var _l2 = “<object>”;
for (var _l3 in obj) {
_l2 = _l2 + (“<property id=\”" + _l3 + “\”>” + flash.external.ExternalInterface._toXML(obj[_l3]) + “</property>”);
}
return (_l2 + “</object>”);
};
flash.external.ExternalInterface._toXML = function (value) {
var _l2 = typeof(value);
if (_l2 == “string”) {
return (“<string>” + flash.external.ExternalInterface._escapeXML(value) + “</string>”);
} else if (_l2 == “undefined”) {
return (“<undefined/>”);
} else if (_l2 == “number”) {
return (“<number>” + value + “</number>”);
} else if (value == null) {
return (“<null/>”);
} else if (_l2 == “boolean”) {
return (value ? (“<true/>”) : (“<false/>”));
} else if (value.hasOwnProperty(“length”)) {
return (flash.external.ExternalInterface._arrayToXML(value));
} else if (_l2 == “object”) {
return (flash.external.ExternalInterface._objectToXML(value));
} else {
return (“<null/>”);
}
};
flash.external.ExternalInterface._objectToAS = function (obj) {
var _l3 = {};
var _l1 = 0;
while (_l1 < obj.childNodes.length) {
if (obj.childNodes[_l1].nodeName == “property”) {
_l3[obj.childNodes[_l1].attributes.id] = flash.external.ExternalInterface._toAS(obj.childNodes[_l1].firstChild);
}
++_l1;
}
return (_l3);
};
flash.external.ExternalInterface._arrayToAS = function (obj) {
var _l3 = [];
var _l1 = 0;
while (_l1 < obj.childNodes.length) {
_l3[obj.childNodes[_l1].attributes.id] = flash.external.ExternalInterface._toAS(obj.childNodes[_l1].firstChild);
++_l1;
}
return (_l3);
};
flash.external.ExternalInterface._toAS = function (obj) {
var type = obj.nodeName;
if (type == “number”) {
return (Number(obj.firstChild.toString()));
} else if (type == “string”) {
return (flash.external.ExternalInterface._unescapeXML(String(obj.firstChild)));
} else if (type == “false”) {
return (false);
} else if (type == “true”) {
return (true);
} else if (type == “null”) {
return (null);
} else if (type == “undefined”) {
return (undefined);
} else if (type == “object”) {
return (flash.external.ExternalInterface._objectToAS(obj));
} else if (type == “array”) {
return (flash.external.ExternalInterface._arrayToAS(obj));
} else if (type == “class”) {
return (String(obj.firstChild));
} else {
return (undefined);
}
};
flash.external.ExternalInterface._argumentsToAS = function (obj) {
var _l3 = [];
var _l1 = 0;
while (_l1 < obj.childNodes.length) {
_l3.push(flash.external.ExternalInterface._toAS(obj.childNodes[_l1]));
++_l1;
}
return (_l3);
};
flash.external.ExternalInterface._arrayToJS = function (value) {
var _l2 = “[";
var _l1 = 0;
while (_l1 < value.length) {
if (_l1 != 0) {
_l2 = _l2 + ",";
}
_l2 = _l2 + flash.external.ExternalInterface._toJS(value[_l1]);
++_l1;
}
return (_l2 + “]”);
};
flash.external.ExternalInterface._objectToJS = function (value) {
var _l1 = “({“;
var _l2 = true;
for (var _l4 in value) {
if (!_l2) {
_l1 = _l1 + “,”;
}
_l2 = false;
_l1 = _l1 + (_l4 + “:” + flash.external.ExternalInterface._toJS(value[_l4]));
}
return (_l1 + “})”);
};
flash.external.ExternalInterface._toJS = function (value) {
if (typeof(value) == “string”) {
return (“\”" + flash.external.ExternalInterface._jsQuoteString(flash.external.ExternalInterface._unescapeXML(value)) + “\”");
} else if (typeof(value) == “object”) {
if (value instanceof Array) {
return (flash.external.ExternalInterface._arrayToJS(value));
} else {
return (flash.external.ExternalInterface._objectToJS(value));
}
} else {
return (String(value));
}
};
ASSetPropFlags(flash.external.ExternalInterface, null, 4103);
var o = null;
——————————————————————————————-
some more infos are here:
http://www.5etdemi.com/blog/archives/2005/07/fp8-two-days-after-the-geeks-are-at-it-again/
——————————————————————————————-
Vienna, 14.07.2005
Following is the COM interface overview from flash player 8 beta (WIN 8,0,0,434)
As you can see, there are promising new functions like ‘CallFunction’ and ‘SetReturnValue’!
We’re already excited about all the other new features we’ve heard about, if you have
found out anything concerning new flash 8 features, don’t hesitate to contact us via
flash8@develotec.com !
Meanwhile, Lots of Fun with Flash Player 8!
Frank Baumgartner, office@develotec.com
——————————————————————————————-
[
uuid(D27CDB6C-AE6D-11CF-96B8-444553540000),
helpstring("Shockwave Flash"),
dual
]
dispinterface IShockwaveFlash {
properties:
methods:
[id(0xfffffdf3), propget, helpstring("property ReadyState")]
long ReadyState();
[id(0x0000007c), propget, helpstring("property TotalFrames")]
long TotalFrames();
[id(0x0000007d), propget, helpstring("property Playing")]
VARIANT_BOOL Playing();
[id(0x0000007d), propput, helpstring("property Playing")]
void Playing([in] VARIANT_BOOL rhs);
[id(0x00000069), propget, helpstring("property Quality")]
int Quality();
[id(0x00000069), propput, helpstring("property Quality")]
void Quality([in] int rhs);
[id(0x00000078), propget, helpstring("property ScaleMode")]
int ScaleMode();
[id(0x00000078), propput, helpstring("property ScaleMode")]
void ScaleMode([in] int rhs);
[id(0x00000079), propget, helpstring("property AlignMode")]
int AlignMode();
[id(0x00000079), propput, helpstring("property AlignMode")]
void AlignMode([in] int rhs);
[id(0x0000007b), propget, helpstring("property BackgroundColor")]
long BackgroundColor();
[id(0x0000007b), propput, helpstring("property BackgroundColor")]
void BackgroundColor([in] long rhs);
[id(0x0000006a), propget, helpstring("property Loop")]
VARIANT_BOOL Loop();
[id(0x0000006a), propput, helpstring("property Loop")]
void Loop([in] VARIANT_BOOL rhs);
[id(0x00000066), propget, helpstring("property Movie")]
BSTR Movie();
[id(0x00000066), propput, helpstring("property Movie")]
void Movie([in] BSTR rhs);
[id(0x0000006b), propget, helpstring("property FrameNum")]
long FrameNum();
[id(0x0000006b), propput, helpstring("property FrameNum")]
void FrameNum([in] long rhs);
[id(0x0000006d), helpstring("method SetZoomRect")]
void SetZoomRect(
[in] long left,
[in] long top,
[in] long right,
[in] long bottom);
[id(0x00000076), helpstring("method Zoom")]
void Zoom([in] int factor);
[id(0x00000077), helpstring("method Pan")]
void Pan(
[in] long x,
[in] long y,
[in] int mode);
[id(0x00000070), helpstring("method Play")]
void Play();
[id(0x00000071), helpstring("method Stop")]
void Stop();
[id(0x00000072), helpstring("method Back")]
void Back();
[id(0x00000073), helpstring("method Forward")]
void Forward();
[id(0x00000074), helpstring("method Rewind")]
void Rewind();
[id(0x0000007e), helpstring("method StopPlay")]
void StopPlay();
[id(0x0000007f), helpstring("method GotoFrame")]
void GotoFrame([in] long FrameNum);
[id(0x00000080), helpstring("method CurrentFrame")]
long CurrentFrame();
[id(0x00000081), helpstring("method IsPlaying")]
VARIANT_BOOL IsPlaying();
[id(0x00000082), helpstring("method PercentLoaded")]
long PercentLoaded();
[id(0x00000083), helpstring("method FrameLoaded")]
VARIANT_BOOL FrameLoaded([in] long FrameNum);
[id(0x00000084), helpstring("method FlashVersion")]
long FlashVersion();
[id(0x00000085), propget, helpstring("property WMode")]
BSTR WMode();
[id(0x00000085), propput, helpstring("property WMode")]
void WMode([in] BSTR rhs);
[id(0x00000086), propget, helpstring("property SAlign")]
BSTR SAlign();
[id(0x00000086), propput, helpstring("property SAlign")]
void SAlign([in] BSTR rhs);
[id(0x00000087), propget, helpstring("property Menu")]
VARIANT_BOOL Menu();
[id(0x00000087), propput, helpstring("property Menu")]
void Menu([in] VARIANT_BOOL rhs);
[id(0x00000088), propget, helpstring("property Base")]
BSTR Base();
[id(0x00000088), propput, helpstring("property Base")]
void Base([in] BSTR rhs);
[id(0x00000089), propget, helpstring("property Scale")]
BSTR Scale();
[id(0x00000089), propput, helpstring("property Scale")]
void Scale([in] BSTR rhs);
[id(0x0000008a), propget, helpstring("property DeviceFont")]
VARIANT_BOOL DeviceFont();
[id(0x0000008a), propput, helpstring("property DeviceFont")]
void DeviceFont([in] VARIANT_BOOL rhs);
[id(0x0000008b), propget, helpstring("property EmbedMovie")]
VARIANT_BOOL EmbedMovie();
[id(0x0000008b), propput, helpstring("property EmbedMovie")]
void EmbedMovie([in] VARIANT_BOOL rhs);
[id(0x0000008c), propget, helpstring("property BGColor")]
BSTR BGColor();
[id(0x0000008c), propput, helpstring("property BGColor")]
void BGColor([in] BSTR rhs);
[id(0x0000008d), propget, helpstring("property Quality2")]
BSTR Quality2();
[id(0x0000008d), propput, helpstring("property Quality2")]
void Quality2([in] BSTR rhs);
[id(0x0000008e), helpstring("method LoadMovie")]
void LoadMovie(
[in] int layer,
[in] BSTR url);
[id(0x0000008f), helpstring("method TGotoFrame")]
void TGotoFrame(
[in] BSTR target,
[in] long FrameNum);
[id(0x00000090), helpstring("method TGotoLabel")]
void TGotoLabel(
[in] BSTR target,
[in] BSTR label);
[id(0x00000091), helpstring("method TCurrentFrame")]
long TCurrentFrame([in] BSTR target);
[id(0x00000092), helpstring("method TCurrentLabel")]
BSTR TCurrentLabel([in] BSTR target);
[id(0x00000093), helpstring("method TPlay")]
void TPlay([in] BSTR target);
[id(0x00000094), helpstring("method TStopPlay")]
void TStopPlay([in] BSTR target);
[id(0x00000097), helpstring("method SetVariable")]
void SetVariable(
[in] BSTR name,
[in] BSTR value);
[id(0x00000098), helpstring("method GetVariable")]
BSTR GetVariable([in] BSTR name);
[id(0x00000099), helpstring("method TSetProperty")]
void TSetProperty(
[in] BSTR target,
[in] int property,
[in] BSTR value);
[id(0x0000009a), helpstring("method TGetProperty")]
BSTR TGetProperty(
[in] BSTR target,
[in] int property);
[id(0x0000009b), helpstring("method TCallFrame")]
void TCallFrame(
[in] BSTR target,
[in] int FrameNum);
[id(0x0000009c), helpstring("method TCallLabel")]
void TCallLabel(
[in] BSTR target,
[in] BSTR label);
[id(0x0000009d), helpstring("method TSetPropertyNum")]
void TSetPropertyNum(
[in] BSTR target,
[in] int property,
[in] double value);
[id(0x0000009e), helpstring("method TGetPropertyNum")]
double TGetPropertyNum(
[in] BSTR target,
[in] int property);
[id(0x000000ac), helpstring("method TGetPropertyAsNumber")]
double TGetPropertyAsNumber(
[in] BSTR target,
[in] int property);
[id(0x0000009f), propget, helpstring("property SWRemote")]
BSTR SWRemote();
[id(0x0000009f), propput, helpstring("property SWRemote")]
void SWRemote([in] BSTR rhs);
[id(0x000000aa), propget, helpstring("property FlashVars")]
BSTR FlashVars();
[id(0x000000aa), propput, helpstring("property FlashVars")]
void FlashVars([in] BSTR rhs);
[id(0x000000ab), propget, helpstring("property AllowScriptAccess")]
BSTR AllowScriptAccess();
[id(0x000000ab), propput, helpstring("property AllowScriptAccess")]
void AllowScriptAccess([in] BSTR rhs);
[id(0x000000be), propget, helpstring("property MovieData")]
BSTR MovieData();
[id(0x000000be), propput, helpstring("property MovieData")]
void MovieData([in] BSTR rhs);
[id(0x000000bf), propget, helpstring("property inline-data")]
IUnknown* InlineData();
[id(0x000000bf), propput, helpstring("property inline-data")]
void InlineData([in] IUnknown* rhs);
[id(0x000000c0), propget, helpstring("property SeamlessTabbing")]
VARIANT_BOOL SeamlessTabbing();
[id(0x000000c0), propput, helpstring("property SeamlessTabbing")]
void SeamlessTabbing([in] VARIANT_BOOL rhs);
[id(0x000000c1), helpstring("method EnforceLocalSecurity")]
void EnforceLocalSecurity();
[id(0x000000c2), propget, helpstring("property Profile")]
VARIANT_BOOL Profile();
[id(0x000000c2), propput, helpstring("property Profile")]
void Profile([in] VARIANT_BOOL rhs);
[id(0x000000c3), propget, helpstring("property ProfileAddress")]
BSTR ProfileAddress();
[id(0x000000c3), propput, helpstring("property ProfileAddress")]
void ProfileAddress([in] BSTR rhs);
[id(0x000000c4), propget, helpstring("property ProfilePort")]
long ProfilePort();
[id(0x000000c4), propput, helpstring("property ProfilePort")]
void ProfilePort([in] long rhs);
[id(0x000000c6), helpstring("method Call")]
BSTR CallFunction([in] BSTR request);
[id(0x000000c7), helpstring("method SetReturnValue")]
void SetReturnValue([in] BSTR returnValue);
};
[个人备份]数据结构算法集—C++语言实现
数据结构算法集—C++语言实现
阅读:120 发表时间:2005-5-13 21:29:02 来源:转载 作者:ihualan
本文关键字:数据结构算法集—C++语言实现|C++语言,C++语言基础|
这是我学数据结构编写的算法,我把他整理出来,都是基本算法,供大家学习。我使用c++面向对象形式编写,各种算法都封装在各自的类里,如果想增加功能,在相应的类里增加函数即可。我对树和图的构造也做了一些人性化设计,输入更加形象化,你可能看不懂,没关系漫漫来。各种类都使用模版设计,可以对各种数据类型操作(整形,字符,浮点)
///////////////////////////
// //
// 堆栈数据结构 stack.h //
// //
//////////////////////////
#include<iostream.h>
template<class Type>class Stack;
template<class Type>
class StackNode
{
friend class Stack<Type>;
private:
Type data;
StackNode<Type> *link;
StackNode(Type D=0,StackNode<Type> *L=NULL):link(L),data(D){}
};
template<class Type>
class Stack
{
public:
Stack():top(NULL),NumItem(0){}
void Push(Type item);
Type Pop();
Type GetTop();
void MakeEmpty();
bool ISEmpty();
int GetNum();
private:
int NumItem;
StackNode<Type> *top;
};
template<class Type>
void Stack<Type>::Push(Type item)
{
top=new StackNode<Type>(item,top);
NumItem++;
}
template<class Type>
Type Stack<Type>::Pop()
{
StackNode<Type> *p;
Type temp;
temp=top->data;
p=top;
top=top->link;
delete p;
NumItem–;
return temp;
}
template<class Type>
Type Stack<Type>::GetTop()
{
return top->data;
}
template<class Type>
bool Stack<Type>::ISEmpty()
{
return top==NULL;
}
template<class Type>
void Stack<Type>::MakeEmpty()
{
delete top;
}
template<class Type>
int Stack<Type>::GetNum()
{
return NumItem;
}
///////////////////////////
// //
// 队列数据结构 Queue.h //
// //
//////////////////////////
#include<iostream.h>
template<class Type> class Queue;
template<class Type> class QueueNode
{
friend class Queue<Type>;
private:
Type data;
QueueNode<Type> *link;
QueueNode(Type d=0,QueueNode *l=NULL):data(d),link(l){}
};
template <class Type> class Queue
{
public:
Queue():rear(NULL),front(NULL){}
~Queue();
void EnQueue(Type item);
Type DelQueue();
Type GetFront();
void MakeEmpty();
bool ISEmpty() { return front==NULL; }
private:
QueueNode<Type> *front,*rear;
};
template<class Type>
Queue<Type>::~Queue()
{
QueueNode<Type> *p;
while(front!=NULL)
{
p=front;
front=front->link;
delete p;
}
}
template<class Type>
void Queue<Type>::EnQueue(Type item)
{
if(front==NULL)
front=rear=new QueueNode<Type> (item,NULL);
else
rear=rear->link=new QueueNode<Type> (item,NULL);
}
template<class Type>
Type Queue<Type>::DelQueue()
{
QueueNode<Type> *p=front;
Type temp=p->data;;
front=front->link;
delete p;
return temp;
}
template<class Type>
Type Queue<Type>::GetFront()
{
return front->data;
}
template<class Type>
void Queue<Type>::MakeEmpty()
{
QueueNode<Type> *p;
while(front!=NULL)
{
p=front;
front=front->link;
delete p;
}
}
///////////////////////////
// //
// 链表数据结构 list.h //
// //
//////////////////////////
#include<iostream.h>
template<class type>
class list;
template<class type>
class listnode
{
public:
friend class list<type>;
private:
type data;
listnode<type> * next;
};
template<class type>
class list
{
public:
list();
~list();
void insertend(type); //向链表尾部插入元素
bool insert(type,int); //向链表任意位置插入元素
void delnode(int i); //删除元素
int find(type T); //查找元素
void makeempty(); //销毁链表
bool print(); //打印链表
int getlen(); //得到链表长度
private:
listnode<type> *first,*last;
int length;
};
template<class type>
void initlist(type &tmp);
template<class type>
void list_exit(list<type> &L,type tmp);
void initation();
template<class type>
void list_insertend(list<type> &L,type tmp);
template<class type> int list<type>::getlen()
{
return length;
}
template<class type> void list<type>::makeempty()
{
listnode<type> *p1,*p2;
p1=first->next;
first->next=NULL;
while(p1!=NULL)
{
p2=p1;
p1=p1->next;
delete p2;
}
length=0;
}
template<class type> void list<type>::insertend(type t)
{
listnode<type> *p;
p=new listnode<type>;
p->data=t;
p->next=NULL;
last->next=p;
last=p;
length++;
}
template<class type> bool list<type>::insert(type t,int i)
{
listnode<type> *p;
p=first;
int k=1;
while(p!=NULL&&k<i)
{
p=p->next;
k++;
}
if(p==NULL&&k!=i)
return false;
else
{
listnode<type> *tp;
tp=new listnode<type>;
tp->data=t;
tp->next=p->next;
p->next=tp;
length++;
return true;
}
}
template<class type> void list<type>::delnode(int i)
{
int k=1;
listnode<type> *p,*t;
p=first;
while(p->next!=NULL&&k!=i)
{
p=p->next;
k++;
}
t=p->next;
cout<<”你已经将数据项 “<<t->data<<”删除”<<endl;
p->next=p->next->next;
length–;
delete t;
}
template<class type> bool list<type>::print()
{
listnode<type> *p=first->next;
if(length==0)
return false;
else
{
cout<<”链表中有”<<length<<”项数据: “<<endl;
while(p)
{
cout<<p->data<<” “;
p=p->next;
}
}
cout<<endl;
return true;
}
template<class type> int list<type>::find(type T)
{
listnode<type> *p=first->next;
int i=1;
while(p&&p->data!=T)
{
p=p->next;
i++;
}
if(p)
return i;
else
return 0;
}
template<class type> list<type>::~list()
{
delete first;
cout<<”欢迎再次使用 (!^!) “<<endl;
}
template<class type> list<type>::list()
{
listnode<type> *node=new listnode<type>;
node->next=NULL;
first=last=node;
length=0;
}
///////////////////////////
// //
// 图数据结构 graph.h //
// //
//////////////////////////
#include<iostream.h>
#include”Queue.h”
template<class NameType,class DisType>class Graph;
template<class NameType,class DisType> struct Node
{
friend class Graph<NameType,DisType>;
int num;
DisType val;
Node<NameType,DisType> *next;
};
template<class NameType,class DisType> struct GpNode
{
friend class Graph<NameType,DisType>;
NameType data;
Node<NameType,DisType> *link;
};
template<class NameType,class DisType>
class Graph
{
public:
void Creat(); //创建图
void PrintNode(); //打印图中的各个数据项
void DFS(); //图的深度优先搜索,主过程
void DFS(int v,int visited[]); // 子过程
void BFS(); //图的广度优先搜索,主过程
void BFS(int v,int visited[]); //子过程
void ShortPath(); //求最短路径
private:
GpNode<NameType,DisType> *table;
Node<NameType,DisType> *p;
int NumNode; //节点个数
};
template<class NameType,class DisType>
void Graph<NameType,DisType>::Creat()
{
do
{
cout<<”请输入节点个数: “;
cin >> NumNode;
}while(NumNode<=0);
table=new GpNode<NameType,DisType>[NumNode];
cout<<”请输入各节点数据项”<<endl;
for(int i=0;i<NumNode;i++)
{
cin>>table[i].data;
table[i].link=NULL;
}
cout<<”请输入各边的关系 (如: A B)”<<endl;
i=1;
NameType nodeA,nodeB;
bool findA,findB;
char ISExit;
int m,n;
do
{
findA=findB=false;
cout<<”请输入第”<<i<<”对边的关系”<<endl;
cin>>nodeA>>nodeB;
for(m=0,n=0;m<NumNode&&n<NumNode&&!(findA & findB);) //查找边的节点
{
if(nodeA!=table[m].data)
m++;
else
findA=true;
if(nodeB!=table[n].data)
n++;
else
findB=true;
}
if(!(findA & findB))
cout<<”输入的节点数据项有错误”<<endl;
else
{
p=new Node<NameType,DisType>;
p->next=table[m].link;
p->num=n;
table[m].link=p;
cout<<”请输入该对边的权值: “;
cin>>p->val;
i++;
}
cout<<”是否继续输入: y)继续,X)任意键退出 “;
cin>>ISExit;
if(ISExit!=’y'&&ISExit!=’Y')
break;
}while(true);
}
template<class NameType,class DisType>
void Graph<NameType,DisType>::PrintNode()
{
cout<<”图中各节点数据项 : “;
for(int i=0;i<NumNode;i++)
cout<<table[i].data<<” “;
cout<<endl;
}
template<class NameType,class DisType>
void Graph<NameType,DisType>::DFS()
{
int *visited=new int[NumNode];
cout<<”图的深度优先搜索 : “;
for(int i=0;i<NumNode;i++)
visited[i]=0;
for(i=1;i<NumNode;i++) //遍厉孤立节点
DFS(i,visited);
delete []visited;
cout<<endl;
}
template<class NameType,class DisType>
void Graph<NameType,DisType>::DFS(int v,int visited[])
{
Node<NameType,DisType> *t;
if(visited[v]==0)
cout<<table[v].data<<” “;
visited[v]=1;
t=table[v].link;
while(t!=NULL)
{
if(visited[t->num]==0)
DFS(t->num,visited);
t=t->next;
}
}
template<class NameType,class DisType>
void Graph<NameType,DisType>::BFS()
{
int *visited=new int[NumNode];
cout<<”图的广度优先搜索 : “;
for(int i=0;i<NumNode;i++)
visited[i]=0;
for( i=0;i<NumNode;i++)
BFS(i,visited);
}
template<class NameType,class DisType>
void Graph<NameType,DisType>::BFS(int v,int visited[])
{
Queue<int> q;
int n;
if(visited[v]==0)
{
visited[v]=1;
cout<<table[v].data<<” “;
q.EnQueue(v);
while(!q.ISEmpty())
{
n=q.DelQueue();
p=table[n].link;
while(p!=NULL)
{
n=p->num;
if(visited[n]==0)
{
cout<<table[n].data<<” “;
visited[n]=1;
}
p=p->next;
}
}
}
}
///////////////////////////
// //
// 排序算法数据结构 Compositor.h //
// //
//////////////////////////
#include<iostream.h>
template<class Type>
class Compositor
{
public:
Compositor():sort(NULL){}
void Creat(); //创建排序数组
void Bubble(); //冒泡排序
void Insert(); //插入排序
//快速排序
void Quick();
void QSort(int,int);
int Partition(int low,int high);
//归并排序
void Merge(Type SR[],Type TR[],int i,int m,int n);
void Msort(Type SR[],Type TR1[],int s,int t);
void MergeSort();
//选择排序
void Select();
void Print(); //打印排序后的结果
protected:
Type *sort;
int leng;
};
template<class Type>
void Compositor<Type>::Creat()
{
cout<<”输入你需要排序的数据个数: “;
cin>>leng;
while(leng<=0)
{
cout<<”输入数据有误”;
cin>>leng;
}
sort=new Type[leng];
cout<<”请输入各数据项:”;
for(int i=0;i<leng;i++)
cin>>sort[i];
}
template<class Type>
void Compositor<Type>::Insert()
{
Creat();
Type temp;
for(int i=1;i<leng;i++)
{
if(sort[i]<sort[i-1])
{
temp=sort[i];
for(int j=i-1;temp<sort[j]&&j>=0;j–)
{
sort[j+1]=sort[j];
}
sort[j+1]=temp;
}
}
Print();
}
template<class Type>
void Compositor<Type>::Bubble()
{
Creat();
Type temp;
for(int i=leng-1;i>=0;i–)
{
for(int j=0;j<leng-1;j++)
{
if(sort[j]>sort[j+1])
{
temp=sort[j];
sort[j]=sort[j+1];
sort[j+1]=temp;
}
}
}
Print();
}
template<class Type>
void Compositor<Type>::Quick()
{
Creat();
QSort(0,leng-1);
Print();
}
template<class Type>
void Compositor<Type>::QSort(int s,int t)
{
if(s<t-1)
{
int pivotloc=Partition(s,t);
QSort(s,pivotloc-1);
QSort(pivotloc+1,t);
}
}
template<class Type>
int Compositor<Type>::Partition(int low,int high)
{
Type pivotkey=sort[low];
while(low < high)
{
while(low<high&&sort[high]>=pivotkey)
–high;
sort[low++]=sort[high];
while(low<high&&sort[low]<=pivotkey)
++low;
sort[high--]=sort[low];
}
sort[low]=pivotkey;
return low;
}
template<class Type>
void Compositor<Type>::MergeSort()
{
Creat();
Msort(sort,sort,0,leng-1);
Print();
}
template<class Type>
void Compositor<Type>::Msort(Type SR[],Type TR1[],int s,int t)
{
int m;
Type *TR2=new Type[t-s];
if(s==t) TR1[s]=SR[s];
else
{
m=(t+s)/2;
Msort(SR,TR2,s,m);
Msort(SR,TR2,m+1,t);
Merge(TR2,TR1,s,m,t);
}
}
template<class Type>
void Compositor<Type>::Merge(Type SR[],Type TR[],int i,int m,int n)
{
for(int j=m+1,k=i;i<=m&&j<=n;k++)
{
if(SR[i]<=SR[j])
TR[k]=SR[i++];
else
TR[k]=SR[j++];
}
while(i<=m)
TR[k++]=SR[i++];
while(j<=n)
TR[k++]=SR[j++];
}
template<class Type>
void Compositor<Type>::Select()
{
Creat();
Type temp;
int t;
for(int i=0;i<leng;i++)
{
t=i;
for(int j=i+1;j<leng;j++)
{
if(sort[t]>sort[j])
t=j;
}
if(t!=i)
{
temp=sort[t];
sort[t]=sort[i];
sort[i]=temp;
}
}
Print();
}
template<class Type>
void Compositor<Type>::Print()
{
cout<<”排序结果为: “;
for(int i=0;i<leng;i++)
cout<<sort[i]<<” “;
cout<<endl;
}
///////////////////////////
// //
// 二叉树数据结构 BinTree.h //
// //
//////////////////////////
#include<iostream.h>
template<class Type>class BinTree;
template<class Type>
class TreeNode
{
protected:
friend class BinTree<Type>;
TreeNode():lchild(NULL),rchild(NULL){}
Type data;
TreeNode *lchild; //左,右子树
TreeNode *rchild;
};
template<class Type>
class BinTree
{
friend void BinTree_PRE(BinTree<Type>& BinTreeOPP); //友元函数
friend void BinTree_INO(BinTree<Type>& BinTreeOPP);
friend void BinTree_POS(BinTree<Type>& BinTreeOPP);
friend void BinTree_Destroy(BinTree<Type>& BinTreeOPP);
public:
BinTree():root(NULL){}
void CreatTree(); //创建二叉树,主过程
void CreatTree(TreeNode<Type>* child,int k); //子过程
void PreTree(TreeNode<Type> *point); //先序遍历二叉树
void InoTree(TreeNode<Type> *point); //中序遍历二叉树
void PosTree(TreeNode<Type> *point); //后序遍历二叉树
void Destroy(TreeNode<Type> *point); //销毁二叉树
bool ISEmpty();
protected:
TreeNode<Type>* root;
};
template<class Type>
void BinTree<Type>::CreatTree()
{
CreatTree(root,1);
}
template<class Type>
void BinTree<Type>::CreatTree(TreeNode<Type>* child,int k)
{
TreeNode<Type>* point;
point=new TreeNode<Type>;
cout<<”输入节点数据项 :”;
cin>>point->data;
switch(k)
{
case 1: root=point; break;
case 2: child->lchild=point;break;
case 3: child->rchild=point;break;
}
char temp;
cout<<”该”<<point->data<<”节点是否有左子树 Y / 任意键 :”;
cin>>temp;
if(temp==’y'||temp==’Y')
{
CreatTree(point,2);
}
cout<<”该”<<point->data<<”节点是否有右子树 Y / 任意键 :”;
cin>>temp;
if(temp==’y'||temp==’Y')
{
CreatTree(point,3);
}
}
template<class Type>
void BinTree<Type>::PreTree(TreeNode<Type> *point)
{
if(point!=NULL)
{
cout<<” “<<point->data;
PreTree(point->lchild);
PreTree(point->rchild);
}
}
template<class Type>
void BinTree<Type>::InoTree(TreeNode<Type> *point)
{
if(point!=NULL)
{
InoTree(point->lchild);
cout<<” “<<point->data;
InoTree(point->rchild);
}
}
template<class Type>
void BinTree<Type>::PosTree(TreeNode<Type> *point)
{
if(point!=NULL)
{
PosTree(point->lchild);
PosTree(point->rchild);
cout<<” “<<point->data;
}
}
template<class Type>
bool BinTree<Type>::ISEmpty()
{
return root==NULL;
}
template<class Type>
void BinTree<Type>::Destroy(TreeNode<Type> *point)
{
if(point!=NULL)
{
Destroy(point->lchild);
Destroy(point->rchild);
delete point;
}
}
///////////////////////////
// //
// 基本功能函数 BaseFun.h //
// //
//////////////////////////
void GRAPH();
void LIST();
void STACK();
void QUEUE();
void COMPOSITOR();
void BINTREE();
///////////////////////////
// //
// 堆栈功能函数 Stack.cpp/ /
// //
//////////////////////////
#include”Stack.h”
#include”iostream.h”
const int INT =13;
const double FLOAT= 13.33;
const char CHAR =’a';
template<class Type>
void Stack_Push(Stack<Type> &StackOPP)
{
cout<<”请输入要插入的数据项: “;
Type item;
cin>>item;
StackOPP.Push(item);
}
template<class Type>
void Stack_Pop(Stack<Type> &StackOPP)
{
if(!StackOPP.ISEmpty())
{
cout<<”出栈数据项: “;
cout<<StackOPP.Pop()<<endl;
}
else
{
cout<<”堆栈已经为空!”<<endl;
}
}
template<class Type>
void Stack_ISEmpty(Stack<Type> &StackOPP)
{
if(!StackOPP.ISEmpty())
cout<<”堆栈不空,还有”<<StackOPP.GetNum()<<”数据项!”<<endl;
else
cout<<”堆栈为空!”<<endl;
}
template<class Type>
void Stack_GetTop(Stack<Type> &StackOPP)
{
if(!StackOPP.ISEmpty())
cout<<”栈顶元素为:”<<StackOPP.GetTop()<<endl;
else
cout<<”堆栈为空!”<<endl;
}
template<class Type>
void Stack_MakeEmpty(Stack<Type> &StackOPP)
{
if(!StackOPP.ISEmpty())
{
StackOPP.MakeEmpty();
cout<<”堆栈已经销毁!”<<endl;
}
else
{
cout<<”销毁失败!”<<endl;
}
}
template<class Type>
void StackINI(Type temp)
{
Stack<Type> StackOPP;
do
{
cout<<”堆栈的操作: “<<endl
<<” 1) 插入堆栈”<<endl
<<” 2) 出栈”<<endl
<<” 3) 堆栈是否为空”<<endl
<<” 4) 得栈顶数据项”<<endl
<<” 5) 销毁堆栈”<<endl
<<” X) 退出堆栈操作”<<endl;
int item;
cin>>item;
switch(item)
{
case 1: Stack_Push(StackOPP); break;
case 2: Stack_Pop(StackOPP); break;
case 3: Stack_ISEmpty(StackOPP); break;
case 4: Stack_GetTop(StackOPP); break;
case 5: Stack_MakeEmpty(StackOPP); break;
default: return ;
}
}while(true);
}
void STACK()
{
int item;
cout<<”清选择数据类型: 1) 整型 2) 浮点型 3) 字符型 X) 退出: “;
cin>>item;
switch(item)
{
case 1: StackINI(INT); break; //根据不同的用户需要选择数据类型
case 2: StackINI(FLOAT); break;
case 3: StackINI(CHAR); break;
default: return ; break;
}
}
///////////////////////////
// //
// 队列功能函数 Queue.h //
// //
//////////////////////////
#include”Queue.h”
const int INT =13;
const double FLOAT= 13.33;
const char CHAR =’a';
template<class Type>
void Queue_Enter(Queue<Type> &QueueOPP)
{
cout<<”请输入要插入队列的数据: “;
Type item;
cin>>item;
QueueOPP.EnQueue(item);
}
template<class Type>
void Queue_Del(Queue<Type> &QueueOPP)
{
if(!QueueOPP.ISEmpty())
{
cout<<”出队数据:”<<QueueOPP.DelQueue()<<endl;
}
else
{
cout<<”队列已为空!”<<endl;
}
}
template<class Type>
void Queue_ISEmpty(Queue<Type> &QueueOPP)
{
if(QueueOPP.ISEmpty())
{
cout<<”队列已空!”<<endl;
}
else
{
cout<<”队列不空!”<<endl;
}
}
template<class Type>
void Queue_GetFront(Queue<Type> &QueueOPP)
{
if(!QueueOPP.ISEmpty())
{
cout<<”队头元素为: “<<QueueOPP.GetFront()<<endl;
}
else
{
cout<<”队列已空!”<<endl;
}
}
template<class Type>
void Queue_MakeEmpty(Queue<Type> &QueueOPP)
{
QueueOPP.MakeEmpty();
cout<<”队列清空!”<<endl;
}
template<class Type>
void QueueINI(Type temp)
{
Queue<Type> QueueOPP;
do
{
cout<<”队列的操作: “<<endl
<<” 1) 插入队列”<<endl
<<” 2) 出队”<<endl
<<” 3) 队列是否为空”<<endl
<<” 4) 得队头数据项”<<endl
<<” 5) 销毁队列”<<endl
<<” X) 退出队列操作”<<endl;
int item;
cin>>item;
switch(item)
{
case 1: Queue_Enter(QueueOPP); break;
case 2: Queue_Del(QueueOPP); break;
case 3: Queue_ISEmpty(QueueOPP); break;
case 4: Queue_GetFront(QueueOPP); break;
case 5: Queue_MakeEmpty(QueueOPP); break;
default: return ;
}
}while(true);
}
void QUEUE() //根据不同的用户需要选择数据类型
{
int item;
cout<<”清选择数据类型: 1) 整型 2) 浮点型 3) 字符型 X) 退出: “;
cin>>item;
switch(item)
{
case 1: QueueINI(INT); break;
case 2: QueueINI(FLOAT); break;
case 3: QueueINI(CHAR); break;
default: return ; break;
}
}
///////////////////////////
// //
// 链表 List.h //
// //
//////////////////////////
#include”list.h”
#include<iostream.h>
#include<stdlib.h>
template<class type>
void initlist(type &tmp)
{
list<type> List;
int n;
while(true)
{
cout<<”请选择你要对链表进行的操作 “<<endl
<<”1) 在末尾插入数据”<<endl
<<”2) 在任意处插入数据”<<endl
<<”3) 删除数据项”<<endl
<<”4) 删除整个链表”<<endl
<<”5) 打印链表”<<endl
<<”6) 查找数据项”<<endl
<<”7) 退出”<<endl;
cout<<”>\\ “;
cin>>n;
while(n<1||n>7)
{
cout<<”输入有误,请从新输入!”<<endl;
cout<<”>\\ “;
cin>>n;
}
switch(n)
{
case 1: list_insertend(List);break;
case 2: list_insert(List);break;
case 3: list_delnode(List);break;
case 4: list_makeempty(List);break;
case 5: list_print(List);break;
case 6: list_find(List);break;
case 7: return ;break;
}
}
}
void LIST()
{
int n;
cout<<”请选择你要构造的链表的数据类型 1)整型,2)字符型,3)浮点型”<<endl;
cout<<”>\\ “;
cin>>n;
while(n<1||n>3)
{
cout<<”输入有误,请从新输入!”<<endl;
cout<<”>\\ “;
cin>>n;
}
char t_c=’c';
int t_i=12;
double t_f=23.3;
switch(n)
{
case 1:initlist(t_i);break;
case 2:initlist(t_c);break;
case 3:initlist(t_f);break;
}
}
template<class type>
void list_insertend(list<type> &L)
{
type t;
cout<<”请输入插入数据: >\\”;
cin>>t;
L.insertend(t);
}
template<class type>
void list_find(list<type> &L)
{
type T;
cout<<”请输入你要查找的数据项:>\\ “;
cin>>T;
int i;
if(!(i=L.find(T)))
cout<<”你要查找的数据项不存在!”<<endl;
else
cout<<”你要查找的数据项在第”<<i<<”个位置”<<endl;
}
template<class type>
void list_insert(list<type> &L)
{
type t;
cout<<”请输入插入数据: >\\”;
cin>>t;
int n;
cout<<”请输入插入位置: >\\”;
cin>>n;
if(L.insert(t,n))
cout<<”插入成功! 在”<<n<<”位置 插入”<<t<<endl;
else
cout<<”插入失败! 插入位置不正确!”<<endl;
}
template<class type>
void list_delnode(list<type>& L)
{
int i;
cout<<”请输入要删除数据项的位置: >\\”;
cin>>i;
while(i<1||i>L.getlen())
{
cout<<”输入有误,可能大与链表长度,请从新输入!”<<endl;
cout<<”>\\ “;
cin>>i;
}
L.delnode(i);
}
template<class type>
void list_makeempty(list<type> &L)
{
L.makeempty();
}
template<class type>
void list_print(list<type> &L)
{
if(!L.print())
cout<<”链表为空!”<<endl;
}
///////////////////////////
// //
// 图功能函数 Graph.h //
// //
//////////////////////////
#include”Graph.h”
template<class NameType,class DisType>
void Graph_Creat(Graph<NameType,DisType> &GraphOPP)
{
GraphOPP.Creat();
}
template<class NameType,class DisType>
void Graph_DFS(Graph<NameType,DisType> &GraphOPP)
{
GraphOPP.DFS();
}
template<class NameType,class DisType>
void Graph_BFS(Graph<NameType,DisType> &GraphOPP)
{
GraphOPP.BFS();
}
template<class NameType,class DisType>
void Graph_PRINT(Graph<NameType,DisType> &GraphOPP)
{
GraphOPP.PrintNode();
}
void GRAPH()
{
Graph<char,int> GraphOPP;
do
{
cout<<”图的操作: “<<endl
<<” 1) 建立图”<<endl
<<” 2) 图的深度优先搜索”<<endl
<<” 3) 图的广度优先搜索”<<endl
<<” 4) 打印图中各结点”<<endl
<<” X) 退出排序操作”<<endl;
int item;
cin>>item;
switch(item)
{
case 1: Graph_Creat(GraphOPP); break;
case 2: Graph_DFS(GraphOPP); break;
case 3: Graph_BFS(GraphOPP); break;
case 4: Graph_PRINT(GraphOPP); break;
default: return ;
}
}while(true);
}
///////////////////////////
// //
// 排序算法功能函数 Compositor.cpp //
// //
//////////////////////////
#include”Compositor.h”
const int INT =13;
const double FLOAT= 13.33;
const char CHAR =’a';
template<class type>
void CompositorINI(type temp)
{
Compositor<type> CompositorOPP;
do
{
cout<<”排序的操作: “<<endl
<<” 1) 插入排序”<<endl
<<” 2) 快速排序”<<endl
<<” 3) 归并排序”<<endl
<<” 4) 冒泡排序”<<endl
<<” 5) 选择排序”<<endl
<<” X) 退出排序操作”<<endl
<<”请选择相应的操作: “;
int item;
cin>>item;
switch(item)
{
case 1: Compositor_Insert(CompositorOPP); break;
case 2: Compositor_Quick(CompositorOPP); break;
case 3: Compositor_Merge(CompositorOPP); break;
case 4: Compositor_Bubble(CompositorOPP); break;
case 5: Compositor_Select(CompositorOPP); break;
default: return ;
}
}while(true);
}
void COMPOSITOR()//根据不同的用户需要选择数据类型
{
int item;
cout<<”清选择数据类型: 1) 整型 2) 浮点型 3) 字符型 X) 退出: “;
cin>>item;
switch(item)
{
case 1: CompositorINI(INT); break;
case 2: CompositorINI(FLOAT); break;
case 3: CompositorINI(CHAR); break;
default: return ; break;
}
}
template<class type>
void Compositor_Insert(Compositor<type> CompositorOPP)
{
CompositorOPP.Insert();
}
template<class type>
void Compositor_Quick(Compositor<type> CompositorOPP)
{
CompositorOPP.Quick();
}
template<class type>
void Compositor_Select(Compositor<type> CompositorOPP)
{
CompositorOPP.Select();
}
template<class type>
void Compositor_Merge(Compositor<type> CompositorOPP)
{
CompositorOPP.MergeSort();
}
template<class type>
void Compositor_Bubble(Compositor<type> CompositorOPP)
{
CompositorOPP.Bubble();
}
///////////////////////////
// //
// 二叉树功能函数 BinTree.cpp//
// //
//////////////////////////
#include<iostream.h>
#include”BinTree.h”
const int INT =13;
const double FLOAT= 13.33;
const char CHAR =’a';
template<class Type>
void BinTree_CREAT(BinTree<Type>& BinTreeOPP)
{
BinTreeOPP. CreatTree();
}
template<class Type>
void BinTree_PRE(BinTree<Type>& BinTreeOPP)
{
if(!BinTreeOPP.ISEmpty())
{
cout<<”先序遍历二叉树 : “;
BinTreeOPP. PreTree(BinTreeOPP.root);
}
else
{
cout<<”二叉树已经为空!”<<endl;
}
}
template<class Type>
void BinTree_INO(BinTree<Type>& BinTreeOPP)
{
if(!BinTreeOPP.ISEmpty())
{
cout<<”中序遍历二叉树 : “;
BinTreeOPP. InoTree(BinTreeOPP.root);
}
else
{
cout<<”二叉树已经为空!”<<endl;
}
}
template<class Type>
void BinTree_POS(BinTree<Type>& BinTreeOPP)
{
if(!BinTreeOPP.ISEmpty())
{
cout<<”后序遍历二叉树 : “;
BinTreeOPP. PosTree(BinTreeOPP.root);
}
else
{
cout<<”二叉树已经为空!”<<endl;
}
}
template<class Type>
void BinTree_Destroy(BinTree<Type>& BinTreeOPP)
{
BinTreeOPP.Destroy(BinTreeOPP.root);
BinTreeOPP.root=NULL;
cout<<”二叉树已经销毁!”<<endl;
}
template<class Type>
void BinTree_THREAD(BinTree<Type>& BinTreeOPP)
{
if(BinTreeOPP.ISThread())
{
cout<<”该二叉树已经线索化!!”<<endl;
}
else
{
BinTreeOPP.ThreadTree();
}
}
template<class Type>
void BinTree_THROUGH(BinTree<Type>& BinTreeOPP)
{
BinTreeOPP.Through();
}
template<class Type>
void BinTreeINI(Type temp)
{
BinTree<Type> BinTreeOPP;
do
{
cout<<”树的操作: “<<endl
<<” 1) 构造二叉数”<<endl
<<” 2) 先序遍历二叉树”<<endl
<<” 3) 中序遍历二叉树”<<endl
<<” 4) 后序遍历二叉树”<<endl
<<” 5) 销毁二叉树 “<<endl
<<” X) 退出二叉树操作”<<endl;
int item;
cin>>item;
switch(item)
{
case 1: BinTree_CREAT(BinTreeOPP); break; //构造二叉数
case 2: BinTree_PRE(BinTreeOPP); break; //先序遍历二叉树
case 3: BinTree_INO(BinTreeOPP); break; //中序遍历二叉树
case 4: BinTree_POS(BinTreeOPP); break; //后序遍历二叉树
case 5: BinTree_Destroy(BinTreeOPP);break; //求树的深度
default: return ;
}
}while(true);
}
void BINTREE()
{
int item;
cout<<”清选择数据类型: 1) 整型 2) 浮点型 3) 字符型 X) 退出: “;
cin>>item;
switch(item)
{
case 1: BinTreeINI(INT); break; //根据不同的用户需要选择数据类型
case 2: BinTreeINI(FLOAT); break;
case 3: BinTreeINI(CHAR); break;
default: return ; break;
}
}
///////////////////////////
// //
// 主函数 index.cpp 用户菜单 //
// //
//////////////////////////
#include <iostream.h>
#include”BaseFun.h”
void main()
{
//功能菜单
do
{
cout<<”欢迎使用数据结构算法集”<<endl
<<”1) 线性表 “<<endl
<<”2) 堆栈 “<<endl
<<”3) 队列 “<<endl
<<”4) 二叉树 “<<endl
<<”5) 图 “<<endl
<<”6) 排序算法 “<<endl
<<”7) 字符串 “<<endl
<<”X) 按任意键退出 “<<endl;
cout<<” 请您选择何种数据结构的操作:”<<endl;
int kind;
cin>>kind;
switch(kind)
{
case 1: LIST(); break;
case 2: STACK(); break;
case 3: QUEUE(); break;
case 4: BINTREE(); break;
case 5: GRAPH(); break;
case 6: COMPOSITOR(); break;
default: return;
}
}while(true);
}
用c++语言实现基本的数据结构(1)
阅读:309 发表时间:2005-5-13 21:29:02 来源:转载 作者:ihualan
本文关键字:用c++语言实现基本的数据结构(1)|C++语言,C++语言基础|
以下是用c++实现的链表的数据结构。
笔者还做了栈,队列,循环队列,串等数据结构,如有需要者请
E-mail:cangzhu@163.com
#include”iostream.h”
#include”stdio.h”
#include”stdlib.h”
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define INFEASIBLE -1
#define OVERFLOAT -2
#define MAXSIZE 100
typedef int status;
typedef int ElemType;
typedef struct LNode{
ElemType data;
struct LNode *next;
} *Link,*Position;
class LinkList
{
private:
Link head;
int len;
public:
status InitList(LinkList &L);
status DestroyList(LinkList &L);
void FreeNode(Link p);
status ClearList(LinkList &L);
status InsFirst(LinkList &L,Link s);
status Remove(LinkList &L,Link p);
status InsBefore(LinkList &L,Link p,Link s);
status InsAfter(LinkList &L,Link p,Link s);
status SetCurElem(Link p,ElemType &e);
ElemType GetElem(Link p);
int ListLength(LinkList L);
Position GetHead(LinkList L);
Position GetLast(LinkList L);
status PriorPos(LinkList L,Link p,Position &q);
status NextPos(LinkList L,Link p,Position &q);
status Search(LinkList L,ElemType e,Position &p);
};
status LinkList::InitList(LinkList &L)
{
Link L1;
L1=(LNode *)malloc (sizeof(LinkList)*MAXSIZE);
L.head=L1;
L.head->next=NULL;
L.len=0;
if(L1==NULL)
return OVERFLOAT;
else
return OK;
}
status LinkList::DestroyList(LinkList &L)
{
return OK;
}
void LinkList::FreeNode(Link p)
{
free(p);
}
status LinkList::ClearList(LinkList &L)
{
L.head->next=NULL;
len=0;
return OK;
}
status LinkList::InsFirst(LinkList &L, Link s)
{
s->next=L.head->next;
L.head->next=s;
len++;
return OK;
}
status LinkList::Remove(LinkList &L,Link p)
{
Link q=L.GetHead(L);
while(q->next!=p)
q=q->next;
q->next=q->next->next;
L.len–;
return OK;
}
status LinkList::InsBefore(LinkList &L,Link p,Link s)
{
Link q=L.head;
while(q->next!=p)
q=q->next;
s->next=q->next;
q->next=s;
len++;
return OK;
}
status LinkList::InsAfter(LinkList &L,Link p,Link s)
{
s->next=p->next;
p->next=s;
len++;
return OK;
}
status LinkList::SetCurElem(Link p,ElemType &e)
{
p->data=e;
return OK;
}
ElemType LinkList::GetElem(Link p)
{
return p->data;
}
int LinkList::ListLength(LinkList L)
{
return L.len;
}
Position LinkList::GetHead(LinkList L)
{
return L.head;
}
Position LinkList::GetLast(LinkList L)
{
Link q=head;
while(q->next!=NULL)
q=q->next;
return q;
}
status LinkList::PriorPos(LinkList L,Link p,Position &q)
{
Link qq=L.GetHead(L);
if(p==qq||p==qq->next)
return FALSE;
while(qq->next!=p)
qq=qq->next;
q=qq;
return OK;
}
status LinkList::NextPos(LinkList L,Link p,Position &q)
{
if(p->next==NULL)
return FALSE;
q=p->next;
return OK;
}
status LinkList::Search(LinkList L,ElemType e,Position &p)
{
Link q=L.GetHead(L);
int i=0;
do
{
i++;
q=q->next;
if(i>L.len)
return FALSE;
}
while(q->data!=e);
p=q;
return OK;
}
//下面是测试程序,读者可以按自己的要求,修改并测试!
void main()
{
/*LinkList LL;
LL.InitList(LL);
LNode node[5];
int i;
for(i=0;i<5;i++)
node[i].next=NULL;
for(i=0;i<5;i++)
node[i].data=10*i;
LNode node2[5];
int j;
for(j=0;j<5;j++)
node2[j].next=NULL;
for(j=0;j<5;j++)
node2[j].data=100+10*j;
for(i=0;i<5;i++)
LL.InsFirst(LL,&node[i]);
for(i=0;i<5;i++)
LL.InsAfter(LL,&node[i],&node2[i]);
for(i=0;i<5;i++)
cout<<LL.GetElem(&node[i])<<endl;
for(i=0;i<5;i++)
cout<<LL.GetElem(&node2[i])<<endl;
int e=22222;
LL.SetCurElem(&node2[3],e);
cout<<”changed:”<<LL.GetElem(&node2[3])<<endl;
cout<<”先面遍历整个线性表:”<<endl;
for(Link q=LL.GetHead(LL)->next;q!=NULL;q=q->next)
cout<<q->data<<endl;
cout<<”last:”<<LL.GetLast(LL)->data<<endl;
cout<<node[4].data<<”的前一个元素:”<<endl;
if(LL.PriorPos(LL,&node[4],q))
cout<<q->data<<endl;
else
cout<<node[4].data<<”是最前一个元素”<<endl;
cout<<node2[4].data<<”的前一个元素:”<<endl;
LL.PriorPos(LL,&node2[4],q);
cout<<q->data<<endl;
cout<<node2[3].data<<”的下一个元素:”<<endl;
LL.NextPos(LL,&node2[3],q);
cout<<q->data<<endl;
cout<<”remove :”<<node[3].data<<endl;
LL.Remove(LL,&node[3]);
cout<<”先面遍历整个线性表:”<<endl;
for(i=0,q=LL.GetHead(LL)->next;i<LL.ListLength(LL);i++)
{
cout<<q->data<<endl;
q=q->next;
}
cout<<”last:”<<LL.GetLast(LL)->data<<endl;
q=LL.GetLast(LL);
Link qq;
if(LL.NextPos(LL,q,qq))
cout<<qq->data<<endl;
else
cout<<q->data<<”是最后一个元素!”<<endl;
cout<<”先面遍历整个线性表:”<<endl;
for(q=LL.GetHead(LL)->next;q!=NULL;q=q->next)
cout<<q->data<<endl;
cout<<”remove :”<<node[3].data<<endl;
Link temp;
if(LL.Search(LL,120,q))
{
LL.NextPos(LL,q,temp);
cout<<”120″<<”在”<<temp->data<<”之前”<<endl;
LL.PriorPos(LL,q,temp);
cout<<”120″<<”在”<<temp->data<<”之后”<<endl;
}
cout<<LL.Search(LL,22222,temp)<<endl;
LL.ClearList(LL);
LNode test;
test.data=10;
LL.InsFirst(LL,&test);
cout<<”先面遍历整个线性表:”<<endl;
for(q=LL.GetHead(LL)->next;q!=NULL;q=q->next)
cout<<q->data<<endl;
if(LL.Search(LL,10,temp))
cout<<temp->data;
LNode no[10];
for(i=0;i<10;i++)
no[i].next=NULL;
for(i=0;i<10;i++)
no[i].data=100*i;
LL.InsFirst(LL,&no[9]);
for(i=8;i>=0;i–)
LL.InsBefore(LL,&no[i+1],&no[i]);
cout<<”测试——先面遍历整个线性表:”<<endl;
for(q=LL.GetHead(LL);q->next!=NULL;q=q->next)
cout<<q->next->data<<endl;*/
int i;
LinkList stu;
stu.InitList(stu);
LNode stu_node[6];
for(i=0;i<6;i++)
stu_node[i].data=i*6;
for(i=0;i<6;i++)
stu.InsFirst(stu,&stu_node[i]);
cout<<stu.GetHead(stu)->next->data<<endl;
}
[个人备份]用遗传算求最值
#include <stdio.h>
#include <math.h>
#define M 80 /*//种群大小*/
#define T 200 /* //终止代数*/
#define Pc 0.6 /* //交叉概率*/
#define Pm 0.001 /*//变异概率*/
#define Clength 20 /*//定义编码的码长*/
/*//初始化种群*/
/*//将种群的数值映射到长度为10的二进值代码,然后连接生成染色体长度为20*/
void initialize(char newgenetic[][Clength],char oldgenetic[][Clength],int n)
{
float flag1,flag2;/*//用于控制种群随机数的符号*/
float var_x1,var_x2;/*//两个随机数*/
int i,j; /*//i控制种群的个数,j控制每个数值到二进值代码的位置*/
int remainder,quotient; /*//余数,商*/
float temp;
char var_ch1[Clength/2],var_ch2[Clength/2]; /*//对应的两个随机数的长度为10的而进值代码*/
int gclength=Clength;
srand((unsigned)time(NULL));/*//伪随机种子*/
for(i=0;i<n;i++)
{
flag1=(float)rand()/32738;
flag2=(float)rand()/32738;
/*//生成两个随机变量(-2.048,2.048)*/
if (flag1>=0.5) var_x1=2.048*(float)rand()/32738;
else var_x1=-2.048*(float)rand()/32738;
if (flag2>=0.5) var_x2=2.048*(float)rand()/32738;
else var_x2=-2.048*(float)rand()/32738;
/*//第一个变量的转换*/
temp=(var_x1+2.048)*1000/4; /*//扩大1000倍,使数值在(0,4096)上然后4分频*/
quotient=(int)temp % 2;
var_ch1[gclength/2-1]=quotient+48; /*//转化为真正的0或1字符*/
remainder=(int)temp/2;
for(j=0;j<gclength/2-1;j++)
{
quotient=remainder%2;
remainder=remainder/2;
var_ch1[gclength/2-2-j]=quotient+48;
}
/*//第二个变量的转换*/
temp=(var_x2+2.048)*1000/4;/*//扩大1000倍,使数值在(0,4096)上然后4分频*/
quotient=(int)temp % 2;
var_ch2[gclength/2-1]=quotient+48;/* //转化为真正的0或1字符*/
remainder=(int)temp/2;
for(j=0;j<gclength/2-1;j++)
{
quotient=remainder%2;
remainder=remainder/2;
var_ch2[gclength/2-2-j]=quotient+48;
}
/*//两个变量连接生成染色体长度为20*/
for(j=0;j<=gclength/2-1;j++)
{ newgenetic[i][j]=var_ch1[j];
newgenetic[i][gclength/2+j]=var_ch2[j];
oldgenetic[i][j]=var_ch1[j];
oldgenetic[i][gclength/2+j]=var_ch2[j];
}
}
}
/*//解码操作*/
void decode(char n_genetic[][Clength],float pop_1[],float pop_2[], int n)
{
int i,j;
float var_1,var_2;
for (i=0;i<n;i++)
{
var_1=var_2=0;
for(j=0;j<Clength/2;j++)
{ var_1=2*var_1+(n_genetic[i][j]-48);
var_2=2*var_2+(n_genetic[i][j+Clength/2]-48);
}
pop_1[i]=var_1*4.096/1023-2.048;
pop_2[i]=var_2*4.096/1023-2.048;
}
}
/*//计算适值*/
float evaluate(char newgenetic[][Clength],char oldgenetic[][Clength],float newfit[],float oldfit[],int n)
{
int i;
float pop1[M],pop2[M]; /*//暂存解码后的两个变量*/
float temp;
float var_1,var_2;
/*//新种群适度的计算*/
decode(newgenetic,pop1,pop2,n);
for(i=0;i<n;i++)
newfit[i]=-1;
for(i=0;i<n;i++)
{
var_1=pop1[i];
var_2=pop2[i];
temp=100*(((var_1)*(var_1)-var_2))*(((var_1)*(var_1)-var_2))+(1-var_1)*(1-var_1);
if ( newfit[i] < temp ) newfit[i]=temp;
}
/*//旧种群适度的计算*/
decode(oldgenetic,pop1,pop2,n);
for(i=0;i<n;i++)
oldfit[i]=-1;
for(i=0;i<n;i++)
{
var_1=pop1[i];
var_2=pop2[i];
temp=100*(((var_1)*(var_1)-var_2))*(((var_1)*(var_1)-var_2))+(1-var_1)*(1-var_1);
if ( oldfit[i] < temp ) oldfit[i]=temp;
}
/*//计算最大的适值*/
for(i=0;i<n;i++)
temp=(newfit[i]>oldfit[i])? newfit[i]:oldfit[i];
return(temp);
}
int flip(float possibility)
{
float ppp;
ppp=(float)rand()/32728;
if(ppp<=possibility) return (1);
else return (0);
}
/*//通过交叉.变异和随机算子进行种群的交叉和变异*/
void genetic(char newgenetic[][Clength],char oldgenetic[][Clength],int n)
{
int i,j,r1,r2,iplace,i_place;
/*//从1到n循环,根据交叉适应度选择,进行交叉,组成oldgenetic*/
for(i=0;i<n;i+=2)
{
/*//r1,r2是随机要交叉的染色体,ipalce是交叉的位置*/
r1=rand()%M;
r2=rand()%M;
iplace=rand()%Clength;
if(j=flip(Pc)) /*//以交叉概率进行交叉*/
for(j=iplace;j<Clength;j++)
{
oldgenetic[r1][j]=newgenetic[r2][j];
oldgenetic[r2][j]=newgenetic[r1][j];
}
}
/*//从1到n循环,对newgenetic进行变异*/
/*//i_palce是变异的位置*/
i_place=rand()%Clength;
for(i=0;i<n;i++)
if(j=flip(Pm)) /*//以变异概率进行变异*/
if(newgenetic[i][i_place]==‘0‘) newgenetic[i][i_place]=‘1‘;
else newgenetic[i][i_place]=‘0‘;
}
/*newgenetic 和oldgenetic 中再次计算评价函数 因为求最大值,所以取评价函数大的进行遗传*/
void statistic(char new_genetic[M][Clength],char old_genetic[M][Clength],float new_fit[],float old_fit[],int n)
{
float temp;
int i,j;
temp=evaluate(new_genetic,old_genetic,new_fit,old_fit,n);
for(i=0;i<n;i++)
if (new_fit[i]<old_fit[i])
for(j=0;j<Clength;j++)
new_genetic[i][j]=old_genetic[i][j];
}
/*//结果的显示*/
void display(float Rosenbrock)
{
printf(”
The maximum of Rosenbrock is : “);
printf(“%f
“,Rosenbrock);
printf(”
Press Enter to continue
“);
getchar();
}
/*//程序入口*/
void main()
{
float newfitness[M],oldfitness[M];
char newgenetic_code[M][Clength];/*//种群1二进值代码*/
char oldgenetic_code[M][Clength];/*//种群2二进值代码*/
float bestfitness;
int gen; /*//终止控制变量*/
initialize(newgenetic_code,oldgenetic_code,M);/* //初始化种群,使种群的初始值保持在(-2.048,2.048),将种群的数值映射到长度为10的二进值代码*/
for(gen=0;gen<T;gen++)
{
bestfitness=evaluate(newgenetic_code,oldgenetic_code,newfitness,oldfitness,M); /* //计算种群的适值,并总的返回适度即最后输出的结果*/
genetic(newgenetic_code,oldgenetic_code,M); /*//交叉和变异*/
/* //进行统计,选出最优染色体遗传*/
statistic(newgenetic_code,oldgenetic_code,newfitness,oldfitness,M);
}
bestfitness=evaluate(newgenetic_code,oldgenetic_code,newfitness,oldfitness,M);;
display(bestfitness);
}
[个人备份]说说字符集
由于作者是美国人的缘故,我发现Windows下的几本名著(如《Windows程序设计》,Jeffrey Richter的《Windows 核心编程》)对字符集的讲解都不甚透彻。现在这里对一些易让人迷惑的问题进行澄清,并指明一些编程时容易出错的问题(我自己就犯过)。
先解释几个概念:
字符集:根据编码特性而分,字符集可分为三类。
l 窄字符集(SBCS) 每个代码由一个字节进行表示,比如ANSI。
l 多字节字符集(MBCS) 字符集中的代码或者是单字节,或者是多字节,比如DBCS,GB2312等。
l 宽字节字符集 字符集中每个字符由两个字节表示。比如UNICODE
代码页:在UNICODE和DBCS中由于包含的代码十分多,为了使用方便就需要对这些代码进行组织。组织的方法就是把不同国家的代码分别放入不同的代码页。
字符集与代码页的关系:由上可知,对于UNICODE和DBCS,代码页是从属于字符集的。但对于SBCS类的字符集(比如ANSI)和DBCS之外的MBCS字符集(比如GB2312等)他们则只对应于一个代码页。
下面看一段潜在有问题的程序:
void ConverAndOutputString(HDC hdc,LPWSTR wstr, int length,int x,int y)
{
int nret;
int sizebuffer= 2*length;
char* lpBuffer=new char[sizebuffer];
nret=WideCharToMultiByte(CP_ACP,0,wstr , length,
lpBuffer, sizebuffer ,NULL,NULL);
TextOut(hdc,x,y, lpBuffer,nret);
delete[]lpBuffer;
}
这段程序很简单,只是把一个宽字符串转为DBCS串而后按指定的坐标进行输出。Jeffrey Richter在他的《Windows核心编程》中的第26页也用几乎的相同的方法进行字符串转换。但这段程序其实是有问题的。问题出在转换字符串时不应该硬编码指定代码页,而应该根据当前字体进行动态获取。否则在某些情况下将无法把wstr中的UNICODE字符转换到正确的代码。如果你用上述代码进行中文输出,你将很有幸看到很多问号被自动添加到你的字符串中。
解决的办法也很简单,但首先你要熟悉如下两个个API函数:
int GetTextCharset(HDC hdc);//这个API用来得到当前字体的字符集。
BOOL TranslateCharsetInfo(
DWORD* pSrc, // information
LPCHARSETINFO lpCs, // character set information
DWORD dwFlags // translation option
);
这个函数可以把字符集、代码页和FONTSIGNATURE互相转换。转换后的信息
放在lpCS中。dwFlags指明需要进行那种转换,是把字符集转换到代码页还是其他。
特别需要注意的是,pSRC参数,这个参数在你进行字符集到代码页转换的时候,需
要的是一个具有指针类型的值而非指向某个值的指针。因此对上述字符串输出函数你
只要加上如下两行,就可以保证字符串在转换期间不会遇到找不到字符代码的情况。
void ConverAndOutputString(HDC hdc,LPWSTR wstr, int length,int x,int y)
{
int nret;
int sizebuffer= 2*length;
char* lpBuffer=new char[sizebuffer];
int charset=GetTextCharset(hDC);
CHARSETINFO csinfo={0};
TranslateCharsetInfo((DWORD*)charset,&csinfo,TCI_SRCCHARSET);
nret=WideCharToMultiByte(csinfo. .ciACP,0,wstr , length,
lpBuffer, sizebuffer ,NULL,NULL);
TextOut(hdc,x,y, lpBuffer,nret);
delete[]lpBuffer;
}
最后总结一下,这篇文章的主题就是在做字符集间的转换时,一定要动态确定代码页。
所涉及函数和结构的进一步细节请参考MSDN。by leezy_2000
关于API HOOK拦截封包原理
作者:不详 来源于:TTee.com 外挂网
http://soft.ttee.com/Article/Catalog32/95.html
我自己做的apihook,是用了陷阱式和导入表式封装在同一个类里的。源代码还没整理,而且是用delphi编写的。本人最近忙其他一个程序,加上工作忙,所以现找来网上的一篇关于apihook的文章。
本论坛很多朋友是用C++的,所以转贴了一篇C++的,原理写的蛮清楚的,用的HOOK方式是陷阱式的。
PS:大名鼎鼎的WPE就是一个优秀的API Hook,怎么样?你也可以编个WPE出来:)
===========================
利用hook截获进程的API调用
作者:Redspider
截获API是个很有用的东西,比如你想分析一下别人的程序是怎样工作的。这里我介绍一下一种我自己试验通过的方法。
首先,我们必须设法把自己的代码放到目标程序的进程空间里去。Windows Hook可以帮我们实现这一点。SetWindowsHookEx的声明如下:
HHOOK SetWindowsHookEx(
int idHook, // hook type
HOOKPROC lpfn, // hook procedure
HINSTANCE hMod, // handle to application instance
DWORD dwThreadId // thread identifier
);
具体的参数含义可以翻阅msdn,没有msdn可谓寸步难行。
这里Hook本身的功能并不重要,我们使用它的目的仅仅只是为了能够让Windows把我们的代码植入别的进程里去。hook Type我们任选一种即可,只要保证是目标程序肯定会调用到就行,这里我用的是WH_CALLWNDPROC。lpfn和hMod分别指向我们的钩子代码及其所在的dll,dwThreadId设为0,表示对所有系统内的线程都挂上这样一个hook,这样我们才能把代码放到别的进程里去。
之后,我们的代码就已经进入了系统内的所有进程空间了。必须注意的是,我们只需要截获我们所关心的目标程序的调用,因此还必须区分一下进程号。我们自己的钩子函数中,第一次运行将进行最重要的API重定向的工作。也就是通过将所需要截获的API的开头几个字节改为一个跳转指令,使其跳转到我们的API中来。这是最关键的部分。这里我想截三个调用,ws2_32.dll中的send和recv、user32.dll中的GetMessageA。
DWORD dwCurrentPID = 0;
HHOOK hOldHook = NULL;
DWORD pSend = 0;
DWORD pRecv = 0;
GETMESSAGE pGetMessage = NULL;
BYTE btNewBytes[8] = { 0x0B8, 0×0, 0×0, 0×40, 0×0, 0x0FF, 0x0E0, 0 };
DWORD dwOldBytes[3][2];
HANDLE hDebug = INVALID_HANDLE_value;
LRESULT CALLBACK CallWndProc( int nCode, WPARAM wParam, LPARAM lParam )
{
DWORD dwSize;
DWORD dwPIDWatched;
HMODULE hLib;
if( dwCurrentPID == 0 )
{
dwCurrentPID = GetCurrentProcessId();
HWND hwndMainHook;
hwndMainHook = ::FindWindow( 0, “MainHook” );
dwPIDWatched = ::SendMessage( hwndMainHook, (WM_USER+100), 0, 0 );
hOldHook = (HHOOK)::SendMessage( hwndMainHook, (WM_USER+101), 0, 0 );
if( dwCurrentPID == dwPIDWatched )
{
hLib = LoadLibrary( “ws2_32.dll” );
pSend = (DWORD)GetProcAddress( hLib, “send” );
pRecv = (DWORD)GetProcAddress( hLib, “recv” );
::ReadProcessMemory( INVALID_HANDLE_value, (void *)pSend, (void *)dwOldBytes[0], sizeof(DWORD)*2, &dwSize );
*(DWORD *)( btNewBytes + 1 ) = (DWORD)new_send;
::WriteProcessMemory( INVALID_HANDLE_value, (void *)pSend, (void *)btNewBytes, sizeof(DWORD)*2, &dwSize );
::ReadProcessMemory( INVALID_HANDLE_value, (void *)pRecv, (void *)dwOldBytes[1], sizeof(DWORD)*2, &dwSize );
*(DWORD *)( btNewBytes + 1 ) = (DWORD)new_recv;
::WriteProcessMemory( INVALID_HANDLE_value, (void *)pRecv, (void *)btNewBytes, sizeof(DWORD)*2, &dwSize );
hLib = LoadLibrary( “user32.dll” );
pGetMessage = (GETMESSAGE)GetProcAddress( hLib, “GetMessageA” );
::ReadProcessMemory( INVALID_HANDLE_value, (void *)pGetMessage, (void *)dwOldBytes[2], sizeof(DWORD)*2, &dwSize );
*(DWORD *)( btNewBytes + 1 ) = (DWORD)new_GetMessage;
::WriteProcessMemory( INVALID_HANDLE_value, (void *)pGetMessage, (void *)btNewBytes, sizeof(DWORD)*2, &dwSize );
hDebug = ::CreateFile( “C:\\Trace.log”, GENERIC_WRITE, 0, 0, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0 );
}
}
if( hOldHook != NULL )
{
return CallNextHookEx( hOldHook, nCode, wParam, lParam );
}
return 0;
}
上面的钩子函数,只有第一次运行时有用,就是把三个函数的首8字节修改一下(实际上只需要7个)。btNewBytes中的指令实际就是
mov eax, 0×400000
jmp eax
这里的0×400000就是新的函数的地址,比如new_recv/new_send/new_GetMessage,此时,偷梁换柱已经完成。再看看我们的函数中都干了些什么。以GetMessageA为例:
BOOL _stdcall new_GetMessage( LPMSG lpMsg, HWND hWnd, UINT wMsgFilterMin, UINT wMsgFilterMax )
{
DWORD dwSize;
char szTemp[256];
BOOL r = false;
//Watch here before it’s executed.
sprintf( szTemp, “Before GetMessage : HWND 0x%8.8X, msgMin 0x%8.8X, msgMax 0x%8.8x \r\n”, hWnd, wMsgFilterMin, wMsgFilterMax );
::WriteFile( hDebug, szTemp, strlen(szTemp), &dwSize, 0 );
//Watch over
// restore it at first
::WriteProcessMemory( INVALID_HANDLE_value, (void *)pGetMessage, (void *)dwOldBytes[2], sizeof(DWORD)*2, &dwSize );
// execute it
r = pGetMessage( lpMsg, hWnd, wMsgFilterMin, wMsgFilterMax );
// hook it again
*(DWORD *)( btNewBytes + 1 ) = (DWORD)new_GetMessage;
::WriteProcessMemory( INVALID_HANDLE_value, (void *)pGetMessage, (void *)btNewBytes, sizeof(DWORD)*2, &dwSize );
//Watch here after it’s executed
sprintf( szTemp, “Result of GetMessage is %d.\r\n”, r );
::WriteFile( hDebug, szTemp, strlen( szTemp ), &dwSize, 0 );
if( r )
{
sprintf( szTemp, “Msg : HWND 0x%8.8X, MSG 0x%8.8x, wParam 0x%8.8X, lParam 0x%8.8X\r\nTime 0x%8.8X, X %d, Y %d\r\n”,
lpMsg->hwnd, lpMsg->message,
lpMsg->wParam, lpMsg->lParam, lpMsg->time,
lpMsg->pt.x, lpMsg->pt.y );
::WriteFile( hDebug, szTemp, strlen( szTemp ), &dwSize, 0 );
}
strcpy( szTemp, “\r\n” );
::WriteFile( hDebug, szTemp, strlen( szTemp ), &dwSize, 0 );
//Watch over
return r;
}
先将截获下来的参数,写入到一个log文件中,以便分析。然后恢复原先保留下来的GetMessageA的首8字节,然后执行真正的GetMessageA调用,完毕后再将执行结果也写入log文件,然后将GetMessageA的执行结果返回给调用者。
整个截获的过程就是这样。你可以把其中的写log部分改成你自己想要的操作。这里有个不足的地方是,截获动作是不能够并发进行的,如果目标进程是多线程的,就会有问题。解决办法是,可以在每次new_GetMessage中加入一个CriticalSection的锁和解锁,以使调用变为串行进行,但这个我没有试验过。
一个中文输入的类
作 者:风戒
不想让IME(Input Method Editor)显示默认的窗口,只想用它的转换和选字功能看过“拿铁游戏论坛”上的一个兄弟的一些代码,修正了一些我认为的bug加入了一组控制函数,使得程序中可以显示一些按钮(button),玩家可以不必用热键就能切换输入法、全角/半角,中/英文标点。但我不知道这个程序能不能解决缩进的问题,程序如下:
#pragma comment ( lib, “imm32.lib” )
#include <windows.h>
#include <imm.h>
class CIme
{
bool g_bIme; // IME允许标志
char g_szCompStr[ MAX_PATH ]; // 存储转换后的串
char g_szCompReadStr[ MAX_PATH ]; // 存储输入的串
char g_szCandList[ MAX_PATH ]; // 存储整理成字符串选字表
int g_nImeCursor; // 存储转换后的串中的光标位置
CANDIDATELIST *g_lpCandList; // 存储标准的选字表
char g_szImeName[ 64 ]; // 存储输入法的名字
bool g_bImeSharp; // 全角标志
bool g_bImeSymbol; // 中文标点标志
void ConvertCandList( CANDIDATELIST *pCandList, char *pszCandList ); // 将选字表整理成串
public:
CIme():
g_lpCandList( NULL )
{
DisableIme(); // 通过DisableIme初始化一些数据
}
~CIme()
{
DisableIme();
if( g_lpCandList )
{
GlobalFree( (HANDLE)g_lpCandList );
g_lpCandList = NULL;
}
}
// 控制函数
void DisableIme(); // 关闭并禁止输入法,如ime已经打开则关闭,此后玩家不能用热键呼出IME
void EnableIme(); // 允许输入法,此后玩家可以用热键呼出IME
void NextIme(); // 切换到下一种输入法,必须EnableIme后才有效
void SharpIme( HWND hWnd ); // 切换全角/半角
void SymbolIme( HWND hWnd ); // 切换中/英文标点
// 状态函数
char* GetImeName(); // 得到输入法名字,如果当前是英文则返回NULL
bool IfImeSharp(); // 是否全角
bool IfImeSymbol(); // 是否中文标点
// 得到输入法状态,四个指针任意可为NULL则此状态不回返回
void GetImeInput(
char **pszCompStr, // 在pszCompStr中返回转换后的串
char **pszCompReadStr, // 在pszCompReadStr中返回键盘直接输入的串
int *pnImeCursor, // 在pnImeCursor中返回szCompStr的光标位置
char **pszCandList //在pszCandList中返回选字表,每项之间以\t分隔
);
// 必须在消息中调用的函数,如果返回是true,则窗口函数应直接返回0,否则应传递给DefWindowProc
bool OnWM_INPUTLANGCHANGEREQUEST();
bool OnWM_INPUTLANGCHANGE( HWND hWnd );
bool OnWM_IME_SETCONTEXT(){ return true; }
bool OnWM_IME_STARTCOMPOSITION(){ return true; }
bool OnWM_IME_ENDCOMPOSITION(){ return true; }
bool OnWM_IME_NOTIFY( HWND hWnd, WPARAM wParam );
bool OnWM_IME_COMPOSITION( HWND hWnd, LPARAM lParam );
};
void CIme::DisableIme()
{
while( ImmIsIME( GetKeyboardLayout( 0 )))
ActivateKeyboardLayout(( HKL )HKL_NEXT, 0 ); // 如果IME打开通过循环切换到下一个关闭
g_bIme = false;
g_szCompStr[ 0 ] = 0;
g_szCompReadStr[ 0 ] = 0;
g_nImeCursor = 0;
g_szImeName[ 0 ] = 0;
g_szCandList[ 0 ] = 0;
}
void CIme::EnableIme()
{
g_bIme = true;
}
void CIme::NextIme()
{
if( !g_bIme )
return;
ActivateKeyboardLayout(( HKL )HKL_NEXT, 0 );
}
void CIme::SharpIme( HWND hWnd )
{
ImmSimulateHotKey( hWnd, IME_CHOTKEY_SHAPE_TOGGLE );
}
void CIme::SymbolIme( HWND hWnd )
{
ImmSimulateHotKey( hWnd, IME_CHOTKEY_SYMBOL_TOGGLE );
}
void CIme::ConvertCandList( CANDIDATELIST *pCandList, char *pszCandList )
{
// 转换CandidateList到一个串,\t分隔每一项
unsigned int i;
if( pCandList->dwCount < pCandList->dwSelection )
{
pszCandList[ 0 ] = 0;
return;
}
待选字序号超出总数,微软拼音第二次到选字表最后一页后再按PageDown会出现这种情况,并且会退出选字状态,开始一个新的输入。但微软拼音自己的IME窗口可以解决这个问题,估计微软拼音实现了更多的接口,所以使用了这种不太标准的数据。我现在无法解决这个问题,而且实际使用中也很少遇到这种事,而且其它标准输入法不会引起这种bug。非标准输入法估计实现的接口比较少,所以应该也不会引起这种缺陷。
for( i = 0; ( i < pCandList->dwCount – pCandList->dwSelection )&&( i < pCandList->dwPageSize ); i++ )
{
*pszCandList++ = ( i % 10 != 9 )? i % 10 + ’1′ : ’0′; // 每项对应的数字键
*pszCandList++ = ‘.’; // 用’.'分隔
strcpy( pszCandList, (char*)pCandList + pCandList->dwOffset[ pCandList->dwSelection + i ] ); // 每项实际的内容
pszCandList += strlen( pszCandList );
*pszCandList++ = ‘\t’; // 项之间以’\t’分隔
}
*( pszCandList – 1 )= 0; // 串尾,并覆盖最后一个’\t’
}
bool CIme::OnWM_INPUTLANGCHANGEREQUEST()
{
return !g_bIme; // 如果禁止IME则返回false,此时窗口函数应返回0,否则DefWindowProc会打开输入法
}
bool CIme::OnWM_INPUTLANGCHANGE( HWND hWnd )
{
// IME改变
HKL hKL = GetKeyboardLayout( 0 );
if( ImmIsIME( hKL ))
{
HIMC hIMC = ImmGetContext( hWnd );
ImmEscape( hKL, hIMC, IME_ESC_IME_NAME, g_szImeName ); // 取得新输入法名字
DWORD dwConversion, dwSentence;
ImmGetConversionStatus( hIMC, &dwConversion, &dwSentence );
g_bImeSharp = ( dwConversion & IME_CMODE_FULLSHAPE )? true : false; // 取得全角标志
g_bImeSymbol = ( dwConversion & IME_CMODE_SYMBOL )? true : false; // 取得中文标点标志
ImmReleaseContext( hWnd, hIMC );
}
else // 英文输入
g_szImeName[ 0 ] = 0;
return false; // 总是返回false,因为需要窗口函数调用DefWindowProc继续处理
}
bool CIme::OnWM_IME_NOTIFY( HWND hWnd, WPARAM wParam )
{
HIMC hIMC;
DWORD dwSize;
DWORD dwConversion, dwSentence;
switch( wParam )
{
case IMN_SETCONVERSIONMODE: // 全角/半角,中/英文标点改变
hIMC = ImmGetContext( hWnd );
ImmGetConversionStatus( hIMC, &dwConversion, &dwSentence );
g_bImeSharp = ( dwConversion & IME_CMODE_FULLSHAPE )? true : false;
g_bImeSymbol = ( dwConversion & IME_CMODE_SYMBOL )? true : false;
ImmReleaseContext( hWnd, hIMC );
break;
case IMN_OPENCANDIDATE: // 进入选字状态
case IMN_CHANGECANDIDATE: // 选字表翻页
hIMC = ImmGetContext( hWnd );
if( g_lpCandList )
{
GlobalFree( (HANDLE)g_lpCandList );
g_lpCandList = NULL;
} // 释放以前的选字表
if( dwSize = ImmGetCandidateList( hIMC, 0, NULL, 0 ))
{
g_lpCandList = (LPCANDIDATELIST)GlobalAlloc( GPTR, dwSize );
if( g_lpCandList )
ImmGetCandidateList( hIMC, 0, g_lpCandList, dwSize );
} // 得到新的选字表
ImmReleaseContext( hWnd, hIMC );
if( g_lpCandList )
ConvertCandList( g_lpCandList, g_szCandList ); // 选字表整理成串
break;
case IMN_CLOSECANDIDATE: // 关闭选字表
if( g_lpCandList )
{
GlobalFree( (HANDLE)g_lpCandList );
g_lpCandList = NULL;
} // 释放
g_szCandList[ 0 ] = 0;
break;
}
return true; // 总是返回true,防止IME窗口打开
}
bool CIme::OnWM_IME_COMPOSITION( HWND hWnd, LPARAM lParam )
{
// 输入改变
HIMC hIMC;
DWORD dwSize;
hIMC = ImmGetContext( hWnd );
if( lParam & GCS_COMPSTR )
{
dwSize = ImmGetCompositionString( hIMC, GCS_COMPSTR, (void*)g_szCompStr, sizeof( g_szCompStr ));
g_szCompStr[ dwSize ] = 0;
} // 取得szCompStr
if( lParam & GCS_COMPREADSTR )
{
dwSize = ImmGetCompositionString( hIMC, GCS_COMPREADSTR, (void*)g_szCompReadStr, sizeof( g_szCompReadStr ));
g_szCompReadStr[ dwSize ] = 0;
} // 取得szCompReadStr
if( lParam & GCS_CURSORPOS )
{
g_nImeCursor = 0xffff & ImmGetCompositionString( hIMC, GCS_CURSORPOS, NULL, 0 );
} // 取得nImeCursor
if( lParam & GCS_RESULTSTR )
{
unsigned char str[ MAX_PATH ];
dwSize = ImmGetCompositionString( hIMC, GCS_RESULTSTR, (void*)str, sizeof( str )); // 取得汉字输入串
str[ dwSize ] = 0;
unsigned char *p = str;
while( *p )PostMessage( hWnd, WM_CHAR, (WPARAM)(*p++), 1 ); // 转成WM_CHAR消息
}
ImmReleaseContext( hWnd, hIMC );
return true; // 总是返回true,防止IME窗口打开
}
char* CIme::GetImeName()
{
return g_szImeName[ 0 ]? g_szImeName : NULL;
}
bool CIme::IfImeSharp()
{
// 是否全角
return g_bImeSharp;
}
bool CIme::IfImeSymbol()
{
// 是否中文标点
return g_bImeSymbol;
}
void CIme::GetImeInput( char **pszCompStr, char **pszCompReadStr, int *pnImeCursor, char **pszCandList )
{
if( pszCompStr )*pszCompStr = g_szCompStr;
if( pszCompReadStr )*pszCompReadStr = g_szCompReadStr;
if( pnImeCursor )*pnImeCursor = g_nImeCursor;
if( pszCandList )*pszCandList = g_szCandList;
}
由于微软拼音实现了很多自己的东西,CIme和它的兼容性有些问题:
1)在函数ConvertCandList中所说的选字表的问题。
2)函数GetImeInput返回的szCompReadStr显然经过了加工而不是最初的键盘输入。
它的每个可组合的输入占以空格补足的8字节(Byte),且新的不可组合的输入存为0xa1。我们可以在输入法名字中有子串“微软拼音”时,只显示末尾的一组8字节(Byte),如果有0xa1就什么都不显示,也可以直接用TextOut显示所有的。
编辑:请不要使用多线程下载,否则会被封IP。
本文附带的源程序(1.1MB)
第一次真正意义上的用VC++实现的一个完整的Win32程序—俄罗斯方块-转帖
第一次真正意义上的用VC++实现的一个完整的Win32程序。
//Block.h
//————————————————————————————————-
/*
定义每个方块的结构
*/
#if !defined _BLOCK_H_
#define _BLOCK_H_
#define BLOCK_VERSION &H01000000 //主版本号、辅版本、附加版本、附加2
#define BLOCK_SIZE 6 //存储到文件时占用的字节数
#define BLOCK_HEADER_SIZE 8 //存储文件头信息的大小
struct _Block
{//注意:这些字段对于存储文件来说是有先后之分的。
unsigned int ID:8;
unsigned int NextID:8;
int Width:4;
int Height:4;
int OffsetY:4;
int OffsetX:4;
unsigned int Elements; //方块的各位是否为实体
};
typedef _Block BLOCK;
#endif
//————————————————————————————————-
//CustomGDI.h
//————————————————————————————————-
#pragma once
#include “windows.h”
//#include “d3d9.h”
#define BORDER_STYLE_NONE 0
#define BORDER_STYLE_FLAT 1
//为简单起见,目前只提供FLAT
//#define BORDER_STYLE_FIXED3D 2
//#define BORDER_STYLE_INNER3D 4
#define BORDER_STYLE_DEFAULT BORDER_STYLE_NONE
#define INNER_STYLE_EMPTY 0
#define INNER_STYLE_SOLID 1
#define INNER_STYLE_DEFAULT INNER_STYLE_EMPTY
#define TRANSPARENT_COLOR RGB(0,0,0)
#define BACKGROUND_DEFAULT_COLOR RGB(0,0,0)
typedef int INNER_STYLE;
typedef int BORDER_STYLE;
typedef DWORD GDI_COLOR;
class CCustomGDI
{
public:
//CCustomGDI(void);
CCustomGDI(HWND hWnd);
~CCustomGDI(void);
void TextOut(int x, int y,const char* lpString, int cbString);
void Drawbox(PRECT prect, BORDER_STYLE bstyle=BORDER_STYLE_DEFAULT, INNER_STYLE istyle=INNER_STYLE_DEFAULT);
void Drawbox(int x, int y, int height, int width, BORDER_STYLE bstyle=BORDER_STYLE_DEFAULT, INNER_STYLE istyle=INNER_STYLE_DEFAULT);
void DrawPic(int x, int y, int height, int width, const char* file);
void DrawPic(PRECT prect, const char* file);
void Clear(void);
void Clear(PRECT prect);
void Clear(GDI_COLOR color);
void Clear(PRECT prect, GDI_COLOR color);
void Clear(int x, int y, int height, int width, GDI_COLOR color);
void SetBkColor(GDI_COLOR color); //设置背景色
void SetColor(GDI_COLOR color); //设置前景色
void Set3DColor(GDI_COLOR ul_color, GDI_COLOR rb_color); //设置绘制3D时左上角与右下角的颜色
void SetBorderColor(GDI_COLOR color);
void SetBorderSize(int size);
protected:
//LPDIRECT3D9 m_pD3D;
//LPDIRECT3DDEVICE9 m_pd3dDevice;
//HDC m_hdc;
HWND m_hwnd;
//HBRUSH m_hbrBkgnd;
GDI_COLOR m_background;
int m_bordersize;
GDI_COLOR m_bordercolor;
GDI_COLOR m_color;
};
//————————————————————————————————-
//CustomGDI.cpp
//————————————————————————————————-
#include “.\customgdi.h”
//
//CCustomGDI::CCustomGDI(void)
//{
//}
//
CCustomGDI::CCustomGDI(HWND hWnd)
{
//初始化图形设备
m_hwnd=hWnd;
//m_hdc=GetDC(hWnd);
m_background=BACKGROUND_DEFAULT_COLOR;
m_bordersize=1;
m_bordercolor=RGB(0×80,0×80,0×80); //gray
m_color=RGB(0xFF,0xFF,0xFF); //white
}
CCustomGDI::~CCustomGDI(void)
{
//ReleaseDC(m_hwnd, m_hdc);
}
void CCustomGDI::TextOut(int x, int y,const char* lpString, int cbString)
{
HDC hdc=GetDC(m_hwnd);
::TextOut(hdc,x,y,lpString,cbString);
ReleaseDC(m_hwnd,hdc);
}
void CCustomGDI::Drawbox(PRECT prect, BORDER_STYLE bstyle, INNER_STYLE istyle)
{
HBRUSH hbr;
HDC hdc;
hdc=GetDC(m_hwnd);
RECT rect;
rect.top=prect->top;
rect.bottom=prect->bottom;
rect.left=prect->left;
rect.right=prect->right;
if(bstyle==BORDER_STYLE_FLAT)
{
//如果为BORDER_STYLE_FLAT
hbr=CreateSolidBrush(m_bordercolor);
FrameRect(hdc, &rect, hbr); //这里不知道如何画线,呵呵。
DeleteObject(hbr);
rect.left+=m_bordersize;
rect.right-=m_bordersize;
rect.top+=m_bordersize;
rect.bottom-=m_bordersize;
}
if(istyle==INNER_STYLE_SOLID) {
hbr=CreateSolidBrush(m_color);
FillRect(hdc, &rect, hbr);
DeleteObject(hbr);
}
ReleaseDC(m_hwnd,hdc);
}
void CCustomGDI::Drawbox(int x, int y, int height, int width, BORDER_STYLE bstyle, INNER_STYLE istyle)
{
RECT rect;
rect.top=y;
rect.left=x;
rect.bottom=y+height-1;
rect.right=x+width-1;
Drawbox(&rect,bstyle,istyle);
}
void CCustomGDI::DrawPic(int x, int y, int height, int width, const char* file)
{
}
void CCustomGDI::DrawPic(PRECT prect, const char* file)
{
}
void CCustomGDI::Clear(void)
{
//清除屏幕
RECT rect;
GetClientRect(m_hwnd,&rect);
Clear(&rect, m_background);
}
void CCustomGDI::Clear(PRECT prect)
{
Clear(prect, m_background);
}
void CCustomGDI::Clear(GDI_COLOR color)
{
RECT rect;
GetClientRect(m_hwnd,&rect);
Clear(&rect, color);
}
void CCustomGDI::Clear(PRECT prect, GDI_COLOR color)
{
HDC hdc;
hdc=GetDC(m_hwnd);
HBRUSH hbr=CreateSolidBrush(color);
FillRect(hdc, prect, hbr);
DeleteObject(hbr);
ReleaseDC(m_hwnd,hdc);
}
void CCustomGDI::Clear(int x, int y, int height, int width, GDI_COLOR color)
{
RECT rect;
rect.left=x;
rect.top=y;
rect.right=x+height-1;
rect.bottom=y+width-1;
Clear(&rect,color);
}
void CCustomGDI::SetBkColor(GDI_COLOR color)
{
m_background=color;
}
void CCustomGDI::SetColor(GDI_COLOR color)
{
m_color=color;
}
void CCustomGDI::Set3DColor(GDI_COLOR ul_color, GDI_COLOR rb_color)
{
}
void CCustomGDI::SetBorderSize(int size)
{
}
void CCustomGDI::SetBorderColor(GDI_COLOR color)
{
}
//————————————————————————————————–
//Els.h
//————————————————————————————————-
#include <windows.h>
//#include <d3d9.h>
#include <stdio.h>
#include <direct.h>
#include <time.h>
#include “Block.h”
#include “CustomGDI.h”
#define PLAYAREA_HEIGHT 24
#define PLAYAREA_WIDTH 12
#define PLAYAREA_EMPTY_COLOR RGB(0,0,0)
#define IDT_PLAY 2005
#define GAME_STATUS_STOPPED 0
#define GAME_STATUS_RUNNING 1
#define GAME_STATUS_PAUSED -1
#define PLAYER_DEFAULT_NAME “<Player>”
#define PLAYER_MAX_LEVEL 12
#define PLAYER_MAX_SCORE 999999999
struct _PLAYER
{
char Name[50];
int Power; //爆了几次
int Score; //得分,最大为999999999
};
struct _ELSSYS
{
int Level; //当前游戏级别
int ClientHeight; //当前客户区域高度
int ClientWidth; //当前客户区域宽度
int PlayAreaX; //游戏区域X坐标(注意:不包含游戏区域外的边框等)
int PlayAreaY; //游戏区域Y坐标(注意:不包含游戏区域外的边框等)
int SingleHeight; //单个格的高度
int SingleWidth; //单个格的宽度
int BorderSize; //边框大小
int Spacing; //格与格之间的间隔
int NextX; //下一个方块显示区域的X坐标
int NextY; //下一个方块显示区域的Y坐标
bool IsNextShown; //下一个方块是否显示
};
typedef _PLAYER PLAYER;
typedef _ELSSYS EVIRONMENT;
//—————————————————————————————————
//Els.cpp
//—————————————————————————————————
#include “Els.h”
//Direct3D Object
//LPDIRECT3D9 g_pD3D = NULL;
//Direct3D Device
//LPDIRECT3DDEVICE9 g_pd3dDevice = NULL;
//窗体的HWND
HWND g_hwnd;
int g_Status=GAME_STATUS_STOPPED; //存储游戏的状态
//当前的时间间隔
//int g_Interval=1000;
//游戏区域,存放每个格的颜色值,如果为0,表示当前格没有占用,否则已占用。
GDI_COLOR g_PlayArea[PLAYAREA_HEIGHT][PLAYAREA_WIDTH];
//当前行、列
int g_CurRow=0;
int g_CurCol=0;
//当前方块的索引
int g_CurBlock;
//当前方块的颜色
GDI_COLOR g_CurBlockColor;
//下一个方块的索引
int g_NextBlock;
GDI_COLOR g_NextBlockColor;
//存放所有的方块
BLOCK* Blocks=NULL;
//方块的个数
int g_BlockCount=0;
//当前级别
int g_Level=0;
int g_NextLevelPower=0;
int g_NextLevelScore=1000;
//环境信息
EVIRONMENT g_Env;
//用户的信息
PLAYER g_Player={“Player”,0,0};
//声明自己的GDI对象
CCustomGDI* g_GDI;
//所有函数定义
extern void CaculateEnv(void); //计算界面环境信息
extern void Render(void); //绘制界面
extern HRESULT LoadBlocks(void); //载入方块
extern void ClearBlocks(void); //清除所有方块所占内存
extern void _Bottom(void); //方块置底后的处理过程
extern void Bottom(void); //方块置底的处理过程
extern void Down(void); //方块下落
extern void MapCurBlockToPlayArea(void); //把当前方块影射到游戏区域
//
//void ShowDebugMsg(const char* sMsg, int x=100, int y=100)
//{
// HDC hdc;
// hdc=GetDC(g_hwnd);
// TextOut(hdc,x,y, sMsg, (int)strlen(sMsg));
//}
//
//清除释放所有方块所占内存
void ClearBlocks()
{
if(Blocks!=NULL)
{
free(Blocks);
}
}
//从文件中调入所有的方块
HRESULT LoadBlocks()
{
int i;
FILE* fp;
char sPath[_MAX_PATH];
char Header[BLOCK_HEADER_SIZE];
//char sMsg[255];
if(Blocks!=NULL)
{
ClearBlocks();
}
_getcwd(sPath, _MAX_PATH); //这里不判断了
strcat(sPath, “\\Turn.Right.blk“);
fp=fopen(sPath, “rb”);
if(fp==NULL) {
//存在错误。
return E_FAIL;
}
fread(Header,1,BLOCK_HEADER_SIZE,fp);
//这里不再判断这个文件是否正确了,同时没有判断版本信息。
//0-2字节为:BLK
//3-6字节为:版本信息
//7字节为方块个数。
g_BlockCount=(unsigned int)Header[BLOCK_HEADER_SIZE-1];
//然后申请g_BlockCount大小的方块数组
Blocks=(BLOCK *)malloc(sizeof(BLOCK)*g_BlockCount);
for(i=0;i<g_BlockCount;i++)
{
fread(&Blocks[i], sizeof(BLOCK), 1, fp);
//测试载入的小片段
//sprintf(sMsg, “ID:%d;Next:%d.”,Blocks[i].ID,Blocks[i].NextID);
//ShowDebugMsg(sMsg, 0, 24*i);
//MessageBox(g_hwnd, sMsg, “test”,MB_OK);
}
fclose(fp);
return S_OK;
}
//_Drawbox:
//在俄罗斯方块区域以颜色color绘制第r行,第c列的单元格方块。
void _Drawbox(int r, int c, GDI_COLOR color)
{
int x,y;
x=g_Env.PlayAreaX + g_Env.BorderSize + (c+1)*g_Env.Spacing + c*g_Env.SingleWidth;
y=g_Env.PlayAreaY + g_Env.BorderSize + (r+1)*g_Env.Spacing + r*g_Env.SingleHeight;
g_GDI->SetColor(color);
//g_GDI->Set3DColor(WHITE,BLACK);
if(color==PLAYAREA_EMPTY_COLOR)
{
g_GDI->Drawbox(x,y,g_Env.SingleHeight,g_Env.SingleWidth,BORDER_STYLE_NONE,INNER_STYLE_SOLID);
}
else
{
g_GDI->Drawbox(x,y,g_Env.SingleHeight,g_Env.SingleWidth,BORDER_STYLE_FLAT,INNER_STYLE_SOLID);
}
}
void HideCurBlock()
{
//清除屏幕上当前方块的显示
int row,col;
for(row=0;row<=Blocks[g_CurBlock].Height;row++)
{
if(g_CurRow+row<0) continue;
for(col=0;col<=Blocks[g_CurBlock].Width;col++)
{
if(((Blocks[g_CurBlock].Elements) & (1<<(row*(Blocks[g_CurBlock].Width+1)+col)))!=0)
{
_Drawbox(g_CurRow+row,g_CurCol+col,PLAYAREA_EMPTY_COLOR);
}
}
}
}
void ShowCurBlock()
{
//在屏幕上显示当前方块
int row,col;
for(row=0;row<=Blocks[g_CurBlock].Height;row++)
{
if(g_CurRow+row<0) continue;
for(col=0;col<=Blocks[g_CurBlock].Width;col++)
{
if(((Blocks[g_CurBlock].Elements) & (1<<(row*(Blocks[g_CurBlock].Width+1)+col)))!=0)
{
_Drawbox(g_CurRow+row,g_CurCol+col,g_CurBlockColor); //注意g_CurBlockColor值是否设置
}
}
}
//char s[200];
//sprintf(s,”Block:%d,%2x;SIZE:%d.”,g_CurBlock, Blocks[g_CurBlock].Elements,sizeof(BLOCK));
//g_GDI->Drawbox(0,g_Env.ClientHeight-35,30,g_Env.ClientWidth*3/10-10,BORDER_STYLE_FLAT,INNER_STYLE_SOLID);
//g_GDI->TextOut(10,g_Env.ClientHeight-30,s,(int)strlen(s));
}
void ShowNextBlock()
{
//在下一个方块的显示框中显示下一个方块
int row,col;
int blkRow,blkCol;
blkRow=(3-Blocks[g_NextBlock].Height)/2;
blkCol=(3-Blocks[g_NextBlock].Width)/2;
g_GDI->SetColor(PLAYAREA_EMPTY_COLOR);
g_GDI->Drawbox(g_Env.NextX,g_Env.NextY,((g_Env.SingleHeight+g_Env.Spacing)<<2)+g_Env.Spacing+(g_Env.BorderSize<<1),((g_Env.SingleWidth+g_Env.Spacing)<<2)+g_Env.Spacing+(g_Env.BorderSize<<1),BORDER_STYLE_FLAT,INNER_STYLE_SOLID);
for(row=0;row<4;row++)
{
for(col=0;col<4;col++)
{
if(row>=blkRow && row<=blkRow+Blocks[g_NextBlock].Height && col>=blkCol && col<=blkCol+Blocks[g_NextBlock].Width)
{
if((Blocks[g_NextBlock].Elements & (1<<((row-blkRow)*(Blocks[g_NextBlock].Width+1)+(col-blkCol))))!=0)
{
g_GDI->SetColor(g_NextBlockColor);
g_GDI->Drawbox(g_Env.NextX+g_Env.BorderSize+g_Env.Spacing+(g_Env.SingleWidth+g_Env.Spacing)*col, g_Env.NextY+g_Env.BorderSize+g_Env.Spacing+(g_Env.SingleHeight+g_Env.Spacing)*row,g_Env.SingleHeight,g_Env.SingleWidth,BORDER_STYLE_FLAT,INNER_STYLE_SOLID);
continue;
}
}
g_GDI->SetColor(PLAYAREA_EMPTY_COLOR);
g_GDI->Drawbox(g_Env.NextX+g_Env.BorderSize+g_Env.Spacing+(g_Env.SingleWidth+g_Env.Spacing)*col, g_Env.NextY+g_Env.BorderSize+g_Env.Spacing+(g_Env.SingleHeight+g_Env.Spacing)*row,g_Env.SingleHeight,g_Env.SingleWidth,BORDER_STYLE_FLAT,INNER_STYLE_SOLID);
}
}
}
void ShowGameInfo()
{
char s[200];
//显示游戏数据信息
if(g_Status==GAME_STATUS_STOPPED)
{
strcpy(s,”Game Status: Stopped.”);
}
if(g_Status==GAME_STATUS_RUNNING)
{
strcpy(s,”Game Status: Running.”);
}
if(g_Status==GAME_STATUS_PAUSED)
{
strcpy(s,”GameStatus: Paused.”);
}
g_GDI->TextOut(g_Env.ClientWidth*3/4,g_Env.ClientHeight-30,” “,30);
g_GDI->TextOut(g_Env.ClientWidth*3/4,g_Env.ClientHeight-30,s,(int)strlen(s));
//用户得分、当前级别
sprintf(s,”Score: %d”,g_Player.Score);
g_GDI->TextOut(g_Env.ClientWidth*3/4,g_Env.ClientHeight/2-50,” “,30);
g_GDI->TextOut(g_Env.ClientWidth*3/4,g_Env.ClientHeight/2-50,s,(int)strlen(s));
sprintf(s,”Level: %d”,g_Level);
g_GDI->TextOut(g_Env.ClientWidth*3/4,g_Env.ClientHeight/2-30,” “,30);
g_GDI->TextOut(g_Env.ClientWidth*3/4,g_Env.ClientHeight/2-30,s,(int)strlen(s));
}
BOOL CanMoveDown()
{
int row,col;
if(Blocks==NULL) return FALSE;
if(g_BlockCount<=0) return FALSE;
if(g_CurBlock<0||g_CurBlock>=g_BlockCount) return FALSE;
//如果已经到达最下面一行,不能再向下移了。
if((g_CurRow+Blocks[g_CurBlock].Height+1)>=PLAYAREA_HEIGHT) return FALSE;
for(col=0;col<=Blocks[g_CurBlock].Width;col++)
{
for(row=Blocks[g_CurBlock].Height;row>=0;row–)
{
//找到最下的非空
if(((Blocks[g_CurBlock].Elements) & (1<<(row*(Blocks[g_CurBlock].Width+1)+col)))!=0)
{
//如果游戏区域的下一行相应位置不空,则也不能再向下移动了。
if(g_PlayArea[g_CurRow+row+1][g_CurCol+col]!=PLAYAREA_EMPTY_COLOR)
{
return FALSE;
}
}
}
}
return TRUE;
}
BOOL CanMoveLeft()
{
int row,col;
if(Blocks==NULL) return FALSE;
if(g_BlockCount<=0) return FALSE;
if(g_CurBlock<0||g_CurBlock>=g_BlockCount) return FALSE;
//如果已经到达最左一列,不能再左移了。
if(g_CurCol<=0) return FALSE;
for(row=0;row<=Blocks[g_CurBlock].Height;row++)
{
for(col=0;col<=Blocks[g_CurBlock].Width;col++)
{
//找到最左的非空
if(((Blocks[g_CurBlock].Elements) & (1<<(row*(Blocks[g_CurBlock].Width+1)+col)))!=0)
{
//如果游戏区域的左位置不空,则也不能再左移动了。
if(g_PlayArea[g_CurRow+row][g_CurCol+col-1]!=PLAYAREA_EMPTY_COLOR)
{
return FALSE;
}
}
}
}
return TRUE;
}
BOOL CanMoveRight()
{
if(Blocks==NULL) return FALSE;
if(g_BlockCount<=0) return FALSE;
if(g_CurBlock<0||g_CurBlock>=g_BlockCount) return FALSE;
//如果已经到达最右一列,不能再右移了。
if(g_CurCol+Blocks[g_CurBlock].Width+1>=PLAYAREA_WIDTH) return FALSE;
int row,col;
for(row=0;row<=Blocks[g_CurBlock].Height;row++)
{
for(col=Blocks[g_CurBlock].Width;col>=0;col–)
{
//找到最右的非空
if(((Blocks[g_CurBlock].Elements) & (1<<(row*(Blocks[g_CurBlock].Width+1)+col)))!=0)
{
//如果游戏区域的右位置不空,则也不能再右移动了。
if(g_PlayArea[g_CurRow+row][g_CurCol+col+1]!=PLAYAREA_EMPTY_COLOR)
{
return FALSE;
}
}
}
}
return TRUE;
}
BOOL CanTurn()
{
int row,col;
int ARow,ACol;
BLOCK* next;
if(Blocks==NULL) return FALSE;
if(g_BlockCount<=0) return FALSE;
if(g_CurBlock<0||g_CurBlock>=g_BlockCount) return FALSE;
if(Blocks[g_CurBlock].NextID<0||Blocks[g_CurBlock].NextID>=(unsigned int)g_BlockCount) return FALSE; //说明原数据文件有错误,需更正
next=&Blocks[Blocks[g_CurBlock].NextID];
//这里的OffsetY、OffsetX,应该是由当前Block提供。
ARow=g_CurRow + Blocks[g_CurBlock].OffsetY;
ACol=g_CurCol + Blocks[g_CurBlock].OffsetX;
//如果超过高度了,应该不允许变换了,要不,一直按变换键,可能就永远落不了地了。
if(ARow+next->Height+1>PLAYAREA_HEIGHT) return FALSE;
//如果列超出游戏区域,可以处理一下。
if(ACol<0) ACol=0;
if(ACol+next->Width+1>=PLAYAREA_WIDTH)
{
ACol=PLAYAREA_WIDTH-next->Width-1;
}
//实现CanTurn时,突然想到,当前方块所占的空,不要在g_PlayArea中记录
for(row=0;row<=next->Height;row++)
{
for(col=0;col<=next->Width;col++)
{
if(((next->Elements) & (1<<(row*next->Width+col+1)))!=0)
{
//如果下一个变换的相应位置非空的话
if(g_PlayArea[ARow+row][ACol+col]!=PLAYAREA_EMPTY_COLOR)
{
//如果游戏区域也非空
return FALSE;
}
}
}
}
return TRUE;
}
void _Turn()
{
g_CurRow = g_CurRow + Blocks[g_CurBlock].OffsetY;
g_CurCol = g_CurCol + Blocks[g_CurBlock].OffsetX;
g_CurBlock = Blocks[g_CurBlock].NextID;
//关于列的超范围值,变换应该同CanTurn中的算法相同。
if(g_CurCol<0) g_CurCol=0;
if(g_CurCol + Blocks[g_CurBlock].Width+1>=PLAYAREA_WIDTH)
{
g_CurCol = PLAYAREA_WIDTH-Blocks[g_CurBlock].Width-1;
}
//变换完毕
}
void Turn()
{
if(g_Status!=GAME_STATUS_RUNNING) return;
if(CanTurn()==TRUE)
{
HideCurBlock();
_Turn();
ShowCurBlock();
}
}
void _MoveLeft()
{
g_CurCol–;
}
void MoveLeft()
{
if(g_Status!=GAME_STATUS_RUNNING) return;
if(CanMoveLeft()==TRUE)
{
HideCurBlock();
_MoveLeft();
ShowCurBlock();
}
}
void _MoveRight()
{
g_CurCol++;
}
void MoveRight()
{
if(g_Status!=GAME_STATUS_RUNNING) return;
if(CanMoveRight()==TRUE)
{
HideCurBlock();
_MoveRight();
ShowCurBlock();
}
}
void _Down()
{
g_CurRow++;
}
void MapCurBlockToPlayArea()
{
int row,col;
row=0;
col=0;
for(row=0;row<=Blocks[g_CurBlock].Height;row++)
{
for(col=0;col<=Blocks[g_CurBlock].Width;col++)
{
if((Blocks[g_CurBlock].Elements & (1<<(row*(Blocks[g_CurBlock].Width+1)+col)))!=0)
{
g_PlayArea[g_CurRow+row][g_CurCol+col]=g_CurBlockColor;
}
}
}
}
void Gain()
{
int row,col;
int gain=0;
BOOL full; //当前行是否全部填满
for(row=0;row<=Blocks[g_CurBlock].Height;row++)
{
full=TRUE;
for(col=0;col<PLAYAREA_WIDTH;col++)
{
if(g_PlayArea[g_CurRow+row][col]==PLAYAREA_EMPTY_COLOR)
{
full=FALSE;
break;
}
}
if(full==TRUE)
{
//消当前行的动画效果
//消当前行
int tmpRow,tmpCol;
for(tmpRow=g_CurRow+row;tmpRow>0;tmpRow–)
{
for(tmpCol=0;tmpCol<PLAYAREA_WIDTH;tmpCol++)
{
g_PlayArea[tmpRow][tmpCol]=g_PlayArea[tmpRow-1][tmpCol];
_Drawbox(tmpRow,tmpCol,g_PlayArea[tmpRow][tmpCol]);
}
}
for(tmpCol=0;tmpCol<PLAYAREA_WIDTH;tmpCol++)
{
g_PlayArea[0][tmpCol]=PLAYAREA_EMPTY_COLOR;
_Drawbox(tmpRow,tmpCol,PLAYAREA_EMPTY_COLOR);
}
gain++;
}
}
//变更用户的相关情况
if(gain>0)
{
g_Player.Score+=(100*(gain*gain-gain+1)); //1:100;2:300;3:700;4:1300;
if(g_Player.Score>PLAYER_MAX_SCORE)
{
g_Player.Power++;
g_Player.Score %= (PLAYER_MAX_SCORE+1);
}
ShowGameInfo();
}
}
void UpdateSys()
{
//变更系统相关情况
if(g_Player.Power==g_NextLevelPower)
{
if(g_Player.Score>=g_NextLevelScore)
{
//变更级别
g_Level++;
g_Level %= PLAYER_MAX_LEVEL;
g_NextLevelScore+=(100*(g_Level*g_Level)+1000);
if(g_NextLevelScore>PLAYER_MAX_SCORE)
{
g_NextLevelPower++;
g_NextLevelScore%=(PLAYER_MAX_SCORE+1);
}
//变更系统速度
KillTimer(g_hwnd,IDT_PLAY);
SetTimer(g_hwnd, IDT_PLAY,1000/(g_Level+1),NULL);
}
}
}
BOOL NextBlock()
{
g_CurBlock=g_NextBlock;
g_CurBlockColor=g_NextBlockColor;
g_CurRow=0;
g_CurCol=(PLAYAREA_WIDTH-Blocks[g_CurBlock].Width)/2;
srand((unsigned)time(NULL));
g_NextBlock=rand()%g_BlockCount;
g_NextBlockColor=RGB((rand()%4)*64+63,(rand()%4)*64+63,(rand()%4)*64+63);
ShowNextBlock();
ShowCurBlock();
int row,col;
for(row=0;row<=Blocks[g_CurBlock].Height;row++)
{
for(col=0;col<=Blocks[g_CurBlock].Width;col++)
{
if((Blocks[g_CurBlock].Elements & (1<<(row*(Blocks[g_CurBlock].Width+1)+col)))!=0)
{
if(g_PlayArea[g_CurRow+row][g_CurCol+col]!=PLAYAREA_EMPTY_COLOR) //如果所在位置已经不为空则Game Over。
{
return FALSE;
}
}
}
}
return TRUE;
}
void Stop()
{
if(g_Status!=GAME_STATUS_RUNNING) return;
KillTimer(g_hwnd,IDT_PLAY);
g_Status=GAME_STATUS_STOPPED;
ShowGameInfo();
}
void Down()
{
if(g_Status!=GAME_STATUS_RUNNING) return;
//g_GDI->Drawbox(0,g_Env.ClientHeight,60,20,BORDER_STYLE_FLAT,INNER_STYLE_SOLID);
//g_GDI->TextOut(10, g_Env.ClientHeight-30,”Downning!”,9);
if(CanMoveDown()==TRUE)
{
//BeginPaint(g_hwnd,NULL);
HideCurBlock();
_Down();
ShowCurBlock();
//ValidateRect(g_hwnd,NULL);
//UpdateWindow(g_hwnd);
}
else
{
_Bottom();
}
}
void _Bottom()
{
//把当前方块映射到游戏区域中
MapCurBlockToPlayArea();
//检查是否有可消行,变更用户得分
Gain();
//检查游戏级别是否需要提高
UpdateSys();
//设置当前方块为下一个方块,并重新产生一个下一方块
if(NextBlock()==FALSE)
{
//如果下一个方块顶死应该Game Over。
Stop(); //首先停止游戏。
//然后检查最高分,记录到排行榜。
}
ShowGameInfo();
}
void Bottom()
{
if(g_Status!=GAME_STATUS_RUNNING) return;
while(CanMoveDown()==TRUE)
{
HideCurBlock();
_Down();
ShowCurBlock();
}
_Bottom();
}
void Pause()
{
if(g_Status!=GAME_STATUS_RUNNING) return;
//clear timer.
KillTimer(g_hwnd, IDT_PLAY);
g_Status=GAME_STATUS_PAUSED;
ShowGameInfo();
}
//写到Resume,觉得应该引入一个变量,用来标识游戏是否已经开始,是否是继续游戏,而Start()只能算作重新从头开始。
void Resume()
{
if(g_Status!=GAME_STATUS_PAUSED) return;
SetTimer(g_hwnd, IDT_PLAY,1000/(g_Level+1),NULL);
g_Status=GAME_STATUS_RUNNING;
ShowGameInfo();
}
void Start()
{
if(g_Status!=GAME_STATUS_STOPPED) return;
int row,col;
for(row=0;row<PLAYAREA_HEIGHT;row++)
{
for(col=0;col<PLAYAREA_WIDTH;col++)
{
g_PlayArea[row][col]=PLAYAREA_EMPTY_COLOR;
}
}
//产生当前方块及下一个方块
srand((unsigned)time(NULL));
g_CurBlock=rand()%g_BlockCount;
g_CurBlockColor=RGB((rand()%4)*64+63,(rand()%4)*64+63,(rand()%4)*64+63);
g_NextBlock=rand()%g_BlockCount;
g_NextBlockColor=RGB((rand()%4)*64+63,(rand()%4)*64+63,(rand()%4)*64+63);
//决定当前方块的位置
g_CurRow=0;
g_CurCol=(PLAYAREA_WIDTH-Blocks[g_CurBlock].Width)/2;
//初始化系统信息
g_Level=0; //将来可以通过用户定制现在级别
g_NextLevelPower=0;
g_NextLevelScore=1000;
//初始化用户信息
strcpy(g_Player.Name, PLAYER_DEFAULT_NAME);
g_Player.Power=0;
g_Player.Score=0;
//然后开始游戏
Render(); //重新绘制界面
g_Status=GAME_STATUS_RUNNING;
SetTimer(g_hwnd, IDT_PLAY,(10-g_Level)*100,NULL);
ShowNextBlock();
ShowCurBlock();
ShowGameInfo();
}
void CaculateEnv()
{
RECT rect;
GetClientRect(g_hwnd, &rect); //得到当前窗口的大小
//更改环境变量
g_Env.ClientHeight=rect.bottom-rect.top+1;
g_Env.ClientWidth=rect.right-rect.left+1;
g_Env.BorderSize=3;
g_Env.Spacing=1;
g_Env.IsNextShown=true;
//得到各区域坐标
//游戏区域
g_Env.PlayAreaX=g_Env.ClientWidth*3/10+g_Env.BorderSize;
g_Env.PlayAreaY=g_Env.BorderSize;
g_Env.SingleHeight = (g_Env.ClientHeight-g_Env.PlayAreaY*2-g_Env.BorderSize*2-g_Env.Spacing)/PLAYAREA_HEIGHT-g_Env.Spacing;
g_Env.SingleWidth = (g_Env.ClientWidth – g_Env.PlayAreaX*2-g_Env.BorderSize*2-g_Env.Spacing)/PLAYAREA_WIDTH-g_Env.Spacing;
//下一个区域
g_Env.NextX = g_Env.ClientWidth*17/20-g_Env.BorderSize-g_Env.Spacing*5/2-g_Env.SingleWidth*2;
g_Env.NextY = g_Env.BorderSize*2;
//UpdateWindow(g_hwnd);
}
VOID Render()
{ //绘制整个界面
char s[200];
//清除所有
g_GDI->Clear(RGB(0×80,0×80,0×80));
//绘制图片
//g_GDI->DrawPic(g_Env.BorderSize*2,g_Env.BorderSize*2, g_Env.ClientWidth/5-g_Env.BorderSize*5,g_Env.ClientWidth/5-g_Env.BorderSize*5, “mydaughter.bmp”);
//绘制Logo
//g_GDI->DrawPic(g_Env.BorderSize*2,rect.bottom-g_Env.BorderSize*2,100,100, “logo.bmp”);
//绘制游戏区域
g_GDI->SetColor(0);
g_GDI->Drawbox(g_Env.PlayAreaX,g_Env.PlayAreaY,(g_Env.SingleHeight+g_Env.Spacing)*PLAYAREA_HEIGHT+g_Env.Spacing+g_Env.BorderSize*2,(g_Env.SingleWidth+g_Env.Spacing)*PLAYAREA_WIDTH+g_Env.Spacing+g_Env.BorderSize*2,BORDER_STYLE_FLAT,INNER_STYLE_SOLID);
int row,col;
for(row=0;row<PLAYAREA_HEIGHT;row++)
{
for(col=0;col<PLAYAREA_WIDTH;col++)
{
if(g_PlayArea[row][col]!=PLAYAREA_EMPTY_COLOR)
{
_Drawbox(row,col,g_PlayArea[row][col]);
}
}
}
//绘制当前方块
if(g_Status!=GAME_STATUS_STOPPED)
{
ShowNextBlock();
ShowCurBlock();
}
//绘制Next
//绘制各按钮
strcpy(s,”[Enter]: Start/Resume”);
g_GDI->TextOut(g_Env.ClientWidth*3/4,g_Env.ClientHeight/2,s,(int)strlen(s));
strcpy(s,”[Pause]: Pause”);
g_GDI->TextOut(g_Env.ClientWidth*3/4,g_Env.ClientHeight/2+20,s,(int)strlen(s));
strcpy(s,”↑: 翻转方块”);
g_GDI->TextOut(g_Env.ClientWidth*3/4,g_Env.ClientHeight/2+40,s,(int)strlen(s));
strcpy(s,”↓: 向下落一格”);
g_GDI->TextOut(g_Env.ClientWidth*3/4,g_Env.ClientHeight/2+60,s,(int)strlen(s));
strcpy(s,”←: 左移”);
g_GDI->TextOut(g_Env.ClientWidth*3/4,g_Env.ClientHeight/2+80,s,(int)strlen(s));
strcpy(s,”→: 右移”);
g_GDI->TextOut(g_Env.ClientWidth*3/4,g_Env.ClientHeight/2+100,s,(int)strlen(s));
strcpy(s,”[Space]: 置底”);
g_GDI->TextOut(g_Env.ClientWidth*3/4,g_Env.ClientHeight/2+120,s,(int)strlen(s));
strcpy(s,”[ESC]: Stop Game”);
g_GDI->TextOut(g_Env.ClientWidth*3/4,g_Env.ClientHeight/2+140,s,(int)strlen(s));
//绘制当前状态
ShowGameInfo();
//以下为调试信息
//sprintf(s,”ClientWidth:%d”,g_Env.ClientWidth);
//g_GDI->TextOut(0,0,s,(int)strlen(s));
//sprintf(s,”ClientHeight:%d”,g_Env.ClientHeight);
//g_GDI->TextOut(0,20,s,(int)strlen(s));
//sprintf(s,”PlayAreaX:%d”,g_Env.PlayAreaX);
//g_GDI->TextOut(0,40,s,(int)strlen(s));
//sprintf(s,”PlayAreaY:%d”,g_Env.PlayAreaY);
//g_GDI->TextOut(0,60,s,(int)strlen(s));
//sprintf(s,”SingleHeight:%d”,g_Env.SingleHeight);
//g_GDI->TextOut(0,80,s,(int)strlen(s));
//sprintf(s,”SingleWidth:%d”,g_Env.SingleWidth);
//g_GDI->TextOut(0,100,s,(int)strlen(s));
}
LRESULT WINAPI MsgProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch(msg)
{
case WM_TIMER:
Down();
return 0;
case WM_DESTROY:
PostQuitMessage(0);
return 0;
case WM_ACTIVATE:
if(wParam==WA_INACTIVE)
{
Pause();
}
break;
case WM_SIZE:
if(wParam!=SIZE_MINIMIZED)
{
CaculateEnv();
if(wParam==SIZE_RESTORED)
{
Render();
}
//UpdateWindow(hWnd);
}
return 0;
case WM_PAINT:
Render();
ValidateRect(hWnd, NULL); //呵呵,目前还不能去掉该行
return 0;
//case WM_SYSKEYDOWN:
case WM_KEYDOWN:
switch(wParam)
{
case VK_UP:
Turn();
break;
case VK_DOWN:
Down();
break;
case VK_LEFT:
MoveLeft();
break;
case VK_RIGHT:
MoveRight();
break;
case VK_SPACE:
Bottom();
break;
case VK_RETURN:
if(g_Status==GAME_STATUS_PAUSED)
{
Resume();
}
else
{
Start();
}
break;
case VK_PAUSE:
Pause();
break;
//case VK_END:
case VK_ESCAPE:
Stop();
break;
}
}
return DefWindowProc(hWnd,msg,wParam,lParam);
}
//系统初始化
HRESULT Initialize()
{
//绑定当前窗口到自己的GDI
g_GDI=new CCustomGDI(g_hwnd);
if(SUCCEEDED(LoadBlocks()))
{
return S_OK;
}
return E_FAIL;
}
//释放系统资源
void Cleanup()
{
//释放方块资源
ClearBlocks();
//释放GDI
delete g_GDI;
}
int WINAPI WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow)
{
//创建窗体
WNDCLASS wndclass={0, MsgProc, 0L, 0L, hInstance, NULL,NULL,NULL,NULL,”Els”};
RegisterClass(&wndclass);
g_hwnd=CreateWindow(“Els”,”Els v1.0.0.0″,
WS_OVERLAPPEDWINDOW,100,100,640,480,GetDesktopWindow(),NULL,wndclass.hInstance,NULL);
//初始化
if(SUCCEEDED(Initialize()))
{
ShowWindow(g_hwnd,SW_SHOWDEFAULT);
UpdateWindow(g_hwnd);
//进入Window消息循环
MSG msg;
while(GetMessage(&msg,NULL,0,0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
Cleanup();
UnregisterClass(“Els”, wndclass.hInstance);
return 0;
}
//——————————————————————————————————–
VC++中DLL的创建和使用
Dynamic-Link-Library
1、 函数
a) DLL中:
extern “C” __declspec(dllexport) BOOL isPrime(int num)
{
BOOL flag = false;
for(int i = 2 ; i < num ; i ++)
{
if(num % i == 0)
break;
}
if (i == num)
flag = true;
else
flag = false;
return flag;
}
b) 应用程序
typedef BOOL ISPRIME(int);
ISPRIME *isPrime;
hm = ::LoadLibrary(“mydll2.dll”);
isPrime = (ISPRIME *)::GetProcAddress(hm,”isPrime”);
if(isPrime(8))
MessageBox(“是素数”);
else
MessageBox(“不是素数”);
hm = ::LoadLibrary(“mydll2.dll”);
2、 类
a) DLL
i. IloveYou.h头文件
class __declspec(dllexport) CILoveYou
{
public:
int GetValue();
void SetValue(int v);
CILoveYou();
virtual ~CILoveYou();
private:
int a;
};
ii. IloveYou.cpp程序文件
CILoveYou::CILoveYou()
{
a = 0;
}
CILoveYou::~CILoveYou()
{
}
__declspec(dllexport) void CILoveYou::SetValue(int v)
{
this->a = v;
}
__declspec(dllexport) int CILoveYou::GetValue()
{
return a;
}
b) 应用程序
先把#include “ILoveYou.h”文件导入进来,然后在StdAfc.h头文件加入:
class __declspec(dllimport) CILoveYou;
访问该类的代码:
CILoveYou ily;
ily.SetValue(900);
char s[100];
wsprintf(s,”调用了类中的成员哦,值是:%d”,ily.GetValue());
ShowMessage(this->GetSafeHwnd(),s);
MFC 规则DLL
1、 函数
a) DLL
此类DLL有一个继承了CwinApp的类,但是函数可以不放在该类中。
extern “C” __declspec(dllexport) BOOL isOdd(int num)
{
AFX_MANAGE_STATE(AfxGetStaticModuleState());//此句一定要
if(num % 2 == 0)
return true;
else
return false;
}
b) 应用程序
void CTestdll2Dlg::OnButton5()
{
// TODO: Add your control notification handler code here
typedef BOOL ISODD(int);
ISODD *isOdd;
HINSTANCE hm;
if(hm = ::LoadLibrary(“mfcdll4.dll”))
{
isOdd = (ISODD *)::GetProcAddress(hm,”isOdd”);
if(isOdd)
{
if(isOdd(9))
MessageBox(“是偶数”);
else
MessageBox(“不是偶数”);
}
else
{
MessageBox(“有问题”);
}
::FreeLibrary(hm);
}
else
{
MessageBox(“DLL加载失败”);
}
}
2、 类
a) DLL中的代码
i. Clzh类的头文件:lzh.h
class AFX_EXT_CLASS Clzh //此处一定要用AFX_EXT_CLASS
{
public:
CString GetValue();
void SetValue(CString str);
Clzh();
private:
CString str;
};
ii. Clzh类的实现文件:lzh.cpp
Clzh::Clzh()
{
}
__declspec(dllexport) void Clzh::SetValue(CString str)
{
AFX_MANAGE_STATE(AfxGetStaticModuleState());
this->str = str;
}
__declspec(dllexport) CString Clzh::GetValue()
{
AFX_MANAGE_STATE(AfxGetStaticModuleState());
return str;
}
b) 应用程序
在StdAfx.h中头文件中加入:class __declspec(dllimport) Clzh;
在要访问该类的地方加入头文件:#include “lzh.h”
程序如下:
void CTestdll2Dlg::OnButton7()
{
// TODO: Add your control notification handler code here
Clzh lzh;
lzh.SetValue(“abc”);
MessageBox(lzh.GetValue());
}
