RubyENet Online Project Template

Hello everyone, some months after releasing my RubyENet online library some people asked me to make an example project using it, so they could see how things could be done and build a custom game on top of it. Today I finished filling the scripts with comments, so everything is easy to understand. So here it is:

RubyENet Game Template


This project shows how to integrate RubyENet into RPG Maker

This project is aimed to people who wants to add online functionality
to their games without to much trouble. This project includes the basic
structure to connect to a server, send and receive data.

It included:
- Methods to connect to a remote server
- Methods to receive and parse packets
- Other players in map
- Automatic global switches and variables
- Basic Chat
- A basic server for ruby 1.8.x and 1.9.x

Basic features to learn and build a solid and custom game on top of them

Explanation of what this project does:
- When clicked "New Game" the game connects to the remote server
- The server gives an unique ID to the game so it can be identified
- The game sends the player data to the server, who sends it to all the
other players, and returns the game the other players data.
- The players can interact throught switches and variables.
- Only players in the same map are updated and visibles.
- When another player disconnects, its deleted from the players list.
- If the game loses the connection to the server a warning appears.

All the new scripts are tagged as [Added]
All the edited default scripts are tagged ad [Edited]

Edited scripts and lines:
Content Hidden Show
-- Game_Temp
-- 57
-- 58

- Game_player
-- 218
-- 219
-- 223
- -224
- -228
- -229
-- 233
-- 234

- Spriteset_Map
-- 40 to 49
-- 68 to 86
--107 to 109
-- 127- 128
-- 175 to 177

- Interpreter 4
--18
-- 174

- Scene_Title
-- 142
-- 143

-Scene_Map
-- 17
-- 18
-- 41
-- 42
-- 67 to 74
-- 139 to 41
-- 144
-- 300 to 305

-Main
--25 to 28


Downloads


Project:
RPG Maker XP Project

Scripts:

____Added Scripts_____

ENet Module:
  1.  
  2. ################################################################################
  3. #
  4. #   ######   #    #   ######   #####                   ENet Ruby Bindings
  5. #   #        ##   #   #          #
  6. #   ####     # #  #   ####       #                     Last Update: 24/8/2010
  7. #   #        #  # #   #          #
  8. #   ######   #   ##   ######     #                     By Dahrkael
  9. #
  10. ################################################################################
  11. #
  12. # ENet's purpose is to provide a relatively thin, simple and robust network
  13. # communication layer on top of UDP (User Datagram Protocol).
  14. # The primary feature it provides is optional reliable, in-order delivery
  15. # of packets.
  16. #
  17. # ENet omits certain higher level networking features such as authentication,
  18. # lobbying, server discovery, encryption, or other similar tasks that are
  19. # particularly application specific so that the library remains flexible,
  20. # portable, and easily embeddable.
  21. #
  22. # Copyright (c) 2002-2010 Lee Salzman
  23. #                                                       http://enet.bespin.org/
  24. #===============================================================================
  25. #
  26. # TODO:
  27. #      - Error control
  28. #      - Add all missing internal functions
  29. #
  30. #===============================================================================
  31. #
  32. # This script is free to use and doesnt need any credits B U T enet library does
  33. #
  34. ################################################################################
  35.  
  36. #==============================================================================
  37. # * Module Enet
  38. #
  39. #   Methods
  40. #    - initialize
  41. #    - deinitialize
  42. #    - destroy_event_packet
  43. #    - get_packet_data
  44. #    - get_packet_datalength
  45. #    - get_packet_from_event
  46. #    - get_channelid_from_event
  47. #    - get_peer_from_event
  48. #    - get_peer_host
  49. #    - get_peer_port
  50. #
  51. #   SubModules
  52. #    - DLLs
  53. #    - Types
  54. #    - Constants
  55. #    - APIFunctions
  56. #
  57. #   SubClasses (and methods)
  58. #    - ENetHost
  59. #       - initialize
  60. #       - create_host
  61. #       - destroy_host
  62. #       - connect
  63. #       - peers_list
  64. #       - send_packet
  65. #       - broadcast_packet
  66. #       - disconnect
  67. #       - service
  68. #       - on_packet_receive
  69. #       - on_connection
  70. #       - on_disconnect
  71. #
  72. #    - ENetAddress
  73. #       - initialize
  74. #       - set_host
  75. #       - set_port
  76. #
  77. #    - ENetEvent
  78. #       - initialize
  79. #       - update
  80. #       - peer
  81. #       - peer_host
  82. #       - peer_port
  83. #       - channel_id
  84. #       - packet
  85. #       - destroy_packet
  86. #
  87. #    - ENetPacket
  88. #       - initialize
  89. #       - update
  90. #       - data_length
  91. #       - data
  92. #
  93. #==============================================================================
  94. module Enet
  95.  
  96. #==============================================================================
  97. # * M O D U L E S
  98. #==============================================================================
  99.   #============================================================================
  100.   # ** DLLs
  101.   #----------------------------------------------------------------------------
  102.   # dlls containing needed functions
  103.   #============================================================================
  104.     module DLLs
  105.         Enet            = "enet.dll"      # enet itself
  106.         RubyEnet      = "RubyENet.dll"  # auxiliar functions
  107.     end
  108.  
  109.   #============================================================================
  110.   # ** Types
  111.   #----------------------------------------------------------------------------
  112.   # Enet types converted to Win32API types
  113.   #============================================================================
  114.     module Types
  115.         ENetAddress     = 'P'
  116.         ENetHost        = 'L'
  117.         ENetEvent     = 'L'
  118.         ENetPacket    = 'L'
  119.         ENetPeer          = 'L'
  120.         Enet_uint32     = 'L'
  121.         Enet_uint16     = 'L'
  122.         Enet_uint8    = 'I'
  123.         Size_t          = 'L'
  124.         Int               = 'I'
  125.         Void              = 'V'
  126.         Const_void    = 'P'
  127.         Const_char    = 'P'
  128.     end
  129.  
  130.   #============================================================================
  131.   # ** Constants
  132.   #----------------------------------------------------------------------------
  133.   # Enet constants, better than numbers
  134.   #============================================================================
  135.     module Constants
  136.         NULL                                        = 0 # yes...
  137.    
  138.         ENET_HOST_ANY                         = 0    
  139.         ENET_HOST_BROADCAST                 = 0xFFFFFFFF
  140.         ENET_PORT_ANY                         = 0  
  141.  
  142.         ENET_EVENT_TYPE_NONE            = 0
  143.         ENET_EVENT_TYPE_CONNECT         = 1
  144.         ENET_EVENT_TYPE_DISCONNECT      = 2
  145.         ENET_EVENT_TYPE_RECEIVE         = 3
  146.  
  147.         ENET_PACKET_FLAG_RELIABLE       = 1 # (1 << 0)
  148.         ENET_PACKET_FLAG_UNSEQUENCED    = 2 # (1 << 1)
  149.         ENET_PACKET_FLAG_NO_ALLOCATE    = 4 # (1 << 2)
  150.     end
  151.  
  152.  
  153.   #============================================================================
  154.   # ** APIFunctions
  155.   #----------------------------------------------------------------------------
  156.   # DLL Functions, some secondary and/or no-vital functions are missing
  157.   #============================================================================
  158.     module APIFunctions
  159.         include Types
  160.    
  161.     #--------------------------------------------------------------------------
  162.     # * Workaround Function (anyone help :3?)
  163.     #--------------------------------------------------------------------------
  164.         RubyEnet_CreateENetEvent              = Win32API.new(DLLs::RubyEnet, "RubyEnet_CreateENetEvent", [''], ENetEvent)
  165.                
  166.     #--------------------------------------------------------------------------
  167.     # * ENetEvent Auxiliar Functions
  168.     #--------------------------------------------------------------------------
  169.         RubyEnet_GetPeerFromEvent             = Win32API.new(DLLs::RubyEnet, "RubyEnet_GetPeerFromEvent", [ENetEvent], ENetPeer)
  170.         RubyEnet_GetEventType                 = Win32API.new(DLLs::RubyEnet, "RubyEnet_GetEventType", [ENetEvent], Int)
  171.         RubyEnet_GetChannelIDFromEvent  = Win32API.new(DLLs::RubyEnet, "RubyEnet_GetChannelIDFromEvent", [ENetEvent], Enet_uint8)
  172.          
  173.     #--------------------------------------------------------------------------
  174.     # * ENetPacket Auxiliar Functions
  175.     #--------------------------------------------------------------------------
  176.         RubyEnet_GetPacketFromEvent       = Win32API.new(DLLs::RubyEnet, "RubyEnet_GetPacketFromEvent", [ENetEvent], ENetPacket)
  177.         RubyEnet_GetPacket_DataLength   = Win32API.new(DLLs::RubyEnet, "RubyEnet_GetPacket_DataLength", [ENetPacket], Size_t)
  178.         RubyEnet_GetPacket_Data               = Win32API.new(DLLs::RubyEnet, "RubyEnet_GetPacket_Data", [ENetPacket], 'P')
  179.        
  180.     #--------------------------------------------------------------------------
  181.     # * ENetPeer Auxiliar Functions
  182.     #--------------------------------------------------------------------------
  183.         RubyEnet_GetPeerHost                    = Win32API.new(DLLs::RubyEnet, "RubyEnet_GetPeerHost", [ENetPeer], Enet_uint32)
  184.         RubyEnet_GetPeerPort                    = Win32API.new(DLLs::RubyEnet, "RubyEnet_GetPeerPort", [ENetPeer], Enet_uint32)
  185.  
  186.     #--------------------------------------------------------------------------
  187.     # * ENet Basic Functions
  188.     #--------------------------------------------------------------------------
  189.         Enet_initialize                           = Win32API.new(DLLs::Enet, "enet_initialize", [''], Int)
  190.         Enet_deinitialize                       = Win32API.new(DLLs::Enet, "enet_deinitialize", [''], Void)
  191.    
  192.         #--------------------------------------------------------------------------
  193.     # * ENetHost Functions
  194.     #--------------------------------------------------------------------------
  195.         Enet_host_create                        = Win32API.new(DLLs::Enet, "enet_host_create", [ENetAddress, Size_t, Size_t, Enet_uint32, Enet_uint32], ENetHost)
  196.         Enet_host_destroy                     = Win32API.new(DLLs::Enet, "enet_host_destroy", [ENetHost], Void)
  197.         Enet_host_connect                     = Win32API.new(DLLs::Enet, "enet_host_connect", [ENetHost, ENetAddress, Size_t, Enet_uint32], ENetPeer)
  198.         Enet_host_service                     = Win32API.new(DLLs::Enet, "enet_host_service", [ENetHost, ENetEvent, Enet_uint32], Int)
  199.         Enet_host_broadcast                     = Win32API.new(DLLs::Enet, "enet_host_broadcast", [ENetHost, Enet_uint8, ENetPacket], Void)
  200.         Enet_host_flush                           = Win32API.new(DLLs::Enet, "enet_host_flush", [ENetHost], Void)
  201.         Enet_address_set_host               = Win32API.new(DLLs::Enet, "enet_address_set_host", [ENetAddress, Const_char], Int)
  202.        
  203.     #--------------------------------------------------------------------------
  204.     # * ENetpacket Functions
  205.     #--------------------------------------------------------------------------
  206.         Enet_packet_create                    = Win32API.new(DLLs::Enet, "enet_packet_create", [Const_void, Size_t, Enet_uint32], ENetPacket)
  207.         Enet_packet_destroy                     = Win32API.new(DLLs::Enet, "enet_packet_destroy", [ENetPacket], Void)
  208.  
  209.     #--------------------------------------------------------------------------
  210.     # * ENetPeer Functions
  211.     #--------------------------------------------------------------------------
  212.         Enet_peer_send                          = Win32API.new(DLLs::Enet, "enet_peer_send", [ENetPeer, Enet_uint8, ENetPacket], Int)
  213.         Enet_peer_disconnect                    = Win32API.new(DLLs::Enet, "enet_peer_disconnect", [ENetPeer, Enet_uint32], Void)
  214.         Enet_peer_reset                           = Win32API.new(DLLs::Enet, "enet_peer_reset", [ENetPeer], Void)
  215.     end
  216.  
  217. #==============================================================================
  218. # * M E T H O D S
  219. #==============================================================================
  220.  
  221.   #----------------------------------------------------------------------------
  222.   # * initialize
  223.   # Starts the library
  224.   #----------------------------------------------------------------------------
  225.   def self.initialize
  226.     APIFunctions::Enet_initialize.call()
  227.   end
  228.  
  229.   #----------------------------------------------------------------------------
  230.   # * deinitialize
  231.   # Stops the library
  232.   #----------------------------------------------------------------------------
  233.   def self.deinitialize
  234.     APIFunctions::Enet_deinitialize.call()
  235.   end
  236.  
  237.   #----------------------------------------------------------------------------
  238.   # * Destroy Event Packet
  239.   # Destroys the packet contained in the event
  240.   #----------------------------------------------------------------------------
  241.   def self.destroy_event_packet(event)
  242.     packet = self.get_packet_from_event(event)
  243.     APIFunctions::Enet_packet_destroy.call(packet)
  244.   end
  245.  
  246.   #----------------------------------------------------------------------------
  247.   # * Get Packet Data
  248.   # Returns a string with the packet data
  249.   #----------------------------------------------------------------------------
  250.   def self.get_packet_data(packet)
  251.     length = APIFunctions::RubyEnet_GetPacket_DataLength.call(packet)
  252.     data = 0.chr * length
  253.     data = APIFunctions::RubyEnet_GetPacket_Data.call(packet)
  254.     return data
  255.   end
  256.  
  257.   #----------------------------------------------------------------------------
  258.   # * Get Packet Datalength
  259.   # Returns the datalength from the packet (the data size)
  260.   #----------------------------------------------------------------------------
  261.   def self.get_packet_datalength(packet)
  262.     return APIFunctions::RubyEnet_GetPacket_DataLength.call(packet)
  263.   end
  264.  
  265.   #----------------------------------------------------------------------------
  266.   # * Get Packet From Event
  267.   # Returns the packet pointer from the event
  268.   #----------------------------------------------------------------------------
  269.   def self.get_packet_from_event(event)
  270.     return APIFunctions::RubyEnet_GetPacketFromEvent.call(event)
  271.   end
  272.  
  273.   #----------------------------------------------------------------------------
  274.   # * Get ChannelID From Event
  275.   # Returns the ChannelID used
  276.   #----------------------------------------------------------------------------
  277.   def self.get_channelid_from_event(event)
  278.     return APIFunctions::RubyEnet_GetChannelIDFromEvent.call(event)
  279.   end
  280.  
  281.   #----------------------------------------------------------------------------
  282.   # * Get Peer From Event
  283.   # gets the peer pointer who generated the event
  284.   #----------------------------------------------------------------------------
  285.   def self.get_peer_from_event(event)
  286.     return APIFunctions::RubyEnet_GetPeerFromEvent.call(event)
  287.   end              
  288.  
  289.   #----------------------------------------------------------------------------
  290.   # * Get Peer Host
  291.   # Returns the hexadecimal peers address
  292.   #----------------------------------------------------------------------------
  293.   def self.get_peer_host(peer)
  294.     return APIFunctions::RubyEnet_GetPeerHost.call(peer)
  295.   end   
  296.  
  297.   #----------------------------------------------------------------------------
  298.   # * Get Peer Port
  299.   # Returns the peers port
  300.   #----------------------------------------------------------------------------
  301.   def self.get_peer_port(peer)
  302.     return APIFunctions::RubyEnet_GetPeerPort.call(peer)
  303.   end   
  304.  
  305. #==============================================================================
  306. # * C L A S S E S
  307. #==============================================================================
  308.  
  309.   #============================================================================
  310.   # ** ENetHost
  311.   #----------------------------------------------------------------------------
  312.   #    Class that represents the computer networking and the connections
  313.   #    associated
  314.   #============================================================================
  315.     class ENetHost
  316.   #----------------------------------------------------------------------------
  317.   # * Public Instance Variables
  318.   #----------------------------------------------------------------------------
  319.         attr_reader :connected # returns true if connected, all peers uses this var :/
  320.   #----------------------------------------------------------------------------
  321.   # * Object Initialization
  322.   #----------------------------------------------------------------------------
  323.         def initialize
  324.             @enet_host = nil
  325.             @peers = {}
  326.             @connections = 0
  327.             @channels = 0
  328.             @downstream = 0
  329.             @upstream = 0
  330.             @event = APIFunctions::RubyEnet_CreateENetEvent.call()
  331.       @external_event = ENetEvent.new(@event)
  332.             @connected = false
  333.       @on_packet_receive = nil
  334.       @on_disconnect = nil
  335.       @on_connection = nil
  336.         end
  337.    
  338.   #----------------------------------------------------------------------------
  339.   # * Event
  340.   #----------------------------------------------------------------------------
  341.     def event
  342.       return @external_event
  343.     end
  344.    
  345.   #----------------------------------------------------------------------------
  346.   # * Create Host
  347.   #     type:         Client or Server, NULL = Client, Pointer to ENetAddress = Server
  348.   #     connections:  Outgoing connections allowed (number)
  349.   #     channels:     Number of avaiable channels for connections (number)
  350.   #     downstream:   Downstream bandwidth in bytes (number)
  351.   #     upstream:     Upstream bandwidth in bytes (number)
  352.   #----------------------------------------------------------------------------
  353.         def create_host(type, connections, channels, downstream, upstream)
  354.             @enet_host = APIFunctions::Enet_host_create.call(type, connections,  channels, downstream, upstream)
  355.             if @enet_host != 0
  356.                 @connections = connections
  357.                 @channels = channels
  358.                 @downstream = downstream
  359.                 @upstream = upstream
  360.                 return true
  361.             else
  362.                 return false
  363.             end
  364.         end
  365.    
  366.   #----------------------------------------------------------------------------
  367.   # * Destroy Host
  368.   #----------------------------------------------------------------------------
  369.         def destroy_host
  370.             APIFunctions::Enet_host_destroy.call(@enet_host)
  371.             @enet_host = nil
  372.             @connections = 0
  373.             @channels = 0
  374.             @downstream = 0
  375.             @upstream = 0
  376.         end
  377.    
  378.   #----------------------------------------------------------------------------
  379.   # * Connect
  380.   #     address: ENetAddres instance with the remote host address and port (ENetAddress)
  381.   #     channels: Number of channels allocated for this connection (number)
  382.   #     extradata: Optional data to send with the connection petition (string)
  383.   #----------------------------------------------------------------------------
  384.         def connect(address, channels, extradata=0)
  385.             peer = APIFunctions::Enet_host_connect.call(@enet_host, address.enet_address, channels, extradata)
  386.             if peer != 0
  387.         address = APIFunctions::RubyEnet_GetPeerHost.call(peer)
  388.         port = APIFunctions::RubyEnet_GetPeerPort.call(peer)
  389.                 @peers["server"] =   {
  390.                              "peer"      => peer,
  391.                              "address" => address,
  392.                              "port"    => port
  393.                             }
  394.         return true
  395.             else
  396.                 return false
  397.             end
  398.         end
  399.    
  400.   #----------------------------------------------------------------------------
  401.   # * Peers List
  402.   #----------------------------------------------------------------------------
  403.         def peers_list
  404.             return @peers
  405.         end
  406.    
  407.   #----------------------------------------------------------------------------
  408.   # * Send packet
  409.   #     peer: peer to send the packet (pointer to peer)
  410.   #     data: data to send in the packet, text, binary, anything (~string)
  411.   #     datalength: data length + 1 (number)
  412.   #     channelID: Channel to send the packet (number)
  413.   #     flags: Optional flags for the packet, default is ENET_PACKET_FLAG_RELIABLE
  414.   #----------------------------------------------------------------------------
  415.         def send_packet(peer, data, datalength, channelID, flags=Constants::ENET_PACKET_FLAG_RELIABLE)
  416.             packet = APIFunctions::Enet_packet_create.call(data, datalength, flags)
  417.             if APIFunctions::Enet_peer_send.call(peer, channelID, packet) < 0
  418.                 return false
  419.             else
  420.                 return true
  421.             end
  422.         end
  423.    
  424.   #----------------------------------------------------------------------------
  425.   # * Broadcast Packet
  426.   #     data: data to send in the packet, text, binary, anything (~string)
  427.   #     datalength: data length + 1 (number)
  428.   #     channelID: Channel to send the packet (number)
  429.   #     flags: Optional flags for the packet, default is ENET_PACKET_FLAG_RELIABLE
  430.   #----------------------------------------------------------------------------
  431.     def broadcast_packet(data, datalength, channelID, flags=Constants::ENET_PACKET_FLAG_RELIABLE)
  432.             packet = APIFunctions::Enet_packet_create.call(data, datalength, flags)
  433.             APIFunctions::Enet_host_broadcast.call(@enet_host, channelID, packet)
  434.       return true
  435.         end
  436.    
  437.   #----------------------------------------------------------------------------
  438.   # * Disconnect
  439.   #     peer: peer to disconnect (peer name string)
  440.   #     data: extra data to send with the disconnection petition (~string)
  441.   #     timeout: time in milliseconds to get answer, when over disconnection is forced (number)
  442.   #----------------------------------------------------------------------------
  443.         def disconnect(peer, data=0, timeout=3000)
  444.             APIFunctions::Enet_peer_disconnect.call(peer, data)
  445.             while APIFunctions::Enet_host_service.call(@enet_host, @event, timeout) > 0
  446.                 case APIFunctions::RubyEnet_GetEventType.call(@event)
  447.                     when Constants::ENET_EVENT_TYPE_RECEIVE
  448.                         APIFunctions::Enet_packet_destroy(RubyEnet_GetPacketFromEvent.call(@event))
  449.                     when Constants::ENET_EVENT_TYPE_DISCONNECT
  450.                         @peers[peer] = nil
  451.                         #print "Disconnected"
  452.                         return true
  453.                 end
  454.             end
  455.             Enet_peer_reset (@peers[peer][peer])
  456.             @peers[peer] = nil
  457.             return true
  458.         end
  459.    
  460.   #----------------------------------------------------------------------------
  461.   # * Service
  462.   #     milliseconds: time to wait for a packet (number)
  463.   #----------------------------------------------------------------------------
  464.         def service(milliseconds=1000)
  465.             while APIFunctions::Enet_host_service.call(@enet_host, @event, milliseconds) > 0
  466.                 case APIFunctions::RubyEnet_GetEventType.call(@event)
  467.                     when Constants::ENET_EVENT_TYPE_NONE
  468.                    
  469.                     when Constants::ENET_EVENT_TYPE_CONNECT
  470.                         #print "new client connected"
  471.             @external_event.update(@event)
  472.             on_connection
  473.                         APIFunctions::Enet_host_flush.call(@enet_host)
  474.                         @connected = true
  475.                     when Constants::ENET_EVENT_TYPE_DISCONNECT
  476.                         @connected = false
  477.                         #print "Disconnected"
  478.             @external_event.update(@event)
  479.             on_disconnect
  480.                     when Constants::ENET_EVENT_TYPE_RECEIVE
  481.             @external_event.update(@event)
  482.                         on_packet_receive
  483.                 end
  484.             end
  485.         end
  486.    
  487.   #----------------------------------------------------------------------------
  488.   # * On Disconnection
  489.   #     Method called when a disconnection event arrives
  490.   #----------------------------------------------------------------------------
  491.     def on_disconnect(&block)
  492.       if block
  493.           @on_disconnect = block
  494.       elsif @on_disconnect
  495.           @on_disconnect.call()
  496.       end
  497.     end
  498.   #----------------------------------------------------------------------------
  499.   # * On Connection
  500.   #     Method called when a connection event arrives
  501.   #----------------------------------------------------------------------------
  502.     def on_connection(&block)
  503.       if block
  504.           @on_connection = block
  505.       elsif @on_connection
  506.           @on_connection.call()
  507.       end
  508.     end
  509.   #----------------------------------------------------------------------------
  510.   # * Packet Received
  511.   #     Method called when an event containing a packet arrives
  512.   #----------------------------------------------------------------------------
  513.     def on_packet_receive(&block)
  514.       if block
  515.           @on_packet_receive = block
  516.       elsif @on_packet_receive
  517.           @on_packet_receive.call()
  518.           #destroy_event_packet(@event)
  519.       end
  520.     end
  521.     end
  522.  
  523.   #============================================================================
  524.   # ** ENetAddress
  525.   #----------------------------------------------------------------------------
  526.   #    Class to simplify C ENetAddress structs
  527.   #============================================================================
  528.     class ENetAddress
  529.   #----------------------------------------------------------------------------
  530.   # * Public Instance Variables
  531.   #----------------------------------------------------------------------------
  532.         attr_reader :address
  533.         attr_reader :port
  534.         attr_reader :enet_address
  535.    
  536.   #----------------------------------------------------------------------------
  537.   # * Object Initialization
  538.   #----------------------------------------------------------------------------
  539.         def initialize
  540.             @address = ""
  541.             @port = 0
  542.             @enet_address = ""
  543.         end
  544.    
  545.   #----------------------------------------------------------------------------
  546.   # * Set Host
  547.   #     host: remote host to get address (string)
  548.   #----------------------------------------------------------------------------
  549.         def set_host(host)
  550.              @enet_address = [Constants::ENET_HOST_ANY, @port].pack("LS")
  551.             if APIFunctions::Enet_address_set_host.call(@enet_address, host) < 0
  552.                 return false
  553.             end
  554.             @address = host
  555.             return true
  556.         end
  557.    
  558.   #----------------------------------------------------------------------------
  559.   # * Set Port
  560.   #     port: port to bind
  561.   #----------------------------------------------------------------------------
  562.         def set_port(port)
  563.             @port = port
  564.             @enet_address = [Constants::ENET_HOST_ANY, @port].pack("LS")
  565.             set_host(@address)
  566.             return true
  567.         end
  568.     end
  569.  
  570.   #============================================================================
  571.   # ** ENetPacket
  572.   #----------------------------------------------------------------------------
  573.   #    Class to simplify C ENetPacket structs
  574.   #============================================================================
  575.   class ENetPacket
  576.   #----------------------------------------------------------------------------
  577.   # * Object Initialization
  578.   #     packet: packet to wrap
  579.   #----------------------------------------------------------------------------
  580.     def initialize(packet)
  581.       @packet = packet
  582.       @length = 0
  583.       @data = 0
  584.     end
  585.   #----------------------------------------------------------------------------
  586.   # * Update
  587.   #     packet: packet to wrap
  588.   #----------------------------------------------------------------------------
  589.     def update(packet)
  590.       @packet = packet
  591.       @length = 0
  592.       @data = 0
  593.     end
  594.   #----------------------------------------------------------------------------
  595.   # * Data Length
  596.   #----------------------------------------------------------------------------
  597.     def data_length
  598.       @length = Enet.get_packet_datalength(@packet)
  599.       return @length
  600.     end
  601.   #----------------------------------------------------------------------------
  602.   # * Data
  603.   #----------------------------------------------------------------------------
  604.     def data
  605.        @data = Enet.get_packet_data(@packet)
  606.        return @data
  607.     end
  608.   end
  609.      
  610.   #============================================================================
  611.   # ** ENetEvent
  612.   #----------------------------------------------------------------------------
  613.   #    Class to simplify C ENetEvent structs
  614.   #============================================================================
  615.   class ENetEvent
  616.   #----------------------------------------------------------------------------
  617.   # * Object Initialization
  618.   #     event: event to wrap
  619.   #----------------------------------------------------------------------------
  620.     def initialize(event)
  621.       @event = event
  622.       @peer = 0
  623.       @peer_host = 0
  624.       @peer_port = 0
  625.       @channel_id = 0
  626.       @packet = 0
  627.     end
  628.   #----------------------------------------------------------------------------
  629.   # * Update
  630.   #     event: event to wrap
  631.   #----------------------------------------------------------------------------
  632.     def update(event)
  633.       @event = event
  634.       @peer = 0
  635.       @peer_host = 0
  636.       @peer_port = 0
  637.       @channel_id = 0
  638.       @packet = 0
  639.     end
  640.   #----------------------------------------------------------------------------
  641.   # * Peer
  642.   #----------------------------------------------------------------------------
  643.     def peer
  644.       @peer = Enet.get_peer_from_event(@event)
  645.       return @peer
  646.     end
  647.   #----------------------------------------------------------------------------
  648.   # * Peer Host
  649.   #----------------------------------------------------------------------------
  650.     def peer_host
  651.       if @peer == 0
  652.         @peer = Enet.get_peer_from_event(@event)
  653.       end
  654.       @host = Enet.get_peer_host(@peer)
  655.       return @host
  656.     end
  657.   #----------------------------------------------------------------------------
  658.   # * Peer Port
  659.   #----------------------------------------------------------------------------
  660.     def peer_port
  661.       if @peer == 0
  662.         @peer = Enet.get_peer_from_event(@event)
  663.       end
  664.       @port = Enet.get_peer_port(@peer)
  665.       return @port
  666.     end
  667.   #----------------------------------------------------------------------------
  668.   # * Channel ID
  669.   #----------------------------------------------------------------------------
  670.     def channel_id
  671.       @channel_id = Enet.get_channelid_from_event(@event)
  672.     end
  673.   #----------------------------------------------------------------------------
  674.   # * Packet
  675.   #----------------------------------------------------------------------------
  676.     def packet
  677.       if @packet == 0
  678.         packet = Enet.get_packet_from_event(@event)
  679.         @packet = ENetPacket.new(packet)
  680.       end
  681.       return @packet
  682.     end
  683.   #----------------------------------------------------------------------------
  684.   # * Destroy Packet
  685.   #----------------------------------------------------------------------------
  686.     def destroy_packet
  687.       Enet.destroy_event_packet(@event)
  688.       @packet = 0
  689.     end
  690.   end
  691. end # Classes end
  692.  
Expand to see the code.


Network Class:

  1.  
  2. #==============================================================================
  3. # ** Network
  4. #------------------------------------------------------------------------------
  5. #  Handles the network.
  6. #
  7. #  Basic demostration of RubyENet game integration
  8. #  To send additional data just add a new packet type and its logic
  9. #==============================================================================
  10. class Network
  11.  
  12.   #--------------------------------------------------------------------------
  13.   # * Public Instance Variables
  14.   #--------------------------------------------------------------------------
  15.   attr_accessor :players              # Other Players data
  16.   attr_reader   :client               # Underlying connections manager
  17.   attr_reader   :chat                 # Chat manager
  18.   attr_reader   :id                   # Unique-per-session Network ID
  19.  
  20.   #--------------------------------------------------------------------------
  21.   # * Object Initialization
  22.   #     server_adress : IP or Hostname where the server is running
  23.   #     port : Port to connect in the server
  24.   #     max_connections : outgoing connections to different hosts allowed
  25.   #     channels : maximum channels allocated for the client
  26.   #     upload_bw : upload bandwidth in bytes, 0 for unlimited
  27.   #     download_bw : download bandwidth in bytes, 0 for unlimited
  28.   #--------------------------------------------------------------------------
  29.   def initialize
  30.     @players = {}
  31.     @server_address = "localhost"
  32.     @port = 8000
  33.     @max_connections = 1
  34.     @channels = 3
  35.     @upload_bw = 14400/8
  36.     @download_bw = 57600/8
  37.     @id = 0
  38.     @ready = false
  39.     @client = nil
  40.     @chat = Chat.new
  41.   end
  42.  
  43.   #--------------------------------------------------------------------------
  44.   # * Connect and Start
  45.   #   Initializes the network and connects to the server.
  46.   #   Gets and ID, sends our initial data and retrieves the other players data.
  47.   #--------------------------------------------------------------------------
  48.   def connect_and_start
  49.     # Initialize the ENet library
  50.     if Enet.initialize != 0 # 0 = all ok
  51.       print "error initializing enet"
  52.       # exit if enet fails
  53.       exit
  54.     end
  55.     # New address object
  56.     @address = Enet::ENetAddress.new
  57.     @address.set_host(@server_address)
  58.     @address.set_port(@port)
  59.     # New host object as client
  60.     @client = Enet::ENetHost.new
  61.     @client.create_host(Enet::Constants::NULL,
  62.                         @max_connections,
  63.                         @channels,
  64.                         @download_bw,
  65.                         @upload_bw)
  66.     # What to do when a data packet arrives
  67.     @client.on_packet_receive do
  68.       parse_packet
  69.     end
  70.     # Connect to the server
  71.     @client.connect(@address, @channels, 0)
  72.     # Wait for the server accepting
  73.     @client.service
  74.     if @client.connected != true
  75.       print "connection aborted"
  76.       exit
  77.     end
  78.     # Select the server pointer
  79.     @server = @client.peers_list["server"]["peer"]
  80.     # Hang up until we have an ID
  81.     while @id == 0
  82.       Graphics.update
  83.       @client.service
  84.     end
  85.     # Send our character data
  86.     send_initial_data
  87.     # Retrieve other players data
  88.     while @ready == false
  89.       Graphics.update
  90.       @client.service
  91.     end
  92.    
  93.     # Now we are connected!!
  94.   end
  95.  
  96.   #--------------------------------------------------------------------------
  97.   # * Send initial data to the server
  98.   #   Contains: ID, name, level, class, map, x, y, direction, graphics and speed
  99.   #--------------------------------------------------------------------------
  100.   def send_initial_data
  101.     data = ""
  102.     data += "0:"
  103.     data += @id.to_s
  104.     data += ";"
  105.     data += $game_actors[1].name
  106.     data += ";"
  107.     data += $game_actors[1].level.to_s
  108.     data += ";"
  109.     data += $game_actors[1].class_name
  110.     data += ";"
  111.     data += $game_map.map_id.to_s
  112.     data += ";"
  113.     data += $game_player.x.to_s
  114.     data += ";"
  115.     data += $game_player.y.to_s
  116.     data += ";"
  117.     data += $game_player.direction.to_s
  118.     data += ";"
  119.     data += $game_player.character_name
  120.     data += ";"
  121.     data += $game_player.character_hue.to_s
  122.     data += ";"
  123.     data += $game_player.opacity.to_s
  124.     data += ";"
  125.     data += $game_player.move_speed.to_s
  126.    
  127.     @client.send_packet(@server, data, data.size+1, 1)
  128.   end
  129.  
  130.   #=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
  131.   # * Functions to update our data
  132.   # * Format is: packet_id:player_id;value;etc
  133.   #=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
  134.  
  135.   #--------------------------------------------------------------------------
  136.   # * Sends our characters x position to the server
  137.   #--------------------------------------------------------------------------
  138.   def update_x
  139.     data = "1:#{@id};#{$game_player.x};#{$game_player.y}"
  140.     @client.send_packet(@server, data, data.size+1, 0)
  141.   end
  142.  
  143.   #--------------------------------------------------------------------------
  144.   # * Sends our characters y position to the server
  145.   #--------------------------------------------------------------------------
  146.   def update_y
  147.     data = "1:#{@id};#{$game_player.x};#{$game_player.y}"
  148.     @client.send_packet(@server, data, data.size+1, 0)
  149.   end
  150.  
  151.   #--------------------------------------------------------------------------
  152.   # * Sends our characters map id to the server
  153.   #--------------------------------------------------------------------------
  154.   def update_map_id
  155.     data = "2:#{@id};#{$game_map.map_id}"
  156.     @client.send_packet(@server, data, data.size+1, 0)
  157.   end
  158.  
  159.   #--------------------------------------------------------------------------
  160.   # * Sends where is the characters facing to the server
  161.   #--------------------------------------------------------------------------
  162.   def update_direction
  163.     data = "3:#{@id};#{$game_player.direction}"
  164.     @client.send_packet(@server, data, data.size+1, 0)
  165.   end
  166.  
  167.   #--------------------------------------------------------------------------
  168.   # * Sends our characters speed to the server
  169.   #--------------------------------------------------------------------------
  170.   def update_move_speed
  171.     data = "4:#{@id};#{$game_player.move_speed}"
  172.     @client.send_packet(@server, data, data.size+1, 0)
  173.   end
  174.  
  175.   #--------------------------------------------------------------------------
  176.   # * Sends our characters graphic name to the server
  177.   #--------------------------------------------------------------------------
  178.   def update_character_name
  179.     data = "5:#{@id};#{$game_player.character_name}"
  180.     @client.send_packet(@server, data, data.size+1, 0)
  181.   end
  182.  
  183.   #--------------------------------------------------------------------------
  184.   # * Sends our characters hue to the server
  185.   #--------------------------------------------------------------------------
  186.   def update_character_hue
  187.     data = "6:#{@id};#{$game_player.character_hue}"
  188.     @client.send_packet(@server, data, data.size+1, 0)
  189.   end
  190.  
  191.   #--------------------------------------------------------------------------
  192.   # * Sends our characters opacity to the server
  193.   #--------------------------------------------------------------------------
  194.   def update_opacity
  195.     data = "7:#{@id};#{$game_player.opacity}"
  196.     @client.send_packet(@server, data, data.size+1, 0)
  197.   end
  198.  
  199.   #--------------------------------------------------------------------------
  200.   # * Sends our characters name to the server
  201.   #--------------------------------------------------------------------------
  202.   def update_name
  203.     data = "10:#{@id};#{$game_actors[1].name}"
  204.     @client.send_packet(@server, data, data.size+1, 0)
  205.   end
  206.  
  207.   #--------------------------------------------------------------------------
  208.   # * Sends our characters level to the server
  209.   #--------------------------------------------------------------------------
  210.   def update_level
  211.     data = "8:#{@id};#{$game_actors[1].level}"
  212.     @client.send_packet(@server, data, data.size+1, 0)
  213.   end
  214.  
  215.   #--------------------------------------------------------------------------
  216.   # * Sends our characters class to the server
  217.   #--------------------------------------------------------------------------
  218.   def update_class_name
  219.     data = "9:#{@id};#{$game_actors[1].class_name}"
  220.     @client.send_packet(@server, data, data.size+1, 0)
  221.   end
  222.  
  223.   #--------------------------------------------------------------------------
  224.   # * Sends a new state for the switch
  225.   #--------------------------------------------------------------------------
  226.   def update_switch(id)
  227.     data = "201:#{id};#{$game_switches[id]}"
  228.     @client.send_packet(@server, data, data.size+1, 0)
  229.   end
  230.  
  231.   #--------------------------------------------------------------------------
  232.   # * Sends a new value for the variable
  233.   #--------------------------------------------------------------------------
  234.   def update_variable(id)
  235.     data = "200:#{id};#{$game_variables[id]}"
  236.     @client.send_packet(@server, data, data.size+1, 0)
  237.   end
  238.  
  239.  
  240.   #--------------------------------------------------------------------------
  241.   # * Network Update
  242.   #   Receive packets for 10 milliseconds and update players in the same map
  243.   #--------------------------------------------------------------------------
  244.   def update
  245.     @client.service(10)
  246.     @players.each_value do |player|
  247.       if player.map_id == $game_map.map_id
  248.         player.update
  249.       end
  250.     end
  251.   end
  252.  
  253.  
  254.   #--------------------------------------------------------------------------
  255.   # * Parse the incoming packets and manipulate them correctly
  256.   #   Each packet type has an unique ID number
  257.   #   values[0] is the id of the player who sent the data
  258.   #   values[1]+ are the actual data sent
  259.   #--------------------------------------------------------------------------
  260.   def parse_packet
  261.     # Retrieve the packet data
  262.     data = @client.event.packet.data.to_s
  263.     # Check if the data contains the correct format
  264.     # If not, the packet is ignored and destroyed
  265.     if data.match(/^([0-9]*):(.*)$/)
  266.       # Packet type
  267.       @part1 = $1
  268.       # Packet data
  269.       @part2 = $2
  270.       # Split the data in an array
  271.       values = @part2.split(";") if @part2.match(";")
  272.      
  273.       # Check the packet type and do something in consequence
  274.       case @part1.to_i
  275.         when 0 # Other players initial data
  276.           # If its a new player, add it to the players hash
  277.           if @players[values[0]] == nil
  278.             @players[values[0]] = Game_NetPlayer.new(values)
  279.             # If the player is in the same map, add it to the map playrs array
  280.             $game_temp.new_map_players.push(@players[values[0]]) if values[4].to_i == $game_map.map_id
  281.           end
  282.          
  283.         when 1 # Other players X and Y position
  284.           # X and Y from other players come at the same time
  285.           # Return if no players with that ID
  286.           return if @players[values[0]] == nil
  287.           # Update x and y values for this player
  288.           @players[values[0]].update_x(values[1])
  289.           @players[values[0]].update_y(values[2])
  290.          
  291.         when 2 # Other players Map ID
  292.           # Return if no players with that ID
  293.           return if @players[values[0]] == nil
  294.           # If the actual map ID is the same as ours
  295.           if @players[values[0]].map_id == $game_map.map_id
  296.             # But the new one is another
  297.             if values[1].to_i != $game_map.map_id
  298.               # Delete this player from the map players array
  299.               $game_temp.old_map_players.push(@players[values[0]])
  300.             end
  301.           # If the actual map ID is different
  302.           elsif @players[values[0]].map_id != $game_map.map_id
  303.             # But the new one is ours
  304.             if values[1].to_i == $game_map.map_id
  305.               # Add this player to the map players array
  306.               $game_temp.new_map_players.push(@players[values[0]])
  307.             end
  308.           end
  309.           # Update this players map ID
  310.           @players[values[0]].update_map_id(values[1])
  311.          
  312.         when 3 # Other players direction
  313.           # Return if no players with that ID
  314.           return if @players[values[0]] == nil
  315.           # Update this players direction
  316.           @players[values[0]].update_direction(values[1])
  317.          
  318.         when 4 # Other players speed
  319.           # Return if no players with that ID
  320.           return if @players[values[0]] == nil
  321.           # Update this players speed
  322.           @players[values[0]].update_move_speed(values[1])
  323.          
  324.         when 5 # Other players graphic
  325.           # Return if no players with that ID
  326.           return if @players[values[0]] == nil
  327.           # Update this players graphic
  328.           @players[values[0]].update_character_name(values[1])
  329.          
  330.         when 6 # Other players hue
  331.           # Return if no players with that ID
  332.           return if @players[values[0]] == nil
  333.           # Update this players hue
  334.           @players[values[0]].update_character_hue(values[1])
  335.          
  336.         when 7 # Other players opacity
  337.           # Return if no players with that ID
  338.           return if @players[values[0]] == nil
  339.           # Update this players opacity
  340.           @players[values[0]].update_opacity(values[1])
  341.          
  342.         when 8 # Other players level
  343.           # Return if no players with that ID
  344.           return if @players[values[0]] == nil
  345.           # Update this players level
  346.           @players[values[0]].update_level(values[1])
  347.          
  348.         when 9 # Other players class
  349.           # Return if no players with that ID
  350.           return if @players[values[0]] == nil
  351.           # Update this players class
  352.           @players[values[0]].update_class_name(values[1])
  353.          
  354.         when 10 # Other players name
  355.           # Return if no players with that ID
  356.           return if @players[values[0]] == nil
  357.           # Update this players name
  358.           @players[values[0]].update_name(values[1])
  359.          
  360.         when 11 # Other players disconnection
  361.           # Return if no players with that ID
  362.           return if @players[@part2] == nil
  363.           # If the player exists
  364.           if @players.has_key?(@part2)
  365.             # Delete it from the map if its in our same map
  366.             $game_temp.old_map_players.push(@players[@part2]) if @players[@part2].map_id == $game_map.map_id
  367.             # Delete it from the players list
  368.             @players.delete(@part2)
  369.           end
  370.          
  371.         when 100 # Our ID arrived
  372.           return if @id != 0
  373.           @id = @part2.to_f
  374.          
  375.         when 101 # Ready ACK
  376.           # This packet arrives when we already sent our initial data
  377.           # and we have the other players data
  378.           @ready = true
  379.          
  380.         when 200 # New variable value
  381.           # Update the variable value
  382.           $game_variables[values[0].to_i] = eval(values[1])
  383.           # Refresh the map to see possible effects
  384.           $game_map.need_refresh = true
  385.          
  386.         when 201 # New switch state
  387.           if values[1] == "true"
  388.             # Update the switch state
  389.             $game_switches[values[0].to_i] = true
  390.           else
  391.             # Update the switch state
  392.             $game_switches[values[0].to_i] = false
  393.           end
  394.           # Refresh the map to see possible effects
  395.           $game_map.need_refresh = true
  396.          
  397.         when 202 # New Chat message
  398.           # Return if no players with that ID
  399.           return if @players[values[0]] == nil
  400.           # Compose the new chat text
  401.           line =  "#{@players[values[0]].name}: #{values[1]}"
  402.           # Add the text to the chat
  403.           $network.chat.add_line(line)
  404.       end
  405.     end
  406.     # Finished with the packet, destroy it to free memory
  407.     @client.event.destroy_packet
  408.   end
  409. end
  410.  
Expand to see the code.


Game_NetPlayer Class
  1.  
  2. #==============================================================================
  3. # * Game_NetPlayer
  4. #------------------------------------------------------------------------------
  5. #  Handles a network player's data.
  6. #==============================================================================
  7.  
  8. class Game_NetPlayer < Game_Character
  9.  
  10.   #--------------------------------------------------------------------------
  11.   # * Public Instance Variables
  12.   #--------------------------------------------------------------------------
  13.   attr_reader   :id                       # Unique-per-session ID
  14.   attr_reader   :name                     # Name
  15.   attr_reader   :level                    # Level
  16.   attr_reader   :class_name               # Class name
  17.   attr_reader   :map_id                   # Map ID
  18.   attr_reader   :x                        # X Position
  19.   attr_reader   :y                        # Y Position
  20.   attr_reader   :direction                # Direction
  21.   attr_reader   :character_name           # Graphic name
  22.   attr_reader   :character_hue            # Graphic hue
  23.   attr_reader   :opacity                  # Graphic opacity
  24.   attr_reader   :move_speed               # Speed
  25.  
  26.   #--------------------------------------------------------------------------
  27.   # * Initializes Network Player
  28.   #--------------------------------------------------------------------------
  29.   def initialize(values)
  30.     super()
  31.     id              = values[0].to_f
  32.     @name           = values[1]
  33.     @level          = values[2].to_i
  34.     @class_name     = values[3]
  35.     @map_id         = values[4].to_i
  36.     @x              = values[5].to_i
  37.     @y              = values[6].to_i
  38.     @old_x          = values[5].to_i
  39.     @old_y          = values[6].to_i
  40.     @direction      = values[7].to_i
  41.     @character_name = values[8]
  42.     @character_hue  = values[9].to_i
  43.     @opacity        = values[10].to_i
  44.     @move_speed     = values[11].to_i
  45.   end
  46.  
  47.   #--------------------------------------------------------------------------
  48.   # * Refreshes Network Player
  49.   #--------------------------------------------------------------------------
  50.   def move_to_actual_position
  51.       if @map_id == $game_map.map_id
  52.         moveto(@x, @y)
  53.       end
  54.   end
  55.  
  56.   #=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
  57.   # * Update Attributes
  58.   # * Methods to update players attributes
  59.   #=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
  60.   def update_x(x)
  61.     @old_x = @x
  62.     @x = x.to_i
  63.   end
  64.  
  65.   def update_y(y)
  66.     @old_y = @y
  67.     @y = y.to_i
  68.   end
  69.  
  70.   def update_map_id(map_id)
  71.     @map_id = map_id.to_i
  72.   end
  73.  
  74.   def update_direction(direction)
  75.     @direction = direction.to_i
  76.   end
  77.  
  78.   def update_move_speed(move_speed)
  79.     @move_speed = move_speed.to_i
  80.   end
  81.  
  82.   def update_character_name(character_name)
  83.     @character_name = character_name
  84.   end
  85.  
  86.   def update_character_hue(character_hue)
  87.     @character_hue = character_hue.to_i
  88.   end
  89.  
  90.   def update_opacity(opacity)
  91.     @opacity = opacity.to_i
  92.   end
  93.  
  94.   def update_name(name)
  95.     @name = name
  96.   end
  97.  
  98.   def update_level(level)
  99.     @level = level.to_i
  100.   end
  101.  
  102.   def update_class_name(class_name)
  103.     @class_name = class_name
  104.   end
  105.  
  106.   #--------------------------------------------------------------------------
  107.   # * Update Network Player
  108.   #--------------------------------------------------------------------------
  109.   def update
  110.     if moving?
  111.       update_move
  112.     else
  113.       straighten
  114.     end
  115.     if @anime_count > 18 - @move_speed * 2
  116.       if not @step_anime and @stop_count > 0
  117.         @pattern = @original_pattern
  118.       else
  119.         @pattern = (@pattern + 1) % 4
  120.       end
  121.       @anime_count = 0
  122.     end
  123.     if @wait_count > 0
  124.       @wait_count -= 1
  125.       return
  126.     end
  127.   end
  128.  
  129.   #--------------------------------------------------------------------------
  130.   # * Update Walking Movement
  131.   #--------------------------------------------------------------------------
  132.   def update_move
  133.     distance = 2 ** @move_speed
  134.     if @y * 128 > @real_y
  135.       @real_y = [@real_y + distance, @y * 128].min
  136.     end
  137.     if @x * 128 < @real_x
  138.       @real_x = [@real_x - distance, @x * 128].max
  139.     end
  140.     if @x * 128 > @real_x
  141.       @real_x = [@real_x + distance, @x * 128].min
  142.     end
  143.     if @y * 128 < @real_y
  144.       @real_y = [@real_y - distance, @y * 128].max
  145.     end
  146.     @anime_count += 1.5
  147.   end
  148. end
  149.  
Expand to see the code.


Sprite_PlayerCharacter Class
  1.  
  2. #==============================================================================
  3. # ** Sprite_Character
  4. #------------------------------------------------------------------------------
  5. #  This sprite is used to display the character.It observes the Game_Character
  6. #  class and automatically changes sprite conditions.
  7. #==============================================================================
  8.  
  9. class Sprite_PlayerCharacter < RPG::Sprite
  10.   #--------------------------------------------------------------------------
  11.   # * Public Instance Variables
  12.   #--------------------------------------------------------------------------
  13.   attr_accessor :character                # character
  14.   #--------------------------------------------------------------------------
  15.   # * Object Initialization
  16.   #     viewport  : viewport
  17.   #     character : character (Game_Character)
  18.   #--------------------------------------------------------------------------
  19.   def initialize(viewport, character = nil)
  20.     super(viewport)
  21.     @character = character
  22.     update
  23.   end
  24.   #--------------------------------------------------------------------------
  25.   # * Frame Update
  26.   #--------------------------------------------------------------------------
  27.   def update
  28.     super
  29.     # If tile ID, file name, or hue are different from current ones
  30.     if @tile_id != @character.tile_id or
  31.        @character_name != @character.character_name or
  32.        @character_hue != @character.character_hue
  33.       # Remember tile ID, file name, and hue
  34.       @tile_id = @character.tile_id
  35.       @character_name = @character.character_name
  36.       # Send the new graphic filename to the server
  37.       $network.update_character_name
  38.       @character_hue = @character.character_hue
  39.       # If tile ID value is valid
  40.       if @tile_id >= 384
  41.         self.bitmap = RPG::Cache.tile($game_map.tileset_name,
  42.           @tile_id, @character.character_hue)
  43.         self.src_rect.set(0, 0, 32, 32)
  44.         self.ox = 16
  45.         self.oy = 32
  46.       # If tile ID value is invalid
  47.       else
  48.         self.bitmap = RPG::Cache.character(@character.character_name,
  49.           @character.character_hue)
  50.         @cw = bitmap.width / 4
  51.         @ch = bitmap.height / 4
  52.         self.ox = @cw / 2
  53.         self.oy = @ch
  54.       end
  55.     end
  56.     # Set visible situation
  57.     self.visible = (not @character.transparent)
  58.     # If graphic is character
  59.     if @tile_id == 0
  60.       # Set rectangular transfer
  61.       sx = @character.pattern * @cw
  62.       sy = (@character.direction - 2) / 2 * @ch
  63.       self.src_rect.set(sx, sy, @cw, @ch)
  64.     end
  65.     # Set sprite coordinates
  66.     self.x = @character.screen_x
  67.     self.y = @character.screen_y
  68.     self.z = @character.screen_z(@ch)
  69.     # Set opacity level, blend method, and bush depth
  70.     self.opacity = @character.opacity
  71.     self.blend_type = @character.blend_type
  72.     self.bush_depth = @character.bush_depth
  73.     # Animation
  74.     if @character.animation_id != 0
  75.       animation = $data_animations[@character.animation_id]
  76.       animation(animation, true)
  77.       @character.animation_id = 0
  78.     end
  79.   end
  80. end
  81.  
Expand to see the code.


Sprite_NetCharacter Class
  1.  
  2. #==============================================================================
  3. # ** Sprite_Character
  4. #------------------------------------------------------------------------------
  5. #  This sprite is used to display the character.It observes the Game_Character
  6. #  class and automatically changes sprite conditions.
  7. #==============================================================================
  8.  
  9. class Sprite_NetCharacter < RPG::Sprite
  10.  
  11.   #--------------------------------------------------------------------------
  12.   # * Public Instance Variables
  13.   #--------------------------------------------------------------------------
  14.   attr_accessor :character                # character
  15.  
  16.   #--------------------------------------------------------------------------
  17.   # * Object Initialization
  18.   #     viewport  : viewport
  19.   #     character : character (Game_Character)
  20.   #--------------------------------------------------------------------------
  21.   def initialize(viewport, character = nil)
  22.     super(viewport)
  23.     @character = character
  24.     # Name over the character
  25.     @name_display = Sprite.new
  26.     @name_display.bitmap = Bitmap.new(120, 32)
  27.     @name_display.bitmap.font.size = 22
  28.     update
  29.   end
  30.  
  31.   #--------------------------------------------------------------------------
  32.   # * Disposes sprite.
  33.   #--------------------------------------------------------------------------
  34.   def dispose
  35.     @name_display.bitmap.dispose
  36.     @name_display.dispose
  37.     super
  38.   end
  39.  
  40.   #--------------------------------------------------------------------------
  41.   # * Frame Update
  42.   #--------------------------------------------------------------------------
  43.   def update
  44.     super
  45.     # Clear&Draw the name
  46.     @name_display.bitmap.clear
  47.     @name_display.bitmap.draw_text(0, 0, 120, 32, @character.name, 1)    
  48.     # If tile ID, file name, or hue are different from current ones
  49.     if @tile_id != @character.tile_id or
  50.        @character_name != @character.character_name or
  51.        @character_hue != @character.character_hue
  52.       # Remember tile ID, file name, and hue
  53.       @tile_id = @character.tile_id
  54.       @character_name = @character.character_name
  55.       @character_hue = @character.character_hue
  56.       # If tile ID value is valid
  57.       if @tile_id >= 384
  58.         self.bitmap = RPG::Cache.tile($game_map.tileset_name,
  59.           @tile_id, @character.character_hue)
  60.         self.src_rect.set(0, 0, 32, 32)
  61.         self.ox = 16
  62.         self.oy = 32
  63.       # If tile ID value is invalid
  64.       else
  65.         self.bitmap = RPG::Cache.character(@character.character_name,
  66.           @character.character_hue)
  67.         @cw = bitmap.width / 4
  68.         @ch = bitmap.height / 4
  69.         self.ox = @cw / 2
  70.         self.oy = @ch
  71.       end
  72.     end
  73.     # Set visible situation
  74.     self.visible = (not @character.transparent)
  75.     # If graphic is character
  76.     if @tile_id == 0
  77.       # Set rectangular transfer
  78.       sx = @character.pattern * @cw
  79.       sy = (@character.direction - 2) / 2 * @ch
  80.       self.src_rect.set(sx, sy, @cw, @ch)
  81.     end
  82.     # Set sprite coordinates
  83.     self.x = @character.screen_x
  84.     self.y = @character.screen_y
  85.     self.z = @character.screen_z(@ch)
  86.     # Set name coordinates
  87.     @name_display.x = self.x - 60
  88.     @name_display.y = self.y - 80
  89.     @name_display.z = self.z
  90.     # Set opacity level, blend method, and bush depth
  91.     self.opacity = @character.opacity
  92.     self.blend_type = @character.blend_type
  93.     self.bush_depth = @character.bush_depth
  94.     # Animation
  95.     if @character.animation_id != 0
  96.       animation = $data_animations[@character.animation_id]
  97.       animation(animation, true)
  98.       @character.animation_id = 0
  99.     end
  100.   end
  101. end
  102.  
Expand to see the code.


Chat Class:

  1.  
  2. #===============================================================================
  3. # ** Chat
  4. #-------------------------------------------------------------------------------
  5. # Contains the text and related methods to control the chat.
  6. #===============================================================================
  7. class Chat
  8.  
  9.   #-----------------------------------------------------------------------------
  10.   # Public variables
  11.   #-----------------------------------------------------------------------------
  12.   attr_reader :text
  13.   attr_reader :visible_lines
  14.   attr_reader :width
  15.  
  16.   #-----------------------------------------------------------------------------
  17.   # * Initialize
  18.   #-----------------------------------------------------------------------------
  19.   def initialize
  20.     @text = []
  21.     @visible_lines = 3
  22.     @width = 440
  23.   end
  24.  
  25.   #-----------------------------------------------------------------------------
  26.   # * Size
  27.   # Returns the chat texts size
  28.   #-----------------------------------------------------------------------------
  29.   def size
  30.     return @text.size
  31.   end
  32.  
  33.   #-----------------------------------------------------------------------------
  34.   # * Reset
  35.   # Resets the chat text
  36.   #-----------------------------------------------------------------------------
  37.   def reset
  38.     @text.clear
  39.   end
  40.  
  41.   #-----------------------------------------------------------------------------
  42.   # * Add Line
  43.   # Adds a line to the end of chats text
  44.   #-----------------------------------------------------------------------------
  45.   def add_line(line)
  46.     @text << line
  47.   end
  48.  
  49.   #-----------------------------------------------------------------------------
  50.   # * Add Line and Send
  51.   # Adds a line to the end of chats text and sends it to the server
  52.   #-----------------------------------------------------------------------------
  53.   def add_line_and_send(line)
  54.     line_to_send = "202:#{$network.id};#{line}"
  55.     $network.client.send_packet($network.client.peers_list["server"]["peer"],
  56.                                 line_to_send, line_to_send.size+1, 2)
  57.     @text << "#{$game_actors[1].name}: #{line}"
  58.   end
  59.  
  60.   #-----------------------------------------------------------------------------
  61.   # * Delete Line
  62.   # Deletes the line at the given index
  63.   #-----------------------------------------------------------------------------
  64.   def delete_line(line_index)
  65.     return false if @text.size == 0
  66.     @text.slice!(line_index)
  67.   end
  68.  
  69.   #-----------------------------------------------------------------------------
  70.   # * Delete First Lines
  71.   # Delete the first lines from 0 to quantity - 1
  72.   #-----------------------------------------------------------------------------
  73.   def delete_first_lines(quantity)
  74.     return false if @text.size == 0
  75.     for i in 0...(quantity - 1)
  76.       @text.slice!(i)
  77.     end
  78.   end
  79.  
  80.   #-----------------------------------------------------------------------------
  81.   # * Last Line
  82.   # Returns the last text line
  83.   #-----------------------------------------------------------------------------
  84.   def last_line
  85.     return false if @text.size == 0
  86.     return @text[@text.size -1]
  87.   end
  88.  
  89.   #-----------------------------------------------------------------------------
  90.   # * Lines
  91.   # Return a range of lines from the text
  92.   #-----------------------------------------------------------------------------
  93.   def lines(first, last)
  94.     return false if @text.size == 0
  95.     lines = []
  96.     for i in (first - 1)..(last - 1)
  97.       lines << @text[i]
  98.     end
  99.     return lines
  100.   end
  101.  
  102.   #-----------------------------------------------------------------------------
  103.   # * Last Lines
  104.   # Return the last lines from the text
  105.   #-----------------------------------------------------------------------------
  106.   def last_lines(quantity)
  107.     return false if @text.size == 0
  108.     if quantity > @text.size
  109.       quantity = @text.size
  110.     end
  111.     j = @text.size - 1
  112.     lines = []
  113.     for i in 0..(quantity - 1)
  114.       lines << @text[j]
  115.       j -= 1
  116.     end
  117.     return lines
  118.   end
  119. end
  120.  
Expand to see the code.


Window_ChatInput Class
  1.  
  2. #==============================================================================
  3. # * Window_ChatInput                                    
  4. #------------------------------------------------------------------------------
  5. #  Captures typing and sends it
  6. #==============================================================================
  7.  
  8. class Window_ChatInput < Window_Base
  9.  
  10.   #--------------------------------------------------------------------------
  11.   # * Initialize
  12.   #--------------------------------------------------------------------------
  13.   def initialize
  14.     @x = 0
  15.     @y = 352 + 80
  16.     @width = $network.chat.width
  17.     @height = 48
  18.     super(@x, @y, @width, @height)
  19.     self.contents = Bitmap.new(width - 32, height - 32)
  20.     self.contents.font.size = 16
  21.     @text = []
  22.     self.visible = false
  23.     refresh
  24.   end
  25.  
  26.   #--------------------------------------------------------------------------
  27.   # * Refresh
  28.   #--------------------------------------------------------------------------
  29.   def refresh
  30.     self.contents.clear
  31.     self.contents.draw_text(0, -16, 620, @height, @text.to_s + "_")
  32.   end
  33.  
  34.   #--------------------------------------------------------------------------
  35.   # * Update
  36.   #--------------------------------------------------------------------------
  37.   def update
  38.     refresh
  39.     # Returns text
  40.     if Keyb.trigger($keys["Enter"])
  41.       if @text.size == 0
  42.         self.visible = false
  43.       else
  44.         $network.chat.add_line_and_send(@text.to_s)
  45.         @text.clear
  46.       end
  47.     end
  48.     # Remove last entry in text
  49.     if Keyb.trigger($keys["Back"])
  50.       @text.delete_at(-1) unless @text.size == 0
  51.     end
  52.    
  53.     # Adds a pressed key
  54.     unless @text.size >= 50
  55.       @text.push(" ") if Keyb.trigger($keys["Space"])
  56.       if Keyb.mayus
  57.         @text.push("A") if Keyb.trigger($keys["A"])
  58.         @text.push("B") if Keyb.trigger($keys["B"])
  59.         @text.push("C") if Keyb.trigger($keys["C"])
  60.         @text.push("D") if Keyb.trigger($keys["D"])
  61.         @text.push("E") if Keyb.trigger($keys["E"])
  62.         @text.push("F") if Keyb.trigger($keys["F"])
  63.         @text.push("G") if Keyb.trigger($keys["G"])
  64.         @text.push("H") if Keyb.trigger($keys["H"])
  65.         @text.push("I") if Keyb.trigger($keys["I"])
  66.         @text.push("J") if Keyb.trigger($keys["J"])
  67.         @text.push("K") if Keyb.trigger($keys["K"])
  68.         @text.push("L") if Keyb.trigger($keys["L"])
  69.         @text.push("M") if Keyb.trigger($keys["M"])
  70.         @text.push("N") if Keyb.trigger($keys["N"])
  71.         @text.push("Ñ") if Keyb.trigger($keys["Ñ"])
  72.         @text.push("O") if Keyb.trigger($keys["O"])
  73.         @text.push("P") if Keyb.trigger($keys["P"])
  74.         @text.push("Q") if Keyb.trigger($keys["Q"])
  75.         @text.push("R") if Keyb.trigger($keys["R"])
  76.         @text.push("S") if Keyb.trigger($keys["S"])
  77.         @text.push("T") if Keyb.trigger($keys["T"])
  78.         @text.push("U") if Keyb.trigger($keys["U"])
  79.         @text.push("V") if Keyb.trigger($keys["V"])
  80.         @text.push("W") if Keyb.trigger($keys["W"])
  81.         @text.push("X") if Keyb.trigger($keys["X"])
  82.         @text.push("Y") if Keyb.trigger($keys["Y"])
  83.         @text.push("Z") if Keyb.trigger($keys["Z"])
  84.         @text.push("!") if Keyb.trigger($keys["1"])
  85.         @text.push("·") if Keyb.trigger($keys["3"])
  86.         @text.push("$") if Keyb.trigger($keys["4"])
  87.         @text.push("%") if Keyb.trigger($keys["5"])
  88.         @text.push("&") if Keyb.trigger($keys["6"])
  89.         @text.push("/") if Keyb.trigger($keys["7"])
  90.         @text.push("(") if Keyb.trigger($keys["8"])
  91.         @text.push(")") if Keyb.trigger($keys["9"])
  92.         @text.push("=") if Keyb.trigger($keys["0"])
  93.         @text.push("?") if Keyb.trigger($keys["Prg2"])
  94.         @text.push("¿") if Keyb.trigger($keys["Prg1"])
  95.         @text.push("^") if Keyb.trigger($keys["Ac2"])    
  96.         @text.push("*") if Keyb.trigger($keys["Plus"])
  97.         @text.push("¨") if Keyb.trigger($keys["Ac1"])      
  98.         @text.push("ç") if Keyb.trigger($keys["Ç"])
  99.         @text.push(";") if Keyb.trigger($keys["Sep"])
  100.         @text.push(":") if Keyb.trigger($keys["Dott"])
  101.         @text.push("_") if Keyb.trigger($keys["Dash"])
  102.         @text.push(">") if Keyb.trigger($keys["Cmp"])    
  103.         @text.push("ª") if Keyb.trigger($keys["Ord"])
  104.       else
  105.         @text.push("a") if Keyb.trigger($keys["A"])
  106.         @text.push("b") if Keyb.trigger($keys["B"])
  107.         @text.push("c") if Keyb.trigger($keys["C"])
  108.         @text.push("d") if Keyb.trigger($keys["D"])
  109.         @text.push("e") if Keyb.trigger($keys["E"])
  110.         @text.push("f") if Keyb.trigger($keys["F"])
  111.         @text.push("g") if Keyb.trigger($keys["G"])
  112.         @text.push("h") if Keyb.trigger($keys["H"])
  113.         @text.push("i") if Keyb.trigger($keys["I"])
  114.         @text.push("j") if Keyb.trigger($keys["J"])
  115.         @text.push("k") if Keyb.trigger($keys["K"])
  116.         @text.push("l") if Keyb.trigger($keys["L"])
  117.         @text.push("m") if Keyb.trigger($keys["M"])
  118.         @text.push("n") if Keyb.trigger($keys["N"])
  119.         @text.push("ñ") if Keyb.trigger($keys["Ñ"])
  120.         @text.push("o") if Keyb.trigger($keys["O"])
  121.         @text.push("p") if Keyb.trigger($keys["P"])
  122.         @text.push("q") if Keyb.trigger($keys["Q"])
  123.         @text.push("r") if Keyb.trigger($keys["R"])
  124.         @text.push("s") if Keyb.trigger($keys["S"])
  125.         @text.push("t") if Keyb.trigger($keys["T"])
  126.         @text.push("u") if Keyb.trigger($keys["U"])
  127.         @text.push("v") if Keyb.trigger($keys["V"])
  128.         @text.push("w") if Keyb.trigger($keys["W"])
  129.         @text.push("x") if Keyb.trigger($keys["X"])
  130.         @text.push("y") if Keyb.trigger($keys["Y"])
  131.         @text.push("z") if Keyb.trigger($keys["Z"])
  132.         @text.push("0") if Keyb.trigger($keys["0"])
  133.         @text.push("1") if Keyb.trigger($keys["1"])
  134.         @text.push("2") if Keyb.trigger($keys["2"])
  135.         @text.push("3") if Keyb.trigger($keys["3"])
  136.         @text.push("4") if Keyb.trigger($keys["4"])
  137.         @text.push("5") if Keyb.trigger($keys["5"])
  138.         @text.push("6") if Keyb.trigger($keys["6"])
  139.         @text.push("7") if Keyb.trigger($keys["7"])
  140.         @text.push("8") if Keyb.trigger($keys["8"])
  141.         @text.push("9") if Keyb.trigger($keys["9"])
  142.         @text.push("`") if Keyb.trigger($keys["Ac2"])
  143.         @text.push("+") if Keyb.trigger($keys["Plus"])      
  144.         @text.push("´") if Keyb.trigger($keys["Ac1"])
  145.         @text.push("ç") if Keyb.trigger($keys["Ç"])    
  146.         @text.push(",") if Keyb.trigger($keys["Sep"])
  147.         @text.push(".") if Keyb.trigger($keys["Dott"])
  148.         @text.push("-") if Keyb.trigger($keys["Dash"])
  149.         @text.push("'") if Keyb.trigger($keys["Prg2"])
  150.         @text.push("¡") if Keyb.trigger($keys["Prg1"])  
  151.         @text.push("<") if Keyb.trigger($keys["Cmp"])
  152.         @text.push("º") if Keyb.trigger($keys["Ord"])
  153.       end
  154.       @text.push("*") if Keyb.trigger($keys["Multiply"])      
  155.       @text.push("+") if Keyb.trigger($keys["Add"])
  156.       @text.push("-") if Keyb.trigger($keys["Substract"])
  157.       @text.push("/") if Keyb.trigger($keys["Divide"])
  158.       @text.push(".") if Keyb.trigger($keys["Decimal"])
  159.       @text.push("0") if Keyb.trigger($keys["Pad0"])
  160.       @text.push("1") if Keyb.trigger($keys["Pad1"])
  161.       @text.push("2") if Keyb.trigger($keys["Pad2"])
  162.       @text.push("3") if Keyb.trigger($keys["Pad3"])
  163.       @text.push("4") if Keyb.trigger($keys["Pad4"])
  164.       @text.push("5") if Keyb.trigger($keys["Pad5"])
  165.       @text.push("6") if Keyb.trigger($keys["Pad6"])
  166.       @text.push("7") if Keyb.trigger($keys["Pad7"])
  167.       @text.push("8") if Keyb.trigger($keys["Pad8"])
  168.       @text.push("9") if Keyb.trigger($keys["Pad9"])
  169.     end
  170.   end
  171. end
  172.  
Expand to see the code.


Window_Chat Class
  1.  
  2. #==============================================================================
  3. # * Window_Chat
  4. #------------------------------------------------------------------------------
  5. #  Displays chat messages
  6. #==============================================================================
  7.  
  8. class Window_Chat < Window_Base
  9.   #--------------------------------------------------------------------------
  10.   # * Initialization
  11.   #--------------------------------------------------------------------------
  12.   def initialize    
  13.     @x = 0
  14.     @y = 352
  15.     @width = $network.chat.width
  16.     @height = 80
  17.     super(@x, @y, @width, @height)
  18.     self.contents = Bitmap.new(width - 32, height - 32)
  19.     self.back_opacity = 50
  20.     self.visible = true
  21.     self.contents.font.size = 16
  22.     refresh
  23.   end
  24.   #--------------------------------------------------------------------------
  25.   # * Refresh
  26.   #--------------------------------------------------------------------------
  27.   def refresh
  28.     self.contents.clear
  29.     lines = $network.chat.last_lines($network.chat.visible_lines)
  30.     return if lines == false
  31.       for i in 1..lines.size
  32.         self.contents.draw_text(0, ($network.chat.visible_lines - i) * 16 - 8, @width, 32, lines[i-1])
  33.       end
  34.   end
  35.   #--------------------------------------------------------------------------
  36.   # * Update
  37.   #--------------------------------------------------------------------------
  38.    def update
  39.     super
  40.     #if Graphics.frame_count % Graphics.frame_rate == 0
  41.       refresh
  42.     #end
  43.   end
  44. end
  45.  
Expand to see the code.


Keyboard Module by Hound
  1.  
  2. ################################################################################
  3. ################################ KEYBOARD MODULE ###############################
  4. ################################################################################
  5. #-------------------------------------------------------------------------------
  6. # Basado en el Keyboard Script de Cybersam
  7. # Script remodelado por Hound
  8. #-------------------------------------------------------------------------------
  9. # Explicación:
  10. # Este script es un módulo para las condiciones de pulsado de teclas, que incluye
  11. # TODAS las teclas del teclado español. Me basé en el famoso script de teclado
  12. # de Cybersam para las funciones y teclas básicas del teclado inglés, pero con
  13. # algunos cambios destacables, asi como las teclas especiales típicas del
  14. # teclado español (Ñ, Ç, acentos, etc), cambios en las funciones y sintaxis, etc
  15. # La mayoría de nombres para las teclas, están conservados en inglés.
  16. #-------------------------------------------------------------------------------
  17. # Instrucciones:
  18. # El comando para la condición de tecla pulsada puedes ponerla desde el comando
  19. # de evento "Condiciones y Efectos" desde la opción "Script" escribiendo:
  20. # Keyb.trigger($keys["nombre de la tecla"]) # Para condición trigger/repeat
  21. # Keyb.press($keys["nombre de la tecla"]) # Para condición mientras es pulsada
  22. # Keyb.bloq($keys["nombre de la tecla"]) # Para condición de tecla bloqueada
  23. # Keyb.mayus # Para condición de bloq mayus activado
  24. # Keyb.empty # Para limpiar/arreglar el rastreo del teclado
  25. # Es recomendable escribir Keyb.empty justo antes de una serie de condicione
  26. # en las que se use este módulo, para limpiar el rastreo.
  27. #-------------------------------------------------------------------------------
  28. # Contacto:
  29. # Para cualquier comentario, duda o sugerencia, mándalas por email
  30. # a [email hidden]
  31. # Espero que sirva de utilidad ;)
  32. #-------------------------------------------------------------------------------
  33.  
  34. module Keyb
  35.   $keys = {}
  36.   $keys["MouseL"] = 0x01 # Botón Izquierdo
  37.   $keys["MouseR"] = 0x02 # Botón Derecho
  38.   $keys["MouseM"] = 0x04 # Botón medio
  39.   $keys["Mouse4"] = 0x05 # Cuarto Botón
  40.   $keys["Mouse5"] = 0x06 # Quinto Botón
  41.   # Teclas de Controles
  42.   $keys["Back"] = 0x08 # Tecla Retroceder/Borrar
  43.   $keys["Tab"] = 0x09 # Tecla Tab
  44.   $keys["Enter"] = 0x0D # Tecla Enter
  45.   $keys["Shift"] = 0x10 # Tecla Shift
  46.   $keys["Ctrl"] = 0x11 # Tecla Control
  47.   $keys["Alt"] = 0x12 # Tecla Alt
  48.   $keys["Pause"] = 0x13 # Tecla de Pausa
  49.   $keys["Caps"] = 0x14 # Tecla Bloq Mayus
  50.   $keys["Esc"] = 0x1B # Tecla Escape (ESC)
  51.   $keys["Space"] = 0x20 # Tecla Espaciadora
  52.   $keys["AvPag"] = 0x21 # Tecla Siguiente
  53.   $keys["RePag"] = 0x22 # Tecla Anterior
  54.   $keys["End"] = 0x23 # Tecla Fin
  55.   $keys["Home"] = 0x24 # Tecla Inicio
  56.   # Teclas de Direcciones
  57.   $keys["Left"] = 0x25 # Tecla Flecha Izquierda
  58.   $keys["Up"] = 0x26 # Tecla Flecha Arriba
  59.   $keys["Right"] = 0x27 # Tecla Flecha Derecha
  60.   $keys["Down"] = 0x28 # Tecla Flecha Abajo
  61.   $keys["Select"] = 0x29
  62.   # Otras teclas
  63.   $keys["Print"] = 0x2A # Tecla Imprimir
  64.   $keys["Snapshot"] = 0x2C # Tecla Capturar Pantalla
  65.   $keys["Ins"] = 0x2D # Tecla Insert
  66.   $keys["Del"] = 0x2E # Tecla Suprimir
  67.   # Teclas Numéricas Superiores
  68.   $keys["0"] = 0x30
  69.   $keys["1"] = 0x31
  70.   $keys["2"] = 0x32
  71.   $keys["3"] = 0x33
  72.   $keys["4"] = 0x34
  73.   $keys["5"] = 0x35
  74.   $keys["6"] = 0x36
  75.   $keys["7"] = 0x37
  76.   $keys["8"] = 0x38
  77.   $keys["9"] = 0x39
  78.   # Teclas de Windows
  79.   $keys["Lwin"] = 0x5B # Tecla Windows Izquierda
  80.   $keys["Rwin"] = 0x5C # Tecla Windows Derecha
  81.   $keys["Apps"] = 0x5D # Tecla Aplicaciones
  82.   # Teclas del Pad Numérico
  83.   $keys["Pad0"] = 0x60
  84.   $keys["Pad1"] = 0x61
  85.   $keys["Pad2"] = 0x62
  86.   $keys["Pad3"] = 0x63
  87.   $keys["Pad4"] = 0x64
  88.   $keys["Pad5"] = 0x65
  89.   $keys["Pad6"] = 0x66
  90.   $keys["Pad7"] = 0x67
  91.   $keys["Pad8"] = 0x68
  92.   $keys["Pad9"] = 0x69
  93.   $keys["Multiply"] = 0x6A # Tecla Multiplicar
  94.   $keys["Add"] = 0x6B # Tecla Sumar
  95.   $keys["Separator"] = 0x6C
  96.   $keys["Substract"] = 0x6D # Tecla Restar
  97.   $keys["Decimal"] = 0x6E
  98.   $keys["Divide"] = 0x6F # Tecla Dividir
  99.   # Teclas de Funciones
  100.   $keys["F1"] = 0x70
  101.   $keys["F2"] = 0x71
  102.   $keys["F3"] = 0x72
  103.   $keys["F4"] = 0x73
  104.   $keys["F5"] = 0x74
  105.   $keys["F6"] = 0x75
  106.   $keys["F7"] = 0x76
  107.   $keys["F8"] = 0x77
  108.   $keys["F9"] = 0x78
  109.   $keys["F10"] = 0x79
  110.   $keys["F11"] = 0x7A
  111.   $keys["F12"] = 0x7B
  112.   $keys["Numlock"] = 0x90
  113.   $keys["Scroll"] = 0x91 # Tecla Bloq Despl
  114.   # Teclas de cada letra
  115.   $keys["A"] = 0x41
  116.   $keys["B"] = 0x42
  117.   $keys["C"] = 0x43
  118.   $keys["D"] = 0x44
  119.   $keys["E"] = 0x45
  120.   $keys["F"] = 0x46
  121.   $keys["G"] = 0x47
  122.   $keys["H"] = 0x48
  123.   $keys["I"] = 0x49
  124.   $keys["J"] = 0x4A
  125.   $keys["K"] = 0x4B
  126.   $keys["L"] = 0x4C
  127.   $keys["M"] = 0x4D
  128.   $keys["N"] = 0x4E
  129.   $keys["O"] = 0x4F
  130.   $keys["P"] = 0x50
  131.   $keys["Q"] = 0x51
  132.   $keys["R"] = 0x52
  133.   $keys["S"] = 0x53
  134.   $keys["T"] = 0x54
  135.   $keys["U"] = 0x55
  136.   $keys["V"] = 0x56
  137.   $keys["W"] = 0x57
  138.   $keys["X"] = 0x58
  139.   $keys["Y"] = 0x59
  140.   $keys["Z"] = 0x5A
  141.   # Teclas de Signos de Puntuación
  142.   $keys["Sep"] = 0xBC # Tecla Coma , ;
  143.   $keys["Dash"] = 0xBD # Tecla Guión - _
  144.   $keys["Dott"] = 0xBE # Tecla Punto . :
  145.   # Teclas de carácteres especiales
  146.   $keys["Ç"] = 0xBF # ç Ç }
  147.   $keys["Ñ"] = 0xc0# ñ Ñ
  148.   $keys["Ac1"] = 0xde # Acento y Diéresis ´¨
  149.   $keys["Ac2"] = 0xBA # Acento al revés `^
  150.   $keys["Plus"] = 0xBB # + * ]
  151.   $keys["Prg2"] = 0xdb # ' ?
  152.   $keys["Ord"] = 0xdc # º ª \
  153.   $keys["Prg1"] = 0xdd # ¡ ¿
  154.   $keys["Cmp"] = 0xe2 # Comparación < >
  155.   # Teclas de Control Específicas
  156.   $keys["Lshift"] = 0xA0 # Shift izquierdo
  157.   $keys["Rshift"] = 0xA1 # Shift derecho
  158.   $keys["Lctrl"] = 0xA2 # Ctrl izquierdo
  159.   $keys["Rctrl"] = 0xA3 # Ctrl derecho
  160.   $keys["Lalt"] = 0xA4 # Alt izquierdo
  161.   $keys["Ralt"] = 0xA5 # Alt derecho
  162.   #--------------------------------------------------------------------------
  163.   # Creamos las variables de llamada Win32api
  164.   #--------------------------------------------------------------------------
  165.   GetKeyState = Win32API.new("user32","GetAsyncKeyState",['i'],'i')
  166.   GetKeyboardState = Win32API.new("user32","GetKeyState",['i'],'i')
  167.   GetSetKeyState = Win32API.new("user32","SetKeyboardState",['i'],'i')
  168.   #--------------------------------------------------------------------------
  169.   module_function #Ponemos los métodos agregados al nombre del módulo
  170.   #--------------------------------------------------------------------------
  171.   def trigger(rkey) # Condición de tecla pulsada repetitivamente
  172.     GetKeyState.call(rkey) & 0x01 == 1
  173.   end
  174.   #--------------------------------------------------------------------------
  175.   def press(key) # Condición de tecla pulsada
  176.     not GetKeyboardState.call(key).between?(0, 1)
  177.   end
  178.   def bloq(key) # Condición de tecla bloqueada
  179.     GetKeyboardState.call(key) == 1
  180.   end
  181.   def mayus # Condición del bloq mayus activado
  182.     GetKeyboardState.call(0x14) == 1
  183.   end
  184.   def empty # Método de arreglo para la condición de teclas
  185.     array = $keys.values
  186.     for i in 0...array.size
  187.       self.trigger(array[i])
  188.     end
  189.   end
  190. end
  191.  
Expand to see the code.



____Edited Scripts____

Game_Temp Class
  1.  
  2. #==============================================================================
  3. # ** Game_Temp
  4. #------------------------------------------------------------------------------
  5. #  Esta clase almacena los datos temporales no incluidos en las partidas guardadas.
  6. #  Llama a "$game_temp" para acceder a las variables globales incluidas aquí.
  7. #==============================================================================
  8.  
  9. class Game_Temp
  10.   #--------------------------------------------------------------------------
  11.   # * Variables Globales
  12.   #--------------------------------------------------------------------------
  13.   attr_accessor :map_bgm                  # Música de Mapa(Se devuelve al terminar batalla)
  14.   attr_accessor :message_text             # Texto del Mensaje
  15.   attr_accessor :message_proc             # Llamada de Mensaje (Proc)
  16.   attr_accessor :choice_start             # Elecciones: Línea de Comienzo
  17.   attr_accessor :choice_max               # Elecciones: Número de Opciones
  18.   attr_accessor :choice_cancel_type       # Elecciones: Añadir Rama al Cancelar
  19.   attr_accessor :choice_proc              # Elecciones: Llamada (Proc)
  20.   attr_accessor :num_input_start          # Dígitos: Línea de Comienzo
  21.   attr_accessor :num_input_variable_id    # Dígitos: Variable en que se guarda
  22.   attr_accessor :num_input_digits_max     # input number: digit amount
  23.   attr_accessor :message_window_showing   # Ejecutando Ventana de Mensaje
  24.   attr_accessor :common_event_id          # ID de Evento Común
  25.   attr_accessor :in_battle                # Indica si estás en la batalla
  26.   attr_accessor :battle_calling           # Llamada a la Batalla
  27.   attr_accessor :battle_troop_id          # ID de Grupo de Enemigos
  28.   attr_accessor :battle_can_escape        # Posibilidad de Escapar
  29.   attr_accessor :battle_can_lose          # Posibilidad de perder batalla
  30.   attr_accessor :battle_proc              # Llamada a Batalla (Proc)
  31.   attr_accessor :battle_turn              # Número de turnos en la batalla
  32.   attr_accessor :battle_event_flags       # battle event flags: completed
  33.   attr_accessor :battle_abort             # Llamada para finalizar batalla
  34.   attr_accessor :battle_main_phase        # battle flag: main phase
  35.   attr_accessor :battleback_name          # Nombre del fondo de batalla
  36.   attr_accessor :forcing_battler          # Combatiente forzado a una acción
  37.   attr_accessor :shop_calling             # Llamada a Tienda
  38.   attr_accessor :shop_goods               # Lista de objetos para la tienda
  39.   attr_accessor :name_calling             # Llamada a Escribir Nombre
  40.   attr_accessor :name_actor_id            # ID de Héroe para Escribir Nombre
  41.   attr_accessor :name_max_char            # Máximo de carácteres para Escribir Nombre
  42.   attr_accessor :menu_calling             # Llamada al Menú
  43.   attr_accessor :menu_beep                # Reproducir sonido del menú
  44.   attr_accessor :save_calling             # Llamada a Pantalla de Guardar
  45.   attr_accessor :debug_calling            # Llamada a Pantalla de Depuración
  46.   attr_accessor :player_transferring      # Llamada a Teletransportar Héroe
  47.   attr_accessor :player_new_map_id        # Destino del Héroe: ID de Mapa
  48.   attr_accessor :player_new_x             # Destino del Héroe: Cordenada X
  49.   attr_accessor :player_new_y             # Destino del Héroe: Cordenada Y
  50.   attr_accessor :player_new_direction     # Destino del Héroe: direction
  51.   attr_accessor :transition_processing    # Llamada a Proceso de Transición
  52.   attr_accessor :transition_name          # Nombre del Archivo de Transición
  53.   attr_accessor :gameover                 # Llamada a GameOver
  54.   attr_accessor :to_title                 # Llamada a Volver a Título
  55.   attr_accessor :last_file_index          # Número de la última partida guardada
  56.   attr_accessor :debug_top_row            # Pantalla de Depuración: Fila Elegida
  57.   attr_accessor :debug_index              # Pantalla de Depuración: Opción Elegida
  58.   attr_accessor :new_map_players
  59.   attr_accessor :old_map_players
  60.   #--------------------------------------------------------------------------
  61.   # * Inicio de Objetos (Aquí se agrega el valor incial a cada variable)
  62.   #--------------------------------------------------------------------------
  63.   def initialize
  64.     @map_bgm = nil
  65.     @message_text = nil
  66.     @message_proc = nil
  67.     @choice_start = 99
  68.     @choice_max = 0
  69.     @choice_cancel_type = 0
  70.     @choice_proc = nil
  71.     @num_input_start = 99
  72.     @num_input_variable_id = 0
  73.     @num_input_digits_max = 0
  74.     @message_window_showing = false
  75.     @common_event_id = 0
  76.     @in_battle = false
  77.     @battle_calling = false
  78.     @battle_troop_id = 0
  79.     @battle_can_escape = false
  80.     @battle_can_lose = false
  81.     @battle_proc = nil
  82.     @battle_turn = 0
  83.     @battle_event_flags = {}
  84.     @battle_abort = false
  85.     @battle_main_phase = false
  86.     @battleback_name = ''
  87.     @forcing_battler = nil
  88.     @shop_calling = false
  89.     @shop_id = 0
  90.     @name_calling = false
  91.     @name_actor_id = 0
  92.     @name_max_char = 0
  93.     @menu_calling = false
  94.     @menu_beep = false
  95.     @save_calling = false
  96.     @debug_calling = false
  97.     @player_transferring = false
  98.     @player_new_map_id = 0
  99.     @player_new_x = 0
  100.     @player_new_y = 0
  101.     @player_new_direction = 0
  102.     @transition_processing = false
  103.     @transition_name = ""
  104.     @gameover = false
  105.     @to_title = false
  106.     @last_file_index = 0
  107.     @debug_top_row = 0
  108.     @debug_index = 0
  109.    
  110.     @new_map_players = []
  111.     @old_map_players = []
  112.   end
  113. end
  114.  
Expand to see the code.


Game_Player Class
  1.  
  2. #==============================================================================
  3. # ** Game_Player
  4. #------------------------------------------------------------------------------
  5. #  This class handles the player. Its functions include event starting
  6. #  determinants and map scrolling. Refer to "$game_player" for the one
  7. #  instance of this class.
  8. #==============================================================================
  9.  
  10. class Game_Player < Game_Character
  11.   #--------------------------------------------------------------------------
  12.   # * Invariables
  13.   #--------------------------------------------------------------------------
  14.   CENTER_X = (320 - 16) * 4   # Center screen x-coordinate * 4
  15.   CENTER_Y = (240 - 16) * 4   # Center screen y-coordinate * 4
  16.   #--------------------------------------------------------------------------
  17.   # * Passable Determinants
  18.   #     x : x-coordinate
  19.   #     y : y-coordinate
  20.   #     d : direction (0,2,4,6,8)
  21.   #         * 0 = Determines if all directions are impassable (for jumping)
  22.   #--------------------------------------------------------------------------
  23.   def passable?(x, y, d)
  24.     # Get new coordinates
  25.     new_x = x + (d == 6 ? 1 : d == 4 ? -1 : 0)
  26.     new_y = y + (d == 2 ? 1 : d == 8 ? -1 : 0)
  27.     # If coordinates are outside of map
  28.     unless $game_map.valid?(new_x, new_y)
  29.       # Impassable
  30.       return false
  31.     end
  32.     # If debug mode is ON and ctrl key was pressed
  33.     if $DEBUG and Input.press?(Input::CTRL)
  34.       # Passable
  35.       return true
  36.     end
  37.     super
  38.   end
  39.   #--------------------------------------------------------------------------
  40.   # * Set Map Display Position to Center of Screen
  41.   #--------------------------------------------------------------------------
  42.   def center(x, y)
  43.     max_x = ($game_map.width - 20) * 128
  44.     max_y = ($game_map.height - 15) * 128
  45.     $game_map.display_x = [0, [x * 128 - CENTER_X, max_x].min].max
  46.     $game_map.display_y = [0, [y * 128 - CENTER_Y, max_y].min].max
  47.   end
  48.   #--------------------------------------------------------------------------
  49.   # * Move to Designated Position
  50.   #     x : x-coordinate
  51.   #     y : y-coordinate
  52.   #--------------------------------------------------------------------------
  53.   def moveto(x, y)
  54.     super
  55.     # Centering
  56.     center(x, y)
  57.     # Make encounter count
  58.     make_encounter_count
  59.   end
  60.   #--------------------------------------------------------------------------
  61.   # * Increaase Steps
  62.   #--------------------------------------------------------------------------
  63.   def increase_steps
  64.     super
  65.     # If move route is not forcing
  66.     unless @move_route_forcing
  67.       # Increase steps
  68.       $game_party.increase_steps
  69.       # Number of steps are an even number
  70.       if $game_party.steps % 2 == 0
  71.         # Slip damage check
  72.         $game_party.check_map_slip_damage
  73.       end
  74.     end
  75.   end
  76.   #--------------------------------------------------------------------------
  77.   # * Get Encounter Count
  78.   #--------------------------------------------------------------------------
  79.   def encounter_count
  80.     return @encounter_count
  81.   end
  82.   #--------------------------------------------------------------------------
  83.   # * Make Encounter Count
  84.   #--------------------------------------------------------------------------
  85.   def make_encounter_count
  86.     # Image of two dice rolling
  87.     if $game_map.map_id != 0
  88.       n = $game_map.encounter_step
  89.       @encounter_count = rand(n) + rand(n) + 1
  90.     end
  91.   end
  92.   #--------------------------------------------------------------------------
  93.   # * Refresh
  94.   #--------------------------------------------------------------------------
  95.   def refresh
  96.     # If party members = 0
  97.     if $game_party.actors.size == 0
  98.       # Clear character file name and hue
  99.       @character_name = ""
  100.       @character_hue = 0
  101.       # End method
  102.       return
  103.     end
  104.     # Get lead actor
  105.     actor = $game_party.actors[0]
  106.     # Set character file name and hue
  107.     @character_name = actor.character_name
  108.     @character_hue = actor.character_hue
  109.     # Initialize opacity level and blending method
  110.     @opacity = 255
  111.     @blend_type = 0
  112.   end
  113.   #--------------------------------------------------------------------------
  114.   # * Same Position Starting Determinant
  115.   #--------------------------------------------------------------------------
  116.   def check_event_trigger_here(triggers)
  117.     result = false
  118.     # If event is running
  119.     if $game_system.map_interpreter.running?
  120.       return result
  121.     end
  122.     # All event loops
  123.     for event in $game_map.events.values
  124.       # If event coordinates and triggers are consistent
  125.       if event.x == @x and event.y == @y and triggers.include?(event.trigger)
  126.         # If starting determinant is same position event (other than jumping)
  127.         if not event.jumping? and event.over_trigger?
  128.           event.start
  129.           result = true
  130.         end
  131.       end
  132.     end
  133.     return result
  134.   end
  135.   #--------------------------------------------------------------------------
  136.   # * Front Envent Starting Determinant
  137.   #--------------------------------------------------------------------------
  138.   def check_event_trigger_there(triggers)
  139.     result = false
  140.     # If event is running
  141.     if $game_system.map_interpreter.running?
  142.       return result
  143.     end
  144.     # Calculate front event coordinates
  145.     new_x = @x + (@direction == 6 ? 1 : @direction == 4 ? -1 : 0)
  146.     new_y = @y + (@direction == 2 ? 1 : @direction == 8 ? -1 : 0)
  147.     # All event loops
  148.     for event in $game_map.events.values
  149.       # If event coordinates and triggers are consistent
  150.       if event.x == new_x and event.y == new_y and
  151.          triggers.include?(event.trigger)
  152.         # If starting determinant is front event (other than jumping)
  153.         if not event.jumping? and not event.over_trigger?
  154.           event.start
  155.           result = true
  156.         end
  157.       end
  158.     end
  159.     # If fitting event is not found
  160.     if result == false
  161.       # If front tile is a counter
  162.       if $game_map.counter?(new_x, new_y)
  163.         # Calculate 1 tile inside coordinates
  164.         new_x += (@direction == 6 ? 1 : @direction == 4 ? -1 : 0)
  165.         new_y += (@direction == 2 ? 1 : @direction == 8 ? -1 : 0)
  166.         # All event loops
  167.         for event in $game_map.events.values
  168.           # If event coordinates and triggers are consistent
  169.           if event.x == new_x and event.y == new_y and
  170.              triggers.include?(event.trigger)
  171.             # If starting determinant is front event (other than jumping)
  172.             if not event.jumping? and not event.over_trigger?
  173.               event.start
  174.               result = true
  175.             end
  176.           end
  177.         end
  178.       end
  179.     end
  180.     return result
  181.   end
  182.   #--------------------------------------------------------------------------
  183.   # * Touch Event Starting Determinant
  184.   #--------------------------------------------------------------------------
  185.   def check_event_trigger_touch(x, y)
  186.     result = false
  187.     # If event is running
  188.     if $game_system.map_interpreter.running?
  189.       return result
  190.     end
  191.     # All event loops
  192.     for event in $game_map.events.values
  193.       # If event coordinates and triggers are consistent
  194.       if event.x == x and event.y == y and [1,2].include?(event.trigger)
  195.         # If starting determinant is front event (other than jumping)
  196.         if not event.jumping? and not event.over_trigger?
  197.           event.start
  198.           result = true
  199.         end
  200.       end
  201.     end
  202.     return result
  203.   end
  204.   #--------------------------------------------------------------------------
  205.   # * Frame Update
  206.   #--------------------------------------------------------------------------
  207.   def update
  208.     # Remember whether or not moving in local variables
  209.     last_moving = moving?
  210.     # If moving, event running, move route forcing, and message window
  211.     # display are all not occurring
  212.     unless moving? or $game_system.map_interpreter.running? or
  213.            @move_route_forcing or $game_temp.message_window_showing
  214.       # Move player in the direction the directional button is being pressed
  215.       case Input.dir4
  216.       when 2
  217.         move_down
  218.         # Send our character x&y and direction to the server
  219.         $network.update_x
  220.         $network.update_direction
  221.       when 4
  222.         move_left
  223.         # Send our character x&y and direction to the server
  224.         $network.update_x
  225.         $network.update_direction
  226.       when 6
  227.         move_right
  228.         # Send our character x&y and direction to the server
  229.         $network.update_x
  230.         $network.update_direction
  231.       when 8
  232.         move_up
  233.         # Send our character x&y and direction to the server
  234.         $network.update_x
  235.         $network.update_direction
  236.       end
  237.     end
  238.     # Remember coordinates in local variables
  239.     last_real_x = @real_x
  240.     last_real_y = @real_y
  241.     super
  242.     # If character moves down and is positioned lower than the center
  243.     # of the screen
  244.     if @real_y > last_real_y and @real_y - $game_map.display_y > CENTER_Y
  245.       # Scroll map down
  246.       $game_map.scroll_down(@real_y - last_real_y)
  247.     end
  248.     # If character moves left and is positioned more let on-screen than
  249.     # center
  250.     if @real_x < last_real_x and @real_x - $game_map.display_x < CENTER_X
  251.       # Scroll map left
  252.       $game_map.scroll_left(last_real_x - @real_x)
  253.     end
  254.     # If character moves right and is positioned more right on-screen than
  255.     # center
  256.     if @real_x > last_real_x and @real_x - $game_map.display_x > CENTER_X
  257.       # Scroll map right
  258.       $game_map.scroll_right(@real_x - last_real_x)
  259.     end
  260.     # If character moves up and is positioned higher than the center
  261.     # of the screen
  262.     if @real_y < last_real_y and @real_y - $game_map.display_y < CENTER_Y
  263.       # Scroll map up
  264.       $game_map.scroll_up(last_real_y - @real_y)
  265.     end
  266.     # If not moving
  267.     unless moving?
  268.       # If player was moving last time
  269.       if last_moving
  270.         # Event determinant is via touch of same position event
  271.         result = check_event_trigger_here([1,2])
  272.         # If event which started does not exist
  273.         if result == false
  274.           # Disregard if debug mode is ON and ctrl key was pressed
  275.           unless $DEBUG and Input.press?(Input::CTRL)
  276.             # Encounter countdown
  277.             if @encounter_count > 0
  278.               @encounter_count -= 1
  279.             end
  280.           end
  281.         end
  282.       end
  283.       # If C button was pressed
  284.       if Input.trigger?(Input::C)
  285.         # Same position and front event determinant
  286.         check_event_trigger_here([0])
  287.         check_event_trigger_there([0,1,2])
  288.       end
  289.     end
  290.   end
  291. end
  292.  
Expand to see the code.


Spriteset_Map Class
  1.  
  2. #==============================================================================
  3. # ** Spriteset_Map
  4. #------------------------------------------------------------------------------
  5. #  This class brings together map screen sprites, tilemaps, etc.
  6. #  It's used within the Scene_Map class.
  7. #==============================================================================
  8.  
  9. class Spriteset_Map
  10.   #--------------------------------------------------------------------------
  11.   # * Object Initialization
  12.   #--------------------------------------------------------------------------
  13.   def initialize
  14.     # Make viewports
  15.     @viewport1 = Viewport.new(0, 0, 640, 480)
  16.     @viewport2 = Viewport.new(0, 0, 640, 480)
  17.     @viewport3 = Viewport.new(0, 0, 640, 480)
  18.     @viewport2.z = 200
  19.     @viewport3.z = 5000
  20.     # Make tilemap
  21.     @tilemap = Tilemap.new(@viewport1)
  22.     @tilemap.tileset = RPG::Cache.tileset($game_map.tileset_name)
  23.     for i in 0..6
  24.       autotile_name = $game_map.autotile_names[i]
  25.       @tilemap.autotiles[i] = RPG::Cache.autotile(autotile_name)
  26.     end
  27.     @tilemap.map_data = $game_map.data
  28.     @tilemap.priorities = $game_map.priorities
  29.     # Make panorama plane
  30.     @panorama = Plane.new(@viewport1)
  31.     @panorama.z = -1000
  32.     # Make fog plane
  33.     @fog = Plane.new(@viewport1)
  34.     @fog.z = 3000
  35.     # Make character sprites
  36.     @character_sprites = []
  37.     for i in $game_map.events.keys.sort
  38.       sprite = Sprite_Character.new(@viewport1, $game_map.events[i])
  39.       @character_sprites.push(sprite)
  40.     end
  41.     @character_sprites.push(Sprite_PlayerCharacter.new(@viewport1, $game_player))
  42.     # Make network sprites
  43.     @network_sprites = []
  44.     for player in $network.players.values
  45.       player.move_to_actual_position
  46.       if player.map_id == $game_map.map_id
  47.         sprite = Sprite_NetCharacter.new(@viewport1, player)
  48.         @network_sprites.push(sprite)
  49.       end
  50.     end
  51.    
  52.     # Make weather
  53.     @weather = RPG::Weather.new(@viewport1)
  54.     # Make picture sprites
  55.     @picture_sprites = []
  56.     for i in 1..50
  57.       @picture_sprites.push(Sprite_Picture.new(@viewport2,
  58.         $game_screen.pictures[i]))
  59.     end
  60.     # Make timer sprite
  61.     @timer_sprite = Sprite_Timer.new
  62.     # Frame update
  63.     update
  64.   end
  65.  
  66.   #--------------------------------------------------------------------------
  67.   # * Refreshes the Network sprites
  68.   #--------------------------------------------------------------------------
  69.   def add_new_player_sprites
  70.     $game_temp.new_map_players.each do |player|
  71.       player.move_to_actual_position
  72.       sprite = Sprite_NetCharacter.new(@viewport1, player)
  73.       @network_sprites.push(sprite)
  74.     end
  75.     $game_temp.new_map_players.clear
  76.   end
  77.   def del_old_player_sprites
  78.     @network_sprites.each do |sprite|
  79.       $game_temp.old_map_players.each do |player|
  80.         if sprite.character == player
  81.           sprite.dispose
  82.           @network_sprites.delete(sprite)
  83.         end
  84.       end
  85.     end
  86.     $game_temp.old_map_players.clear
  87.   end
  88.  
  89.   #--------------------------------------------------------------------------
  90.   # * Dispose
  91.   #--------------------------------------------------------------------------
  92.   def dispose
  93.     # Dispose of tilemap
  94.     @tilemap.tileset.dispose
  95.     for i in 0..6
  96.       @tilemap.autotiles[i].dispose
  97.     end
  98.     @tilemap.dispose
  99.     # Dispose of panorama plane
  100.     @panorama.dispose
  101.     # Dispose of fog plane
  102.     @fog.dispose
  103.     # Dispose of character sprites
  104.     for sprite in @character_sprites
  105.       sprite.dispose
  106.     end
  107.     # Dispose of network sprites
  108.     for sprite in @network_sprites
  109.       sprite.dispose
  110.     end    
  111.     # Dispose of weather
  112.     @weather.dispose
  113.     # Dispose of picture sprites
  114.     for sprite in @picture_sprites
  115.       sprite.dispose
  116.     end
  117.     # Dispose of timer sprite
  118.     @timer_sprite.dispose
  119.     # Dispose of viewports
  120.     @viewport1.dispose
  121.     @viewport2.dispose
  122.     @viewport3.dispose
  123.   end
  124.   #--------------------------------------------------------------------------
  125.   # * Frame Update
  126.   #--------------------------------------------------------------------------
  127.   def update
  128.     add_new_player_sprites if !($game_temp.new_map_players.empty?)
  129.     del_old_player_sprites if !($game_temp.old_map_players.empty?)
  130.     # If panorama is different from current one
  131.     if @panorama_name != $game_map.panorama_name or
  132.        @panorama_hue != $game_map.panorama_hue
  133.       @panorama_name = $game_map.panorama_name
  134.       @panorama_hue = $game_map.panorama_hue
  135.       if @panorama.bitmap != nil
  136.         @panorama.bitmap.dispose
  137.         @panorama.bitmap = nil
  138.       end
  139.       if @panorama_name != ""
  140.         @panorama.bitmap = RPG::Cache.panorama(@panorama_name, @panorama_hue)
  141.       end
  142.       Graphics.frame_reset
  143.     end
  144.     # If fog is different than current fog
  145.     if @fog_name != $game_map.fog_name or @fog_hue != $game_map.fog_hue
  146.       @fog_name = $game_map.fog_name
  147.       @fog_hue = $game_map.fog_hue
  148.       if @fog.bitmap != nil
  149.         @fog.bitmap.dispose
  150.         @fog.bitmap = nil
  151.       end
  152.       if @fog_name != ""
  153.         @fog.bitmap = RPG::Cache.fog(@fog_name, @fog_hue)
  154.       end
  155.       Graphics.frame_reset
  156.     end
  157.     # Update tilemap
  158.     @tilemap.ox = $game_map.display_x / 4
  159.     @tilemap.oy = $game_map.display_y / 4
  160.     @tilemap.update
  161.     # Update panorama plane
  162.     @panorama.ox = $game_map.display_x / 8
  163.     @panorama.oy = $game_map.display_y / 8
  164.     # Update fog plane
  165.     @fog.zoom_x = $game_map.fog_zoom / 100.0
  166.     @fog.zoom_y = $game_map.fog_zoom / 100.0
  167.     @fog.opacity = $game_map.fog_opacity
  168.     @fog.blend_type = $game_map.fog_blend_type
  169.     @fog.ox = $game_map.display_x / 4 + $game_map.fog_ox
  170.     @fog.oy = $game_map.display_y / 4 + $game_map.fog_oy
  171.     @fog.tone = $game_map.fog_tone
  172.     # Update character sprites
  173.     for sprite in @character_sprites
  174.       sprite.update
  175.     end
  176.     for sprite in @network_sprites
  177.       sprite.update
  178.     end  
  179.     # Update weather graphic
  180.     @weather.type = $game_screen.weather_type
  181.     @weather.max = $game_screen.weather_max
  182.     @weather.ox = $game_map.display_x / 4
  183.     @weather.oy = $game_map.display_y / 4
  184.     @weather.update
  185.     # Update picture sprites
  186.     for sprite in @picture_sprites
  187.       sprite.update
  188.     end
  189.     # Update timer sprite
  190.     @timer_sprite.update
  191.     # Set screen color tone and shake position
  192.     @viewport1.tone = $game_screen.tone
  193.     @viewport1.ox = $game_screen.shake
  194.     # Set screen flash color
  195.     @viewport3.color = $game_screen.flash_color
  196.     # Update viewports
  197.     @viewport1.update
  198.     @viewport3.update
  199.   end
  200. end
  201.  
Expand to see the code.


Interpreter 4 Class
  1.  
  2. #==============================================================================
  3. # ** Interpreter (part 4)
  4. #------------------------------------------------------------------------------
  5. #  This interpreter runs event commands. This class is used within the
  6. #  Game_System class and the Game_Event class.
  7. #==============================================================================
  8.  
  9. class Interpreter
  10.   #--------------------------------------------------------------------------
  11.   # * Control Switches
  12.   #--------------------------------------------------------------------------
  13.   def command_121
  14.     # Loop for group control
  15.     for i in @parameters[0] .. @parameters[1]
  16.       # Change switch
  17.       $game_switches[i] = (@parameters[2] == 0)
  18.       # Send the new state to the server
  19.       $network.update_switch(i)
  20.     end
  21.     # Refresh map
  22.     $game_map.need_refresh = true
  23.     # Continue
  24.     return true
  25.   end
  26.   #--------------------------------------------------------------------------
  27.   # * Control Variables
  28.   #--------------------------------------------------------------------------
  29.   def command_122
  30.     # Initialize value
  31.     value = 0
  32.     # Branch with operand
  33.     case @parameters[3]
  34.     when 0  # invariable
  35.       value = @parameters[4]
  36.     when 1  # variable
  37.       value = $game_variables[@parameters[4]]
  38.     when 2  # random number
  39.       value = @parameters[4] + rand(@parameters[5] - @parameters[4] + 1)
  40.     when 3  # item
  41.       value = $game_party.item_number(@parameters[4])
  42.     when 4  # actor
  43.       actor = $game_actors[@parameters[4]]
  44.       if actor != nil
  45.         case @parameters[5]
  46.         when 0  # level
  47.           value = actor.level
  48.         when 1  # EXP
  49.           value = actor.exp
  50.         when 2  # HP
  51.           value = actor.hp
  52.         when 3  # SP
  53.           value = actor.sp
  54.         when 4  # MaxHP
  55.           value = actor.maxhp
  56.         when 5  # MaxSP
  57.           value = actor.maxsp
  58.         when 6  # strength
  59.           value = actor.str
  60.         when 7  # dexterity
  61.           value = actor.dex
  62.         when 8  # agility
  63.           value = actor.agi
  64.         when 9  # intelligence
  65.           value = actor.int
  66.         when 10  # attack power
  67.           value = actor.atk
  68.         when 11  # physical defense
  69.           value = actor.pdef
  70.         when 12  # magic defense
  71.           value = actor.mdef
  72.         when 13  # evasion
  73.           value = actor.eva
  74.         end
  75.       end
  76.     when 5  # enemy
  77.       enemy = $game_troop.enemies[@parameters[4]]
  78.       if enemy != nil
  79.         case @parameters[5]
  80.         when 0  # HP
  81.           value = enemy.hp
  82.         when 1  # SP
  83.           value = enemy.sp
  84.         when 2  # MaxHP
  85.           value = enemy.maxhp
  86.         when 3  # MaxSP
  87.           value = enemy.maxsp
  88.         when 4  # strength
  89.           value = enemy.str
  90.         when 5  # dexterity
  91.           value = enemy.dex
  92.         when 6  # agility
  93.           value = enemy.agi
  94.         when 7  # intelligence
  95.           value = enemy.int
  96.         when 8  # attack power
  97.           value = enemy.atk
  98.         when 9  # physical defense
  99.           value = enemy.pdef
  100.         when 10  # magic defense
  101.           value = enemy.mdef
  102.         when 11  # evasion correction
  103.           value = enemy.eva
  104.         end
  105.       end
  106.     when 6  # character
  107.       character = get_character(@parameters[4])
  108.       if character != nil
  109.         case @parameters[5]
  110.         when 0  # x-coordinate
  111.           value = character.x
  112.         when 1  # y-coordinate
  113.           value = character.y
  114.         when 2  # direction
  115.           value = character.direction
  116.         when 3  # screen x-coordinate
  117.           value = character.screen_x
  118.         when 4  # screen y-coordinate
  119.           value = character.screen_y
  120.         when 5  # terrain tag
  121.           value = character.terrain_tag
  122.         end
  123.       end
  124.     when 7  # other
  125.       case @parameters[4]
  126.       when 0  # map ID
  127.         value = $game_map.map_id
  128.       when 1  # number of party members
  129.         value = $game_party.actors.size
  130.       when 2  # gold
  131.         value = $game_party.gold
  132.       when 3  # steps
  133.         value = $game_party.steps
  134.       when 4  # play time
  135.         value = Graphics.frame_count / Graphics.frame_rate
  136.       when 5  # timer
  137.         value = $game_system.timer / Graphics.frame_rate
  138.       when 6  # save count
  139.         value = $game_system.save_count
  140.       end
  141.     end
  142.     # Loop for group control
  143.     for i in @parameters[0] .. @parameters[1]
  144.       # Branch with control
  145.       case @parameters[2]
  146.       when 0  # substitute
  147.         $game_variables[i] = value
  148.       when 1  # add
  149.         $game_variables[i] += value
  150.       when 2  # subtract
  151.         $game_variables[i] -= value
  152.       when 3  # multiply
  153.         $game_variables[i] *= value
  154.       when 4  # divide
  155.         if value != 0
  156.           $game_variables[i] /= value
  157.         end
  158.       when 5  # remainder
  159.         if value != 0
  160.           $game_variables[i] %= value
  161.         end
  162.       end
  163.       # Maximum limit check
  164.       if $game_variables[i] > 99999999
  165.         $game_variables[i] = 99999999
  166.       end
  167.       # Minimum limit check
  168.       if $game_variables[i] < -99999999
  169.         $game_variables[i] = -99999999
  170.       end
  171.     end
  172.     # Refresh map
  173.     $game_map.need_refresh = true
  174.     # Send the new value to the server
  175.     $network.update_variable(i)
  176.     # Continue
  177.     return true
  178.   end
  179.   #--------------------------------------------------------------------------
  180.   # * Control Self Switch
  181.   #--------------------------------------------------------------------------
  182.   def command_123
  183.     # If event ID is valid
  184.     if @event_id > 0
  185.       # Make a self switch key
  186.       key = [$game_map.map_id, @event_id, @parameters[0]]
  187.       # Change self switches
  188.       $game_self_switches[key] = (@parameters[1] == 0)
  189.     end
  190.     # Refresh map
  191.     $game_map.need_refresh = true
  192.     # Continue
  193.     return true
  194.   end
  195.   #--------------------------------------------------------------------------
  196.   # * Control Timer
  197.   #--------------------------------------------------------------------------
  198.   def command_124
  199.     # If started
  200.     if @parameters[0] == 0
  201.       $game_system.timer = @parameters[1] * Graphics.frame_rate
  202.       $game_system.timer_working = true
  203.     end
  204.     # If stopped
  205.     if @parameters[0] == 1
  206.       $game_system.timer_working = false
  207.     end
  208.     # Continue
  209.     return true
  210.   end
  211.   #--------------------------------------------------------------------------
  212.   # * Change Gold
  213.   #--------------------------------------------------------------------------
  214.   def command_125
  215.     # Get value to operate
  216.     value = operate_value(@parameters[0], @parameters[1], @parameters[2])
  217.     # Increase / decrease amount of gold
  218.     $game_party.gain_gold(value)
  219.     # Continue
  220.     return true
  221.   end
  222.   #--------------------------------------------------------------------------
  223.   # * Change Items
  224.   #--------------------------------------------------------------------------
  225.   def command_126
  226.     # Get value to operate
  227.     value = operate_value(@parameters[1], @parameters[2], @parameters[3])
  228.     # Increase / decrease items
  229.     $game_party.gain_item(@parameters[0], value)
  230.     # Continue
  231.     return true
  232.   end
  233.   #--------------------------------------------------------------------------
  234.   # * Change Weapons
  235.   #--------------------------------------------------------------------------
  236.   def command_127
  237.     # Get value to operate
  238.     value = operate_value(@parameters[1], @parameters[2], @parameters[3])
  239.     # Increase / decrease weapons
  240.     $game_party.gain_weapon(@parameters[0], value)
  241.     # Continue
  242.     return true
  243.   end
  244.   #--------------------------------------------------------------------------
  245.   # * Change Armor
  246.   #--------------------------------------------------------------------------
  247.   def command_128
  248.     # Get value to operate
  249.     value = operate_value(@parameters[1], @parameters[2], @parameters[3])
  250.     # Increase / decrease armor
  251.     $game_party.gain_armor(@parameters[0], value)
  252.     # Continue
  253.     return true
  254.   end
  255.   #--------------------------------------------------------------------------
  256.   # * Change Party Member
  257.   #--------------------------------------------------------------------------
  258.   def command_129
  259.     # Get actor
  260.     actor = $game_actors[@parameters[0]]
  261.     # If actor is valid
  262.     if actor != nil
  263.       # Branch with control
  264.       if @parameters[1] == 0
  265.         if @parameters[2] == 1
  266.           $game_actors[@parameters[0]].setup(@parameters[0])
  267.         end
  268.         $game_party.add_actor(@parameters[0])
  269.       else
  270.         $game_party.remove_actor(@parameters[0])
  271.       end
  272.     end
  273.     # Continue
  274.     return true
  275.   end
  276.   #--------------------------------------------------------------------------
  277.   # * Change Windowskin
  278.   #--------------------------------------------------------------------------
  279.   def command_131
  280.     # Change windowskin file name
  281.     $game_system.windowskin_name = @parameters[0]
  282.     # Continue
  283.     return true
  284.   end
  285.   #--------------------------------------------------------------------------
  286.   # * Change Battle BGM
  287.   #--------------------------------------------------------------------------
  288.   def command_132
  289.     # Change battle BGM
  290.     $game_system.battle_bgm = @parameters[0]
  291.     # Continue
  292.     return true
  293.   end
  294.   #--------------------------------------------------------------------------
  295.   # * Change Battle End ME
  296.   #--------------------------------------------------------------------------
  297.   def command_133
  298.     # Change battle end ME
  299.     $game_system.battle_end_me = @parameters[0]
  300.     # Continue
  301.     return true
  302.   end
  303.   #--------------------------------------------------------------------------
  304.   # * Change Save Access
  305.   #--------------------------------------------------------------------------
  306.   def command_134
  307.     # Change save access flag
  308.     $game_system.save_disabled = (@parameters[0] == 0)
  309.     # Continue
  310.     return true
  311.   end
  312.   #--------------------------------------------------------------------------
  313.   # * Change Menu Access
  314.   #--------------------------------------------------------------------------
  315.   def command_135
  316.     # Change menu access flag
  317.     $game_system.menu_disabled = (@parameters[0] == 0)
  318.     # Continue
  319.     return true
  320.   end
  321.   #--------------------------------------------------------------------------
  322.   # * Change Encounter
  323.   #--------------------------------------------------------------------------
  324.   def command_136
  325.     # Change encounter flag
  326.     $game_system.encounter_disabled = (@parameters[0] == 0)
  327.     # Make encounter count
  328.     $game_player.make_encounter_count
  329.     # Continue
  330.     return true
  331.   end
  332. end
  333.  
Expand to see the code.


Scene_Title Class
  1.  
  2. #==============================================================================
  3. # ** Scene_Title
  4. #------------------------------------------------------------------------------
  5. #  This class performs title screen processing.
  6. #==============================================================================
  7.  
  8. class Scene_Title
  9.   #--------------------------------------------------------------------------
  10.   # * Main Processing
  11.   #--------------------------------------------------------------------------
  12.   def main
  13.     # If battle test
  14.     if $BTEST
  15.       battle_test
  16.       return
  17.     end
  18.     # Load database
  19.     $data_actors        = load_data("Data/Actors.rxdata")
  20.     $data_classes       = load_data("Data/Classes.rxdata")
  21.     $data_skills        = load_data("Data/Skills.rxdata")
  22.     $data_items         = load_data("Data/Items.rxdata")
  23.     $data_weapons       = load_data("Data/Weapons.rxdata")
  24.     $data_armors        = load_data("Data/Armors.rxdata")
  25.     $data_enemies       = load_data("Data/Enemies.rxdata")
  26.     $data_troops        = load_data("Data/Troops.rxdata")
  27.     $data_states        = load_data("Data/States.rxdata")
  28.     $data_animations    = load_data("Data/Animations.rxdata")
  29.     $data_tilesets      = load_data("Data/Tilesets.rxdata")
  30.     $data_common_events = load_data("Data/CommonEvents.rxdata")
  31.     $data_system        = load_data("Data/System.rxdata")
  32.     # Make system object
  33.     $game_system = Game_System.new
  34.     # Make title graphic
  35.     @sprite = Sprite.new
  36.     @sprite.bitmap = RPG::Cache.title($data_system.title_name)
  37.     # Make command window
  38.     s1 = "Nuevo"
  39.     s2 = "Cargar"
  40.     s3 = "Salir"
  41.     @command_window = Window_Command.new(192, [s1, s2, s3])
  42.     @command_window.back_opacity = 160
  43.     @command_window.x = 320 - @command_window.width / 2
  44.     @command_window.y = 288
  45.     # Continue enabled determinant
  46.     # Check if at least one save file exists
  47.     # If enabled, make @continue_enabled true; if disabled, make it false
  48.     @continue_enabled = false
  49.     for i in 0..3
  50.       if FileTest.exist?("Save#{i+1}.rxdata")
  51.         @continue_enabled = true
  52.       end
  53.     end
  54.     # If continue is enabled, move cursor to "Continue"
  55.     # If disabled, display "Continue" text in gray
  56.     if @continue_enabled
  57.       @command_window.index = 1
  58.     else
  59.       @command_window.disable_item(1)
  60.     end
  61.     # Play title BGM
  62.     $game_system.bgm_play($data_system.title_bgm)
  63.     # Stop playing ME and BGS
  64.     Audio.me_stop
  65.     Audio.bgs_stop
  66.     # Execute transition
  67.     Graphics.transition
  68.     # Main loop
  69.     loop do
  70.       # Update game screen
  71.       Graphics.update
  72.       # Update input information
  73.       Input.update
  74.       # Frame update
  75.       update
  76.       # Abort loop if screen is changed
  77.       if $scene != self
  78.         break
  79.       end
  80.     end
  81.     # Prepare for transition
  82.     Graphics.freeze
  83.     # Dispose of command window
  84.     @command_window.dispose
  85.     # Dispose of title graphic
  86.     @sprite.bitmap.dispose
  87.     @sprite.dispose
  88.   end
  89.   #--------------------------------------------------------------------------
  90.   # * Frame Update
  91.   #--------------------------------------------------------------------------
  92.   def update
  93.     # Update command window
  94.     @command_window.update
  95.     # If C button was pressed
  96.     if Input.trigger?(Input::C)
  97.       # Branch by command window cursor position
  98.       case @command_window.index
  99.       when 0  # New game
  100.         command_new_game
  101.       when 1  # Continue
  102.         command_continue
  103.       when 2  # Shutdown
  104.         command_shutdown
  105.       end
  106.     end
  107.   end
  108.   #--------------------------------------------------------------------------
  109.   # * Command: New Game
  110.   #--------------------------------------------------------------------------
  111.   def command_new_game
  112.     # Play decision SE
  113.     $game_system.se_play($data_system.decision_se)
  114.     # Stop BGM
  115.     Audio.bgm_stop
  116.     # Reset frame count for measuring play time
  117.     Graphics.frame_count = 0
  118.     # Make each type of game object
  119.     $game_temp          = Game_Temp.new
  120.     $game_system        = Game_System.new
  121.     $game_switches      = Game_Switches.new
  122.     $game_variables     = Game_Variables.new
  123.     $game_self_switches = Game_SelfSwitches.new
  124.     $game_screen        = Game_Screen.new
  125.     $game_actors        = Game_Actors.new
  126.     $game_party         = Game_Party.new
  127.     $game_troop         = Game_Troop.new
  128.     $game_map           = Game_Map.new
  129.     $game_player        = Game_Player.new
  130.     # Set up initial party
  131.     $game_party.setup_starting_members
  132.     # Set up initial map position
  133.     $game_map.setup($data_system.start_map_id)
  134.     # Move player to initial position
  135.     $game_player.moveto($data_system.start_x, $data_system.start_y)
  136.     # Refresh player
  137.     $game_player.refresh
  138.     # Run automatic change for BGM and BGS set with map
  139.     $game_map.autoplay
  140.     # Update map (run parallel process event)
  141.     $game_map.update
  142.     # Initialize Network
  143.     $network = Network.new
  144.     $network.connect_and_start
  145.     # Switch to map screen
  146.     $scene = Scene_Map.new
  147.   end
  148.   #--------------------------------------------------------------------------
  149.   # * Command: Continue
  150.   #--------------------------------------------------------------------------
  151.   def command_continue
  152.     # If continue is disabled
  153.     unless @continue_enabled
  154.       # Play buzzer SE
  155.       $game_system.se_play($data_system.buzzer_se)
  156.       return
  157.     end
  158.     # Play decision SE
  159.     $game_system.se_play($data_system.decision_se)
  160.     # Switch to load screen
  161.     $scene = Scene_Load.new
  162.   end
  163.   #--------------------------------------------------------------------------
  164.   # * Command: Shutdown
  165.   #--------------------------------------------------------------------------
  166.   def command_shutdown
  167.     # Play decision SE
  168.     $game_system.se_play($data_system.decision_se)
  169.     # Fade out BGM, BGS, and ME
  170.     Audio.bgm_fade(800)
  171.     Audio.bgs_fade(800)
  172.     Audio.me_fade(800)
  173.     # Shutdown
  174.     $scene = nil
  175.   end
  176.   #--------------------------------------------------------------------------
  177.   # * Battle Test
  178.   #--------------------------------------------------------------------------
  179.   def battle_test
  180.     # Load database (for battle test)
  181.     $data_actors        = load_data("Data/Actors.rxdata")
  182.     $data_classes       = load_data("Data/Classes.rxdata")
  183.     $data_skills        = load_data("Data/Skills.rxdata")
  184.     $data_items         = load_data("Data/Items.rxdata")
  185.     $data_weapons       = load_data("Data/Weapons.rxdata")
  186.     $data_armors        = load_data("Data/Armors.rxdata")
  187.     $data_enemies       = load_data("Data/Enemies.rxdata")
  188.     $data_troops        = load_data("Data/Troops.rxdata")
  189.     $data_states        = load_data("Data/States.rxdata")
  190.     $data_animations    = load_data("Data/Animations.rxdata")
  191.     $data_tilesets      = load_data("Data/Tilesets.rxdata")
  192.     $data_common_events = load_data("Data/CommonEvents.rxdata")
  193.     $data_system        = load_data("Data/System.rxdata")
  194.     # Reset frame count for measuring play time
  195.     Graphics.frame_count = 0
  196.     # Make each game object
  197.     $game_temp          = Game_Temp.new
  198.     $game_system        = Game_System.new
  199.     $game_switches      = Game_Switches.new
  200.     $game_variables     = Game_Variables.new
  201.     $game_self_switches = Game_SelfSwitches.new
  202.     $game_screen        = Game_Screen.new
  203.     $game_actors        = Game_Actors.new
  204.     $game_party         = Game_Party.new
  205.     $game_troop         = Game_Troop.new
  206.     $game_map           = Game_Map.new
  207.     $game_player        = Game_Player.new
  208.     # Set up party for battle test
  209.     $game_party.setup_battle_test_members
  210.     # Set troop ID, can escape flag, and battleback
  211.     $game_temp.battle_troop_id = $data_system.test_troop_id
  212.     $game_temp.battle_can_escape = true
  213.     $game_map.battleback_name = $data_system.battleback_name
  214.     # Play battle start SE
  215.     $game_system.se_play($data_system.battle_start_se)
  216.     # Play battle BGM
  217.     $game_system.bgm_play($game_system.battle_bgm)
  218.     # Switch to battle screen
  219.     $scene = Scene_Battle.new
  220.   end
  221. end
  222.  
Expand to see the code.


Scene_Map Class
  1.  
  2. #==============================================================================
  3. # ** Scene_Map
  4. #------------------------------------------------------------------------------
  5. #  This class performs map screen processing.
  6. #==============================================================================
  7.  
  8. class Scene_Map
  9.   #--------------------------------------------------------------------------
  10.   # * Main Processing
  11.   #--------------------------------------------------------------------------
  12.   def main
  13.     # Make sprite set
  14.     @spriteset = Spriteset_Map.new
  15.     # Make message window
  16.     @message_window = Window_Message.new
  17.     # Chat Windows
  18.     @chat_window = Window_Chat.new
  19.     @chat_input_window = Window_ChatInput.new
  20.     # Transition run
  21.     Graphics.transition
  22.     # Main loop
  23.     loop do
  24.       # Update game screen
  25.       Graphics.update
  26.       # Update input information
  27.       Input.update
  28.       # Frame update
  29.       update
  30.       # Abort loop if screen is changed
  31.       if $scene != self
  32.         break
  33.       end
  34.     end
  35.     # Prepare for transition
  36.     Graphics.freeze
  37.     # Dispose of sprite set
  38.     @spriteset.dispose
  39.     # Dispose of message window
  40.     @message_window.dispose
  41.     # Dispose of chat windows
  42.     @chat_window.dispose
  43.     @chat_input_window.dispose
  44.     # If switching to title screen
  45.     if $scene.is_a?(Scene_Title)
  46.       # Fade out screen
  47.       Graphics.transition
  48.       Graphics.freeze
  49.     end
  50.   end
  51.   #--------------------------------------------------------------------------
  52.   # * Frame Update
  53.   #--------------------------------------------------------------------------
  54.   def update
  55.     # Loop
  56.     loop do
  57.       # Update map, interpreter, and player order
  58.       # (this update order is important for when conditions are fulfilled
  59.       # to run any event, and the player isn't provided the opportunity to
  60.       # move in an instant)
  61.       $game_map.update
  62.       $game_system.map_interpreter.update
  63.       $game_player.update
  64.       # Update system (timer), screen
  65.       $game_system.update
  66.       $game_screen.update
  67.       # Update network
  68.       $network.update
  69.       if $network.client.connected == false
  70.         print "Disconnected from the server\nClosing..."
  71.         exit
  72.       end
  73.       # Update Chat
  74.       @chat_input_window.update if @chat_input_window.visible == true
  75.       @chat_window.update
  76.       # Abort loop if player isn't place moving
  77.       unless $game_temp.player_transferring
  78.         break
  79.       end
  80.       # Run place move
  81.       transfer_player
  82.       # Abort loop if transition processing
  83.       if $game_temp.transition_processing
  84.         break
  85.       end
  86.     end
  87.     # Update sprite set
  88.     @spriteset.update
  89.     # Update message window
  90.     @message_window.update
  91.     # If game over
  92.     if $game_temp.gameover
  93.       # Switch to game over screen
  94.       $scene = Scene_Gameover.new
  95.       return
  96.     end
  97.     # If returning to title screen
  98.     if $game_temp.to_title
  99.       # Change to title screen
  100.       $scene = Scene_Title.new
  101.       return
  102.     end
  103.     # If transition processing
  104.     if $game_temp.transition_processing
  105.       # Clear transition processing flag
  106.       $game_temp.transition_processing = false
  107.       # Execute transition
  108.       if $game_temp.transition_name == ""
  109.         Graphics.transition(20)
  110.       else
  111.         Graphics.transition(40, "Graphics/Transitions/" +
  112.           $game_temp.transition_name)
  113.       end
  114.     end
  115.     # If showing message window
  116.     if $game_temp.message_window_showing
  117.       return
  118.     end
  119.     # If encounter list isn't empty, and encounter count is 0
  120.     if $game_player.encounter_count == 0 and $game_map.encounter_list != []
  121.       # If event is running or encounter is not forbidden
  122.       unless $game_system.map_interpreter.running? or
  123.              $game_system.encounter_disabled
  124.         # Confirm troop
  125.         n = rand($game_map.encounter_list.size)
  126.         troop_id = $game_map.encounter_list[n]
  127.         # If troop is valid
  128.         if $data_troops[troop_id] != nil
  129.           # Set battle calling flag
  130.           $game_temp.battle_calling = true
  131.           $game_temp.battle_troop_id = troop_id
  132.           $game_temp.battle_can_escape = true
  133.           $game_temp.battle_can_lose = false
  134.           $game_temp.battle_proc = nil
  135.         end
  136.       end
  137.     end
  138.    
  139.     # If F5 button was pressed
  140.     if Keyb.trigger($keys["F5"])
  141.       @chat_input_window.visible = true
  142.     end
  143.    
  144.     # If B button was pressed
  145.     if Input.trigger?(Input::B) and @chat_input_window.visible == false
  146.       # If event is running, or menu is not forbidden
  147.       unless $game_system.map_interpreter.running? or
  148.              $game_system.menu_disabled
  149.         # Set menu calling flag or beep flag
  150.         $game_temp.menu_calling = true
  151.         $game_temp.menu_beep = true
  152.       end
  153.     end
  154.     # If debug mode is ON and F9 key was pressed
  155.     if $DEBUG and Input.press?(Input::F9)
  156.       # Set debug calling flag
  157.       $game_temp.debug_calling = true
  158.     end
  159.     # If player is not moving
  160.     unless $game_player.moving?
  161.       # Run calling of each screen
  162.       if $game_temp.battle_calling
  163.         call_battle
  164.       elsif $game_temp.shop_calling
  165.         call_shop
  166.       elsif $game_temp.name_calling
  167.         call_name
  168.       elsif $game_temp.menu_calling
  169.         call_menu
  170.       elsif $game_temp.save_calling
  171.         call_save
  172.       elsif $game_temp.debug_calling
  173.         call_debug
  174.       end
  175.     end
  176.   end
  177.   #--------------------------------------------------------------------------
  178.   # * Battle Call
  179.   #--------------------------------------------------------------------------
  180.   def call_battle
  181.     # Clear battle calling flag
  182.     $game_temp.battle_calling = false
  183.     # Clear menu calling flag
  184.     $game_temp.menu_calling = false
  185.     $game_temp.menu_beep = false
  186.     # Make encounter count
  187.     $game_player.make_encounter_count
  188.     # Memorize map BGM and stop BGM
  189.     $game_temp.map_bgm = $game_system.playing_bgm
  190.     $game_system.bgm_stop
  191.     # Play battle start SE
  192.     $game_system.se_play($data_system.battle_start_se)
  193.     # Play battle BGM
  194.     $game_system.bgm_play($game_system.battle_bgm)
  195.     # Straighten player position
  196.     $game_player.straighten
  197.     # Switch to battle screen
  198.     $scene = Scene_Battle.new
  199.   end
  200.   #--------------------------------------------------------------------------
  201.   # * Shop Call
  202.   #--------------------------------------------------------------------------
  203.   def call_shop
  204.     # Clear shop call flag
  205.     $game_temp.shop_calling = false
  206.     # Straighten player position
  207.     $game_player.straighten
  208.     # Switch to shop screen
  209.     $scene = Scene_Shop.new
  210.   end
  211.   #--------------------------------------------------------------------------
  212.   # * Name Input Call
  213.   #--------------------------------------------------------------------------
  214.   def call_name
  215.     # Clear name input call flag
  216.     $game_temp.name_calling = false
  217.     # Straighten player position
  218.     $game_player.straighten
  219.     # Switch to name input screen
  220.     $scene = Scene_Name.new
  221.   end
  222.   #--------------------------------------------------------------------------
  223.   # * Menu Call
  224.   #--------------------------------------------------------------------------
  225.   def call_menu
  226.     # Clear menu call flag
  227.     $game_temp.menu_calling = false
  228.     # If menu beep flag is set
  229.     if $game_temp.menu_beep
  230.       # Play decision SE
  231.       $game_system.se_play($data_system.decision_se)
  232.       # Clear menu beep flag
  233.       $game_temp.menu_beep = false
  234.     end
  235.     # Straighten player position
  236.     $game_player.straighten
  237.     # Switch to menu screen
  238.     $scene = Scene_Menu.new
  239.   end
  240.   #--------------------------------------------------------------------------
  241.   # * Save Call
  242.   #--------------------------------------------------------------------------
  243.   def call_save
  244.     # Straighten player position
  245.     $game_player.straighten
  246.     # Switch to save screen
  247.     $scene = Scene_Save.new
  248.   end
  249.   #--------------------------------------------------------------------------
  250.   # * Debug Call
  251.   #--------------------------------------------------------------------------
  252.   def call_debug
  253.     # Clear debug call flag
  254.     $game_temp.debug_calling = false
  255.     # Play decision SE
  256.     $game_system.se_play($data_system.decision_se)
  257.     # Straighten player position
  258.     $game_player.straighten
  259.     # Switch to debug screen
  260.     $scene = Scene_Debug.new
  261.   end
  262.   #--------------------------------------------------------------------------
  263.   # * Player Place Move
  264.   #--------------------------------------------------------------------------
  265.   def transfer_player
  266.     # Clear player place move call flag
  267.     $game_temp.player_transferring = false
  268.     # If move destination is different than current map
  269.     if $game_map.map_id != $game_temp.player_new_map_id
  270.       # Set up a new map
  271.       $game_map.setup($game_temp.player_new_map_id)
  272.     end
  273.     # Set up player position
  274.     $game_player.moveto($game_temp.player_new_x, $game_temp.player_new_y)
  275.     # Set player direction
  276.     case $game_temp.player_new_direction
  277.     when 2  # down
  278.       $game_player.turn_down
  279.     when 4  # left
  280.       $game_player.turn_left
  281.     when 6  # right
  282.       $game_player.turn_right
  283.     when 8  # up
  284.       $game_player.turn_up
  285.     end
  286.     # Straighten player position
  287.     $game_player.straighten
  288.     # Update map (run parallel process event)
  289.     $game_map.update
  290.     # Remake sprite set
  291.     @spriteset.dispose
  292.     @spriteset = Spriteset_Map.new
  293.     # If processing transition
  294.     if $game_temp.transition_processing
  295.       # Clear transition processing flag
  296.       $game_temp.transition_processing = false
  297.       # Execute transition
  298.       Graphics.transition(20)
  299.     end
  300.     # Update Player Information
  301.     $network.update_x
  302.     $network.update_y
  303.     $network.update_map_id
  304.     $network.update_direction
  305.     # Update network
  306.     $network.update
  307.     # Run automatic change for BGM and BGS set on the map
  308.     $game_map.autoplay
  309.     # Frame reset
  310.     Graphics.frame_reset
  311.     # Update input information
  312.     Input.update
  313.   end
  314. end
  315.  
Expand to see the code.


Main
  1.  
  2. #==============================================================================
  3. # ** Main
  4. #------------------------------------------------------------------------------
  5. #  After defining each class, actual processing begins here.
  6. #==============================================================================
  7.  
  8. begin
  9.   # Prepare for transition
  10.   Graphics.freeze
  11.   # Make scene object (title screen)
  12.   $scene = Scene_Title.new
  13.   # Call main method as long as $scene is effective
  14.   while $scene != nil
  15.     $scene.main
  16.   end
  17.   # Fade out
  18.   Graphics.transition(20)
  19. rescue Errno::ENOENT
  20.   # Supplement Errno::ENOENT exception
  21.   # If unable to open file, display message and end
  22.   filename = $!.message.sub("No se encontó el archivo o directorio - ", "")
  23.   print("Error RGSS: #{filename}")
  24.  
  25. ensure
  26.   $network.client.disconnect($network.client.peers_list["server"]["peer"],
  27.                              0,
  28.                              1000)
  29. end
  30.  
Expand to see the code.




____Extra Script____
Server Example:
  1.  
  2. #==============================================================================
  3. # ** RubyENet Server
  4. #------------------------------------------------------------------------------
  5. #  Server for the RubyENet Template
  6. #
  7. #  Basic demostration of RubyENet game integration
  8. #  Tested with ruby 1.8.6 and ruby 1.9.1
  9. #
  10. #  To send additional data just add a new packet type and its logic
  11. #  This applies to login/register too, for example:
  12. #
  13. #      - server accepts the connection
  14. #      - waits for the client to send its login
  15. #      - if not a valid login or timeout, close the connection
  16. #      - if valid login, receive and send id&data
  17. #
  18. #   Check http://enet.bespin.org/ to understand the ENet protocol
  19. #
  20. #==============================================================================
  21.  
  22. class Server
  23.     #--------------------------------------------------------------------------
  24.         # * Object Initialization
  25.     #--------------------------------------------------------------------------
  26.     def initialize
  27.         @players = {}
  28.         @address = 0
  29.         @port = 8000
  30.         @channels = 3
  31.         @max_number_of_players = 32
  32.     end
  33.    
  34.     #--------------------------------------------------------------------------
  35.     # Run the server
  36.     # Initialize the library
  37.     # Bind the server to an addres and port
  38.     # Generate and send an ID when a players connects
  39.     # Warn all the players when a player disconnects and delete it
  40.     # Parse packets when they arrive
  41.     # Loop forever giving service
  42.     #--------------------------------------------------------------------------
  43.     def run
  44.         print "------------------------------------------------------------------\r\n\n"
  45.         print "                     RubyENet Template Server\r\n"
  46.         print "                          Version 1.0\r\n"
  47.         print "------------------------------------------------------------------\r\n\n"
  48.         print "Initializing ENetlibrary\r\n\n"
  49.         if Enet.initialize != 0
  50.             print "Error initializing ENet\r\n"
  51.             print "Press a key to exit\r\n"
  52.             gets.chomp
  53.             exit
  54.         end  
  55.        
  56.         print "Server will run in:\r\n"
  57.         print "    Address: localhost\r\n" if @address == 0
  58.         print "    Address: #{@address}\r\n" if @address != 0
  59.         print "    Port: #{@port}\r\n\n"
  60.         address = [@address, @port].pack("LS")
  61.  
  62.         print "Binding server\r\n"
  63.         @server = Enet::ENetHost.new
  64.  
  65.         if @server.create_host(address, @max_number_of_players, @channels, 0, 0) == true
  66.             print "Server created\n"
  67.         else
  68.             print "Error binding the server\r\n"
  69.             print "Press a key to exit\r\n"
  70.             gets.chomp
  71.             exit
  72.         end
  73.          
  74.         @server.on_connection do
  75.             print "New user connected: #{Enet.get_peer_host(@server.event.peer)}\r\n"
  76.             id = 0
  77.             for i in 0...5
  78.                 id += rand() % 256
  79.             end
  80.             @players[id.to_s] = { "peer" => @server.event.peer }
  81.             data = "100:#{id}"
  82.             @server.send_packet(@server.event.peer, data, data.size+1, 1)
  83.             print "ID #{id} sent to the new player\r\n"
  84.         end
  85.      
  86.       @server.on_disconnect do
  87.         print "User disconnected: #{Enet.get_peer_host(@server.event.peer)}\r\n"
  88.         @players.each_key { |id|
  89.             if @players[id]["peer"] == @server.event.peer
  90.                 data = "11:#{id}"
  91.                 @server.broadcast_packet(data, data.size+1, 1)
  92.                 @players.delete(id) if @players.has_key?(id)
  93.             end
  94.         }
  95.       end
  96.      
  97.       @server.on_packet_receive do
  98.         parse_packet
  99.         @server.event.destroy_packet
  100.       end
  101.  
  102.     print "Server service started\r\n\n"
  103.     begin
  104.         loop do
  105.             @server.service
  106.         end
  107.     rescue
  108.         print "Deinitializing ENet library\r\n!"
  109.         Enet.deinitialize
  110.         print "Closing server\r\n"
  111.         print "Press a key to exit\r\n"
  112.         gets.chomp
  113.         exit
  114.     end
  115.     end
  116.    
  117.     #--------------------------------------------------------------------------
  118.     # * Resend Data
  119.     #   Sends throught the channel specified to all the players except
  120.     #   to the player who sent the data
  121.     #--------------------------------------------------------------------------
  122.     def resend_data(channel_id)
  123.         @players.each_key { |id|
  124.             if @players[id]["peer"] != @server.event.peer
  125.             @server.send_packet( @players[id]["peer"], @server.event.packet.data, @server.event.packet.data_length, channel_id)
  126.             end
  127.         }
  128.     end
  129.    
  130.     #--------------------------------------------------------------------------
  131.     # * Initial Data
  132.     #   Generates the data of a player to send it when a new player arrives
  133.     #--------------------------------------------------------------------------
  134.     def initial_data(id)
  135.         data = ""
  136.         data += "0:"
  137.         data += id.to_s
  138.         data += ";"
  139.         data += @players[id]["name"]
  140.         data += ";"
  141.         data += @players[id]["level"]
  142.         data += ";"
  143.         data += @players[id]["class_name"]
  144.         data += ";"
  145.         data += @players[id]["map_id"]
  146.         data += ";"
  147.         data += @players[id]["x"]
  148.         data += ";"
  149.         data += @players[id]["y"]
  150.         data += ";"
  151.         data += @players[id]["direction"]
  152.         data += ";"
  153.         data += @players[id]["character_name"]
  154.         data += ";"
  155.         data += @players[id]["character_hue"]
  156.         data += ";"
  157.         data += @players[id]["opacity"]
  158.         data += ";"
  159.         data += @players[id]["move_speed"]
  160.        
  161.         return data
  162.     end
  163.    
  164.     #--------------------------------------------------------------------------
  165.     # * Parse Packet
  166.     #    Parse the received packets and usually resend them to the rest
  167.     #    of players
  168.     #    This method is similar to the clients parse_data
  169.     #    Check it if you have problems understanding this
  170.     #--------------------------------------------------------------------------
  171.     def parse_packet
  172.         data = @server.event.packet.data.to_s
  173.         print "Packet Arrived: "
  174.         print data +"\r\n"
  175.         if data.match(/^([0-9]*):(.*)$/)
  176.             @part1 = $1
  177.             @part2 = $2
  178.           values = @part2.split(";") if @part2.match(";")
  179.           case @part1.to_i
  180.         when 0 # Initial data
  181.           values[0] = values[0].to_s
  182.           if @players[values[0]] != nil
  183.               print "New player data. Creating information\n"
  184.             @players[values[0]]["name"]             = values[1]
  185.             @players[values[0]]["level"]            = values[2]
  186.             @players[values[0]]["class_name"]       = values[3]
  187.             @players[values[0]]["map_id"]           = values[4]
  188.             @players[values[0]]["x"]                = values[5]
  189.             @players[values[0]]["y"]                = values[6]
  190.             @players[values[0]]["direction"]        = values[7]
  191.             @players[values[0]]["character_name"]   = values[8]
  192.             @players[values[0]]["character_hue"]        = values[9]
  193.             @players[values[0]]["opacity"]          = values[10]
  194.             @players[values[0]]["move_speed"]       = values[11]
  195.             @players.each_key { |id|
  196.                 if @players[id]["peer"] != @server.event.peer
  197.                 data = initial_data(id)
  198.                 @server.send_packet(@server.event.peer, data, data.size+1,  1)
  199.                 end
  200.             }
  201.             @server.send_packet(@server.event.peer,  "101:ok",  7,  1)
  202.             print "Initial state finished, sent ACK\r\n"
  203.             resend_data(1)
  204.             print "Sent new player data to all the players\r\n"
  205.           end
  206.         when 1 # x / y
  207.           return if @players[values[0]] == nil
  208.           @players[values[0]]["x"] = values[1]
  209.           @players[values[0]]["y"] = values[2]
  210.           resend_data(0)
  211.          
  212.         when 2 # map_id
  213.           return if @players[values[0]] == nil
  214.           @players[values[0]]["map_id"] = values[1]
  215.           resend_data(0)
  216.          
  217.         when 3 # direction
  218.           return if @players[values[0]] == nil
  219.           @players[values[0]]["direction"] = values[1]
  220.           resend_data(0)
  221.          
  222.         when 4 # move_speed
  223.           return if @players[values[0]] == nil
  224.           @players[values[0]]["move_speed"] = values[1]
  225.           resend_data(0)
  226.          
  227.         when 5 # character_name
  228.           return if @players[values[0]] == nil
  229.           @players[values[0]]["character_name"] = values[1]
  230.           resend_data(0)
  231.          
  232.         when 6 # character_hue
  233.           return if @players[values[0]] == nil
  234.           @players[values[0]]["character_hue"] = values[1]
  235.           resend_data(0)
  236.          
  237.         when 7 # opacity
  238.           return if @players[values[0]] == nil
  239.           @players[values[0]]["opacity"] = values[1]
  240.           resend_data(0)
  241.          
  242.         when 8 # level
  243.           return if @players[values[0]] == nil
  244.           @players[values[0]]["level"] = values[1]
  245.           resend_data(0)
  246.          
  247.         when 9 # class_name
  248.           return if @players[values[0]] == nil
  249.           @players[values[0]]["class_name"] = values[1]
  250.           resend_data(0)
  251.          
  252.         when 10 # name
  253.           return if @players[values[0]] == nil
  254.           @players[values[0]]["name"] = values[1]
  255.           resend_data(0)
  256.          
  257.         when 11 # disconnection
  258.           @server.on_disconnect
  259.          
  260.         when 200
  261.             resend_data(0)
  262.            
  263.         when 201
  264.             resend_data(0)
  265.            
  266.         when 202
  267.             resend_data(2)
  268.           end
  269.         end
  270.       end
  271. end
  272.  
Expand to see the code.



Additional Information and Notes



Servers can be done in C/C++, this can give a huge boost to your games
performance, also Server that doesnt display information (puts/print)
works faster.

This template connects to the server in Scene_Title when New Game is
selected.
The network is only updated in Scene_Map, if you are in another scene
the connection will be lost after 10 seconds or so. Update the network
in all the scenes you need.

The Chat input uses Hounds Keyboard Module,it uses this module because
it doesnt need external dlls, but its performance is pretty bad. Dont
think Chat is broken if you need to press the keys twice. It should be
rewritten using vgvgfs AInput module to get a perfect performance.

The RGSS Player stops updating the game when it doesnt have focus,
this is not a problem with TCP, where the stream just sleeps but ENet
uses UDP (which is a lot faster) and datagrams doesnt sleep. If the
game lose focus the connection will be lost after 10 seconds or so,
because the client isnt answering server petitions.
Workarounds:
- Use Win32API calls so the game has always the focus
- Make the game fullscreen so the player wont lose focus
- Hack the player so it updates without focus too

To fully understand how ENet works visit http://enet.bespin.org/


Comments, questions, petitions, fixes, etc are welcome.
Interesting script but why you dont use alias in the default classes and methods?
gerrtunk wrote:
Interesting script but why you dont use alias in the default classes and methods?


Because the order is important, some things cant be at the beginning or ending of the methods. Said this, this isnt made for copy&paste&works, scripters oriented, they should know how to deal with it.

Edit:

Fixed the problem with ruby 1.9.x, now the server will run fine in 1.8.x and 1.9.x, faster servers, better gameplay.

Also added and ensure in main to instant-disconnect the clients who close the game.
Also, what im thinking is that... ¿you are overwritting all that default methods? Every one of that? I readed some and are exactly like the default ones.

I suggest you to put just the methods you edit. I think thats better for scritpers they can learn in a few seconds what have been modified or not.
gerrtunk wrote:
Also, what im thinking is that... ¿you are overwritting all that default methods? Every one of that? I readed some and are exactly like the default ones.

I suggest you to put just the methods you edit. I think thats better for scritpers they can learn in a few seconds what have been modified or not.


Thats why i wrote this
Dahrkael wrote:
Edited scripts and lines:
Content Hidden Show
-- Game_Temp
-- 57
-- 58

- Game_player
-- 218
-- 219
-- 223
- -224
- -228
- -229
-- 233
-- 234

- Spriteset_Map
-- 40 to 49
-- 68 to 86
--107 to 109
-- 127- 128
-- 175 to 177

- Interpreter 4
--18
-- 174

- Scene_Title
-- 142
-- 143

-Scene_Map
-- 17
-- 18
-- 41
-- 42
-- 67 to 74
-- 139 to 41
-- 144
-- 300 to 305

-Main
--25 to 28



Some edits are just an added $network.update or such, yes.

Added: GetPeerIP method, so the server can print understandable dotted ips (127.0.0.1 for example).
Yes but better thant that is that you just put the methods you rewrite. Is still better for scripters, saves time and also improves de compatibility of your script because if an other script rewrites one of that methods that your script dont use it wont work...

Its just that i dont understand why to put that useless code here. The scene title have 6 methods and you only modifiy one...

  1.  
  2. #==============================================================================
  3. # ** Scene_Title
  4. #------------------------------------------------------------------------------
  5. #  This class performs title screen processing.
  6. #==============================================================================
  7.  
  8. class Scene_Title
  9.  
  10.   #--------------------------------------------------------------------------
  11.   # * Command: New Game
  12.   #--------------------------------------------------------------------------
  13.   def command_new_game
  14.     # Play decision SE
  15.     $game_system.se_play($data_system.decision_se)
  16.     # Stop BGM
  17.     Audio.bgm_stop
  18.     # Reset frame count for measuring play time
  19.     Graphics.frame_count = 0
  20.     # Make each type of game object
  21.     $game_temp          = Game_Temp.new
  22.     $game_system        = Game_System.new
  23.     $game_switches      = Game_Switches.new
  24.     $game_variables     = Game_Variables.new
  25.     $game_self_switches = Game_SelfSwitches.new
  26.     $game_screen        = Game_Screen.new
  27.     $game_actors        = Game_Actors.new
  28.     $game_party         = Game_Party.new
  29.     $game_troop         = Game_Troop.new
  30.     $game_map           = Game_Map.new
  31.     $game_player        = Game_Player.new
  32.     # Set up initial party
  33.     $game_party.setup_starting_members
  34.     # Set up initial map position
  35.     $game_map.setup($data_system.start_map_id)
  36.     # Move player to initial position
  37.     $game_player.moveto($data_system.start_x, $data_system.start_y)
  38.     # Refresh player
  39.     $game_player.refresh
  40.     # Run automatic change for BGM and BGS set with map
  41.     $game_map.autoplay
  42.     # Update map (run parallel process event)
  43.     $game_map.update
  44.     # Initialize Network
  45.     $network = Network.new
  46.     $network.connect_and_start
  47.     # Switch to map screen
  48.     $scene = Scene_Map.new
  49.   end
  50.  
  51. end
  52.  
Expand to see the code.


Thats better.

Also i dont know if your network class needs the rest but if you make an alias of the scene title new game method you gain compatibility with all the scripts that modify that, and also, reduce the lines of your script:


  1.  
  2. #==============================================================================
  3. # ** Scene_Title
  4. #------------------------------------------------------------------------------
  5. #  This class performs title screen processing.
  6. #==============================================================================
  7.  
  8. class Scene_Title
  9.  
  10.   #--------------------------------------------------------------------------
  11.   # * Command: New Game
  12.   #--------------------------------------------------------------------------
  13.   alias new_dk_command_new_game command_new_game
  14.   def command_new_game
  15.  
  16.     # Initialize Network
  17.     $network = Network.new
  18.     $network.connect_and_start
  19.     # Call original method
  20.     new_dk_command_new_game
  21.  
  22.   end
  23.  
  24. end
  25.  
Expand to see the code.


Note that it may be valid to put it after the original in some scripts, but here is a scene transistion so i dont know if it will give problems...
As I said before, this is not intented to be a copy&paste&ItWorks. It doesnt even make sense to connect to the server when clicking new game. Its just an example. Each person uses what they want where they want. Alias are cool for non-scripters and quick-hacks, not for a serious game.

I dont get why do you waste time reading my-omg-so-bad-written-code :shock:

Original thread: https://www.hbgames.org/forums/viewtopic.php?t=73458