You may use the following example code on this page anyway you want - they are public domain.
- 1 Source Code Examples
- 1.1 Commenting
- 1.2 Hello World
- 1.3 Launching Forms
- 1.4 Arithmetic Operations
- 1.5 Label Text Manipulation
- 1.6 Object Picture Manipulation
- 1.7 Form Colour Manipulation
- 1.8 Using Probability
- 1.9 Using Shell Commands
- 1.10 Moving an Object
- 1.11 Grid Collisions
- 1.12 Align to Grid
- 1.13 Relative Collisions
- 1.14 Changing a Border
- 1.15 Frame Animation
- 1.16 Playing Sounds and Music
- 1.17 Scrolling
- 2 Gambas Project Examples
Source Code Examples
Comments are invaluable ways to keep code organized, and help other programmers comprehend what you have written. To add them to Gambas code you need to start them with an apostrophe ('):
'This is a comment. Public Sub Form_Open() 'The above and below lines are actual code. End
You can also do comments in bold using double apostrophes.
To create the venerable "Hello World" application from a graphical project, add this code to the start up form's .class file:
Public Sub Form_Open() Message("Hello World!") End
To make one form ("FOne") launch another form ("FTwo") with a button ("BLink"), add this to "FOne"'s .class file:
Public Sub BLink_MouseDown() FTwo.Show End
To close a form, try this:
The following shows you how to do an addition operation (+).
On a form ("FOne"), have a label or other object ("LNumber") that has a .Text property and set it to "1" and have a button ("BAdd").
Public Sub BAdd_MouseDown() LNumber.Text = LNumber.Text + 1 End
Gambas also supports the short-cuts often associated with C family languages:
LNumber.Text += 1
For clarity's sake, we shall refrain from using this in the below examples, although we recommend it in practice.
Label Text Manipulation
To make a label ("LText") on a form ("FOne") change its text with a click of a button ("BChange"), add this to "FOne"'s .class file:
Public Sub BLink_MouseDown() LText.Text = "The label now has different text." End
Object Picture Manipulation
Public Sub BChange_MouseDown() PicBox.Picture = Picture["NewImage.png"] End
Form Colour Manipulation
To change the background colour of a form, create a button called "BChange" and add this code:
Public Sub BChange_MouseDown() Form.Background = &H000000& End
This changes the from's background colour to black. This works to change any object's hexadecimal colour setting.
Common Hexadecimal Colours
Black: &H000000& White: &HFFFFFF& Red: &HFF0000& Blue: &H0000FF& Purple: &H55007F& Green: &H00AA00& Yellow: &HFFFF00& Orange: &HFF5500& Pink: &HFF557F& Grey: &H787878& Light Blue: &H00AAFF& Light Green: &H55FF00& Light Grey: &HACACAC&
You can use probability (from the system's random seed) to make Gambas randomly display a message box. If you add this code to a form's .class file, it will make it so that If you click a button ("BDice") it will randomly pick a message box:
Public Dice AS Integer Public Sub BDice_Click() Randomize Dice = Int(Rnd(0, 2)) If Dice = 1 Then Message("You rolled a One") End If If Dice = 2 Then Message("You rolled a Two") End If End
Using Shell Commands
A very useful ability of Gambas is its ability to link directly into the command line of your Unix-like operating system, which allows you to load programs, do system and file management and even create front-ends for CLI applications. To access the command line, simply use the shell command:
Shell("Insert command here")
Note that many console related tasks, such as shut-down, program installation and most administration requires the program to be run in root or as super-user.
Moving an Object
On a form ("FOne"), create an object (in this Case a picture box: "PBPlayer") and four buttons: "BLeft", "BRight", "BUp", "BDown".
Public Sub BLeft_MouseDown() PBPlayer.X = PBPlayer.X - 32 End Public Sub BRight_MouseDown() PBPlayer.X = PBPlayer.X + 32 End Public Sub BUp_MouseDown() PBPlayer.Y = PBPlayer.Y - 32 End Public Sub BDown_MouseDown() PBPlayer.Y = PBPlayer.Y + 32 End
Alternately, you can move an object with the keyboard's arrow keys:
Public Sub Form_Keypress() Select Key.Code Case Key.Left PBPlayer.X = PBPlayer.X - 32 Case Key.Right PBPlayer.X = PBPlayer.X + 32 Case Key.Up PBPlayer.Y = PBPlayer.Y - 32 Case Key.Down PBPlayer.Y = PBPlayer.Y + 32 End Select End
You can also see how the arithmetic short-cuts laid out earlier can be used here.
Expand on "Moving an Object", and add another object ("PBCollectible"). Both must fit an even grid (32x32 or 48x48 recommend) and as such their dimensions should fit these parameters as well as their placement must be even to grid. Create a timer ("TmrCollisions") and add this code, set it to be enabled and a delay of "1", so that it checks for collisions every one millisecond.
Public Sub TmrCollisions_Timer() If PBPlayer.X = PBCollectible.X And PBPlayer.Y = PBCollectible.Y Then PBCollectible.X = -9000 Message("You have collected this object!") End If End
Align to Grid
This code aligns an object ("PBObject") to a given grid, (in this Case 48x48). This is needed to allow grid-based collisions to work.
PBObject.x = (Round(PBObject.x/48))*48 PBObject.y = (Round(PBObject.y/48))*48
This can also be used to move an object to the grid point nearest your cursor:
PBObject.X = (Round(Mouse.x/48))*48 PBObject.y = (Round(Mouse.y/48))*48
If you wish for more free-form movement, and not be restricted to a grid, you modify your collision code from = to > and < signs (relative to the widths and heights of the colliding objects), which creates a bounding volume within which positional coordinates are checked.
Public Sub TmrCollisions_Timer() If PBPlayer.X > PBCollectible1.X - PBPlayer.Width And PBPlayer.X < PBCollectible1.X + PBCollectible1.Width Then If PBPlayer.Y > PBCollectible1.Y - PBPlayer.Height And PBPlayer.Y < PBCollectible1.Y + PBCollectible2.Height Then PBCollectible.X = -9000 Message("You have collected this object!") End If End If End
Changing a Border
You can change a given object's border property (in this case, between plain and none) by using this code.
First put this on the very top of your class file:
CONST None AS Integer = 0 CONST Plain AS Integer = 1
Then you can use this to change your object's ("PBObject") border:
PBObject.Border = Plain
PBObject.Border = None
Frame animation (as opposed to animations done through object manipulation) is somewhat more difficult in Gambas than in some other development tools. You can not make an animated image file, like say a GIF or SVG, and then just import it into a picture box or load it into a drawing area and have the animation play. Instead you must specify slide transitions and timing in code, but this can be done fairly simply, while also giving you more control and allowing for more dynamic animation. The following has a picture box named Animation and a timer called Animations, with an integer called Frame used as a control variable for the iteration.
Public Frame AS Integer Public Sub Animations_Timer() If Exist("Animation-" & Frame & ".png") Then Animation.Picture = Picture["Animation-" & Frame & ".png"] Else Frame = 1 Animation.Picture = Picture["Animation-" & Frame & ".png"] End If Frame = Frame + 1 End
The above example even works independent of the number of frames in an animation, as it detects whether or not there is a frame ahead of it before proceeding, and if it does not find one it returns the animation to its beginning.
Playing Sounds and Music
The Simple DirectMedia Layer (SDL) can be used to add sounds and music to your project, via the sdl.sound component (as opposed to the regular SDL component for drawing). You use this by clicking the "Project" menu, then clicking on "Properties", and finally clicking the "Components" tab. Scroll through the list that appears until you find one called "gb.sdl.sound". Click the check-box beside the text and click the "OK" button. Once this is set up, you can place a sound file ("AudioFile.ogg") into your project's directory. Finally, add the code below to the top of your start-up form's class file. When you start your project, you should hear a sound.
Public AudioFile AS Sound Public Sub Form_Open() AudioFile = NEW Sound("audiofile.ogg") AudioFile.Play End
The music channel is another useful function of the Gambas SDL sound component. Using it, you not only get to play a sound, but specify how often you want it to repeat and when to pause or stop. This is useful for ambient sounds in games just as much as it is useful for music. Sadly there can only be one user of the music channel at one time, unlike the sound channel where you can have up to 32 sounds playing. However, it should be noted that you do not have to define anything for this channel, unlike the sound equivalent. To use this channel, simply input this code and add a music or ambient sound file ("Music.ogg") to your project directory.
Note that "-1" is infinite loop, to specify it to repeat five times for example simply replace it with "5".
Scrolling is a useful way to make your game world or GUI larger than the screen's display. In order to allow you to have a scene that user can scroll through, you need to put your objects into a container ("World"), such as a panel or drawing area. Make it so the container is as large as the environment you wish the user to scroll through - do not worry if it goes beyond the form's borders as that is the effect we are looking for. Once everything is in the given container, you can put in this code to allow you to scroll through it all with the container:
Public Sub Form_Keypress() Select Key.Code Case Key.Left World.X = World.X + 48 Case Key.Right World.X = World.X - 48 Case Key.Down World.Y = World.Y - 48 Case Key.Up World.Y = World.Y + 48 End Select End
This will allow the user to scroll the container around using the keyboard, but you can move it around infinitely. If you wish to make it so you can't move it beyond certain parameters you will have to add the following code to you keyboard function.
Case Key.Left If World.X = 0 OR World.X < 0 Then Else World.X = World.X + 48 End If Case Key.Right If World.X = World.Width OR World.X > World.With Then Else World.X = World.X - 48 End If Case Key.Down If World.Y = World.Height OR World.Y > World.Height Then Else World.Y = World.Y - 48 End If Case Key.Up If World.Y = 0 OR World.Y < 0 Then Else World.Y = World.Y + 48 End If
To see this technique in action you can download the Lamp Refugee technical demo.
Gambas Project Examples
Gambler is a probability example built with Gambas 2.7.0, and tested on Fedora 9. It allows you to gamble with virtual money (represented by a variable) using probability to simulate the throw of a die. Aspiring Gambas programmers should find this example useful in learning how to use probability and variable manipulation. The example is released as free software under version three of the GNU General Public License.
Walk About is a movement example built with Gambas 2.7.0, and tested on Fedora 9. It allows you to move a player (represented by picture box) around, as well as being blocked by walls. Aspiring Gambas programmers should find this example useful in learning how to use coordinates for object movement and control. The example is released as free software under version three of the GNU General Public License.
String Fun is a command line example built with Gambas 2.7.0, and tested on Fedora 9. It allows you to manipulate strings to create a humorous paragraph. Aspiring Gambas programmers should find this example useful in learning how to manipulate strings and create simple command line programs. The example is released as free software under version three of the GNU General Public License.
A tech demo created for the Gambas Genie engine project tested on Fedora 8. It shows you how to make a selectable object, and how to make it so you can drop a movement beacon with your mouse which the object will move too. The example is released as free software under version three of the GNU General Public License.
A newer technical demo for Gambas Genie, tested on Fedora 15, that demonstrates a terrain model utilizing either tiling or texturing. A must see for aspiring Gambas graphics programmers, this demo allows the placement, modification, resizing stacking of graphics on top of a Gambas drawing area. Much to learn here, as it shows the basics of drawing and the controlling of them afterwards.
Another technical demo for Gambas Genie, released on August 7, 2013 and tested on Fedora 17, that demonstrates isometric projection, with rendering, movement, collisions and a randomly positioned object. Can be used as an initial basis for a number of isometric games. Written in Gambas 3.4.1; the example is released as free software under version three of the GNU General Public License.
A demo that places down two objects randomly onto a small grid when the player clicks the mouse, regulated in such a way that an object can not land on a grey square or the other object. In such an instance, it recalculates.
Smooth Movement + Diagonals
The first proper release of the "third generation" of 2D graphic engines made in Gambas by Piga Software, featuring a combination of drawing areas for terrain tiling and picture boxes for dynamic elements. This demonstrates an array-based tile engine featuring smooth player movement in both cardinal and ordinal directions, controllable with both mouse and keyboard, with working collision detection. The user may also place down or remove wall tiles using the mouse. The demo was released on September 1, 2014.
Piga's Pumpkin Carving
Although not exactly a technical demo, it is still a fairly small program, though expanded notably in its subsequent versions. It will teach you the basics about using drawing areas, which support a wide variety of graphics features, including transparency! With version 2.0's inclusion of the "Creepy Jukebox" it is also a good guide to using the music channel and it also features simulated global variables; version 2.5 also provides a working model for using shell commands. The program is released as free software under version three of the GNU General Public License, though the music is under the Creative Commons Attribution 3.0 Unported license (not share-alike/copyleft license meaning it can be license changed).
Gambas Arcade Engine
Similar to Carving, the games using this engine are somewhat larger than a code demo but still highly instructive and small enough to be easily examined. Studying them will teach you the basics of using drawing areas but more along the lines of a game instead of a graphics program. It will show you how to define game objects, render them and manipulate them in real time, use them in cutscenes, as well as game logic functions such as collisions, score, artificial intelligence, game physics and more! In addition, each game comes with score board code which will teach you how to save and load information from text files. The article on the engine provides more complete technical information.
Donkey (DONKEY.GB) is a modern free software GNU/Linux remake of the classic BASIC computer game Donkey. Written in Gambas, it is based on the original by Bill Gates and Neil Konzen that was created to demonstrate the power of GW-BASIC for the original IBM PC. It was also ported to QBasic, and a first-person version was later made for Visual Basic .NET. As an example, it helps show basic collisions, computer-controlled movement patterns, keyboard control, treadmill-type scrolling and the basics of a Gambas "picture box"-type graphics engine.