用Delphi开发DirectX控件

用Delphi开发DirectX控件
整理编辑:China ASP

  Microsoft推出的DirectX使我们在Windows9x下开发游戏软件便利了许多。一般在介绍DirectX 的资料里都讲的是如何用VC++来开发,其实inprise公司的语言也可以用来开发基于DirectX的游戏软件。我们这里用的是DirectX控件,它有Delphi3和Delphi4不同的版本。在
http://www.ingjapan.ne.jp/hori/ 处你可以download,是由一个日本人写的,而且,这套控件是完全免费的,你可以自由使用。在这套控件里有DirectX的各种范例程序,我们今天来讨论一下其中基于DirectX的网络通信程序如何开发。

  想必大家都看到过那些硝烟纷飞的即时战略游戏,这些游戏中一个很诱人的买点就是可以几个人同时加入战斗,各自扮演一方高手,杀它个你死我活。那么这些即时战略游戏中的网络对战部分是怎么写的呢?其实在Microsoft的DirectX中专门有一类API就是负责网络通信的,不管是基于IPX,还是TCP/IP,或者是Modem,它都可以圆满解决。而作为程序设计的我们一般来说不用操心这些连接方式不同而带来的代码的不同,我们可以一视同仁,只要写一套统一的代码就可以了,各种连接方式的细节问题我们就交给DirectX去处理了。

  下面我们具体分析一下一个chat聊天程序的构造。运行samples/network/chat.dpr,我们就看到了一个最简单的聊天程序了。首先程序会让你选择连接的方式:IPX连接、Internet TCP/IP连接、调制解调器连接和串行连接;选择好连接方式后(下面假设你是选择用TCP/IP方式连接),你可以选择是创建一个新游戏还是进入一个已经存在的游戏(当然现在这里的游戏就是指一个聊天程序!);如果你是选择建立一个新游戏,那么接下来要你输入游戏的名字和你的名字,然后聊天就开始了;如果你是选择加入一个已经存在的游戏的话,那么你可以通过输入指定的IP地址来连接或者索性让程序去搜索有哪些已经存在的游戏名字。如果你在连接方式中选择的是调制解调器连接的话,就稍微复杂一些,需要选择调制解调器,并准备拨号和应答等。有没有发现这些连接的方式和过程和我们通常在游戏中看到的很相似?由于这些关于连接的对话框都是由DirectX提供的,因而会有一点语言上的问题。如果你安装的是DirectX的中文版本的话,那么你看见的将全部是中文。(顺便说一句,这套Delphi 控件所支持的DirectX必须在5.0版本以上。)
  这个程序本身并不复杂,下面是其主要的几个过程,我们已经加上了较为详细的注释:

  //增加游戏者
  procedure TMainForm.DXPlay1AddPlayer(Sender: TObject; Player: TDXPlayPlayer);
  begin
     Memo1.Lines.Add(Format(' %s entered a room.', [Player.Name]));
  end;


  //游戏者离开
  procedure TMainForm.DXPlay1DeletePlayer(Sender: TObject;Player: TDXPlayPlayer);
  begin
     Memo1.Lines.Add(Format(' %s left a room.', [Player.Name]));
  end;

  
  //DirectPlay打开
  procedure TMainForm.DXPlay1Open(Sender: TObject);
  var
     i: Integer;
  begin
     for i:=0 to DXPlay1.Players.Count-1 do
          if DXPlay1.Players[i].RemotePlayer then
            Memo1.Lines.Add(Format(' %s is entering a room.', [DXPlay1.Players[i].Name]));
    end;

   procedure TMainForm.FormDestroy(Sender: TObject);
  begin
     DXPlay1.Close;
  end;

  //窗口创建执行事件
  procedure TMainForm.FormCreate(Sender: TObject);
  begin
   try
      //DirectPlay 打开
        DXPlay1.Open;
   except
     //防错处理
        on E: Exception do
        begin
          Application.ShowMainForm := False;
          Application.HandleException(E);
          Application.Terminate;
        end;
   end;

   //显示有关信息在窗口的caption
   MainForm.Caption := Format('%s : %s', [DXPlay1.ProviderName, DXPlay1.SessionName]);
  end;

  //当有消息发送时
  procedure TMainForm.DXPlay1Message(Sender: TObject; Player: TDXPlayPlayer; Data: Pointer;DataSize: Integer);
  var
     s: string;
  begin
   case DXPlayMessageType(Data) of
      DXCHAT_MESSAGE:
      begin
          if TDXChatMessage(Data^).Len<=0 then
            s := ''
          else begin
            //计算字符串长度和内容
            SetLength(s, TDXChatMessage(Data^).Len);
            StrLCopy(PChar(s), @TDXChatMessage(Data^).c, Length(s));
          end;

          //显示收到的消息
          Memo1.Lines.Add(Format('%s> %s', [Player.Name, s]));
      end;
   end;
  end;

  //发送按钮
  procedure TMainForm.Button1Click(Sender: TObject);
  var
   Msg: ^TDXChatMessage;
   MsgSize: Integer;
  begin
     MsgSize := SizeOf(TDXChatMessage)+Length(Edit1.Text);
     GetMem(Msg, MsgSize);
     try
        Msg.dwType := DXCHAT_MESSAGE;
        Msg.Len := Length(Edit1.Text);
        StrLCopy(@Msg^.c, PChar(Edit1.Text), Length(Edit1.Text));
     
        //发送消息到所有的人
        DXPlay1.SendMessage(DPID_ALLPLAYERS, Msg, MsgSize);

        //发送消息到自己
        DXPlay1.SendMessage(DXPlay1.LocalPlayer.ID, Msg, MsgSize);
        Edit1.Text := '';
   finally
     FreeMem(Msg);
   end;
  end;

  TDXPlay控件是写这类程序的关键,其属性、事件和方法并不多。GUID属性用来程序的自我识别,具有相同GUID的程序互相之间就能识别,所以你可以看到GUID是一个很长的数字;Open方法用来打开通讯端口,Close用来关闭通讯端口;SendMessage方法是用来发送消息到所有的游戏者,当你的程序收到消息的时候,会产生OnMessage 事件。

  这个程序的代码应该是相当简练了,但是却完成了点对点的多点聊天功能。如果你在自己的程序里约定好一套规则,那么你的程序也就具备了互相的通信能力,是不是感觉很简单?可以说,利用DirectX来写这方面的通信程序是最佳的选择,你可以对网络的知识完全不懂,因为这一切已经由Microsoft花费了大量人力物力进行优化的代码来完成了。如果说有什么缺点,就是要求用户的电脑上一定要安装上DirectX,这在现在win98越来越普及的情况下,并不是一件难事。再说,Microsoft的DirectX也是一套完全免费的软件。利用DirectX优秀的性能加上功能强大的 Delphi语言,相信你一定能写出一套优秀的游戏软件(当然拥有设计良好的对战功能)。

Copyright &copy; 上海聚声计算机系统工程有限责任公司 1999-2000, All Rights Reserved



  • 0
    点赞
  • 0
    收藏
  • 打赏
    打赏
  • 0
    评论
================================== ==注意:一共2个压缩包,这是第2个== ================================== *提示:无自动安装程序,包含所有源码、例子、帮助,请按照安装顺序安装!!! DevExpress VCL v2012 vol 2.6 包含所有源码、例子、帮助 如果你安装过其它版本的DevExpressVCL,安装前请完全卸载老版本的Dev控件,并执行“清理Dev残余文件”,清理System32下的DevExpress的BPL文件。 What's New in DevExpress VCL 12.2.6 Release Notes Feature Highlights To learn about feature highlights in this version, please refer to the following page: New Features - DevExpress VCL 12.2.6 Known Issues To learn about known issues in this version, please refer to the following page: Known Issues - DevExpress VCL 12.2.6 The following sections list all minor and major changes in DevExpress VCL 12.2.6. Note that products, controls and libraries which aren't mentioned in the list below are included in the unified installer for compatibility, but have not been updated. New Features/Changes ExpressQuantumTreeList Suite Q484199 - Documentation - Provide an example of how to use the TcxCustomTreeList.Find function Resolved Issues VCL Subscription B232998 - Documentation - The OnValidateDrawValue event is not described ExpressBars Suite Q492229 - Activating an MDI child window always repaints it, regardless of the bar manager's AlwaysMerge property value Q490246 - Changing a bar item's Visible property when a form is being destroyed results in an AV Q489146 - Ribbon - A Ribbon tab group's Caption property does not apply to the group caption if this group is displayed in a popup window Q489457 - Ribbon - TdxRibbonBackstageView - In RAD Studio XE or later, an AV occurs when changing the parent of a currently hidden form with the BackstageView after the form Position property has been set to poDesigned and the toolbar on this form made visible Q486834 - Ribbon - TdxRibbonBackstageView - Invoking the BackstageView does not move focus to it from the currently focused control that resides on a form with this BackstageView B233045 - Ribbon - TdxRibbonBackstageView - Right-clicking an empty space within the left panel invokes the customizing popup menu Q493950 - Ribbon Form - In Windows XP, switching between skinned MDI child windows using Ctrl+Tab displays background windows if merging is enabled and the SupportNonClientDrawing property of the Ribbon control residing on the MDI child windows is set to False Q373762 - Ribbon Form - Restoring down a minimized application incorrectly resizes the Windows Aero Glass frame after the Ribbon form was programmatically hidden when minimizing the application B232887 - Shadows for drop-down windows are painted twice B234839 - TcxBarEditItem - ColorEdit - White color cannot be selected within the editor drop-down window ExpressDocking Library B233009 - An AV occurs when debugging a docking operation with TdxDockPanel in Delphi 7 if a breakpoint is set within the dock panel OnDock event handler ExpressNavBar B234038 - Customization Form - Item names cannot be edited if the 'uses' clause includes the dxNavBarAdvancedCustomization unit ExpressPageControl Q488278 - TcxPageControl - The Properties.TabSheetClass property setting is ignored in a page control docked to a control using its ManualDock method ExpressPivotGrid Suite Q495313 - Clicking OK within a filter drop-down window using the mouse results in an AV in certain cases B232801 - Documentation - The TcxPivotGridOLAPField.SortMode property is not described Q487923 - OLAP mode - Empty data cells are displayed when a dimension includes a large number of grouping values Q487520 - OLAP mode - The "List index out of bounds" exception when expanding a grouping value of an inner column/row field after an outer field has been hidden in the same area Q485882 - TcxPivotGridChartConnection - Row totals are included to the sdAllShown source data if the pivot grid's OptionsView.RowTotalsLocation property is set to rtlTree ExpressQuantumGrid Suite Q479920 - An AV occurs when the View navigator's information panel is resized in response to changing the panel text if the View is not currently locked for updates Q490851 - Banded Table View - The text specified via the View's FilterRow.InfoText or NewItemRow.InfoText property is not centered in the View with fixed bands Q495393 - Card View - Moving a row within a card using drag and drop scrolls the card content up to the first visible row and hides this row under the card bottom edge in certain cases Q487880 - Changing certain properties of the embedded navigator produces painting artifacts Q490502 - Chart View - Stacked column/bar diagrams incorrectly visualize negative values if the diagram AxisValue.MinMaxValues property is set to mmvAuto Q487902 - Documentation - The TcxCustomGridTableOptionsBehavior.CopyRecordsToClipboard property is not described B233429 - Server Mode - Changing the group order and then moving focus from the currently focused group row may result in an exception when debugging an application in the IDE Q488926 - Table and Banded Table Views - In-place cxCurrencyEdit - Auto sizing can be erroneously enabled via EditAutoHeight property settings Q486905 - Table and Banded Table Views - Possible vertical scrollbar issues if View includes preview sections Q491534 - The "<No data to display>" text shown in an empty grid blends with the background if certain skins are applied ExpressQuantumTreeList Suite B234886 - An expanded node displaces its vertical tree line displayed below the node image if this image is narrower than the default indent cell (the image width is less than the tree list's DefaultIndentSize.cx property value) Q492957 - The TcxTreeListSummary.Recalculate method does not recalculate the summary ExpressScheduler Suite Q486537 - The skinned Scheduler does not paint selected or dragged events that are not adjacent to the timeline bar ExpressSkins Library B234764 - Alert windows - Window corners are rounded using the Common.AlertWindow.CornerRadius additional property setting if the skin controller's UseImageSet property is set to imsAlternate Q485324 - ExpressVerticalGrid - Row header text is unreadable when exporting grid content if certain skins are applied ExpressSpreadSheet Q489485 - An AV occurs when saving an Excel document with a workbook containing more than 170 sheets ExpressTile Control Q490110 - The Back button and the title glyph have an incorrect vertical alignment within the Tile control's title if the glyph is taller than the title text Q488443 - The 'Control has no parent window' exception is raised when clicking the Back button on a tile detail page if the tile control is located on a form whose FormStyle property is set to fsMDIForm B233640 - When dropping a tile item to a new tile group, the tile item is immediately displayed in this group before transition animation B233675 - With certain Tile control's OptionsView.IndentVert settings, a detail page control overlaps the Tile control's title if the title glyph and text are not specified Common Libraries ExpressEditors Library B217390 - All drop-down editors - If the native painting style is applied, the first click on the down arrow button does not open the drop-down window that was closed using the keyboard B231657 - All TcxCustomDropDownEdit descendants - A drop-down window may appear detached from its editor to prohibit this window from crossing monitor edges on a desktop that spans across multiple monitors Q488933 - cxDateEdit - The variant value conversion exception is raised when posting a valid editing value if the Properties.EditFormat property is set to "mm.yyyy" and the Properties.MinDate/Properties.MaxDate range is specified Q490912 - cxMaskEdit - The editor does not accept non-Latin characters if the Properties.MaskKind property is set to emkStandard and the mask contains the 'L' character S171163 - cxTrackBar and dxZoomTrackBar - The change buttons remain enabled in a disabled editor Q493102 - Documentation - Incorrect default values of the TcxShellOptions.ShowToolTip and TcxDlgShellOptions.ShowToolTip properties B233815 - In-place cxProgressBar - The Font style applied via the OnGetContentStyle event only to specific records is erroneously applied to all records B234191 - Linking shell controls does not synchronize their root settings Q372947 - TcxEditRepositorySpinItem - The Properties.ValueType property is initialized with vtFloat rather than vtInt that is used in cxSpinEdit controls Q488183 - TcxShellListView - The OnDblClick event does not fire if the Options.AutoNavigate property is set to False Q493416 - TcxShellTreeView - Changing the Options.FileMask property value collapses tree view nodes Q493642 - TdxShellBreadcrumbEdit control allows entering a path of the existing folder that is not a part of the currently selected Root folder when running on Windows XP Q491045 - The TcxBrowseFolder.bfNetHood enumeration value erroneously corresponds to Network Neighborhood rather than to My Network Places ExpressLibrary Q492107 - A JPEG image loaded from a stream and then cloned by the TdxSmartImage.Clone method is incompletely painted by TdxSmartImage draw routines Q488736 - An AV occurs when closing an application with a statically linked DLL file that contains one or more DevExpress controls if the native painting style is applied Q489278 - Changing the dxFormatSettings.ThousandSeparator property modifies the dxFormatSettings.TimeSeparator property in error Q487518 - Export - Exporting special characters (&, ", <, or >) in the Korean(Korea) locale makes the resulting XLSX file unreadable

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
©️2022 CSDN 皮肤主题:大白 设计师:CSDN官方博客 返回首页
评论

打赏作者

xiaodong

你的鼓励将是我创作的最大动力

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值