SlideShare a Scribd company logo
Ring Documentation, Release 1.10
59.4 Client Example
Example:
load "libuv.ring"
? "Testing RingLibuv - Client Side"
DEFAULT_PORT = 13370
DEFAULT_BACKLOG = 1024
addr = new_sockaddr_in()
connect = NULL
buffer = null
socket = null
func main
myloop = uv_default_loop()
Socket = new_uv_tcp_t()
connect = new_uv_connect_t()
uv_tcp_init(myloop, Socket)
uv_ip4_addr("127.0.0.1", DEFAULT_PORT, addr)
uv_tcp_connect(connect,Socket, addr, "connect()")
uv_run(myloop, UV_RUN_DEFAULT)
destroy_uv_tcp_t(socket)
destroy_uv_connect_t(connect)
func connect
? "Client: Start Connection"
aPara = uv_Eventpara(connect,:connect)
req = aPara[1]
nStatus = aPara[2]
if nStatus = -1
? "Error : on_write_end "
return
ok
buf = new_uv_buf_t()
message = "hello from the client"
set_uv_buf_t_len(buf,len(message))
set_uv_buf_t_base(buf,varptr("message","char *"))
tcp = get_uv_connect_t_handle(req)
write_req = new_uv_write_t()
buf_count = 1
uv_write(write_req, tcp, buf, buf_count, "on_write_end()")
func on_write_end
uv_read_start(socket, uv_myalloccallback(), "echo_read()")
func echo_read
aPara = uv_Eventpara(socket,:read)
nRead = aPara[2]
buf = aPara[3]
if nRead > 0
wrbuf = uv_buf_init(get_uv_buf_t_base(buf), nread);
? uv_buf2str(wrbuf)
ok
Output:
59.4. Client Example 548
Ring Documentation, Release 1.10
We will run the client after the server
Testing RingLibuv - Client Side
Client: Start Connection
hello from the client
message from the server to the client
59.5 Server Example Using Classes
Example:
load "libuv.ring"
load "objectslib.ring"
? "Testing RingLibuv - Server Side - Using Classes"
open_object(:MyServer)
class MyServer from ObjectControllerParent
DEFAULT_PORT = 13370
DEFAULT_BACKLOG = 1024
addr = new_sockaddr_in()
server = NULL
client = NULL
myloop = NULL
func start
myloop = uv_default_loop()
server = new_uv_tcp_t()
uv_tcp_init(myloop, server)
uv_ip4_addr("127.0.0.1", DEFAULT_PORT, addr)
uv_tcp_bind(server, addr, 0)
r = uv_listen(server, DEFAULT_BACKLOG, Method(:newconnection) )
if r
? "Listen error " + uv_strerror(r)
return 1
ok
uv_run(myloop, UV_RUN_DEFAULT)
destroy_uv_tcp_t(server)
destroy_uv_sockaddr_in(addr)
func newconnection
? "New Connection"
aPara = uv_Eventpara(server,:connect)
nStatus = aPara[2]
if nStatus < 0
? "New connection error : " + nStatus
return
ok
client = new_uv_tcp_t()
uv_tcp_init(myloop, client)
if uv_accept(server, client) = 0
uv_read_start(client, uv_myalloccallback(),
Method(:echo_read))
ok
59.5. Server Example Using Classes 549
Ring Documentation, Release 1.10
func echo_read
aPara = uv_Eventpara(client,:read)
nRead = aPara[2]
buf = aPara[3]
if nRead > 0
req = new_uv_write_t()
wrbuf = uv_buf_init(get_uv_buf_t_base(buf), nread)
uv_write(req, client, wrbuf, 1, Method(:echo_write))
? uv_buf2str(wrbuf)
message = "message from the server to the client"
buf = new_uv_buf_t()
set_uv_buf_t_len(buf,len(message))
set_uv_buf_t_base(buf,varptr("message","char *"))
uv_write(req, client, buf, 1, Method(:echo_write))
ok
func echo_write
aPara = uv_Eventpara(client,:read)
req = aPara[1]
Output:
When we run the client, We will see the message “New Connection”
Then the message “hello from the client”
Testing RingLibuv - Server Side - Using Classes
New Connection
hello from the client
59.6 Client Example Using Classes
Example:
load "libuv.ring"
load "objectslib.ring"
? "Testing RingLibuv - Client Side - Using Classes"
open_object(:MyClient)
Class MyClient from ObjectControllerParent
DEFAULT_PORT = 13370
DEFAULT_BACKLOG = 1024
addr = new_sockaddr_in()
connect = NULL
buffer = null
socket = null
func start
myloop = uv_default_loop()
Socket = new_uv_tcp_t()
connect = new_uv_connect_t()
uv_tcp_init(myloop, Socket)
uv_ip4_addr("127.0.0.1", DEFAULT_PORT, addr)
59.6. Client Example Using Classes 550
Ring Documentation, Release 1.10
uv_tcp_connect(connect,Socket, addr, Method(:connect))
uv_run(myloop, UV_RUN_DEFAULT)
destroy_uv_tcp_t(socket)
destroy_uv_connect_t(connect)
func connect
? "Client: Start Connection"
aPara = uv_Eventpara(connect,:connect)
req = aPara[1]
nStatus = aPara[2]
if nStatus = -1
? "Error : on_write_end "
return
ok
buf = new_uv_buf_t()
message = "hello from the client"
set_uv_buf_t_len(buf,len(message))
set_uv_buf_t_base(buf,varptr("message","char *"))
tcp = get_uv_connect_t_handle(req)
write_req = new_uv_write_t()
buf_count = 1
uv_write(write_req, tcp, buf, buf_count, Method(:on_write_end))
func on_write_end
uv_read_start(socket, uv_myalloccallback(), Method(:echo_read))
func echo_read
aPara = uv_Eventpara(socket,:read)
nRead = aPara[2]
buf = aPara[3]
if nRead > 0
wrbuf = uv_buf_init(get_uv_buf_t_base(buf), nread);
? uv_buf2str(wrbuf)
ok
Output:
We will run the client after the server
Testing RingLibuv - Client Side - Using Classes
Client: Start Connection
hello from the client
message from the server to the client
59.7 Threads Example
Example:
load "libuv.ring"
? "Testing RingLibuv - Threads"
func main
one_id = new_uv_thread_t()
two_id = new_uv_thread_t()
uv_thread_create(one_id, "one()")
uv_thread_create(two_id, "two()")
59.7. Threads Example 551
Ring Documentation, Release 1.10
uv_thread_join(one_id)
uv_thread_join(two_id)
destroy_uv_thread_t(one_id)
destroy_uv_thread_t(two_id)
func one
? "Message from the First Thread!"
func two
? "Message from the Second Thread!"
Output:
Testing RingLibuv - Threads
Message from the First Thread!
Message from the Second Thread!
59.8 Threads Example - Using Classes
Example:
load "libuv.ring"
load "objectslib.ring"
? "Testing RingLibuv - Threads - Using Classes"
open_object(:MyThreads)
class MyThreads from ObjectControllerParent
func Start
one_id = new_uv_thread_t()
two_id = new_uv_thread_t()
uv_thread_create(one_id, Method(:One))
uv_thread_create(two_id, Method(:Two))
uv_thread_join(one_id)
uv_thread_join(two_id)
destroy_uv_thread_t(one_id)
destroy_uv_thread_t(two_id)
func one
? "Message from the First Thread!"
func Two
? "Message from the Second Thread!"
Output:
Testing RingLibuv - Threads - Using Classes
Message from the First Thread!
Message from the Second Thread!
59.8. Threads Example - Using Classes 552
CHAPTER
SIXTY
DEMO PROJECT - GAME ENGINE FOR 2D GAMES
In this chapter we will learn about using the different programming paradigms in the same project.
We will create a simple Game Engine for 2D Games.
You can use the Engine directly to create 2D Games for Desktop or Mobile.
60.1 Project Layers
The project contains the next layers
• Games Layer (Here we will use declarative programming)
• Game Engine Classes (Here we will use the Object-Oriented Programming paradigm)
• Interface to graphics library (Here we will use procedural programming)
• Graphics Library bindings (Here we have RingAllegro and RingLibSDL)
60.2 Graphics Library bindings
We already have RingAllegro to use the Allegro game programming library and we have RingLibSDL to use the
LibSDL game programming library.
Both of RingAllegro and RingLibSDL are created using the C language with the help of the Ring code generator for
extensions.
Each of them is over 10,000 lines of C code which is generated after writing simple configuration files (That are
processed by the code generator).
Each configuration file determines the functions names, structures information and constants then the generator process
this configuration file to produce the C code and the library that can be loaded from Ring code.
Using RingAllegro and RingLibSDL is very similar to using Allegro and LibSDL from C code where you have the
same functions but we can build on that using the Ring language features
• RingAllegro Source Code : https://github.com/ring-lang/ring/tree/master/extensions/ringallegro
• RingLibSDL Source Code : https://github.com/ring-lang/ring/tree/master/extensions/ringsdl
553
Ring Documentation, Release 1.10
60.3 Interface to graphics library
In this layer we have gl_allegro.ring and gl_libsdl.ring
Each library provides the same functions to be used with interacting with the Graphics Library.
This layer hides the details and the difference between RingAllegro and RingLibSDL.
You have the same functions, Just use it and you can switch between Allegro and LibSDL at anytime.
Why ?
Allegro is very simple, we can use it to quickly create 2D games for Windows, Linux and MacOS X.
In Ring 1.0 we started by supporting Allegro.
Also LibSDL is very powerful and popular, very easy to use for Mobile Development.
Ring 1.1 comes with support for LibSDL so we can quickly create games for Mobile.
Note: We can use just one library for Desktop and Mobile development.
• gl_allegro.ring source code : https://github.com/ring-lang/ring/blob/master/ringlibs/gameengine/gl_allegro.ring
• gl_libsdl.ring source code : https://github.com/ring-lang/ring/blob/master/ringlibs/gameengine/gl_libsdl.ring
60.4 Game Engine Classes
The Engine comes with the next classes
• GameBase class
• Resources class
• Game class
• GameObject class
• Sprite class
• Text class
• Animate class
• Sound class
• Map class
• Source Code : https://github.com/ring-lang/ring/blob/master/ringlibs/gameengine/gameengine.ring
60.5 Games Layer
In this layer we create our games using the Game Engine classes
The classes are designed to be used through Declarative Programming.
In our games we will use the next classes
• Game class
• Sprite class
60.3. Interface to graphics library 554
Ring Documentation, Release 1.10
• Text class
• Animate class
• Sound class
• Map class
Note: Other classes in the engine are for internal use by the engine.
We will introduce some examples and three simple games :-
• Stars Fighter Game
• Flappy Bird 3000 Game
• Super Man 2016 Game
60.6 Game Class
The next table present the class attributes.
Attributes Description
FPS Number determines how many times the draw() method will be called per second.
FixedFPS Number determines how many times the animate() method will be called per second.
Title String determines the window title of the game.
aObjects List contains all objects in the game
shutdown True/False value to end the game loop
The next table present the class methods.
Method Description
refresh() Delete objects.
settitle(cTitle) Set the window title using a string parameter.
shutdown() Close the application.
The next table present a group of keywords defined by the class.
Keyword Description
sprite Create new Sprite object and add it to the game objects.
text Create new Text object and add it to the game objects.
animate Create new Animate object and add it to the game objects.
sound Create new Sound object and add it to the game objects.
map Create new Map object and add it ot the game objects.
60.7 GameObject Class
The next table present the class attributes.
60.6. Game Class 555
Ring Documentation, Release 1.10
Attributes Description
enabled True/False determine the state of the object (Active/Not Active)
x Number determine the x position of the object.
y Number determine the y position of the object.
width Number determine the width of the object.
height Number determine the height of the object.
nIndex Number determine the index of the object in objects list.
animate True/False to animate the object or not.
move True/False to move the object using the keyboard or not.
Scaled True/False to scale the object image or not.
draw Function to be called when drawing the object.
state Function to be called for object animation.
keypress Function to be called when a key is pressed.
mouse Function to be called when a mouse event happens.
The next table present the class methods.
Method Description
keyboard(oGame,nkey) Check Keyboard Events
mouse(oGame,nType,aMouseList) Check Mouse Events
rgb(r,g,b) Return new color using the RGB (Red, Green and Blue) Values.
60.8 Sprite Class
Parent Class : GameObject Class
The next table present the class attributes.
Attributes Description
image String determine the image file name.
point Number determine the limit of automatic movement of the object.
direction Number determine the direction of movement.
nstep Number determine the increment/decrement during movement.
type Number determine the object type in the game (Optional).
transparent True/False value determine if the image is transparent.
The next table present the class methods.
Method Description
Draw(oGame) Draw the object
60.9 Text Class
Parent Class : Sprite Class
The next table present the class attributes.
Attributes Description
size Number determine the font size
font String determine the font file name
text String determine the text to be displayed
color Number determine the color
The next table present the class methods.
60.8. Sprite Class 556
Ring Documentation, Release 1.10
Method Description
Draw(oGame) Draw the object
60.10 Animate Class
Parent Class : Sprite Class
The next table present the class attributes.
Attributes Description
frames Number determine the number of frames
frame Number determine the active frame
framewidth Number determine the frame width.
animate True/False determine using animate or not.
scaled True/False determine scaling image or not.
The next table present the class methods.
Method Description
Draw(oGame) Draw the object
60.11 Sound Class
Parent Class : GameObject Class
The next table present the class attributes.
Attributes Description
file String determine the sound file name.
once True/False determine to play the file one time or not (loop).
The next table present the class methods.
Method Description
playsound() Play the sound file
60.12 Map Class
Parent Class : Sprite Class
The next table present the class attributes.
Attributes Description
aMap List determine the map content using numbers.
aImages List determine the image used for each number in the map.
BlockWidth Number determine the block width (default = 32).
BlockHeight Number determine the block height (default = 32).
Animate True/False determine the animation status.
The next table present the class methods.
Method Description
getvalue(x,y) Return the item value in the Map according to the visible part
60.10. Animate Class 557

More Related Content

PDF
The Ring programming language version 1.8 book - Part 54 of 202
PDF
Python Asíncrono - Async Python
PDF
Fun Teaching MongoDB New Tricks
PPT
Python multithreading session 9 - shanmugam
PPTX
C#을 이용한 task 병렬화와 비동기 패턴
PDF
Book
PPTX
Advanced #3 threading
PDF
The Ring programming language version 1.10 book - Part 13 of 212
The Ring programming language version 1.8 book - Part 54 of 202
Python Asíncrono - Async Python
Fun Teaching MongoDB New Tricks
Python multithreading session 9 - shanmugam
C#을 이용한 task 병렬화와 비동기 패턴
Book
Advanced #3 threading
The Ring programming language version 1.10 book - Part 13 of 212

What's hot (20)

PPTX
Do we need Unsafe in Java?
PDF
The Ring programming language version 1.5.1 book - Part 44 of 180
PDF
Current State of Coroutines
PDF
The Ring programming language version 1.5.2 book - Part 39 of 181
PPTX
分散式系統
PPTX
Multithreaded programming
PDF
JJUG CCC 2011 Spring
PDF
JCConf 2015 - 輕鬆學google的雲端開發 - Google App Engine入門(上)
PDF
The Ring programming language version 1.9 book - Part 11 of 210
PDF
Mastering Kotlin Standard Library
PDF
The Ring programming language version 1.8 book - Part 9 of 202
PDF
Understanding Source Code Differences by Separating Refactoring Effects
PDF
The Ring programming language version 1.5.2 book - Part 13 of 181
PDF
Java libraries you can't afford to miss
PDF
Magic Clusters and Where to Find Them 2.0 - Eugene Pirogov
PDF
Stubる - Mockingjayを使ったHTTPクライアントのテスト -
PPTX
#5 (Remote Method Invocation)
PDF
The Ring programming language version 1.5.3 book - Part 85 of 184
PDF
The (unknown) collections module
Do we need Unsafe in Java?
The Ring programming language version 1.5.1 book - Part 44 of 180
Current State of Coroutines
The Ring programming language version 1.5.2 book - Part 39 of 181
分散式系統
Multithreaded programming
JJUG CCC 2011 Spring
JCConf 2015 - 輕鬆學google的雲端開發 - Google App Engine入門(上)
The Ring programming language version 1.9 book - Part 11 of 210
Mastering Kotlin Standard Library
The Ring programming language version 1.8 book - Part 9 of 202
Understanding Source Code Differences by Separating Refactoring Effects
The Ring programming language version 1.5.2 book - Part 13 of 181
Java libraries you can't afford to miss
Magic Clusters and Where to Find Them 2.0 - Eugene Pirogov
Stubる - Mockingjayを使ったHTTPクライアントのテスト -
#5 (Remote Method Invocation)
The Ring programming language version 1.5.3 book - Part 85 of 184
The (unknown) collections module
Ad

Similar to The Ring programming language version 1.10 book - Part 59 of 212 (20)

PDF
The Ring programming language version 1.7 book - Part 52 of 196
PDF
The Ring programming language version 1.9 book - Part 58 of 210
PDF
The Ring programming language version 1.9 book - Part 57 of 210
PDF
The Ring programming language version 1.3 book - Part 8 of 88
PDF
The Ring programming language version 1.5.4 book - Part 15 of 185
PDF
The Ring programming language version 1.8 book - Part 19 of 202
PDF
The Ring programming language version 1.9 book - Part 21 of 210
PDF
The Ring programming language version 1.5.3 book - Part 15 of 184
PDF
The Ring programming language version 1.4 book - Part 14 of 30
PDF
The Ring programming language version 1.5.1 book - Part 45 of 180
PDF
The Ring programming language version 1.5.4 book - Part 48 of 185
PDF
The Ring programming language version 1.6 book - Part 79 of 189
PDF
The Ring programming language version 1.10 book - Part 57 of 212
PDF
The Ring programming language version 1.3 book - Part 38 of 88
PDF
The Ring programming language version 1.7 book - Part 53 of 196
PDF
The Ring programming language version 1.5.2 book - Part 46 of 181
PDF
The Ring programming language version 1.6 book - Part 49 of 189
PDF
The Ring programming language version 1.10 book - Part 22 of 212
PDF
The Ring programming language version 1.4 book - Part 22 of 30
PDF
The Ring programming language version 1.5.3 book - Part 48 of 184
The Ring programming language version 1.7 book - Part 52 of 196
The Ring programming language version 1.9 book - Part 58 of 210
The Ring programming language version 1.9 book - Part 57 of 210
The Ring programming language version 1.3 book - Part 8 of 88
The Ring programming language version 1.5.4 book - Part 15 of 185
The Ring programming language version 1.8 book - Part 19 of 202
The Ring programming language version 1.9 book - Part 21 of 210
The Ring programming language version 1.5.3 book - Part 15 of 184
The Ring programming language version 1.4 book - Part 14 of 30
The Ring programming language version 1.5.1 book - Part 45 of 180
The Ring programming language version 1.5.4 book - Part 48 of 185
The Ring programming language version 1.6 book - Part 79 of 189
The Ring programming language version 1.10 book - Part 57 of 212
The Ring programming language version 1.3 book - Part 38 of 88
The Ring programming language version 1.7 book - Part 53 of 196
The Ring programming language version 1.5.2 book - Part 46 of 181
The Ring programming language version 1.6 book - Part 49 of 189
The Ring programming language version 1.10 book - Part 22 of 212
The Ring programming language version 1.4 book - Part 22 of 30
The Ring programming language version 1.5.3 book - Part 48 of 184
Ad

More from Mahmoud Samir Fayed (20)

PDF
The Ring programming language version 1.10 book - Part 212 of 212
PDF
The Ring programming language version 1.10 book - Part 211 of 212
PDF
The Ring programming language version 1.10 book - Part 210 of 212
PDF
The Ring programming language version 1.10 book - Part 208 of 212
PDF
The Ring programming language version 1.10 book - Part 207 of 212
PDF
The Ring programming language version 1.10 book - Part 205 of 212
PDF
The Ring programming language version 1.10 book - Part 206 of 212
PDF
The Ring programming language version 1.10 book - Part 204 of 212
PDF
The Ring programming language version 1.10 book - Part 203 of 212
PDF
The Ring programming language version 1.10 book - Part 202 of 212
PDF
The Ring programming language version 1.10 book - Part 201 of 212
PDF
The Ring programming language version 1.10 book - Part 200 of 212
PDF
The Ring programming language version 1.10 book - Part 199 of 212
PDF
The Ring programming language version 1.10 book - Part 198 of 212
PDF
The Ring programming language version 1.10 book - Part 197 of 212
PDF
The Ring programming language version 1.10 book - Part 196 of 212
PDF
The Ring programming language version 1.10 book - Part 195 of 212
PDF
The Ring programming language version 1.10 book - Part 194 of 212
PDF
The Ring programming language version 1.10 book - Part 193 of 212
PDF
The Ring programming language version 1.10 book - Part 192 of 212
The Ring programming language version 1.10 book - Part 212 of 212
The Ring programming language version 1.10 book - Part 211 of 212
The Ring programming language version 1.10 book - Part 210 of 212
The Ring programming language version 1.10 book - Part 208 of 212
The Ring programming language version 1.10 book - Part 207 of 212
The Ring programming language version 1.10 book - Part 205 of 212
The Ring programming language version 1.10 book - Part 206 of 212
The Ring programming language version 1.10 book - Part 204 of 212
The Ring programming language version 1.10 book - Part 203 of 212
The Ring programming language version 1.10 book - Part 202 of 212
The Ring programming language version 1.10 book - Part 201 of 212
The Ring programming language version 1.10 book - Part 200 of 212
The Ring programming language version 1.10 book - Part 199 of 212
The Ring programming language version 1.10 book - Part 198 of 212
The Ring programming language version 1.10 book - Part 197 of 212
The Ring programming language version 1.10 book - Part 196 of 212
The Ring programming language version 1.10 book - Part 195 of 212
The Ring programming language version 1.10 book - Part 194 of 212
The Ring programming language version 1.10 book - Part 193 of 212
The Ring programming language version 1.10 book - Part 192 of 212

Recently uploaded (20)

PDF
Which alternative to Crystal Reports is best for small or large businesses.pdf
PDF
top salesforce developer skills in 2025.pdf
PDF
medical staffing services at VALiNTRY
PPTX
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
PDF
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
PDF
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
PDF
Design an Analysis of Algorithms II-SECS-1021-03
PDF
Softaken Excel to vCard Converter Software.pdf
PDF
wealthsignaloriginal-com-DS-text-... (1).pdf
PDF
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
PPTX
Transform Your Business with a Software ERP System
PDF
Nekopoi APK 2025 free lastest update
PPTX
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
PPTX
Reimagine Home Health with the Power of Agentic AI​
PDF
Wondershare Filmora 15 Crack With Activation Key [2025
PDF
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
PPTX
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
PPTX
ai tools demonstartion for schools and inter college
PDF
AI in Product Development-omnex systems
PDF
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
Which alternative to Crystal Reports is best for small or large businesses.pdf
top salesforce developer skills in 2025.pdf
medical staffing services at VALiNTRY
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
Design an Analysis of Algorithms II-SECS-1021-03
Softaken Excel to vCard Converter Software.pdf
wealthsignaloriginal-com-DS-text-... (1).pdf
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
Transform Your Business with a Software ERP System
Nekopoi APK 2025 free lastest update
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
Reimagine Home Health with the Power of Agentic AI​
Wondershare Filmora 15 Crack With Activation Key [2025
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
ai tools demonstartion for schools and inter college
AI in Product Development-omnex systems
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...

The Ring programming language version 1.10 book - Part 59 of 212

  • 1. Ring Documentation, Release 1.10 59.4 Client Example Example: load "libuv.ring" ? "Testing RingLibuv - Client Side" DEFAULT_PORT = 13370 DEFAULT_BACKLOG = 1024 addr = new_sockaddr_in() connect = NULL buffer = null socket = null func main myloop = uv_default_loop() Socket = new_uv_tcp_t() connect = new_uv_connect_t() uv_tcp_init(myloop, Socket) uv_ip4_addr("127.0.0.1", DEFAULT_PORT, addr) uv_tcp_connect(connect,Socket, addr, "connect()") uv_run(myloop, UV_RUN_DEFAULT) destroy_uv_tcp_t(socket) destroy_uv_connect_t(connect) func connect ? "Client: Start Connection" aPara = uv_Eventpara(connect,:connect) req = aPara[1] nStatus = aPara[2] if nStatus = -1 ? "Error : on_write_end " return ok buf = new_uv_buf_t() message = "hello from the client" set_uv_buf_t_len(buf,len(message)) set_uv_buf_t_base(buf,varptr("message","char *")) tcp = get_uv_connect_t_handle(req) write_req = new_uv_write_t() buf_count = 1 uv_write(write_req, tcp, buf, buf_count, "on_write_end()") func on_write_end uv_read_start(socket, uv_myalloccallback(), "echo_read()") func echo_read aPara = uv_Eventpara(socket,:read) nRead = aPara[2] buf = aPara[3] if nRead > 0 wrbuf = uv_buf_init(get_uv_buf_t_base(buf), nread); ? uv_buf2str(wrbuf) ok Output: 59.4. Client Example 548
  • 2. Ring Documentation, Release 1.10 We will run the client after the server Testing RingLibuv - Client Side Client: Start Connection hello from the client message from the server to the client 59.5 Server Example Using Classes Example: load "libuv.ring" load "objectslib.ring" ? "Testing RingLibuv - Server Side - Using Classes" open_object(:MyServer) class MyServer from ObjectControllerParent DEFAULT_PORT = 13370 DEFAULT_BACKLOG = 1024 addr = new_sockaddr_in() server = NULL client = NULL myloop = NULL func start myloop = uv_default_loop() server = new_uv_tcp_t() uv_tcp_init(myloop, server) uv_ip4_addr("127.0.0.1", DEFAULT_PORT, addr) uv_tcp_bind(server, addr, 0) r = uv_listen(server, DEFAULT_BACKLOG, Method(:newconnection) ) if r ? "Listen error " + uv_strerror(r) return 1 ok uv_run(myloop, UV_RUN_DEFAULT) destroy_uv_tcp_t(server) destroy_uv_sockaddr_in(addr) func newconnection ? "New Connection" aPara = uv_Eventpara(server,:connect) nStatus = aPara[2] if nStatus < 0 ? "New connection error : " + nStatus return ok client = new_uv_tcp_t() uv_tcp_init(myloop, client) if uv_accept(server, client) = 0 uv_read_start(client, uv_myalloccallback(), Method(:echo_read)) ok 59.5. Server Example Using Classes 549
  • 3. Ring Documentation, Release 1.10 func echo_read aPara = uv_Eventpara(client,:read) nRead = aPara[2] buf = aPara[3] if nRead > 0 req = new_uv_write_t() wrbuf = uv_buf_init(get_uv_buf_t_base(buf), nread) uv_write(req, client, wrbuf, 1, Method(:echo_write)) ? uv_buf2str(wrbuf) message = "message from the server to the client" buf = new_uv_buf_t() set_uv_buf_t_len(buf,len(message)) set_uv_buf_t_base(buf,varptr("message","char *")) uv_write(req, client, buf, 1, Method(:echo_write)) ok func echo_write aPara = uv_Eventpara(client,:read) req = aPara[1] Output: When we run the client, We will see the message “New Connection” Then the message “hello from the client” Testing RingLibuv - Server Side - Using Classes New Connection hello from the client 59.6 Client Example Using Classes Example: load "libuv.ring" load "objectslib.ring" ? "Testing RingLibuv - Client Side - Using Classes" open_object(:MyClient) Class MyClient from ObjectControllerParent DEFAULT_PORT = 13370 DEFAULT_BACKLOG = 1024 addr = new_sockaddr_in() connect = NULL buffer = null socket = null func start myloop = uv_default_loop() Socket = new_uv_tcp_t() connect = new_uv_connect_t() uv_tcp_init(myloop, Socket) uv_ip4_addr("127.0.0.1", DEFAULT_PORT, addr) 59.6. Client Example Using Classes 550
  • 4. Ring Documentation, Release 1.10 uv_tcp_connect(connect,Socket, addr, Method(:connect)) uv_run(myloop, UV_RUN_DEFAULT) destroy_uv_tcp_t(socket) destroy_uv_connect_t(connect) func connect ? "Client: Start Connection" aPara = uv_Eventpara(connect,:connect) req = aPara[1] nStatus = aPara[2] if nStatus = -1 ? "Error : on_write_end " return ok buf = new_uv_buf_t() message = "hello from the client" set_uv_buf_t_len(buf,len(message)) set_uv_buf_t_base(buf,varptr("message","char *")) tcp = get_uv_connect_t_handle(req) write_req = new_uv_write_t() buf_count = 1 uv_write(write_req, tcp, buf, buf_count, Method(:on_write_end)) func on_write_end uv_read_start(socket, uv_myalloccallback(), Method(:echo_read)) func echo_read aPara = uv_Eventpara(socket,:read) nRead = aPara[2] buf = aPara[3] if nRead > 0 wrbuf = uv_buf_init(get_uv_buf_t_base(buf), nread); ? uv_buf2str(wrbuf) ok Output: We will run the client after the server Testing RingLibuv - Client Side - Using Classes Client: Start Connection hello from the client message from the server to the client 59.7 Threads Example Example: load "libuv.ring" ? "Testing RingLibuv - Threads" func main one_id = new_uv_thread_t() two_id = new_uv_thread_t() uv_thread_create(one_id, "one()") uv_thread_create(two_id, "two()") 59.7. Threads Example 551
  • 5. Ring Documentation, Release 1.10 uv_thread_join(one_id) uv_thread_join(two_id) destroy_uv_thread_t(one_id) destroy_uv_thread_t(two_id) func one ? "Message from the First Thread!" func two ? "Message from the Second Thread!" Output: Testing RingLibuv - Threads Message from the First Thread! Message from the Second Thread! 59.8 Threads Example - Using Classes Example: load "libuv.ring" load "objectslib.ring" ? "Testing RingLibuv - Threads - Using Classes" open_object(:MyThreads) class MyThreads from ObjectControllerParent func Start one_id = new_uv_thread_t() two_id = new_uv_thread_t() uv_thread_create(one_id, Method(:One)) uv_thread_create(two_id, Method(:Two)) uv_thread_join(one_id) uv_thread_join(two_id) destroy_uv_thread_t(one_id) destroy_uv_thread_t(two_id) func one ? "Message from the First Thread!" func Two ? "Message from the Second Thread!" Output: Testing RingLibuv - Threads - Using Classes Message from the First Thread! Message from the Second Thread! 59.8. Threads Example - Using Classes 552
  • 6. CHAPTER SIXTY DEMO PROJECT - GAME ENGINE FOR 2D GAMES In this chapter we will learn about using the different programming paradigms in the same project. We will create a simple Game Engine for 2D Games. You can use the Engine directly to create 2D Games for Desktop or Mobile. 60.1 Project Layers The project contains the next layers • Games Layer (Here we will use declarative programming) • Game Engine Classes (Here we will use the Object-Oriented Programming paradigm) • Interface to graphics library (Here we will use procedural programming) • Graphics Library bindings (Here we have RingAllegro and RingLibSDL) 60.2 Graphics Library bindings We already have RingAllegro to use the Allegro game programming library and we have RingLibSDL to use the LibSDL game programming library. Both of RingAllegro and RingLibSDL are created using the C language with the help of the Ring code generator for extensions. Each of them is over 10,000 lines of C code which is generated after writing simple configuration files (That are processed by the code generator). Each configuration file determines the functions names, structures information and constants then the generator process this configuration file to produce the C code and the library that can be loaded from Ring code. Using RingAllegro and RingLibSDL is very similar to using Allegro and LibSDL from C code where you have the same functions but we can build on that using the Ring language features • RingAllegro Source Code : https://github.com/ring-lang/ring/tree/master/extensions/ringallegro • RingLibSDL Source Code : https://github.com/ring-lang/ring/tree/master/extensions/ringsdl 553
  • 7. Ring Documentation, Release 1.10 60.3 Interface to graphics library In this layer we have gl_allegro.ring and gl_libsdl.ring Each library provides the same functions to be used with interacting with the Graphics Library. This layer hides the details and the difference between RingAllegro and RingLibSDL. You have the same functions, Just use it and you can switch between Allegro and LibSDL at anytime. Why ? Allegro is very simple, we can use it to quickly create 2D games for Windows, Linux and MacOS X. In Ring 1.0 we started by supporting Allegro. Also LibSDL is very powerful and popular, very easy to use for Mobile Development. Ring 1.1 comes with support for LibSDL so we can quickly create games for Mobile. Note: We can use just one library for Desktop and Mobile development. • gl_allegro.ring source code : https://github.com/ring-lang/ring/blob/master/ringlibs/gameengine/gl_allegro.ring • gl_libsdl.ring source code : https://github.com/ring-lang/ring/blob/master/ringlibs/gameengine/gl_libsdl.ring 60.4 Game Engine Classes The Engine comes with the next classes • GameBase class • Resources class • Game class • GameObject class • Sprite class • Text class • Animate class • Sound class • Map class • Source Code : https://github.com/ring-lang/ring/blob/master/ringlibs/gameengine/gameengine.ring 60.5 Games Layer In this layer we create our games using the Game Engine classes The classes are designed to be used through Declarative Programming. In our games we will use the next classes • Game class • Sprite class 60.3. Interface to graphics library 554
  • 8. Ring Documentation, Release 1.10 • Text class • Animate class • Sound class • Map class Note: Other classes in the engine are for internal use by the engine. We will introduce some examples and three simple games :- • Stars Fighter Game • Flappy Bird 3000 Game • Super Man 2016 Game 60.6 Game Class The next table present the class attributes. Attributes Description FPS Number determines how many times the draw() method will be called per second. FixedFPS Number determines how many times the animate() method will be called per second. Title String determines the window title of the game. aObjects List contains all objects in the game shutdown True/False value to end the game loop The next table present the class methods. Method Description refresh() Delete objects. settitle(cTitle) Set the window title using a string parameter. shutdown() Close the application. The next table present a group of keywords defined by the class. Keyword Description sprite Create new Sprite object and add it to the game objects. text Create new Text object and add it to the game objects. animate Create new Animate object and add it to the game objects. sound Create new Sound object and add it to the game objects. map Create new Map object and add it ot the game objects. 60.7 GameObject Class The next table present the class attributes. 60.6. Game Class 555
  • 9. Ring Documentation, Release 1.10 Attributes Description enabled True/False determine the state of the object (Active/Not Active) x Number determine the x position of the object. y Number determine the y position of the object. width Number determine the width of the object. height Number determine the height of the object. nIndex Number determine the index of the object in objects list. animate True/False to animate the object or not. move True/False to move the object using the keyboard or not. Scaled True/False to scale the object image or not. draw Function to be called when drawing the object. state Function to be called for object animation. keypress Function to be called when a key is pressed. mouse Function to be called when a mouse event happens. The next table present the class methods. Method Description keyboard(oGame,nkey) Check Keyboard Events mouse(oGame,nType,aMouseList) Check Mouse Events rgb(r,g,b) Return new color using the RGB (Red, Green and Blue) Values. 60.8 Sprite Class Parent Class : GameObject Class The next table present the class attributes. Attributes Description image String determine the image file name. point Number determine the limit of automatic movement of the object. direction Number determine the direction of movement. nstep Number determine the increment/decrement during movement. type Number determine the object type in the game (Optional). transparent True/False value determine if the image is transparent. The next table present the class methods. Method Description Draw(oGame) Draw the object 60.9 Text Class Parent Class : Sprite Class The next table present the class attributes. Attributes Description size Number determine the font size font String determine the font file name text String determine the text to be displayed color Number determine the color The next table present the class methods. 60.8. Sprite Class 556
  • 10. Ring Documentation, Release 1.10 Method Description Draw(oGame) Draw the object 60.10 Animate Class Parent Class : Sprite Class The next table present the class attributes. Attributes Description frames Number determine the number of frames frame Number determine the active frame framewidth Number determine the frame width. animate True/False determine using animate or not. scaled True/False determine scaling image or not. The next table present the class methods. Method Description Draw(oGame) Draw the object 60.11 Sound Class Parent Class : GameObject Class The next table present the class attributes. Attributes Description file String determine the sound file name. once True/False determine to play the file one time or not (loop). The next table present the class methods. Method Description playsound() Play the sound file 60.12 Map Class Parent Class : Sprite Class The next table present the class attributes. Attributes Description aMap List determine the map content using numbers. aImages List determine the image used for each number in the map. BlockWidth Number determine the block width (default = 32). BlockHeight Number determine the block height (default = 32). Animate True/False determine the animation status. The next table present the class methods. Method Description getvalue(x,y) Return the item value in the Map according to the visible part 60.10. Animate Class 557