Volume 2 - digital- · PDF fileHands On AGK2 BASIC Volume 2 Alistair Stewart Digital Skills...

30
Hands On AGK2 BASIC Volume 2 Digital Skills www.digital-skills.co.uk Alistair Stewart

Transcript of Volume 2 - digital- · PDF fileHands On AGK2 BASIC Volume 2 Alistair Stewart Digital Skills...

Page 1: Volume 2 - digital- · PDF fileHands On AGK2 BASIC Volume 2 Alistair Stewart Digital Skills Milton Barr Ayrshire KA26 9TY UK   tel: +44(0)1465 861 638

Hands On AGK2 BASICVolume 2

Digital Skills

www.digital-skills.co.ukAlistair Stewart

Page 2: Volume 2 - digital- · PDF fileHands On AGK2 BASIC Volume 2 Alistair Stewart Digital Skills Milton Barr Ayrshire KA26 9TY UK   tel: +44(0)1465 861 638

Hands On AGK2 BASICVolume 2

Alistair Stewart

Digital SkillsMiltonBarrAyrshireKA26 9TYUK

www.Digital-Skills.co.uk+44(0)1465 861 638tel:

www.digital-skills.co.uk

Page 3: Volume 2 - digital- · PDF fileHands On AGK2 BASIC Volume 2 Alistair Stewart Digital Skills Milton Barr Ayrshire KA26 9TY UK   tel: +44(0)1465 861 638

Copyright © Digital Skills 2017

All rights reserved.

No part of this work may be reproduced or used in any form without written permission from Digital Skills.

Although every effort has been made to ensure accuracy, the author and publisher accept neither liability nor responsibility for any loss or damage arising from the information in this book.

AppGameKit is developed and owned by The Game Creators Ltd. All Rights Reserved.

Cover Image: NASA

First Published November 2017

Title: Hands On AGK2 BASIC Volume 2

ISBN: 978-1-874107-23-1

Page 4: Volume 2 - digital- · PDF fileHands On AGK2 BASIC Volume 2 Alistair Stewart Digital Skills Milton Barr Ayrshire KA26 9TY UK   tel: +44(0)1465 861 638
Page 5: Volume 2 - digital- · PDF fileHands On AGK2 BASIC Volume 2 Alistair Stewart Digital Skills Milton Barr Ayrshire KA26 9TY UK   tel: +44(0)1465 861 638

DownloadThe resources required by the activities in this book can be downloaded from

www.digital-skills.co.uk

Page 6: Volume 2 - digital- · PDF fileHands On AGK2 BASIC Volume 2 Alistair Stewart Digital Skills Milton Barr Ayrshire KA26 9TY UK   tel: +44(0)1465 861 638

Comments Please take the time to help improve this book by emailing us any constructive comments you have on its contents.

Any mistakes, omissions or suggests will be processed and where necessary the text will be updated.

Any minor/medium updates will be made available for free to those who have already purchased this ebook.

email: [email protected]

Page 7: Volume 2 - digital- · PDF fileHands On AGK2 BASIC Volume 2 Alistair Stewart Digital Skills Milton Barr Ayrshire KA26 9TY UK   tel: +44(0)1465 861 638

The Previous Text

What went BeforeBook (Volume 1)

This is the second volume of the Hands On AGK2 BASIC text.

In the previous book we started with the very fundamentals of programming and travelled through the basics of control structures, arrays and functions. We also looked at various aspects of games programming covering images, sprites, animation, multimedia and using input devices.

Along the way we developed a core structure for all our programs and built a library of useful user-defied functions. And, of course, we programmed a few games!

Syntax Diagrams

When describing the structure of an AGK2 statement or function call we made use of syntax diagrams such as that shown below.

■ Terms within the orange-coloured capsules must be included exactly as shown.

■ Terms in the green boxes signify variable names or fixed values the exact value of which are dependent on the programmer.

■ Items within square brackets are optional and may be omitted.

■ Items within braces offer a choice of structure (one option per row).

A description of what each programmer-defined value represents will be included beneath the syntax diagram.

Some syntax diagrams begin with the term integer, float or string to signify the type of value returned by a function:

Program Structure

For simple one-play games we developed a set of functions to be called which resulted in the following program structure:

// Project: project name // Created: date created

//*** Include required library files ***#include “../Function Library/Name of library file”

SetObjectShapeCapsule objidwidth height depth

vecid

GetObject3DPhysicsFriction objid�oat

Page 8: Volume 2 - digital- · PDF fileHands On AGK2 BASIC Volume 2 Alistair Stewart Digital Skills Milton Barr Ayrshire KA26 9TY UK   tel: +44(0)1465 861 638

//*** User-defined types ***type GameType main data elements of the program endtype

//*** Global variables ***global g as GameType

//***************************************//*** Main program ***//***************************************InitialiseScreen(width,height,”Title”, background colour, orientations allowed) ShowSplashScreen(“name of image file”) LoadResources() HideSplashScreen(seconds before hide) InitialiseGameVariables()CreateInitialLayout()do in = GetUserInput() HandleUSerInput(in) HandleOther() Sync()loop //***************************************//*** Main Functions ***//***************************************Functions defined here

The code required by the functions InitialiseScreen(), ShowSplashScreen() and HideSplashScreen() is defined within a library file (see below) since their logic is the same for every program.

The other functions named in the main program need to be coded within the Main Functions area of the code since the logic these execute will differ from app to app.

Libraries

Several library files were developed in the earlier volume. The libraries can be downloaded from this book’s resources ZIP file. You’ll find the relevant file at AGK2_2/Resources/Ch00/Function Library. This should be installed as a sub-folder off your main AGK2 working folder.

Details of the functions containing in the library (as we’ll as the GUI library functions created in Chapter 4 of this book) are given in the PDF file UDLibs.pdf which can be found in the resources ZIP file under AGK2_2/Resources/Ch00/UDLibs.pdf.

Text Style

In this text code is shown in blue monospaced type:in = GetUserInput() HandleUSerInput(in)HandleOther()Sync()

as is any reference to AGK2-defined terms with the descriptive paragraphs.

Function names are always shown with terminating parentheses to distinguish them

Page 9: Volume 2 - digital- · PDF fileHands On AGK2 BASIC Volume 2 Alistair Stewart Digital Skills Milton Barr Ayrshire KA26 9TY UK   tel: +44(0)1465 861 638

from variable names. AGK2 function names are in blue monospaced type while user-defined function names are shown in italics.

Important terms, when used for the first time are shown in bold.

Lines of code which, because of space restrictions, have had to be spread over two or more lines, start subsequent lines with the symbol – this symbol is not part of the code.

This text is designed primarily as a tutorial. As such many Activities build on work that has been carried out on previous pages, so jumping straight in to a specific section may sometimes make for a confusing read!

Page 10: Volume 2 - digital- · PDF fileHands On AGK2 BASIC Volume 2 Alistair Stewart Digital Skills Milton Barr Ayrshire KA26 9TY UK   tel: +44(0)1465 861 638

Contents

TweeningSprite Tweening ................................................................................................2

Introduction ...............................................................................................2Sprite Tween Commands .........................................................................2Summary ..................................................................................................12

Text and Character Tweening .......................................................................14Introduction .............................................................................................14Text Tween Commands ..........................................................................14Character Tween Command Set ...........................................................19Summary ..................................................................................................25

Custom Tweening ..........................................................................................26Introduction .............................................................................................26Custom Tween Commands ....................................................................26Summary ..................................................................................................32

Chaining Tweens ............................................................................................33Introduction .............................................................................................33Tween Chaining Commands .................................................................33Summary ..................................................................................................38

Solutions ..........................................................................................................39

SkeletonsSkeletons ..........................................................................................................42

Introduction .............................................................................................42Animation Construction ........................................................................432D Skeleton Commands .........................................................................45Manipulating Bones ................................................................................54Summary ..................................................................................................59

Solutions ..........................................................................................................61

Date and TimeDate and Time ................................................................................................68

Introduction .............................................................................................68Current Date and Time Statements.......................................................68Unix Date and Time Statements ............................................................71Summary ..................................................................................................73

User-Defined Date Functions .......................................................................75Day of the Week .......................................................................................75

Solutions ..........................................................................................................81

Page 11: Volume 2 - digital- · PDF fileHands On AGK2 BASIC Volume 2 Alistair Stewart Digital Skills Milton Barr Ayrshire KA26 9TY UK   tel: +44(0)1465 861 638

Creating GUI ControlsCreating GUI Controls ..................................................................................84

Introduction .............................................................................................84Buttons ......................................................................................................84Dialog Boxes .............................................................................................95Checkboxes .............................................................................................105Radio Buttons .........................................................................................117Frames .....................................................................................................132Scissor Commands ................................................................................133Back to the Frame Widget ....................................................................134PopUp Menus .........................................................................................156Numeric Keypads ..................................................................................158

Solutions ........................................................................................................164

MemblocksAccessing Memory .......................................................................................184

Introduction ...........................................................................................184Memblock Commands .........................................................................185Storing Characters and Strings in a Memory Block .........................192Memory Blocks and Files .....................................................................195Summary ................................................................................................199

Handling Multiple Memblocks ..................................................................201Introduction ...........................................................................................201The List Data Structure - Design .........................................................203The List Data Structure - Implementation .........................................204Memblocks and List ..............................................................................209Using Lists in a Game Environment ...................................................211

Memory Blocks For Images ........................................................................217Introduction ...........................................................................................217Memory Block Image Statements ........................................................217Mapping a Pixel to a Memory Block ...................................................219Modifying an Image’s Data ...................................................................220Creating Images from Scratch .............................................................222Discovering the Colour of a Screen Pixel ...........................................224Summary ................................................................................................226

Memblocks for Sound .................................................................................228Introduction ...........................................................................................228Memory Block Sound Commands ......................................................228

Solutions ........................................................................................................232

Mandelbrot ImagesCreating a Mandelbrot Image .....................................................................236

Page 12: Volume 2 - digital- · PDF fileHands On AGK2 BASIC Volume 2 Alistair Stewart Digital Skills Milton Barr Ayrshire KA26 9TY UK   tel: +44(0)1465 861 638

Introduction ...........................................................................................236Producing the Program ........................................................................238Zooming In ............................................................................................243Bugs .........................................................................................................246Shortcomings .........................................................................................247

Solutions ........................................................................................................248

2D PhysicsSprite Physics - 1 ..........................................................................................254

Introduction ...........................................................................................254Basic 2D Physic Statements ..................................................................254Physics Collisions ..................................................................................271Physics Sprite Bounding Shapes ..........................................................278Summary ................................................................................................284

World Physics ...............................................................................................286Introduction ...........................................................................................286General Statements ................................................................................286Attractive/Repulsive Forces ..................................................................290Summary ................................................................................................294

Sprite Physics - 2 ..........................................................................................295Contacts ..................................................................................................295Physics Groups and Categories ............................................................300Physics Ray Casting ...............................................................................306Summary ................................................................................................311

Physics Efficiency and Debugging .............................................................312Introduction ...........................................................................................3122D Physics Efficiency and Debug Commands ..................................312Summary ................................................................................................314

Solutions ........................................................................................................315

2D Physics - JointsJoints ..............................................................................................................322

Introduction ...........................................................................................322Joint Statements .....................................................................................322Summary ................................................................................................353

Solutions ........................................................................................................355

3D Graphics: The BasicsConcepts and Terminology.........................................................................360

Introduction ...........................................................................................360Modelling Ideas and Terminology ......................................................364Summary ................................................................................................374

Quaternion Rotation....................................................................................376

Page 13: Volume 2 - digital- · PDF fileHands On AGK2 BASIC Volume 2 Alistair Stewart Digital Skills Milton Barr Ayrshire KA26 9TY UK   tel: +44(0)1465 861 638

Creating a First 3D App ..............................................................................378Introduction ...........................................................................................3783D Commands .......................................................................................378Summary ................................................................................................381

Solutions ........................................................................................................382

3D Graphics: ObjectsObject Creation and Modification .............................................................384

Creating Primitives................................................................................384Object Appearance ................................................................................391Transforming Objects ...........................................................................404Mapping Objects in 3D Space ..............................................................423Quaternion-Based Object Commands ...............................................428Summary ................................................................................................430

Object Tweening ..........................................................................................433Introduction ...........................................................................................433Object Tweening Commands ............................................................433Summary ................................................................................................440

Solutions ........................................................................................................441

3D - Cameras and LightsCameras .........................................................................................................448

Introduction ...........................................................................................448Camera-Related Statements .................................................................448Creating a Simple Camera Controller ................................................457Mapping 3D Space to and from the Screen........................................460Using Camera Commands to Create First Person Perspective .......466Billboarding ............................................................................................471Quaternion-Based Camera Commands .............................................472Camera Tweening ..................................................................................473Summary ................................................................................................481

Lights .............................................................................................................483Introduction ...........................................................................................483Directional Light....................................................................................483Ambient Light ........................................................................................485Point Lights ............................................................................................486Object Reflectivity .................................................................................488Summary ................................................................................................491

Solutions ........................................................................................................493

Solitaire - The Board GameSolitaire ..........................................................................................................500

Introduction ...........................................................................................500

Page 14: Volume 2 - digital- · PDF fileHands On AGK2 BASIC Volume 2 Alistair Stewart Digital Skills Milton Barr Ayrshire KA26 9TY UK   tel: +44(0)1465 861 638

Implementing the Game .......................................................................500Multi-Platform Considerations ...........................................................519

Solutions ........................................................................................................525

3D Advanced ModelsMulti-Mesh Models .....................................................................................544

Introduction ...........................................................................................544Mesh Commands...................................................................................544Meshes and Memblocks ........................................................................551Summary ................................................................................................561

Parent/Child Models ....................................................................................563Introduction ...........................................................................................563Parent/Child Commands .....................................................................563Summary ................................................................................................565

Bones and Animated Models ....................................................................566Introduction ...........................................................................................566Bone and Animation Commands .......................................................566Bone Commands ...................................................................................572Quaternion-Related Bone Commands ...............................................580Summary ................................................................................................581

Solutions ........................................................................................................584

3D - ExtrasFog ..................................................................................................................588

Introduction ...........................................................................................588Fog Commands ......................................................................................588Summary ................................................................................................591

Sky Boxes .......................................................................................................592Introduction ...........................................................................................592Skybox Commands ...............................................................................592Summary ................................................................................................595

Terrain ...........................................................................................................596Introduction ...........................................................................................596Terrain Commands ...............................................................................597Summary ................................................................................................602

3D Vectors .....................................................................................................603Introduction ...........................................................................................6033D Vector Commands ..........................................................................603Summary ................................................................................................609

Ray and Sphere Casts ...................................................................................610Introduction ...........................................................................................6103D Ray Cast Commands ......................................................................611Detecting Collisions ..............................................................................614

Page 15: Volume 2 - digital- · PDF fileHands On AGK2 BASIC Volume 2 Alistair Stewart Digital Skills Milton Barr Ayrshire KA26 9TY UK   tel: +44(0)1465 861 638

Summary ................................................................................................625Shadows .........................................................................................................627

Introduction ...........................................................................................627Shadow Commands ..............................................................................627Summary ................................................................................................634

3D Particles ...................................................................................................635Introduction ...........................................................................................6353D Particle Commands.........................................................................635Summary ................................................................................................648

Shaders...........................................................................................................650Introduction ...........................................................................................650Shaders and 3D Objects ........................................................................650Shaders and the Quad Plane ................................................................659Shaders and Sprites ................................................................................663Summary ................................................................................................664

Solutions ........................................................................................................666

Basic 3D Physics3D Physics .....................................................................................................672

Introduction ...........................................................................................6723D World Commands ...........................................................................672Basic Object Commands ......................................................................673Collision Shape Commands .................................................................677Movement-Related Commands ...........................................................684Summary ................................................................................................697

Collision Handling .......................................................................................700Introduction ...........................................................................................700Collision Commands ............................................................................700Summary ................................................................................................706

3D Physics Ray Casting ...............................................................................707Introduction ...........................................................................................707Ray Trace Commands ...........................................................................707Summary ................................................................................................713

Support Material for this Chapter ..............................................................715Collision Groups and Masks (GroupAndMask3D.exe) .....................715

Solutions ........................................................................................................716

3D Physics: Joints, Rag Doll, and Character ControllersJoints ..............................................................................................................720

Introduction ...........................................................................................7203D Joint Commands .............................................................................720Summary ................................................................................................742

Ragdoll Physics .............................................................................................744

Page 16: Volume 2 - digital- · PDF fileHands On AGK2 BASIC Volume 2 Alistair Stewart Digital Skills Milton Barr Ayrshire KA26 9TY UK   tel: +44(0)1465 861 638

Introduction ...........................................................................................744 Ragdoll Commands ..............................................................................744Summary ................................................................................................753

Character Controllers ..................................................................................755Introduction ...........................................................................................755Controller Commands ..........................................................................755Summary ................................................................................................769

Solutions ........................................................................................................771

Using a Lan Multiplayer Games .......................................................................................776

Introduction ...........................................................................................776Networking Basics .................................................................................776The Host and its Clients ........................................................................777Setting Up and Managing the Network ..............................................778Creating a Network Function Library ................................................793Sending Messages ..................................................................................795Host and Client Code Differences .......................................................797Using Local Variables ............................................................................803Network Broadcasts ..............................................................................812Network Timing ....................................................................................814Summary ................................................................................................815

Sockets ...........................................................................................................818Introduction ...........................................................................................818Socket Commands .................................................................................818Using Sockets .........................................................................................822Summary ................................................................................................826

Solutions ........................................................................................................827

Accessing a ServerHypertext Transfer Protocol .......................................................................830

Introduction ...........................................................................................830HTTP Statements ..................................................................................830HTTP Methods ......................................................................................845Security ...................................................................................................845Summary ................................................................................................846

Solutions ........................................................................................................848

A Multi-Player GameTic Tac Toe ....................................................................................................850

Introduction ...........................................................................................850Implementing the Game .......................................................................850

Solutions ........................................................................................................859

Page 17: Volume 2 - digital- · PDF fileHands On AGK2 BASIC Volume 2 Alistair Stewart Digital Skills Milton Barr Ayrshire KA26 9TY UK   tel: +44(0)1465 861 638

Game Artificial IntelligenceArtificial Intelligence ...................................................................................864

An Overview ..........................................................................................864Gomoku .........................................................................................................865

Introduction ...........................................................................................865Implementing the Game .......................................................................865Game AI - Position Weighting.............................................................878Scanning the Lines ................................................................................884Calculating Weights ..............................................................................889Further Improvements ..........................................................................901

Solutions ........................................................................................................902

Page 18: Volume 2 - digital- · PDF fileHands On AGK2 BASIC Volume 2 Alistair Stewart Digital Skills Milton Barr Ayrshire KA26 9TY UK   tel: +44(0)1465 861 638

Hands On AGK2 BASIC Vol 2: Creating GUI Controls 83

In this Chapter:

T Creating a Button Control

T Creating a Modal Dialog Box

T Creating a Checkbox Control

T Creating a Radio Button Control

T Creating a Frame Control

T Creating a Pop-Up Menu

T Creating a Numeric Keypad

Creating GUI Controls

Page 19: Volume 2 - digital- · PDF fileHands On AGK2 BASIC Volume 2 Alistair Stewart Digital Skills Milton Barr Ayrshire KA26 9TY UK   tel: +44(0)1465 861 638

84 Hands On AGK2 BASIC Vol 2: Creating GUI Controls

Creating GUI Controls

IntroductionWhile AGK2 does offer buttons and edit boxes, there is little else in the way of graphical user interface (GUI) elements (often known as widgets).

Even though they may not be required for most games, there are times when it would be useful to have such widgets as checkboxes, radio buttons and dialog boxes.

Although it is not practical to create a full set of controls in a book of this nature, we will create a range of controls (each with a minimum set of associated functions) which should give us enough experience to create any others we might need in future projects.

ButtonsAGK2’s virtual buttons are fine for most apps but sometimes rather limiting since we can have no more than 12 and the buttons themselves are square shaped.

In this, our first widget, we’ll describe the complete process from design to implementation and testing; for later widgets, we’ll be more brief.

Description

Our button will be created using a three-framed animated sprite. The first frame will be displayed when no mouse pointer is over its position; the second will appear when the pointer moves over the button; and the third will appear while the button is pressed.

We’ll allow three options for the image being used:

a) The button is created from a user-supplied image which includes text.

b) The button is created from a user-supplied image with text added separately.

c) The button is created from a default image of a white background with text added separately.

Examples of user-defined images and a default image are shown in FIG-4.1.

When creating a button image, the three frames must be stacked vertically as shown in the sample above.

FIG-4.1 Image-Based and Default Buttons

User-de�ned imagewhich includes text

User-de�ned imageto which text mustbe added

Default white imagewith user-speci�edtext

Page 20: Volume 2 - digital- · PDF fileHands On AGK2 BASIC Volume 2 Alistair Stewart Digital Skills Milton Barr Ayrshire KA26 9TY UK   tel: +44(0)1465 861 638

Hands On AGK2 BASIC Vol 2: Creating GUI Controls 85

Data

To begin implementing our Button widget, we need to consider what information we’ll need to store about individual buttons. In fact, we need surprisingly little. We’ll need to store the ID of the image used in the button (even if its the computer-generated image) and the ID of the sprite used to display that image. We'll also need to record the current state of the button (mouse not over, mouse over, mouse over and pressed).

Assuming we’ll want to be able to delete buttons, we’re going to need to make use of a deleted indicator, for, as we will soon see, we cannot easily physically delete the data associated with a button.

So our code for the data associated with a single button becomes:type ButtonType img as integer //ID of image used spr as integer //ID of sprite used state as integer //Button state (1,2,3) deleted as integer //(0: exists, 1:deleted)endtype

But, of course, most programs will need more than one button, so we’ll also need an array of our ButtonType structure where we can store details of every button:

global GUIButtons as ButtonType[0]

Notice that the array has been created with only a single element (cell zero – which we won’t be using). We’ll grow the array each time a button is added. And although this is not an efficient way to increase the size of an array, it has the advantage of keeping things simple.

In AGK2, every resource we create, such as images, sprites and text, is assigned an ID. We’ll use this same approach for all our widgets, including buttons. In this case, the ID will be the subscript of the cell in which a button’s details are stored. FIG-4.2 demonstrates the idea.

Functions

When creating the functions of a widget, we have to second-guess what other programs are likely to want that widget to do and, using this guess, create all the necessary functions. Luckily, we have the existing AGK2 functions for elements such as sprites and text resources to help guide us with what is likely to be required.

Another advantage of looking at the functions associated with existing AGK2

FIG-4.2 Button Data Management

When a button is created, its detailsare added to the GUIButtons array.

The subscript of the cell to which thedetails were added becomes the ID of the button.

New button ID is 1

GUIButtons

0

1

GUIButtons

0

1

Detailsadded here Button ID

is subscriptCell 0

unused

Page 21: Volume 2 - digital- · PDF fileHands On AGK2 BASIC Volume 2 Alistair Stewart Digital Skills Milton Barr Ayrshire KA26 9TY UK   tel: +44(0)1465 861 638

86 Hands On AGK2 BASIC Vol 2: Creating GUI Controls

resources is that we can make use of similarly structured function names in our own code, and therefore add to the chances that we might remember the names that we’ve used when making use of our GUI library in the weeks and months to come. Below is a list of the few functions we’ll put in place for our Button widget:

CreateGUIButton() This function creates the button and returns the ID assigned to it. It makes use of the specified image file, but if none is supplied, it will create its own default image showing specified text.

HandleGUIButton() This function modifies and returns the current state of a button. The displayed frame depends on the mouse pointer not being over the button (frame 1 showing); the mouse pointer being over the button (frame 2) or the mouse button pressed over the button (frame 3). The returned value is 1 if the button is pressed, else zero.

SetGUIButtonSize() This function resizes an existing button.

SetGUIButtonPosition() This function repositions an existing button.

DeleteGUIButton() This function sets the deleted field of the specified button and deletes the associated image and sprite. It returns 1 if the button was deleted, otherwise zero is returned.

SetGUIButtonDepth() This function sets the button to a specified screen depth.

There is one final function, BuildDefaultGUIButton(), which is used to create the default button image used when no button image is specified or when text needs to be added to the underlying image.

With the help of mini-specs and program code, we’ll examine each of the functions in more detail

CreateGUIButton()

Mini-spec:

FUNCTION NAME : CreateGUIButton PARAMETERS In : x : real y : real w : real h : real image : string legend: string Out : id : integer PRE-CONDITION : None DESCRIPTION : Createsathree-framebuttonspriteusingthefile image. If image is an empty string a default image is created.

Page 22: Volume 2 - digital- · PDF fileHands On AGK2 BASIC Volume 2 Alistair Stewart Digital Skills Milton Barr Ayrshire KA26 9TY UK   tel: +44(0)1465 861 638

Hands On AGK2 BASIC Vol 2: Creating GUI Controls 87

Function logic: Add a new cell to the GUIButtons array Set the button’s ID to the subscript of the new cell IFnolegendhasbeenspecifiedTHEN Load the image ELSE Create a image showing text in legend ENDIF Load the image into a sprite Convert the sprite to a three-frame animation Setthespritetoshowthefirstframe Set sprite size to w by h Set sprite position to (x,y) Set state to mouse not over (1) Set the sprite details to indicate not deleted Return ID assigned to the button

Function code:

FUNCTION NAME : CreateGUIButton (continued) DESCRIPTION : The button image is overlaid by the text given in legend. The displayed image has its top-left corner at position (x,y) and has the dimensions w width by h height. The three frames of any image used are assumed to be in a vertical stack.

//*** Creates a button at (x,y) dimensions (w by h) ***//*** Uses image/default image and overlays legend *** function CreateGUIButton(x as float, y as float, w as float, h as float, image as string, legend as string) //*** Add cell to button list *** GUIButtons.length = GUIButtons.length+1 //*** Last position in array is new button’s ID *** id = GUIButtons.length //*** If no text, load image, else build button image *** if legend = “” GUIButtons[id].img = LoadImage(image) else result = BuildDefaultGUIButton(w,h,image,legend) GUIButtons[id].img = result endif //*** Load image into sprite *** GUIButtons[id].spr = CreateSprite(GUIButtons[id].img) //*** Convert to an animated sprite 3 frames)*** SetSpriteAnimation(GUIButtons[id].spr, GetImageWidth( GUIButtons[id].img),GetImageHeight(GUIButtons[id].img)/3,3) //*** Show first frame *** SetSpriteFrame(GUIButtons[id].spr,1) //*** Size sprite *** SetSpriteSize(GUIButtons[id].spr,w,h) //*** Position Sprite *** SetSpritePosition(GUIButtons[id].spr,x,y) //*** Mouse not over *** GUIButtons[id].state = 1 //*** Button not deleted *** GUIButtons[id].deleted = 0endfunction id

Page 23: Volume 2 - digital- · PDF fileHands On AGK2 BASIC Volume 2 Alistair Stewart Digital Skills Milton Barr Ayrshire KA26 9TY UK   tel: +44(0)1465 861 638

88 Hands On AGK2 BASIC Vol 2: Creating GUI Controls

HandleGUIButton()

Mini-spec:

Function logic: IFinvalidIDorbuttondeletedTHEN return 0 ENDIF IFmouseoverbuttonTHEN IFinstate1THEN Change to state 2 ENDIF IFmousebuttonjustpressedANDinstate2THEN Change to state 3 ENDIF IFmousebuttonreleasedANDinstate3 Set to state 2 Set result to 1 ENDIF ELSE Set to state 1 ENDIF Show appropriate button frame Return result

Function code:

FUNCTION NAME : HandleGUIButton PARAMETERS In : id : integer Out : result : integer PRE-CONDITION : id is a valid button ID DESCRIPTION : Changes the button’s displayed frame depending on the state of the mouse pointer and button. Frame 1 is displayed when the mouse pointer is not over the button. Frame 2 is displayed when the mouse pointer is over the button. Frame 3 is displayed when the mouse pointer is over the button and the mouse left button is pressed. result is set to 1 if button pressed, else 0.

//*** Changes the buttons visual according to the position of ***//*** the mouse pointer and the mouse left button ***function HandleGUIButton(id as integer) //*** If invalid button ID, exit *** if id < 1 or id > GUIButtons.length exitfunction 0 //*** If button deleted, exit *** elseif GUIButtons[id].deleted = 1 exitfunction 0 endif //*** Assume button not pressed *** result = 0 //*** If pointer over button ... if GetSpriteHit(GetPointerX(),GetPointerY())=GUIButtons[id].spr //*** If in state 1, go to state 2 if GUIButtons[id].state = 1 GUIButtons[id].state = 2 endif

Page 24: Volume 2 - digital- · PDF fileHands On AGK2 BASIC Volume 2 Alistair Stewart Digital Skills Milton Barr Ayrshire KA26 9TY UK   tel: +44(0)1465 861 638

Hands On AGK2 BASIC Vol 2: Creating GUI Controls 89

SetGUIButtonSize()

Mini-spec:

The function uses the following logic: IFIDinvalidTHEN Return 0 ENDIF Set button’s dimensions to w by h Return 1

Function code:

//*** If pointerPressed and in state 2, go to state 3 *** if GetPointerPressed() and GUIButtons[id].state = 2 GUIButtons[id].state = 3 endif //*** IF mouse released and in state 3 THEN *** if GetPointerReleased() and GUIButtons[id].state = 3 //*** Change to state 2 and return 1 *** GUIButtons[id].state = 2 result = 1 endif else // mouse not over,set to state 1 GUIButtons[id].state = 1 endif //*** Set sprite to correct frame *** SetSpriteFrame(GUIButtons[id].spr,GUIButtons[id].state)endfunction result

FUNCTION NAME : SetGUIButtonSize PARAMETERS In : id : integer w : real h : real Out : result : integer PRE-CONDITION : id is a valid button ID DESCRIPTION : Resizes button with ID id, to w width by h height. result is set to 1 if the operation is successful, otherwise result is set to zero.

//*** Resizes button. Returns 1 if successful *** function SetGUIButtonSize(id as integer, w as float, h as float) //*** If id invalid, exit *** if id < 1 or id > GUIButtons.length exitfunction 0 elseif GUIButtons[id].deleted = 1 exitfunction 0 endif //*** resize button *** SetSpriteSize(GUIButtons[id].spr,w,h)endfunction 1

Page 25: Volume 2 - digital- · PDF fileHands On AGK2 BASIC Volume 2 Alistair Stewart Digital Skills Milton Barr Ayrshire KA26 9TY UK   tel: +44(0)1465 861 638

90 Hands On AGK2 BASIC Vol 2: Creating GUI Controls

SetGUIButtonPosition()

Mini-spec:

Function logic: IFIDinvalidTHEN Return 0 ENDIF Set button’s position to (x,y) Return 1

Function code:

DeleteGUIButton()

Mini-spec:

Function logic: IFinvalidIDTHEN return 0 ENDIF Mark the button as deleted Delete the button’s image Delete the button’s sprite Return 1

FUNCTION NAME : SetGUIButtonPosition PARAMETERS In : id : integer x : real y : real Out : result : integer PRE-CONDITION : id is a valid button ID DESCRIPTION : Repositions button with ID id, placing the top- left corner at (x,y). result is set to 1 if the operation is successful, otherwise result is set to zero.

//*** Repositions button. Returns 1 if successful ***function SetGUIButtonPosition(id as integer, x as float, y as float) //*** If id invalid, exit *** if id < 1 or id > GUIButtons.length exitfunction 0 elseif GUIButtons[id].deleted = 1 exitfunction 0 endif //*** resize button *** SetSpritePosition(GUIButtons[id].spr,x,y)endfunction 1

FUNCTION NAME : DeleteGUIButton PARAMETERS In : id : integer Out : result : integer PRE-CONDITION : id is a valid button ID DESCRIPTION : Marks the button whose ID is id as deleted. Deletes the sprite and image associated with the button.

Page 26: Volume 2 - digital- · PDF fileHands On AGK2 BASIC Volume 2 Alistair Stewart Digital Skills Milton Barr Ayrshire KA26 9TY UK   tel: +44(0)1465 861 638

Hands On AGK2 BASIC Vol 2: Creating GUI Controls 91

Function code:

SetGUIButtonDepth()

Mini-Spec:

Function Logic:IFIDORlayerinvalidTHEN Return 0 ENDIF Set button’s sprite to depth layer Return 1

Function code:

//*** Marks button entry in GUIButtons as deleted ***//*** and deletes visual elements *** function DeleteGUIButton(id as integer) //*** If invalid button ID, exit 0 (fail)*** if id < 1 or id > GUIButtons.length exitfunction 0 endif //*** Set to deleted *** GUIButtons[id].deleted = 1 //*** Delete visual elements *** DeleteSprite(GUIButtons[id].spr) DeleteImage(GUIButtons[id].img) //*** Return 1 (success) *** result = 1endfunction result

FUNCTION NAME : SetGUIButtonDepth PARAMETERS In : id : integer layer : integer Out : result : integer PRE-CONDITION : id is a valid button ID AND layer is a valid depth DESCRIPTION : Repositions button with ID id to depth layer. result is set to 1 if the operation is successful, otherwise result is set to zero.

//*** Sets button’s depth *** function SetGUIButtonDepth(id as integer, layer as integer) //*** If id invalid, exit *** if id < 1 or id > GUIButtons.length exitfunction 0 elseif GUIButtons[id].deleted = 1 exitfunction 0 endif //*** If layer invalid, exit *** if layer < 0 or layer > 10000 exitfunction 0 endif //*** Adjust button’s depth *** SetSpriteDepth(GUIButtons[id].spr, layer)endfunction 1

Page 27: Volume 2 - digital- · PDF fileHands On AGK2 BASIC Volume 2 Alistair Stewart Digital Skills Milton Barr Ayrshire KA26 9TY UK   tel: +44(0)1465 861 638

92 Hands On AGK2 BASIC Vol 2: Creating GUI Controls

BuildDefaultGUIButton()

Unlike the previous six functions, this one is not meant to be called directly by a programmer wishing to make use of a button in their app. Instead, it is merely a helper function for CreateGUIButton(), allowing it to construct visuals for the three frames of a button which has not been supplied with a named image file.

Mini-spec:

Function logic: Create a sprite w by 3h in size Create text resource containing txt string Resizetexttofitbuttonwidth Position grey, centre-aligned txt text in top third of sprite Create duplicate text resource Position black, centre aligned txt text resource in middle third of sprite Create duplicate text resource Position red, centre-aligned txt text resource in bottom third of sprite Rendervisualstobackbuffer Createimagefromcontentsofbackbuffer Delete the sprite and text resources Return ID of image created

Function code:

FUNCTION NAME : BuildDefaultGUIButton PARAMETERS In : w : real h : real image : string legend: string Out : result : integer PRE-CONDITION : None DESCRIPTION : Ifanimageisspecifieditisloaded,otherwiseagrey background image is produced. The button image is w wide and 3h high. Each third of the image represents a frame. legend is overlaid on top of each frame and text size adjustedifnecessarytofitthebutton. Each frame shows the text in a different colour (grey, black, yellow). result is set to the ID of the image created.

//*** Creates a default image for button ***//*** Used when no button image supplied *** function BuildDefaultGUIButton(w as float, h as float, image as string, legend as string) //*** If image specified *** if image <> “” //*** Create sprite using image *** tempimg = LoadImage(image) tempspr = CreateSprite(tempimg) //*** Determine height for three frames *** if h = -1 SetSpriteSize(tempspr,w,h) else SetSpriteSize(tempspr,w,h*3)

Page 28: Volume 2 - digital- · PDF fileHands On AGK2 BASIC Volume 2 Alistair Stewart Digital Skills Milton Barr Ayrshire KA26 9TY UK   tel: +44(0)1465 861 638

Hands On AGK2 BASIC Vol 2: Creating GUI Controls 93

Testing the Code

Now we need to test our routines. To do that we’ll create three buttons (one from an image which includes text, one from a background button image to which text is added separately, and finally using the default image with text added).

Pressing the left-most button (button 1) will reposition button 3, pressing button 2 will resize button 3 and pressing button 3 will cause the button to delete itself!

This requires the following main program:

endif h = GetSpriteHeight(tempspr) else //*** Else create blank image sprite *** tempspr = CreateSprite(0) if h = -1 h = w*0.5*3 else h = h*3 endif SetSpriteSize(tempspr,w,h) endif //*** Position text on each frame area *** //** First text ** txt1 = CreateText(legend) //*** Resize to fit button *** while GetTextTotalWidth(txt1) > w*0.95 SetTextSize(txt1, GetTextSize(txt1)*0.95) endwhile //*** Centre align *** SetTextAlignment(txt1,1) //*** Grey translucent text *** SetTextColor(txt1,200,200,200,200) //*** Positon text in first button area *** SetTextPosition(txt1,w/2,h*0.165-GetTextTotalHeight(txt1)/2) //*** Second copy of text (black) over second button area *** txt2 = CreateText(legend) SetTextSize(txt2,GetTextSize(txt1)) SetTextAlignment(txt2,1) SetTextColor(txt2,0,0,0,255) SetTextPosition(txt2,w/2, h*0.5-GetTextTotalHeight(txt1)/2) //*** Third copy of text (yellow) over second button area *** txt3 = CreateText(legend) SetTextSize(txt3,GetTextSize(txt1)) SetTextAlignment(txt3,1) SetTextColor(txt3, 255,255,0,255) SetTextPosition(txt3,w/2, h*0.83-GetTextTotalHeight(txt1)/2) //***Grab buttons states as single image *** Render() result = GetImage(0,0,w,h) ClearScreen() //*** Delete elements used *** DeleteSprite(tempspr) DeleteImage(tempimg) DeleteText(txt1) DeleteText(txt2) DeleteText(txt3)endfunction result

Page 29: Volume 2 - digital- · PDF fileHands On AGK2 BASIC Volume 2 Alistair Stewart Digital Skills Milton Barr Ayrshire KA26 9TY UK   tel: +44(0)1465 861 638

94 Hands On AGK2 BASIC Vol 2: Creating GUI Controls

// Project: TestGUIButton// Created: 2016-11-10

//*** Include required library files ***#include "../Function Library/CoreLibrary.agc"

type GameType but as integer[3]endtype

global g as GameType

//***************************************//*** Main program ***//***************************************InitialiseScreen(1024,768,"", 0xA8A8A8,%1111)CreateInitialLayout()do in = GetUserInput() HandleUserInput(in) Sync()loop

//***************************************//*** Functions ***//***************************************function CreateInitialLayout() g.but[1] = CreateGUIButton(10,10,10,8,"okbut.png","") g.but[2] = CreateGUIButton(32,10,10,8,"blankbut.png","NO") g.but[3] = CreateGUIButton(54,10,10,8,"","YES")endfunction

function GetUserInput() result = 0 //*** Return order of any button pressed *** for c = 1 to 3 if HandleGUIButton(g.but[c]) result = c endif next cendfunction result

function HandleUserInput(in as integer) select in case 0: // no button pressed exitfunction endcase case 1: // first button pressed //*** Reposition third *** SetGUIButtonPosition(g.but[3],54,20) endcase case 2: // second button ppressed //*** Resize third *** SetGUIButtonSize(g.but[3],12,-1) endcase case 3: // third button pressed //*** Delete third *** DeleteGUIButton(g.but[3]) endcase endselectendfunction

Page 30: Volume 2 - digital- · PDF fileHands On AGK2 BASIC Volume 2 Alistair Stewart Digital Skills Milton Barr Ayrshire KA26 9TY UK   tel: +44(0)1465 861 638

Hands On AGK2 BASIC Vol 2: Creating GUI Controls 95

Dialog BoxesA dialog box is a small window designed to supply the user with information and await a response. A modal dialog box is one which forces the user to respond to it before the app in which it appears can continue.

Description

Our dialog box will be modal. In effect this means that there is no possibility of more than one dialog box appearing in a game at any one moment.

Our approach to coding the dialog box will be in some ways similar to that of the button. We will allow the programmer to supply an image for the dialog box or create a default one with a text heading. We will also allow the programmer to add a selected set of buttons to the dialog box.

Any button added will be assumed to have an associated image if the supplied button name ends “but”, otherwise a default button will be created.

Examples of an image-based dialog box and a default one are shown in FIG-4.3.

� Remember to copy the required files into the media folder.

Activity 4.1 Start a new project called TestGUIButton and implement the code given above, also adding the GUIButton functions coded in the previous pages. Check that the program buttons change correctly as the mouse pointer moves over them and that button 3 is affected when any of the three buttons is pressed.

Activity 4.2 Add a new file to the project calling it GUILibrary.agc and copy the code relating to the definition of GUIButtonType and the associated functions to that file. Add comments at the start of the file describing briefly what each of the three main GUIButton functions do. Remove the GUIButton code from the TestGUIButton project and replace it with an include instruction for the new library file, then check that the program still runs as before.

FIG-4.3 Image-Based and Default Dialog Boxes

Image-based Dialog Box and Button Default Dialog Box and Button