Team LRN
Game Developer’s Guide to Cybiko™
Ernest Pazera
Wordware Publishing, Inc.
Team LRN
Library of Congress C...
117 downloads
1233 Views
13MB Size
Report
This content was uploaded by our users and we assume good faith they have the permission to share this book. If you own the copyright to this book and it is wrongfully on our website, we offer a simple DMCA procedure to remove your content from our site. Start by pressing the button below!
Report copyright / DMCA form
Team LRN
Game Developer’s Guide to Cybiko™
Ernest Pazera
Wordware Publishing, Inc.
Team LRN
Library of Congress Cataloging-in-Publication Data Pazera, Ernest. Game developer’s guide to Cybiko / by Ernest Pazera. p. cm. ISBN 1-55622-854-6 (pbk.) 1. Computer games--Programming. I. Title. QA76.76.C672 P39 2001 794.8'167765--dc21
2001046843 CIP
© 2002, Wordware Publishing, Inc. All Rights Reserved 2320 Los Rios Boulevard Plano, Texas 75074
No part of this book may be reproduced in any form or by any means without permission in writing from Wordware Publishing, Inc. Printed in the United States of America
ISBN 1-55622-854-6 10 9 8 7 6 5 4 3 2 1 0110
Cybiko is a trademark of Cybiko, Inc. Other product names mentioned are used for identification purposes only and may be trademarks of their respective companies.
All inquiries for volume purchases of this book should be addressed to Wordware Publishing, Inc., at the above address. Telephone inquiries may be made by calling: (972) 423-0090
Team LRN
Contents Foreword . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xvi Chapter 1 Welcome . . . . . . . . . . . Overview . . . . . . . . . . . . . . . . . . . . About Me . . . . . . . . . . . . . . . . . . . . About You . . . . . . . . . . . . . . . . . . . . Things You Will Need. . . . . . . . . . . . . . Configuring the Software. . . . . . . . . . . . CyberLoad . . . . . . . . . . . . . . . . . . Cybiko SDK . . . . . . . . . . . . . . . . . Text Editor . . . . . . . . . . . . . . . . . . Test CyberLoad and the CyConsole . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
1 1 1 1 2 2 2 3 3 3
Chapter 2 Your First Cybiko Application. . . . . . . . . . . . . . . . . . . . . . 4 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 A Simple Cybiko “Hello, world!” . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 Res . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 Src . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 Trying Out CyBk2_1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8 A Real Cybiko “Hello, world” Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 Res . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 Root.inf . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 Root.spl . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 Root.ico . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 Intro.pic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 Src Subfolder . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12 Filer.list . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12 CyBk2_2’s Src Directory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16 Chapter 3 Introduction to Message Handling Overview. . . . . . . . . . . . . . . . . . . . . . . . Message Queues . . . . . . . . . . . . . . . . . . . Initializing the Module . . . . . . . . . . . . . . . . Grabbing Messages . . . . . . . . . . . . . . . . . . cWinApp_get_message . . . . . . . . . . . . . . Message_delete . . . . . . . . . . . . . . . . . . cWinApp_peek_message . . . . . . . . . . . . . Contents of a Message . . . . . . . . . . . . . . . . Common Messages . . . . . . . . . . . . . . . . . . Keyboard Messages . . . . . . . . . . . . . . . . Default Message Processing . . . . . . . . . . . . . A Basic Message Pump . . . . . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . .
17 17 17 18 19 19 21 21 23 24 25 27 28
iii
Team LRN
Contents
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29 Chapter 4 Resources and Development Tools . Overview. . . . . . . . . . . . . . . . . . . . . . . . . Resources Defined . . . . . . . . . . . . . . . . . . . Text Resources . . . . . . . . . . . . . . . . . . . . Picture Resources . . . . . . . . . . . . . . . . . . Music Resources . . . . . . . . . . . . . . . . . . . Other Binary Resources . . . . . . . . . . . . . . . Special Resources (Root.*, Intro.pic, and 0.help) . . . Root.ico . . . . . . . . . . . . . . . . . . . . . . . . Root.inf . . . . . . . . . . . . . . . . . . . . . . . . Root.spl . . . . . . . . . . . . . . . . . . . . . . . . Intro.pic . . . . . . . . . . . . . . . . . . . . . . . . 0.help . . . . . . . . . . . . . . . . . . . . . . . . . Compiling Resources with Makeres.bat . . . . . . . . 2mus . . . . . . . . . . . . . . . . . . . . . . . . . mus2txt . . . . . . . . . . . . . . . . . . . . . . . . t2mf . . . . . . . . . . . . . . . . . . . . . . . . . . 2pic . . . . . . . . . . . . . . . . . . . . . . . . . . PicView . . . . . . . . . . . . . . . . . . . . . . . . Third-Party Resource Conversion Tools . . . . . . . . Fontmake.exe. . . . . . . . . . . . . . . . . . . . . Bseqmake.exe . . . . . . . . . . . . . . . . . . . . Adding Resources Using Filer.list . . . . . . . . . . . Makefiles. . . . . . . . . . . . . . . . . . . . . . . . . Summary . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
30 30 30 31 31 31 31 32 32 32 33 33 33 34 35 35 35 36 37 38 38 39 41 42 44
Chapter 5 The Cybiko Way of Object-Oriented Programming Overview. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . OOP (Object-Oriented Programming) . . . . . . . . . . . . . . . . . . Encapsulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Polymorphism . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Constructors and Destructors . . . . . . . . . . . . . . . . . . . . . . Constructors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Dynamic Allocation Constructors . . . . . . . . . . . . . . . . . . . Destructors. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . .
45 45 45 46 47 49 49 49 50 51 52
Chapter 6 Program Frameworks Overview. . . . . . . . . . . . . . . . Quick-Running Framework . . . . . . Event-Driven Framework . . . . . . Idle-Loop Framework . . . . . . . . . Real-Time Framework . . . . . . . . Dialog-Based Framework . . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . .
53 53 53 54 62 63 64
. . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . .
iv
Team LRN
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . .
. . . . . . .
Contents
Multi-threaded Framework . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65 Chapter 7 Messages . . . . . Overview. . . . . . . . . . . . . . Event-Driven Operating Systems The Message Class . . . . . . . . Types of Messages . . . . . . . . Retrieving Messages . . . . . . . Handling Messages . . . . . . . . Keyboard Messages . . . . . . MSG_KEYDOWN . . . . . MSG_CHARTYPED . . . . MSG_KEYUP . . . . . . . . The KeyParam Struct. . . . Focus Messages . . . . . . . . Quit and Shut Up . . . . . . . . Sending Messages. . . . . . . . . User-Defined Messages . . . . . Summary . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
66 66 66 68 69 69 70 71 71 71 72 72 73 74 74 75 75
Chapter 8 Basic Graphics . . . . . . . . Overview. . . . . . . . . . . . . . . . . . . . . TGraph, Graphics, and DisplayGraphics . . . . Creating a DisplayGraphics Object . . . . . Clearing the Screen . . . . . . . . . . . . . . . color_t . . . . . . . . . . . . . . . . . . . . DisplayGraphics_fill_screen. . . . . . . . . DisplayGraphics_show. . . . . . . . . . . . Screen Filling Example . . . . . . . . . . . Plotting Pixels . . . . . . . . . . . . . . . . . . Pixel Plotting Example . . . . . . . . . . . Retrieving Pixels . . . . . . . . . . . . . . . . Drawing Lines . . . . . . . . . . . . . . . . . . Setting the Current Color . . . . . . . . . . Horizontal Lines . . . . . . . . . . . . . . . Vertical Lines. . . . . . . . . . . . . . . . . Free-Form Lines . . . . . . . . . . . . . . . Random Lines Example . . . . . . . . . . . Rectangles . . . . . . . . . . . . . . . . . . . . Framed Rectangles. . . . . . . . . . . . . . Filled Rectangles . . . . . . . . . . . . . . . rect_t . . . . . . . . . . . . . . . . . . . . . The rect_t Functions. . . . . . . . . . . . . rect_set . . . . . . . . . . . . . . . . . . rect_and . . . . . . . . . . . . . . . . . . rect_or . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . .
77 77 77 78 78 78 79 79 80 82 82 84 85 85 85 86 86 87 88 88 89 90 90 90 91 91
v
Team LRN
Contents
Rectangle Drawing Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93 Chapter 9 Bitmap and Font Basics . . . . . . . . . . . . . . . . . . . . . . . . 94 Overview. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94 Bitmap Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94 Creating a Bitmap Resource. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95 Bitmap_ctor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95 Bitmap_ctor_Ex1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95 Bitmap_ctor_Ex2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96 Bitmap_ctor_Ex3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96 Drawing a Bitmap on Screen . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97 Draw Modes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98 Cleaning Up after a Bitmap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100 Bitmap Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100 Font Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103 Global Fonts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103 Setting the Current Font . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104 Writing Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105 Formatting Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105 Font Demo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111 Chapter 10 Sounds, Music, and Vibration Overview . . . . . . . . . . . . . . . . . . . . . Beeps . . . . . . . . . . . . . . . . . . . . . . . Tone Generation . . . . . . . . . . . . . . . . . Raw Tone Generation . . . . . . . . . . . . . . MSequence . . . . . . . . . . . . . . . . . . . . MSequence_ctor . . . . . . . . . . . . . . . MSequence_dtor . . . . . . . . . . . . . . . Playing and Stopping . . . . . . . . . . . . . Information Functions . . . . . . . . . . . . Muting . . . . . . . . . . . . . . . . . . . . . MSequence Example . . . . . . . . . . . . . The Voice of Sanity . . . . . . . . . . . . . . Enabling and Disabling Tone Generation . . . . is_tone_playing . . . . . . . . . . . . . . . . get_sounds_enabled and enable_sounds . . Key Clicks . . . . . . . . . . . . . . . . . . . . Enabling and Disabling Key Clicks . . . . . Advanced Disables . . . . . . . . . . . . . . Kinds of Clicks . . . . . . . . . . . . . . . . Vibration . . . . . . . . . . . . . . . . . . . . . Summary . . . . . . . . . . . . . . . . . . . . .
vi
Team LRN
. . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . .
112 112 112 113 114 115 115 116 116 117 118 118 118 118 119 119 120 120 120 121 122 122
Contents
Chapter 11 Basic Dialogs . . . . . . . . . . . Overview . . . . . . . . . . . . . . . . . . . . . . . Cybiko Dialogs . . . . . . . . . . . . . . . . . . . . cDialog_ctor. . . . . . . . . . . . . . . . . . . . cDialog Styles . . . . . . . . . . . . . . . . . cDialog_dtor. . . . . . . . . . . . . . . . . . . . cDialog_ShowModal . . . . . . . . . . . . . . . cDialog_GetEditText and cDialog_SetEditText. Simple Message Box. . . . . . . . . . . . . . . . . The Cybiko Way . . . . . . . . . . . . . . . . . My Way . . . . . . . . . . . . . . . . . . . . . . Simple Input Box. . . . . . . . . . . . . . . . . . . The Cybiko Way . . . . . . . . . . . . . . . . . My Way . . . . . . . . . . . . . . . . . . . . . . Interface Standards . . . . . . . . . . . . . . . . . Summary . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
123 123 123 123 124 127 127 128 129 129 131 132 132 133 135 135
Chapter 12 Some Miscellaneous Basics . . . Overview . . . . . . . . . . . . . . . . . . . . . . . Input Files . . . . . . . . . . . . . . . . . . . . . . Opening a Resource . . . . . . . . . . . . . . . Opening an External File. . . . . . . . . . . . . Destroying an Input or FileInput Object . . . . Retrieving Information about an Input Stream . Reading from an Input Stream . . . . . . . . . . Maneuvering through an Input Stream . . . . . The Wait Icon. . . . . . . . . . . . . . . . . . . . . Summary . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
136 136 136 137 137 138 138 139 139 140 141
Chapter 13 A Simple Cybiko Game . . . . Overview . . . . . . . . . . . . . . . . . . . . . Game Theory. . . . . . . . . . . . . . . . . . . What is a Game? . . . . . . . . . . . . . . . What Purpose Do Games Serve? . . . . . . Where Do Games Come From? . . . . . . . . . Game Design . . . . . . . . . . . . . . . . . . . Game Analysis Case Study: Pac-Man . . . . Fleshing Out the Design . . . . . . . . . . . Simulation . . . . . . . . . . . . . . . . . . . Making the Game . . . . . . . . . . . . . . . . Faux Functions . . . . . . . . . . . . . . . . Extending the MainCharacter Class. . . . . The Monster Class . . . . . . . . . . . . . . Base Class for Monster and MainCharacter Deriving MainCharacter from Character . . MainCharacter Implementation . . . . . . . Monster Implementation . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
142 142 142 142 143 144 144 144 147 147 148 150 151 152 153 154 155 156
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
vii
Team LRN
Contents
Levels. . . . . . . . . . . . . Dots and Power Pellets . . . Where Do We Go from Here Summary . . . . . . . . . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
156 161 163 163
Chapter 14 Intermediate Graphics . . . . . Overview . . . . . . . . . . . . . . . . . . . . . . Writing to Bitmaps . . . . . . . . . . . . . . . . . Constructing/Destructing a Graphics Object . Setting and Getting the Bitmap . . . . . . . . Attributes of a Graphics Object . . . . . . . . Font. . . . . . . . . . . . . . . . . . . . . . Color . . . . . . . . . . . . . . . . . . . . . Draw Mode. . . . . . . . . . . . . . . . . . Background Color . . . . . . . . . . . . . . Clipping Rectangle. . . . . . . . . . . . . . Drawing Primitives . . . . . . . . . . . . . . . Text Metrics . . . . . . . . . . . . . . . . . . Drawing Bitmaps and Text . . . . . . . . . . . Other Functions. . . . . . . . . . . . . . . . . Graphics_put_background. . . . . . . . . . Graphics_fill_screen . . . . . . . . . . . . . Graphics_scroll . . . . . . . . . . . . . . . More Functions to Come... . . . . . . . . . . . Draw Modes . . . . . . . . . . . . . . . . . . . . Bitmap Draw Modes . . . . . . . . . . . . . . . . The BitmapSequence Class . . . . . . . . . . . . Construction and Destruction . . . . . . . . . Retrieving Information . . . . . . . . . . . . . The Font Class . . . . . . . . . . . . . . . . . . . Construction and Destruction . . . . . . . . . Attributes of a Font Object . . . . . . . . . . . Name . . . . . . . . . . . . . . . . . . . . . Fixed-Width and Proportional Fonts . . . . Spacing . . . . . . . . . . . . . . . . . . . . Bitmap Array. . . . . . . . . . . . . . . . . Size . . . . . . . . . . . . . . . . . . . . . . Image Offsets . . . . . . . . . . . . . . . . Text Metrics . . . . . . . . . . . . . . . . . . Loading a Font Object from an Input Stream . Splitting Strings. . . . . . . . . . . . . . . . . Summary . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
164 164 164 164 165 166 166 166 166 167 167 168 168 169 169 169 169 170 170 170 173 174 174 175 175 176 176 176 176 177 177 177 178 179 179 179 180
Chapter 15 Form and Menu Basics . . . . Overview . . . . . . . . . . . . . . . . . . . . . Structure of the UI System . . . . . . . . . . . cObject . . . . . . . . . . . . . . . . . . . .
. . . .
. . . .
. . . .
. . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . . . . . . . . . . . . . . . . . . . . .
181 181 181 182
. . . .
viii
Team LRN
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
Contents
cClip . . . . . . . . . . . . . . . . . . . . cEngine. . . . . . . . . . . . . . . . . cCustomForm . . . . . . . . . . . . . cList . . . . . . . . . . . . . . . . . . Making a cCustomForm . . . . . . . . . . . Adding Controls to the Form. . . . . . . Creating Simple Objects for Your Form . cBevel . . . . . . . . . . . . . . . . . cBitmap . . . . . . . . . . . . . . . . cBox . . . . . . . . . . . . . . . . . . cText . . . . . . . . . . . . . . . . . . Interacting with Controls. . . . . . . . . cButton . . . . . . . . . . . . . . . . . cEdit . . . . . . . . . . . . . . . . . . cList and cItem . . . . . . . . . . . . . . cList . . . . . . . . . . . . . . . . . . cItem . . . . . . . . . . . . . . . . . . Custom Form Behavior . . . . . . . . . . . cObject and cClip Common Functionality . cObject Common Functionality . . . . . cClip Common Functionality . . . . . . . Summary . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . .
182 182 183 183 183 184 185 185 186 187 188 188 189 190 193 193 193 196 201 201 202 203
Chapter 16 More Miscellaneous . . . . . . . . . . . . . . . . Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Output and FileOutput . . . . . . . . . . . . . . . . . . . . . . . . . Creating Output and FileOutput Objects . . . . . . . . . . . . . Destroying Output and FileOutput Objects . . . . . . . . . . . . Getting Information about Output/FileOutput Objects. . . . . . Writing to a File or Resource . . . . . . . . . . . . . . . . . . . Navigating through a File . . . . . . . . . . . . . . . . . . . . . About Writing to Resources . . . . . . . . . . . . . . . . . . . . Buffers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Creating and Destroying Buffers . . . . . . . . . . . . . . . . . Retrieving Information . . . . . . . . . . . . . . . . . . . . . . . Locking and Unlocking Buffers . . . . . . . . . . . . . . . . . . Storing and Reading Information . . . . . . . . . . . . . . . . . Buffer Sizing . . . . . . . . . . . . . . . . . . . . . . . . . . . . Buffers and Messages . . . . . . . . . . . . . . . . . . . . . . . DirectKeyboard . . . . . . . . . . . . . . . . . . . . . . . . . . . . Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
204 204 204 204 205 205 206 206 207 207 207 208 208 209 210 210 211 212
Chapter 17 Advanced Cybiko Graphics . Overview . . . . . . . . . . . . . . . . . . . . . Direct Memory Access . . . . . . . . . . . . . Pixel Formats . . . . . . . . . . . . . . . . . Monochrome Pixel Format . . . . . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . .
213 213 213 214 214
. . . . .
. . . . . . . . . . . . . . . . . . . . . .
. . . . .
. . . . . . . . . . . . . . . . . . . . . .
. . . . .
. . . . . . . . . . . . . . . . . . . . . .
. . . . .
. . . . . . . . . . . . . . . . . . . . . .
. . . . .
. . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . .
ix
Team LRN
Contents
Four-Color Pixel Format . . . . . . . . Using Direct Memory Access for Drawing Signed Values . . . . . . . . . . . . . . . . Pixel Alignment. . . . . . . . . . . . . . . Four-Color Transparency. . . . . . . . . . cy3d . . . . . . . . . . . . . . . . . . . . . . . Fundamental Types Used in cy3d . . . . . fixed_t . . . . . . . . . . . . . . . . . . point_t and pos_t . . . . . . . . . . . . raster_t . . . . . . . . . . . . . . . . . . How cy3d Works . . . . . . . . . . . . . . Textures . . . . . . . . . . . . . . . . . Looking Around . . . . . . . . . . . . . Moving Around . . . . . . . . . . . . . Sprites . . . . . . . . . . . . . . . . . . Collision Detection . . . . . . . . . . . Summary . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
216 217 218 218 219 222 222 222 225 226 227 227 231 236 238 240 241
. . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . .
242 242 242 243 245
Chapter 19 Wireless Communication . . . Overview . . . . . . . . . . . . . . . . . . . . . CyIDs . . . . . . . . . . . . . . . . . . . . . . . Finding Another CyID . . . . . . . . . . . . . . Launching the Application or Game . . . . . . Running a Game Session . . . . . . . . . . . . Summary . . . . . . . . . . . . . . . . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
250 250 250 251 253 254 255
Chapter 20 File System. . . . . . . . . . . . . . Overview . . . . . . . . . . . . . . . . . . . . . . . . The File and FileFind Class . . . . . . . . . . . . . . The File Class. . . . . . . . . . . . . . . . . . . . The FileFind Class . . . . . . . . . . . . . . . . . Archive Class. . . . . . . . . . . . . . . . . . . . . . Creating and Destroying an Archive Object . . . Retrieving Information about an Archive Object . Connecting with an Archive Object’s Resources . Opening a Resource for Input . . . . . . . . . . Opening a Resource for Output . . . . . . . . . Other Devices . . . . . . . . . . . . . . . . . . . . . Getting Information about a Device . . . . . . . . mFileName Functions . . . . . . . . . . . . . . . Summary . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
256 256 256 257 258 260 260 260 261 262 262 262 263 264 264
Chapter 18 Advanced Forms Overview . . . . . . . . . . . . . Form Class Template . . . . . . Skeleton Code . . . . . . . . . . The proc Function . . . . . . . .
. . . . .
. . . . .
x
Team LRN
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
Contents
Chapter 21 Modules and Processes . . . Overview . . . . . . . . . . . . . . . . . . . . . module_t . . . . . . . . . . . . . . . . . . . . . cWinApp (m_process member of module_t) SystemThread . . . . . . . . . . . . . . . Thread . . . . . . . . . . . . . . . . . . . Process . . . . . . . . . . . . . . . . . . . AppGeneric . . . . . . . . . . . . . . . . cWinApp . . . . . . . . . . . . . . . . . . Summary . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
265 265 265 266 266 268 268 269 271 272
Chapter 22 Odds and Ends . . . . . . . . . . . . Overview . . . . . . . . . . . . . . . . . . . . . . . . . imin and imax. . . . . . . . . . . . . . . . . . . . . . . Memory Management . . . . . . . . . . . . . . . . . . Allocation, Reallocation, and Deallocation . . . . . Running on Empty . . . . . . . . . . . . . . . . . . Memory Manipulation . . . . . . . . . . . . . . . . Other Memory Management Functions . . . . . . . Random Numbers . . . . . . . . . . . . . . . . . . . . Randomizer Seeds . . . . . . . . . . . . . . . . . . Score and score_t . . . . . . . . . . . . . . . . . . . . score_t. . . . . . . . . . . . . . . . . . . . . . . . . score.inf . . . . . . . . . . . . . . . . . . . . . . . . Score class . . . . . . . . . . . . . . . . . . . . . . Retrieving Information about a Score Object . . Reading and Writing to and from a Score Object . String Manipulation . . . . . . . . . . . . . . . . . . . Copying Strings . . . . . . . . . . . . . . . . . . . . Measuring Strings . . . . . . . . . . . . . . . . . . Concatenation . . . . . . . . . . . . . . . . . . . . . Comparison . . . . . . . . . . . . . . . . . . . . . . Searching for Characters and Strings . . . . . . . . Alpha and Omega . . . . . . . . . . . . . . . . . . . The Match Game . . . . . . . . . . . . . . . . . . . White Space . . . . . . . . . . . . . . . . . . . . . . Time . . . . . . . . . . . . . . . . . . . . . . . . . . . clock_t . . . . . . . . . . . . . . . . . . . . . . . . . time_t . . . . . . . . . . . . . . . . . . . . . . . . . Timer Resolution . . . . . . . . . . . . . . . . . . . Trusted Time . . . . . . . . . . . . . . . . . . . . . The Time Struct . . . . . . . . . . . . . . . . . . . Encoding and Decoding . . . . . . . . . . . . . . The Real-Time Clock . . . . . . . . . . . . . . . Alarm On, Alarm Off . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
273 273 273 274 274 275 275 276 276 277 278 278 278 279 279 280 280 281 281 281 282 283 283 284 284 284 285 285 285 286 286 286 287 287
xi
Team LRN
Contents
Chapter 23 Libs and Classes . . . . . . . . . . . . . . . . . Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Utility Libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . . DynAlloc.h . . . . . . . . . . . . . . . . . . . . . . . . . . . . . coord.h/c. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . IO_Ext.h/c. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string_ext.h/c . . . . . . . . . . . . . . . . . . . . . . . . . . . . Dialogs and Forms . . . . . . . . . . . . . . . . . . . . . . . . . StdDlg.h/c . . . . . . . . . . . . . . . . . . . . . . . . . . . . MenuForm.h/c . . . . . . . . . . . . . . . . . . . . . . . . . . FileListForm.h/c . . . . . . . . . . . . . . . . . . . . . . . . . Utility Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Image, Animation Sequence, and Animation Sequence Set . . . Image . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . AniSeq . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . AniSeqSet . . . . . . . . . . . . . . . . . . . . . . . . . . . . Linked Lists and Nodes . . . . . . . . . . . . . . . . . . . . . . Nodes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Containers . . . . . . . . . . . . . . . . . . . . . . . . . . . . Miscellaneous Classes . . . . . . . . . . . . . . . . . . . . . . . Cursor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . View . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Parser . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Games. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
289 289 289 289 290 291 291 295 295 296 297 297 297 298 299 300 301 301 303 305 305 306 308 308 309
Appendix A The C Programming Language. Overview . . . . . . . . . . . . . . . . . . . . . . What is Programming?. . . . . . . . . . . . . . . How Do Computing Devices Work? . . . . . . . How Does a Program Work? . . . . . . . . . . . How is Memory/Storage Structured?. . . . . . . What is Cybiko C? . . . . . . . . . . . . . . . . . How Do I Program in Cybiko C? . . . . . . . . . The main Function . . . . . . . . . . . . . . . int main() . . . . . . . . . . . . . . . . . . . The Curly Braces . . . . . . . . . . . . . . return 0; . . . . . . . . . . . . . . . . . . . A Cybiko main Function . . . . . . . . . . . Built-in Types and Variables . . . . . . . . . . int and Binary Representations . . . . . . . Other Built-in Types. . . . . . . . . . . . . Assigning Values to Variables . . . . . . . . Operators . . . . . . . . . . . . . . . . . . Arrays . . . . . . . . . . . . . . . . . . . . Pointers . . . . . . . . . . . . . . . . . . . Structures . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
310 310 310 310 312 312 313 313 313 314 314 314 314 315 315 317 318 319 334 337 341
xii
Team LRN
. . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Contents
Loops . . . . . . . . . . . . . . . . Switches . . . . . . . . . . . . . . typedef . . . . . . . . . . . . . . . Functions. . . . . . . . . . . . . . #define . . . . . . . . . . . . . . . #ifndef, #ifdef, #else, and #endif #include . . . . . . . . . . . . . . Summary . . . . . . . . . . . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
343 345 347 348 351 353 354 355
Appendix B File Format for Pic Files . . . Overview . . . . . . . . . . . . . . . . . . . . . Contents of a Pic File . . . . . . . . . . . . . . File Header . . . . . . . . . . . . . . . . . . Bitmap Record . . . . . . . . . . . . . . . . Bitmap Record Header . . . . . . . . . . Bitmap Data . . . . . . . . . . . . . . . . Conversion from Image to Bitmap Record . . . Conversion from Binary Data to Image. . . . . Summary . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
356 356 356 356 357 357 358 358 364 366
Appendix C File Format—Fnt . Overview . . . . . . . . . . . . . Header . . . . . . . . . . . . . . Bitmap Records . . . . . . . . . Bitmap Data . . . . . . . . . . . Encoding a Monochrome Bitmap Summary . . . . . . . . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
367 367 367 368 368 368 371
Appendix D Cybiko Graphics Quick Reference . TGraph, Graphics, and DisplayGraphics . . . . . . . Constructors and Destructors . . . . . . . . . . . . Constructor and Destructor Function Details . . Drawing Primitives . . . . . . . . . . . . . . . . . . Drawing Primitives Function Details . . . . . . . Pixel Functions . . . . . . . . . . . . . . . . . Line Functions . . . . . . . . . . . . . . . . . . Framed Rectangle Functions . . . . . . . . . . Filled Rectangle Functions . . . . . . . . . . . Fill Screen Function . . . . . . . . . . . . . . . Context Attributes . . . . . . . . . . . . . . . . . . . Context Function Details. . . . . . . . . . . . . . Current Color Functions . . . . . . . . . . . . Drawing Mode Functions . . . . . . . . . . . . Background Color Function . . . . . . . . . . . Clipping Area Functions . . . . . . . . . . . . . Current Font Functions . . . . . . . . . . . . . Current Bitmap Functions . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
372 372 372 373 374 374 374 375 377 378 378 379 380 380 381 381 382 384 384
. . . . . . .
. . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
xiii
Team LRN
Contents
Page Functions. . . . . . . . . . . . . . . . . . . . . . . Writing Bitmaps, Characters, and Text . . . . . . . . . . . . . Bitmap, Character, and Text Drawing Function Details . . Bitmap and Character Drawing Functions . . . . . . . . String Drawing Functions . . . . . . . . . . . . . . . . . Text Metrics . . . . . . . . . . . . . . . . . . . . . . . . . . . Text Metrics Function Details . . . . . . . . . . . . . . . . Character Size Functions . . . . . . . . . . . . . . . . . String Size Functions . . . . . . . . . . . . . . . . . . . Page Operations . . . . . . . . . . . . . . . . . . . . . . . . . Page Operation Function Details . . . . . . . . . . . . . . Page Copying Functions . . . . . . . . . . . . . . . . . . Show Functions . . . . . . . . . . . . . . . . . . . . . . Miscellaneous Functions . . . . . . . . . . . . . . . . . . . . Miscellaneous Function Details . . . . . . . . . . . . . . . Other Functions Dealing with Drawing Graphics . . . . . . . Function Details . . . . . . . . . . . . . . . . . . . . . . . Types and Constants Associated with TGraph, Graphics, and DisplayGraphics Objects. . . . . . . . . . . . . . . . . . . . . color_t . . . . . . . . . . . . . . . . . . . . . . . . . . . . . drawmode_t . . . . . . . . . . . . . . . . . . . . . . . . . . rect_t . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rect_t Function Details . . . . . . . . . . . . . . . . . . Other Constants . . . . . . . . . . . . . . . . . . . . . . . Screen Constants . . . . . . . . . . . . . . . . . . . . . Rounded Rectangle Styles . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
385 386 386 386 387 388 389 389 390 391 391 391 392 393 393 395 395
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
397 397 397 397 398 399 399 400
Appendix E Cybiko Bitmap Quick Reference . . . . . . . . . . . . . . . . . . . Bitmap, BitmapSequence, and Font. . . . . . . . . . . . . . . . . . . . . . . . . . . . . Constructors and Destructors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Constructor and Destructor Details . . . . . . . . . . . . . . . . . . . . . . . . . . . Bitmap Constructors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . BitmapSequence/Font Constructors . . . . . . . . . . . . . . . . . . . . . . . . . Destructor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Bitmap Member Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Bitmap Member Function Details . . . . . . . . . . . . . . . . . . . . . . . . . . . . Loading and Storing Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Loading and Storing Function Details . . . . . . . . . . . . . . . . . . . . . . . . . . Attributes Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Attribute Function Details . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Character and String Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Character and String Function Details . . . . . . . . . . . . . . . . . . . . . . . . . Miscellaneous Functions (draw_lib) . . . . . . . . . . . . . . . . . . . . . . . . . . . . Constants and Variables Associated with Bitmaps, BitmapSequences, and Fonts . . . . Bitmap Mode Flags . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Built-in Font Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
401 401 401 402 402 403 404 404 404 406 406 406 407 410 411 412 413 413 413
xiv
Team LRN
Contents
Appendix F Cybiko UI Classes . cObject . . . . . . . . . . . . . . . cClip. . . . . . . . . . . . . . . . . cEngine . . . . . . . . . . . . . . . Controls. . . . . . . . . . . . . . . cBevel . . . . . . . . . . . . . . cProgressBar . . . . . . . . . . cBitmap . . . . . . . . . . . . . cBox . . . . . . . . . . . . . . . cButton . . . . . . . . . . . . . cEdit . . . . . . . . . . . . . . . cText . . . . . . . . . . . . . . . Forms and Dialogs . . . . . . . . . cList and cItem . . . . . . . . . . . cList . . . . . . . . . . . . . . . cItem and cSItem . . . . . . . . cXItem, cXStr, and cXByte . . . . Types and Enums . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
414 415 422 429 430 431 431 432 433 434 434 439 440 443 443 445 447 452
Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 455
xv
Team LRN
Foreword I’ve long considered myself a Windows game programmer. Although I started with Atari computers (back in the day), most of my game programming knowledge has been gained using Windows PCs. In recent years, however, I’ve found myself developing for the Pocket PC, Palm Pilot, and UNIX, and I now make my living developing for the Playstation 2, X-box, and GameCube. As chance would have it, I’m writing this on an Apple iBook laptop. It turns out that I’m not really a Windows game programmer after all; I’m simply a game programmer. I develop for the platform that offers the greatest opportunities to create games that interest me. Almost a year ago, I decided to try developing for the Cybiko, mainly because several of my associates were making games for it that I thought I could outdo. I came up with the basic design for a game—with a working title of BattleQuest—and set to coding. I quickly found that although Cybiko provides a software development kit specifically tailored to game development, it is poorly documented. Through experimentation, I was able to work out some of it on my own, but I eventually found myself turning again and again to a friend of mine who had already figured everything out. Who was that friend? Ernest Pazera. You have in your hands the only comprehensive guide to game programming on the Cybiko. Whether you’re new to game programming, or you’re adding a new platform to your repertoire, this book will provide you with the resources you need to begin making a name for yourself in a relatively new and untapped market. It will be well worth your effort to develop for the Cybiko. At the very least, it will give you experience in developing for a platform with a proprietary API and limited hardware resources. In addition, the number of Cybiko owners is growing rapidly. So far, there are few good third-party developers making Cybiko games. Accordingly, there is a big demand from Cybiko owners for better, richer games. Good things await those savvy developers who meet that demand. So, what are you waiting for? Dive on in and become a game programmer. Dave Astle Avalanche Software
xvi
Team LRN
Chapter 1
Welcome Overview Welcome to the first book on Cybiko development. This book was written from a game developer’s perspective (I am a game developer after all), and so you’ll notice that a lot of what I say brings to mind games and aspects of games. In this chapter, you will get to know me a little bit. It’s important for the reader to know the author, even if just a little. Also, you’ll learn what the book is about and what you need to get set up for Cybiko development.
About Me I am a 27-year-old programmer from Kenosha, WI. I’ve been programming for over 14 years, in a variety of languages, including dialects of BASIC, Pascal, C++, and C. Currently, I am considered primarily to be a Windows programmer, although lately it would appear that I have been primarily a Cybiko programmer. My methods of programming are intentionally simple and easy to understand. This is how my skills have developed over the years. I write what is easy for me to decipher, and hopefully easy for you to decipher.
About You You are interested in Cybiko development, and you are at least familiar with programming, although being an expert isn’t required. There is a sort of “refresher course” for C in Appendix A, but this book does not teach you how to program from scratch. At least a nominal amount of exposure to C will be helpful. If you don’t know anything about C, you’ll likely have a hard time. I suggest getting a good book on C if you don’t have one already.
1
Team LRN
2
Chapter 1: Welcome
Things You Will Need There are a number of things you will need in order to make full use of this book. First and foremost, you will need a Cybiko. Without one, you will not be able to run the programs. At the time of this writing, there is an emulator in the works, but I have no guarantee that it will be done by the time this book hits the shelves. Also, while emulators are nice, it is best to test things out on the real thing. Second, you will need a computer that can run the various applications needed to develop software. Not all platforms have a good set of tools for this. If you have Windows, you should be just fine. If you have Linux, you should be all right, too. I use Windows, so I write from the Windows perspective. Third, you need to install the necessary applications for Cybiko development. This means putting CyberLoad and the Cybiko SDK on your machine. I have included copies of these on the companion CD-ROM. When this book gets to the shelves, these applications may not be the most up-to-date versions, so you may want to check on http://www.cybiko.com for newer versions. Fourth, you will need an Internet connection. It is possible to get by without one, but in order to download applications from Cybiko, Inc., you need to connect to them through the Internet. Also, you will need an Internet connection to go to this book’s support site, http://www.cybikodev.com. By the time you purchase this book, there will be new information available on this site.
Configuring the Software There are two important pieces of software you will need, CyberLoad and the Cybiko SDK. Both of these can be found at www.cybiko.com, and I have included versions of these on the CD-ROM as well. NOTE: On the off chance that you’ve never used WinZip before, you simply copy the zip archive over onto your hard drive (I usually put them in a new folder I name MyProjects), turn off the read-only properties, right-click on the zip archive, and select “Extract to folder.... filename.” This will extract the archive into a new folder named filename, with all of the files located where they are supposed to be.
CyberLoad You can find CyberLoad on the CD-ROM under Tools, with the filename CyberloadSetup.exe. This is a Windows program that interfaces your computer to the Cybiko. You need it to transfer content from Cybiko, Inc., to your device.
Team LRN
Chapter 1: Welcome
Cybiko SDK The Cybiko SDK is a collection of tools used to create new software for the Cybiko. You can find the Windows and Linux versions on the CD-ROM under Tools. The Windows version is in Cybiko_SDK_2112_Std.exe, and the Linux version is in Cybiko_SDK_2.1.13.i386.rpm. Install the appropriate one.
Text Editor In order to view, edit, and create code for your programs, you will need some sort of text editor. You can get by with something like Notepad, but I suggest getting a tool made for writing code. UltraEdit is a good text editor. You can find it at http://www.ultraedit.com. It is shareware, and it does expire, but it’ll do the job. Personally, I use Microsoft Visual C++ 6.0, but then again, I’m usually a Windows programmer, so this is no surprise.
Test CyberLoad and the CyConsole Before doing anything else, plug your Cybiko into your machine, and test to make sure that CyberLoad works. If it doesn’t, look on www.cybiko.com for support. If that doesn’t help, call the Cybiko support line; it’s what they are paid to do. Also, be sure to test the CyConsole. The CyConsole is part of the SDK, and gives you a command-line interface on your computer to your Cybiko. If you have trouble, Cybiko should help you, or you can look on www.cybikodev.com for some of the common problems people have with the CyConsole. That’s it. You’re all set up. Now we can start with the fun stuff.
Team LRN
3
Chapter 2
Your First Cybiko Application Overview Ever since Kernigan and Ritchie created the C programming language, the tradition has been to make a “Hello, world!” program as your initial foray into programming in C. I’m going to respect this fine tradition, and to get you into programming for the Cybiko, you are going to make your own “Hello, world!” application, Cybiko style. The K&R Hello.C looks something like the code in Listing 2.1. Listing 2.1 Hello.C, K&R style /******************* Hello.C *******************/ #include <stdio.h> int main() { printf(“Hello, world!\n”); return(0); }
Hello.C is used as the very first program by teachers for a couple reasons. One, it contains all of the parts essential to larger programs (it has a main function and includes a header file). Two, it is easy to understand. All that Hello.C does is write “Hello, world!” and then quit. Unfortunately, if you were to look through the Inc folder of the Cybiko SDK, you would not find a file named stdio.h, and if you were to look through the Cybiko SDK help files you would see that there is no printf function anywhere. Therefore, the traditional Hello.C cannot be compiled and run on your Cybiko.
4
Team LRN
Chapter 2: Your First Cybiko Application
In addition, for an application or game to work on the Cybiko, there are a few extra files (resources) that must accompany it in order for you to see it in the application or game section. This chapter will get your feet wet (or at least slightly damp) in Cybiko programming.
A Simple Cybiko “Hello, world!” While there may not be a printf function, there is a cprintf function on the Cybiko. This function prints to the console, not to the Cybiko’s screen. Even though you won’t see anything on the Cybiko itself, the code in Listing 2.2 is pretty close to the original K&R Hello.C. Listing 2.2 Hello.C, Cybiko style /* ************************************* *CyBk2_1.C * *16FEB2001 * *Simple "Hello, world!" application ************************************* */ //Master Include file for entire Cybiko SDK #include "cywin.h" //main function long main(int argc, char* argv[], bool start) { //print to the console cprintf("Hello, world!"); //exit the program, and return zero return(0); }
This code is found on the CD, under Examples, in a file named CyBk2_1. Once you’ve copied the file, take a look at it. The folder CyBk2_1 should look something like Figure 2.1. NOTE: You will need WinZip to open some of the files on the CD. A copy of WinZip can be downloaded from www.winzip.com.
Team LRN
5
6
Chapter 2: Your First Cybiko Application
Figure 2.1: CyBk2_1 folder
You will see three subfolders, named Res, Src, and Tmp, and two files, Make.bat and Makefile. The Res subfolder contains any resources that are used by an application (I’ll show you more about resources later). The Src subfolder contains any source files (*.c and *.h) and any object files (*.o) that are part of the application. The Tmp subfolder is for temporary files created and used by the compiler, so don’t worry about it too much. The Make.bat file contains the commands shown in Listing 2.3. Listing 2.3 Make.bat path %CYBIKO_SDK%/bin vmake new –p2 %1
The makefile is shown in Listing 2.4. I don’t even like makefiles, and the one in Listing 2.4 is going to be the one we’ll use over and over, just changing the value of the NAME variable. Listing 2.4 Makefile NAME = CyBk2_1 OBJ = src/$(NAME).o RES = res/filer.list PP CC AS LN LD RM
= = = = = =
vcpp vcc1 vas vlink filer vrm
Team LRN
Chapter 2: Your First Cybiko Application
.SUFFIXES : .c all : $(NAME).app $(NAME).app : tmp/bytecode.bin $(RES) @echo building app archive... @$(LD) a $@ @res/filer.list tmp/bytecode.bin "$(CYBIKO_SDK)"/lib/main.e tmp/bytecode.bin : $(OBJ) @echo linking ... @$(LN) –o $@ src/*.o .c.o : @echo compiling $<... @$(PP) –I"$(CYBIKO_SDK)"/inc $< | $(CC) | $(AS) –O –o $@ src/$(NAME).o : src/$(NAME).c clean : @echo cleaning... @$(RM) –f tmp/*.* src/*.o $(NAME).app new : clean all
A makefile just contains a script that tells vmake what to do. If you are unfamiliar with makefiles, they’ll look like a bunch of gobbledegook. If you come from a UNIX programming background, you’re probably quite comfortable with makefiles, and I’ll leave exploring the features of the makefile script up to you. For those of you scratching your head and saying “Huh?”, don’t sweat it. I’m going to show you how to set up a project so that the only thing you need to change in the makefile is the first line.
Res The Res subfolder of CyBk2_1 contains another subfolder named Src, and a file named Filer.list. The Res/src folder contains a single file called Makeres.bat. The Filer.list file is blank, but for all but the simplest applications, it would contain a list of the resources used by the application, and there would be more files in the Res subfolder. Similarly, there would be source bitmaps for whatever pictures you were using in the Res/src subfolder, and Makeres.bat would contain code to convert a normal Windows bitmap to a Cybiko picture. There will be more on resources later.
Src The Src subfolder contains the C source files and the object files for your application (which you probably won’t be messing with). The CyBk2_1.C file contains the source shown in Listing 2.2. There is also CyBk2_1.o, which isn’t terribly important at the moment.
Team LRN
7
8
Chapter 2: Your First Cybiko Application
Trying Out CyBk2_1 Browse over to the CyBk2_1 folder, and double-click Make.bat. If all goes well, a DOS window will pop up and show you the progress of building the application, and CyBk2_1.app will appear in the CyBk2_1 folder. If things don’t go well, you probably need to reinstall the Cybiko SDK, or you just haven’t installed it. If it still doesn’t work, go to http://www.cybikodev.com, and check out the FAQ, where you can probably read how to fix the problem you are having. Once you have CyBk2_1.app built, hook up your Cybiko to the serial port, and start the console program. Make sure it connects to the proper COM port, and then drag CyBk2_1.app into the console. You’ll get a status bar showing the download process (it usually only takes about a second). Once you have done this, the console should look like Figure 2.2. Figure 2.2: Downloading an app to the Cybiko with the console
Next, run the application through the console by typing the name of the app into the input field at the bottom of the console’s window and then hitting Enter. The result should look like Figure 2.3.
Team LRN
Chapter 2: Your First Cybiko Application
Figure 2.3: Running an application from the console
And that’s all there is to our little “Hello, world!” program. I admit it isn’t much, but it’s at least a start. Now that we’ve got this, it’s time to take it to the next step, and make a program that you can actually see on the Cybiko.
A Real Cybiko “Hello, world” Program CyBk2_1 is fine and dandy, but you aren’t reading this to learn to write programs that can only be seen on the console. That was just the simplest program with an actual visible result that I could think of. Most of the time, you’ll only use the cprintf function if you are debugging an application or just want to be able to get a log file of a running application, so it’s still a handy thing to know. Now, it is time to make a real Cybiko application that responds to keyboard input, complete with an icon, a splash screen, and scrolling instructions. Also, it will show “Hello, world!” on the Cybiko display, and it will show up in the application list. Simply adding resources to the project does most of this. Go ahead and copy CyBk2_2 from the CD onto your hard drive. This file contains another set of subfolders similar to the CyBk2_1 file we used earlier. Before I get into the actual code for CyBk2_2, I want to show you the contents of the Res subfolder.
Team LRN
9
10
Chapter 2: Your First Cybiko Application
Res The Res subfolder for CyBk2_2 contains a number of files besides the Src subfolder and Filer.list. Also present are Root.inf, Root.spl, Root.ico, and Intro.pic. All of these files have special meaning to a Cybiko application.
Root.inf This is a special file that you must include in your applications in order for the Cybiko to show it on the desktop. It is a simple text file that contains information about the application. This crucial information is stored in ten lines. Each line has a particular meaning for the file manager, as shown in Listing 2.5. Listing 2.5 Format of Root.inf 01: 02: 03: 04: 05: 06: 07: 08: 09: 10:
Where the application will be shown, app, game, or root Name of the application, as shown on the desktop and in CyberLoad (blank) (blank) (blank) (blank) Name of .app archive Version of the application Version of CyOS required to run this application Copyright information for this application
CAUTION: You must leave lines three through six of Root.inf empty! Putting something in them will make your application not work!
If you open up CyBk2_2’s Root.inf in Notepad (or another simple text editor of your choice), you will see the information in Listing 2.6. Listing 2.6 CyBk2_2’s Root.inf 01: 02: 03: 04: 05: 06: 07: 08: 09: 10:
app CyBk2_2
CyBk2_2 1.0.0 1.2.56 Copyright (C) DTM Software 2001
Naturally, the numbers and colons aren’t there. I just put those in to more easily reference the line numbers. Line 01 contains the word “app.” This indicates to the Cybiko desktop that this program is an application, and should be listed when the Applications icon is selected by the user, just like the Phone Book program. Other values for line 01 include
Team LRN
Chapter 2: Your First Cybiko Application
11
“game,” which will list the application under “Games,” or “root” which will list the application at the highest level of the desktop. Line 02 contains the name you want to show underneath the icon in the desktop. Often, it is not the same as the name of the .app file. For example, a tic-tac-toe program might show up on the desktop as “Tic-Tac-Toe,” but the file is TicTacToe.app. This line also dictates how your application will show up in CyberLoad. Line 07 contains the name of the app archive, without the “.app” on the end. In the tic-tac-toe example above, line 07 would contain “TicTacToe.” Line 08 is the version number of your application. Put whatever version number you have for your app. Most of the time I just leave mine as 1.0.0, unless I really have a need to change it. Line 09 contains the version of CyOS required to run your application. It is difficult, if not impossible, to determine which prior versions of CyOS will run your application, so a good rule of thumb is to just put whatever the current version of CyOS is, and update this whenever you recompile the application and the CyOS version has changed. You can generally rely on Cybiko users to have the most current version of CyOS, since CyberLoad updates it automatically. Line 10 is your copyright information. My company is DTM Software, so I put it in. If you don’t have a company, you can either make one up or just put your name.
Root.spl The Root.spl file is just a simple text file, much like Root.inf. Unlike Root.inf, it doesn’t have any special format. This file just contains the text you want the users of your application to see when the application starts up, after either the icon moves into the corner or the intro picture is shown. Common things to include in Root.spl: name of the application, copyright information, basic instructions on program use, and a general description of the program. Third-party developers (that would be me and you) tend to also put an e-mail address for contacting the author and/or a web site where the user can download other games written by you and your friends.
Root.ico The Root.ico file contains a Cybiko format picture that will serve as the icon for your application on the desktop. The source for this image is in Res/src under the name Icon.bmp. The source image name is unimportant, but this file must be named Root.ico. The picture is 48 pixels wide and 47 pixels high.
Intro.pic This file is optional. It is the full screen picture that is shown while an application is loading up, and before Root.spl is shown as the picture scrolls up. The source for this image is located in Res/src under the name Intro.bmp. The picture is 160x100, taking up the entire screen.
Team LRN
12
Chapter 2: Your First Cybiko Application
If you opt not to have an Intro.pic, then there will be an animated sequence using Root.ico when the application is loading instead of showing Intro.pic on the screen.
Src Subfolder The Res/src subfolder contains three files, Intro.bmp (the source image for Intro.pic), Icon.bmp (the source image for Root.ico), and Makeres.bat. I’ve already covered what Intro.bmp and Icon.bmp are used for, so I’ll just cover Makeres.bat, which is shown in Listing 2.7. Listing 2.7 Makeres.bat path %CYBIKO_SDK%/bin 2pic ../root.ico icon.bmp 2pic ../intro.pic intro.bmp
This batch file is intended to be double-clicked in My Computer or Windows Explorer, and its task is to convert any of the source images or sounds in Res/src into the Cybiko format images in the Res folder. Since we only are converting images, we are only concerned with using 2pic.exe, which you can find in the Bin subfolder of the Cybiko SDK. Full documentation for using 2pic.exe can be found in the Cybiko SDK help files. Basically, any image you need to convert to the Cybiko format will have its own line calling 2pic in Makeres.bat, so any time you add a new image, you’ll want to add another line to Makeres.bat. Any time you modify any of the source images, you’ll want to run Makeres.bat, so that your resources are up to date.
Filer.list As I said earlier, Filer.list contains a list of all resources that are to be included in a project’s application archive. Back in CyBk2_1, this file was empty. Now that we have resources, we have to list them in Filer.list, so that when we run Make.bat, they will be included in the application. Listing 2.8 shows the contents of Filer.list. Listing 2.8 Filer.list res/root.ico res/root.inf res/root.spl res/intro.pic
NOTE: All of the resources have “res/” in front of them. This is because Filer.list is going to be accessed from one folder up, so the subfolder must precede the resource name.
It might seem overwhelming to throw all of this resource stuff at you at once, but it’s not as complicated as it may seem. You’ll get used to this resource management scheme in time.
Team LRN
Chapter 2: Your First Cybiko Application
CyBk2_2’s Src Directory We’re still only doing really simple applications, so there is only one source file for CyBk2_2, named (to no one’s surprise) CyBk2_2.C. It is shown in Listing 2.9. Listing 2.9 CyBk2_2.C /* ******************************************* *CyBk2_2.C * *16FEB2001 * *Cybiko style Hello World application ******************************************* */ //master include file for cybiko sdk #include "cywin.h" //global variables struct module_t main_module; bool exit_application;
//main module //exit application flag
//forward declarations for functions bool Prog_Init(); //initialize the program void Prog_Loop(); //idle loop for the program void Prog_Done(); //clean up for the program //main functions long main(int argc, char* argv[], bool start) { //declare local variable for message retrieval struct Message* ptr_message; //initialize the main module init_module(&main_module); //initialize the program exit_application=!Prog_Init(); //while program is still running while(!exit_application) { //check for a message ptr_message = cWinApp_get_message(main_module.m_process,1,1,MSG_USER); //if there is a message... if(ptr_message) { //...check what kind of message it is, and process it switch(ptr_message–>msgid)
Team LRN
13
14
Chapter 2: Your First Cybiko Application
{ case MSG_SHUTUP: //Processes system exit signal. case MSG_QUIT: exit_application = TRUE; break; case MSG_GOTFOCUS: //Redraws screen. break; case MSG_KEYDOWN: //Processes keyboard messages. if(Message_get_key_param(ptr_message)–>scancode == KEY_ESC) //escape key has been pressed { exit_application = TRUE; //set the exit flag break; } default: //Processes all unprocessed messages. cWinApp_defproc(main_module.m_process, ptr_message); } //delete the message Message_delete(ptr_message); } else { //no message, so execute an idle loop Prog_Loop(); }
} //while(!exit_application)
//clean up after the program Prog_Done(); //return 0, we're done return 0; } bool Prog_Init() { //initialization //return TRUE if program initialized, and FALSE if it did not return(TRUE); } void Prog_Loop() { //idle loop //fill the screen with white DisplayGraphics_fill_screen(main_module.m_gfx,CLR_WHITE);
Team LRN
Chapter 2: Your First Cybiko Application
15
//select font DisplayGraphics_set_font(main_module.m_gfx,cool_normal_font); //select color DisplayGraphics_set_color(main_module.m_gfx,CLR_BLACK); //write text DisplayGraphics_draw_text(main_module.m_gfx,"Hello, world!",0,0); //show the screen DisplayGraphics_show(main_module.m_gfx); } void Prog_Done() { //cleanup }
This only looks like a lot of code. It is the fundamental code to have a simple Cybiko application run, plus a few lines that will print “Hello, world!” on the screen. I will cover the details of what’s going on in the main function in Chapter 3, so don’t worry about it yet. These are the basic steps that this program is taking: 1.
Initialize the application (run Prog_Init).
2.
Check for a message.
3.
If there is a message, process it.
4.
If there is no message, run the idle loop (run Prog_Loop).
5.
Repeat steps 2-4 until the Esc key is pressed.
6.
Clean up the application and exit (run Prog_Done).
For this application, we are only concerned with the idle loop (the code within Prog_Loop), since that’s what does the drawing on the screen. These are the steps taken by Prog_Loop (all of the functions used in Prog_Loop are covered in greater detail in future chapters). 1.
Clear the screen to white.
2.
Set the current font.
3.
Set the current color.
4.
Draw the text.
5.
Show the screen.
As you might notice from the code, all of the screen drawing uses functions that start with DisplayGraphics, and pass main_module.m_gfx as the first parameter. This might seem a little strange right now, but most of Cybiko programming is like this. It is
Team LRN
16
Chapter 2: Your First Cybiko Application
object oriented, while being completely in C. (I’ll be clearing this all up in Chapter 5, once you’ve gotten a more solid footing in Cybiko programming.) For now, just build the application using Make.bat, and transfer it over to your Cybiko using the console. Reboot your Cybiko, either by typing “reboot” into the console program or just turning it off and back on again. Once the desktop shows up, go into Applications, and you should find CyBk2_2. Run it, and you will see the Intro.pic, the contents of Root.spl, and, after you hit a key, the words “Hello, world!” at the top of the screen. That’s it for the Cybiko-style “Hello, world!” program.
Summary In this chapter, I’ve kind of bogged you down with a lot of stuff, and I didn’t explain it as well as I could have. This is mainly because I wanted to put the detailed descriptions of things in their appropriate chapters, and not have two explanations for things or make you have to hunt down explanations for functions that logically belong in the same chapter.
Team LRN
Chapter 3
Introduction to Message Handling Overview If you have experience programming message-based operating systems, you should have no trouble with Cybiko message handling. It is very similar to Windows and other operating systems. If you’ve never programmed for a message-based operating system before (perhaps you used to program in DOS), messages might seem a little strange.
Message Queues In any operating system, there must be a way to gain information about what keys were pressed, what messages are coming from other devices, and so on. For the moment, I’m going to use keyboard presses as an example, since they are so common. In DOS, keyboard response was handled through interrupts by hardware. When a key was pressed, the hardware would interrupt whatever application was currently running and read information about what key was pressed, translate this information into a character code, and place it into a keyboard buffer, which the application would later read using a function like Inkey or getch. In the Windows environment, a similar thing happens, except that more than one application might be running at the same time. This leads to such concepts as the “active window” and the application with “keyboard focus.” The active window is the window with the highlighted title bar; all other applications have gray title bars. Only the active window receives keyboard messages. When a key is pressed, Windows sends a WM_KEYDOWN message to the active window, along with data saying which key was pressed. Then, if the key corresponds to a generated character (“A” or “/”) it will generate a WM_CHAR event, and send data corresponding to which character was generated. Not all keys generate character
17
Team LRN
18
Chapter 3: Introduction to Message Handling
data (for example, the Shift and Ctrl keys do not), but serve only to modify the character codes generated in a WM_CHAR. When a key is released, Windows sends a WM_KEYUP message, stating which key was released. CyOS works in much the same way that Windows does, as far as keyboard messages are concerned. When a key is pressed, the active application receives a MSG_KEYDOWN. When a character is generated, it receives a MSG_CHARTYPED, and when a key is released, it receives a MSG_KEYUP. So, this leaves us with the quandary of which application is the active one. When you run an application from the desktop, that application is the active application, until you exit, or something else preempts it. A couple of cases where your application might be preempted are when another Cybiko user comes into the area (you get the “person has entered your area” message box), and when another user is trying to send you a file (you get the “file send confirmation” box). During these times, those message boxes are the “active application” and receive all keyboard input. In order for messages to be delivered to their appropriate recipients, each application has a message queue. A message queue is just a list of messages that have been sent to that application but have not been processed yet. This allows input to come in whenever it needs to, but doesn’t interrupt an application while it is busy (which would be a nightmare). In order for everything to work properly, an application is responsible for periodically checking for messages and handling them. There are a couple of ways to go about this. Before this happens, however, we need to set up the message queue.
Initializing the Module In order for us to run an application in CyOS, we must first initialize a module. A module is nothing more than a graphics context (which allows us to draw onto the screen) and a thread (which sets up a message queue for us to check messages). This was done in the last chapter in CyBk2_2, but here I’m actually going to explain it. First, you must have a variable of type struct module_t. This is shown below in Listing 3.1. Listing 3.1 struct module_t main_module;//declare the module
The declaration of the module is most commonly a global declaration, outside of any functions. This isn’t strictly required. You could also make it a local variable within your main function, but then you have to send a pointer to main_module every time you need to use part of it, so it is probably best left as a global. struct module_t contains two data members: m_gfx and m_process. The m_gfx member is a pointer to a graphics context, which you use to draw on, and m_process is a cWinApp pointer, which is the thread and contains the message queue (i.e., you send this member to functions that read in messages).
Team LRN
Chapter 3: Introduction to Message Handling
19
For the remainder of the chapter, we will primarily be concerned with main_module.m_process. We initialize this module by calling the init_module function, shown below in Listing 3.2. Listing 3.2 init_module(&main_module);//initialize the main module
This call sets up the m_process and m_gfx members of main_module. Calling the init_module function is kind of like saying, “I want a graphics context and a message queue.” We only have to call this once, at the very beginning of the program, and we are all set up.
Grabbing Messages Once our module has been initialized, we are ready to receive messages. There are two methods of checking your messages, and each has its pros and cons. The two functions are cWinApp_get_message and cWinApp_peek_message.
cWinApp_get_message Listing 3.3 shows the syntax for the cWinApp_get_message function. Listing 3.3 struct Message* cWinApp_get_message ( struct cWinApp* ptr_win_app, //pointer to a cWinApp structure long timeout, //time to wait for a message int min, //lowest value of message to look for int max); //highest value of message to look for
This function returns a pointer to a Message struct. You do not have to allocate space for it, you simply use an uninitialized pointer. The parameters for cWinApp_get_message are shown in Table 3.1. Table 3.1 cWinApp_get_message parameters Parameter
Meaning
ptr_win_app
A pointer to a cWinApp structure (i.e., main_module.m_process).
timeout
A time to wait for a message to be retrieved (zero waits forever).
min
The lowest value for the message allowed (usually 1).
max
The highest value for the message allowed (usually MSG_USER).
You can specify a timeout value in the timeout parameter, or put zero to tell the function to wait until a message shows up. Whether you use zero or not depends entirely
Team LRN
20
Chapter 3: Introduction to Message Handling
upon what kind of application or game you are writing. For example, if you are making a text editing program, you have the luxury of just waiting for a message before doing anything. This is the event-driven model. However, if you are continuously playing music or need to update enemy positions in real time, then you can’t just wait until a message occurs before updating the application, so you might specify a timeout value other than zero. The timeout value is measured in clock ticks, which occur once every 10 milliseconds, or 100 times per second, so if you wanted to wait no more than half a second for a message, you would use 50 for the timeout. If no message is received within the timeout period, cWinApp_get_message returns NULL, and you can go ahead and do whatever updating you need to do in the absence of user input. Listings 3.4 and 3.5 show abbreviated examples of each of these uses for cWinApp_get_message. Listing 3.4 Event-driven message retrieval //ptr_msg is a pointer to a struct Message //exit_app is a bool, where TRUE means to exit the program while(!exit_app) { //wait for a message ptr_msg=cWinApp_get_message(main_module.m_process,0,1,MSG_USER); //handle message here //destroy the message //update the application }
Listing 3.5 Real-time message retrieval //ptr_msg is a pointer to a struct Message //exit_app is a bool, where TRUE means to exit the program while(!exit_app) { //wait for a message for half a second(50 clock ticks) ptr_msg=cWinApp_get_message(main_module.m_process,50,1,MSG_USER); //make sure a message occured if(ptr_msg!=NULL) { //handle message here //destroy the message } //update the application }
Team LRN
Chapter 3: Introduction to Message Handling
21
There are only subtle differences between Listings 3.4 and 3.5. In Listing 3.4, a message will occur during each loop. In Listing 3.5, a message may or may not occur before the timeout, so you need to check and make sure the message is not NULL before handling it. In 3.4, the application is only updated after a message occurs, and in 3.5 the application will be updated at least once every half a second.
Message_delete While you don’t ever have to allocate space for a message you receive, you do need to free up the memory it uses once you have handled it. To do this, you use the Message_delete function, shown in Listing 3.6. Listing 3.6 void Message_delete( struct Message* ptr_message );
//message that must be deleted
This function returns no value and has only one parameter—a pointer to a message that must be destroyed. Its use is pretty simple, as shown in Listing 3.7. Listing 3.7 //destroy the message Message_delete(ptr_msg);
CAUTION: Every time you read a message, you must delete it using Message_delete. If you don’t, then your application will leak memory, and eventually, unpredictable behavior (the device may lock up or your data might become garbled) will be the final result, requiring you to reboot the machine and lose whatever data you have. A similar caution is necessary for making sure you are checking messages often enough. If you aren’t checking messages frequently enough, the message queue might overflow the memory, giving you the same result.
cWinApp_peek_message Another way to read messages from the message queue is to use cWinApp_peek_ message. The syntax is shown in Listing 3.8. Listing 3.8 struct Message * cWinApp_peek_message ( struct cWinApp * ptr_win_app, //pointer to a thread(main_module.m_process) bool remove, //flag to remove the message from the queue int min, //lowest message to check for int max //highest message to check for );
Team LRN
22
Chapter 3: Introduction to Message Handling
This function returns a pointer to a Message struct, just like cWinApp_get_message. The parameters are shown in Table 3.2. Table 3.2 cWinApp_peek_message parameters Parameter
Meaning
ptr_win_app
Pointer to a thread.
remove
Flag telling function to remove message from queue; TRUE removes the message.
min
Minimum message value to look for.
max
Maximum message value to look for.
Be careful with this one. It sounds like a really great function to use, but I’ve experienced frequent lockups while using it. cWinApp_peek_message checks to see whether or not a message exists in the queue, and optionally can remove it from the queue, which might make you think that cWinApp_peek_message is like using cWinApp_get_message, which returns immediately. It is, sort of. However, the SDK help files warn us only to use it if we absolutely need it, and from tests I’ve done using it, I have to agree. Half the time the application works fine, and half the time the application locks up. Lesson learned: Try to avoid using cWinApp_peek_message, and instead use cWinApp_get_message with a timeout value whenever possible. So, when is a good time to use cWinApp_peek_message? The answer is during long operations, such as world generation, long file loads, or uploads to other Cybiko devices. As an example, we’ll say you’re saving a file, and it’s pretty big, so you think it might take some time. Listing 3.9 shows an example. Listing 3.9 //first part of long file operation //check for a message, but do not remove it if(cWinApp_peek_message(main_module.m_process,FALSE,1,MSG_USER)!=NULL) { //message has been found, so do something about it } //second part of long file operation //etc.
The idea here is that during a lengthy operation you periodically check for a message. If you find one, you should handle it at that time, so you avoid overflowing the message queue.
Team LRN
Chapter 3: Introduction to Message Handling
23
Contents of a Message By now, you understand how to retrieve a message, but you don’t know what’s in it, how it is formatted, and what it means. In this section, I go into the anatomy of a message. Let’s begin with how the actual Message struct looks. Check out Listing 3.10. Listing 3.10 struct Message{ struct Message* next; char* dst_name; cyid_t cyid_from; cyid_t cyid_to; bool deleted; short msgid; long param [2] = ; };
There are a few new members here. Some of them are pretty obvious, like cyid_from and cyid_to. All of the members are explained a little better in Table 3.3. Table 3.3 struct Message members Member
Meaning
next
Points to the next message in the queue.
dst_name
The destination application for which this message is intended.
cyid_from
The ID of the Cybiko that originated this message.
cyid_to
The ID of the Cybiko that is the recipient of this message.
deleted
Whether or not the message has been deleted.
msgid
Which message was sent.
param
An array of message parameters, specifying extra information about the message.
For the most part, the only parts of the Message struct you have to concern yourself with are msgid and param. Only when you are sending messages manually do you need to worry about any of the others. You never have to worry about them for keyboard messages. The way to send messages manually is with Message_post. The syntax for it is shown in Listing 3.11. Listing 3.11 bool Message_post ( struct Message * ptr_message, char * sz_process_name,
Team LRN
24
Chapter 3: Introduction to Message Handling
cyid_t cyid )
This function returns TRUE if the message found its way into the destination application’s message queue, and FALSE if it does not. sz_process_name is the name of the application to which you are sending the message, and cyid is the ID of the Cybiko that is to receive the message. Place get_own_id() in cyid if you are sending the message to the same Cybiko as you are sending from. Listing 3.12 shows you how to manually create and send a message. Listing 3.12 struct Message* ptr_message = Message_new( sizeof( struct Message ) ); ptr_message–>msgid = MSG_USER; Message_post( ptr_message, "app_name", get_own_id() );
This snippet sends MSG_USER to application app_name, on the same Cybiko unit as it is sent. The call to Message_new in the first line of the listing is simply how you create a blank, new message.
Common Messages There are many types of messages. You don’t have to worry about most of them as they are handled just fine by CyOS through default processing. Table 3.4 shows the most common messages you will receive, and under what circumstances you will receive them. Table 3.4 Common messages Message
Meaning
MSG_KEYDOWN
A key has been pressed or a key has autorepeated.
MSG_KEYUP
A key has been released.
MSG_CHARTYPED
A character has been generated based on key presses.
MSG_QUIT
A quit message has been posted.
MSG_GOTFOCUS
The application has received focus.
MSG_SHUTUP
Something has happened that requires emergency shutdown of the application.
MSG_USER
A user-defined message.
If you make your own messages, you can start with MSG_USER, and use MSG_USER+1, MSG_USER+2, and so on. I suggest making #defines for your own messages. If you make and use your own messages, don’t forget to change the
Team LRN
Chapter 3: Introduction to Message Handling
25
maximum number of messages to look for in your call to cWinApp_get_message! Look at Listing 3.13 to see what I mean. Listing 3.13 //extra defines for user messages #define MSG_SYNC MSG_USER+1 #define MSG_UPDATE MSG_USER+2 //the call to cWinApp_get_message //include searching for MSG_SYNC and MSG_UPDATE ptr_msg=cWinApp_get_message(main_module.m_process,100,1,MSG_UPDATE);
Keyboard Messages By far, the most common messages you will receive and have to process are those that come from the keyboard: MSG_KEYDOWN, MSG_KEYUP, and, to a lesser extent, MSG_CHARTYPED. These are handled in a special way, using the Message_get_ key_param function. The syntax for this function is shown in Listing 3.14. Listing 3.14 struct KeyParam*
Message_get_key_param (struct Message* ptr_message);
Not much to it. The function takes in a pointer to a Message struct and returns a pointer to a KeyParam struct. That leads us to the question of what is in a KeyParam struct. The KeyParam struct contains encoded information about a keyboard event. Details of the structure can be found in Listing 3.15. Listing 3.15 struct KeyParam { int scancode; int mask; char ch; };
The scancode member is the scancode of the pressed key. The mask member contains information about the Shift key, the Fn key, and whether or not this is an autorepeat key. The ch member contains the ASCII code for the character generated. So, whenever the msgid field of a Message struct contains MSG_KEYDOWN, you know that a key has been pressed. You can use Message_get_key_param to find out information about what key was pressed and whether or not the Shift key is affecting it. Unless you are writing an application that deals with text manipulation, you usually won’t be concerned with the ch member of KeyParam. Instead, you will respond to the scancode member of KeyParam. Each key has its own scancode, including the seven section keys at the top of the device. Whether or not you respond to any or all
Team LRN
26
Chapter 3: Introduction to Message Handling
of the keys is entirely up to you, the programmer. A bit of a warning, though: some keys, like the section keys at the top of the device, have a special meaning to CyOS; for example, one of them brings you to the Applications section of the desktop, and when combined with the Fn key, these toggle sound or music, or change the contrast of the display, or put the device into suspend mode. For this reason, you might not want to override the behavior of those keys, unless you have a good reason for doing so. All of the scancodes start with KEY_, and most of them have common-sense names. All of the numeric keys and all of the alphabet keys are KEY_0 through KEY_9, and KEY_A through KEY_Z, so those are pretty easy to remember. The other keys are shown in Table 3.5. Table 3.5 KEY_* Constants Constant
Meaning
KEY_SECTION1
First section key (with the Cybiko icon below it)
KEY_SECTION2
Second section key (with the phone icon below it)
KEY_SECTION3
Third section key (with a person’s profile below it)
KEY_SECTION4
Fourth section key (with a picture of a clock below it)
KEY_SECTION5
Fifth section key (with a picture of a die below it)
KEY_SECTION6
Sixth section key (with a picture of a target below it)
KEY_SECTION7
Seventh section key (with a picture of a CyB’s head below it)
KEY_ESC
The Escape key
KEY_LEFT
Left arrow
KEY_UP
Up arrow
KEY_RIGHT
Right arrow
KEY_DOWN
Down arrow
KEY_INS
Insert key
KEY_DEL
Delete key
KEY_TAB
Tab key
KEY_SELECT
Select key
KEY_ENTER
Enter key
KEY_BACKSPACE
Backspace key
KEY_HELP
Help key (above the main keyboard, with the ? on it)
KEY_SHIFT
Shift key
KEY_CONTROL
Fn key
KEY_SPACE
Spacebar
KEY_QUOTE
The apostrophe/quote key
Team LRN
Chapter 3: Introduction to Message Handling
Constant
Meaning
KEY_COMMA
The comma/less than key
KEY_MINUS
The minus/underscore key
KEY_PERIOD
The period/greater than key
KEY_SLASH
The slash/question mark key
KEY_SEMICOLON
The semicolon/colon key
KEY_BACKSLASH
The backslash/pipe key
KEY_EQUAL
The equals/plus key
KEY_OPEN_SBRACKET
The open bracket/open brace key
KEY_CLOSE_SBRACKET
The close bracket/close brace key
KEY_BACKQUOTE
The reverse single quote key
27
Most of the keys in Table 3.5 have names that imply which key you are pressing, so you shouldn’t have much problem remembering which key has which scancode. Also, you are usually going to respond to the keys above the main keyboard anyway. KEY_ESC, KEY_UP, KEY_RIGHT, KEY_DOWN, KEY_LEFT, KEY_DEL, KEY_INS, KEY_TAB, KEY_SELECT, and KEY_ENTER are usually more than enough to do most of what you want to do. They are conveniently positioned, and don’t require the use of the stylus.
Default Message Processing If for some reason you don’t handle a message (and this includes any keyboard message you aren’t handling), you should send the message off to the default processing function, cWinApp_defproc. The syntax is shown in Listing 3.16. Listing 3.16 bool cWinApp_defproc ( struct cWinApp * ptr_app, struct Message * ptr_msg ) ;
This function returns TRUE if the message was handled, and FALSE if it was not. The ptr_app parameter is a pointer to a thread (main_module.m_process, usually), and ptr_msg is a pointer to the message you want to send to be handled by the default handler. The benefit of using the default handler is that you don’t have to write the code to handle section keys being pressed, or the special function keys. CyOS takes care of those for you. Treat it like a contract between you and CyOS; CyOS pledges to take care of all the special keypresses, and you promise to send them if you get them.
Team LRN
28
Chapter 3: Introduction to Message Handling
A Basic Message Pump So, you’ve got the goods on how to read messages, what is contained in them, and how to pass them along to CyOS when you don’t need them. Now you are ready to build a skeleton application, the foundation upon which you can build greater things. First, we need to take some basic steps, no matter what the program does. 1.
Initialize the module, so that your application will have a message queue.
2.
Read in messages and handle them.
3.
If you don’t make use of a message, be sure to send it to default processing.
4.
A program may end for several reasons, including receiving a MSG_QUIT or a MSG_SHUTUP, or the user telling the application to quit.
Listing 3.17 shows a main function that does all of these things. Listing 3.17 #include “cywin.h” module_t main_module; bool exit_application; long main(int argc, char* argv[], bool start) { struct Message* ptr_message; init_module(&main_module); exit_application=FALSE; while(!exit_application) { ptr_message = cWinApp_get_message(main_module.m_process,100,1, MSG_USER); if(ptr_message) { switch(ptr_message–>msgid) { case MSG_SHUTUP: // Processes system exit signal. case MSG_QUIT: exit_application = TRUE; break; case MSG_GOTFOCUS: // Redraws screen. break; case MSG_KEYDOWN: // Processes keyboard messages. if(Message_get_key_param(ptr_message)–>scancode == KEY_ESC) { exit_application = TRUE; break; } default: // Processes all unprocessed messages. cWinApp_defproc(main_module.m_process, ptr_message); }
Team LRN
Chapter 3: Introduction to Message Handling
29
Message_delete(ptr_message); } } // while(!exit_application) return(0); }
Now, if you were to take this code and compile it, move it to the Cybiko and run it, it would work just fine. Of course, it doesn’t actually do anything. It simply waits patiently for you to press the Escape key, and then exits back to the desktop. It’s not all that different from the Hello, world program you did in Chapter 2. You can use this very code as a framework upon which to develop real applications. Listing 3.17 shows the required “junk” the program has to have in order for it to work on the Cybiko.
Summary So ends my bit about messages. As you can see, they are highly important, which is why I spent so much time on them. This isn’t the last word on messages, either, but the remainder of the topic is covered in Chapter 21, when I show you wireless communications. Hopefully, you got enough out of this crash course on Cybiko messaging to be able to handle just about any message the Cybiko throws at you.
Team LRN
Chapter 4
Resources and Development Tools Overview I touched on the topic of resources back in Chapter 2, but I didn’t give them a complete explanation. There is a lot you can do with resources to help minimize the space taken up by your application archive, and in a memory-constrained environment like the Cybiko, you want to do everything you can to minimize application size. I’ll also go more in depth on the resources that have a special meaning in a Cybiko application, including Root.ico, Root.inf, Root.spl, and Intro.pic. Also, I’ll cover using the media converting utilities that come with the Cybiko SDK. Cybiko has made resource conversion very easy for us, and it is best that we make use of it.
Resources Defined A resource is simply a file stored within an application archive that is not code. Technically, the code itself is a resource, but that is not what I mean when I talk about resources. In this book, resource means something other than code stored in a .app archive. Resources come in several different forms. They can be compressed or uncompressed. They can be text data or binary data. Whether the resource is compressed or not depends on the usage of that resource. If the resource is read-only (and most resources are), you should probably make it compressed, so you can save space in the application archive. If the application stores data in the resource (like a top ten list, or a name field), you probably want to make a blank file big enough to store the data, and leave that file uncompressed. I’ve divided resources into four basic categories: text resources, picture resources, music resources, and other binary resources.
30
Team LRN
Chapter 4: Resources and Development Tools
31
Text Resources Text resources are just what they sound like. They are files containing nothing but text. This text could be anything from a Root.inf file, which contains important information about your application, to Root.spl, which contains the text shown during application startup, to help files, which are read when the help key is pressed. For the most part, text files should be compressed, since string data is one of the worst hogs of space. Only if you are going to write to this file from the program should you leave it uncompressed. Any file extension may be used for a text resource. Text resources do not have to be compiled. You can simply use a text editor like Notepad to create and modify them.
Picture Resources Picture resources contain binary data about one or more bitmaps. These are usually named with the .pic file extension, but it is not a requirement. I use .pic since I can then see what kind of resource it is at a glance. Root.ico is also a picture resource. Normally, you probably won’t find a reason to have a picture resource uncompressed, as pictures are almost always read-only. Picture resources come in several flavors. Some contain only a single image, some contain multiple images (up to 255 can be stored in a resource). Some are monochrome (black and white) and others are four-color grayscale. Fonts are a special type of picture resource. They are always monochrome and contain many images to allow the writing of text. Usually, fonts have the .fnt extension. In later chapters, I discuss loading bitmaps, bitmap sequences, and fonts. Bitmaps and fonts start out in another format that you use tools on your computer to edit. Then, you use a media converter utility to convert them into the Cybiko format.
Music Resources Music resources contain binary data about a music sequence. These are usually named with the .mus file extension, but that’s just a general rule, not a requirement. There is a media converting utility that takes MIDI files and converts them to the Cybiko music format.
Other Binary Resources “Other binary resources” is just a name I give to any resources that are not text, pictures, or music. You might have a special file format that describes a level in your game, or details what a map looks like, or whatever.
Team LRN
32
Chapter 4: Resources and Development Tools
Pick whatever file extension you like for these. For example, if you are describing a level, you might want to make it an .lvl file, or if it’s a map, a .map file. Unless your application needs to write to it, make it read-only. If you are going to be writing to the resource, make sure it will always be a fixed size. If you need to write out a file somewhere and it isn’t a fixed size, you are better off just saving it to a file.
Special Resources (Root.*, Intro.pic, and 0.help) I’ve already briefly described these in Chapter 2, but a treatment of resources could not be complete without talking about them again and in more detail. Each of these special resources absolutely must have the filenames listed here, and some of the text resources must be formatted in a particular way in order for them to work properly.
Root.ico We looked at root.ico back in Chapter 2. Root.ico is a picture resource that must be 48 pixels wide and 47 pixels tall. It is the picture that is shown on the desktop for your application. This resource may be compressed, but must be named Root.ico. This file is optional for an application archive, but if you do not include one, your application will show up with the default Cybiko icon. NOTE: Root.ico does not have to be 48x47, but using a different size will make the icon look disproportionate.
Root.inf I covered Root.inf in Chapter 2, but it is such an important file that it bears repeating. This is a text file with ten lines in it, each of which has a particular meaning. Line one contains where the application is to be shown. This value can be app, game, or root. If it is app, the application will show up on the desktop under the Applications icon (or upon hitting the Section 4 key). If game, it will show up under the Game icon (or upon hitting the Section 5 key). If root, it will show up on the root part of the desktop. As a general rule, try to avoid making too many root applications. Line two contains the name of the application, as it shows up on the desktop and in CyberLoad. Lines three through six should be left blank. If you don’t, unpredictable behavior will result. Line seven is the name of the application. If your application is named Test.app, then “Test” should be on line seven of Root.inf. Line eight is the version of the SDK used to compile the application.
Team LRN
Chapter 4: Resources and Development Tools
33
Line nine is the version number of CyOS needed to run this application. Before the desktop runs this application, it will reference the current version of CyOS on the device and check against line nine of the Root.inf. If the number in root.inf isn’t prior to or the same as the CyOS version, the application won’t run. You’ll get a little pop-up box telling you that you cannot run this application. Line ten is your copyright information. The Root.inf resource is special in that it is absolutely required for your application to show up on the desktop. None of the other special resources are required for your application to run. It must be named Root.inf, but it may be compressed if you wish.
Root.spl The Root.spl file is just a simple text file that you put in as a resource. It scrolls during application loading, right after Intro.pic is shown (if there is an Intro.pic resource) or the animated sequence with Root.ico is shown. There is no special format for Root.spl, but that must be the filename. It can be compressed if you like, and since it is generally a read-only file, it probably should be. This file is optional. If you don’t include it, you’ll just get the animated sequence using Root.ico. If you have an Intro.pic, you must have a Root.spl, and it must not be an empty file.
Intro.pic The Intro.pic resource is a picture resource containing a single four-color image that measures 160x100. It is shown during program startup. You can make it larger or smaller than this, but if it is smaller, it will still be against the top and left of the display, and the rest of the screen will be filled with white. If you use a larger image, it will be cropped to 160x100, and the extra bits of the picture will never be shown. NOTE: I found out while experimenting with these resources that Intro.pic file will only be shown if there is a non-empty Root.spl file.
0.help The help system for the Cybiko is very simple. Help files are simple text resources, but they do have something of a format. The first line in the *.help file contains the text to be shown in the title bar of the help window. A simple help file would look something like Listing 4.1. Listing 4.1 Help Title Text of help file.
Team LRN
34
Chapter 4: Resources and Development Tools
This case is, of course, extremely simple, and your own help files will naturally contain more information (after all, it’s not a help file unless it actually helps, right?). In order to make use of the default Cybiko help system, you must call cWinApp_defproc whenever you receive a KEY_HELP message. If you make your own help system, you can respond to KEY_HELP in any manner you wish. From the application itself, the only help file that will be called is 0.help, in which you should put key information about using your application. You can use other help files as well, as part of the Cybiko GUI (covered in Chapters 16 and 19). From experiments I’ve done, the help system runs in a separate thread, so it won’t look right unless you are using cWinApp_get_message with 0 as the timeout value.
Compiling Resources with Makeres.bat Picture resources and music resources need to be in the Cybiko format, and there are no editing tools currently available for the Cybiko format that you can use (I’m working on some, and I know there are others that are working on this problem as well). As luck would have it, Cybiko did provide us with some command-line tools to convert from other formats into the special Cybiko formats. These tools are listed in Table 4.1. Each of these utilities can be found in the Bin subfolder of the Cybiko SDK installation folder. Table 4.1 Utilities for resource conversion Tool
Purpose
2mus
Converts MIDI to Cybiko music file.
mus2txt
Converts Cybiko music file to MIDI sequence text format.
t2mf
Converts MIDI sequence text format to MIDI.
2pic
Converts one or more bitmaps into the Cybiko picture format.
PicView
(Non-command line) Allows viewing of Cybiko pictures/picture sequences.
Normally, when compiling resources, I put a batch file in Res/src of the project’s directory. I call this file Makeres.bat, so that all I have to do is double-click on the batch file, and all of my resources are rebuilt (as you might be able to tell, I don’t really like using the command line!). A normal Makeres.bat file looks something like Listing 4.2. Listing 4.2 path %CYBIKO_SDK%/bin 2pic ../root.ico icon.bmp 2pic ../intro.pic intro.bmp
Team LRN
Chapter 4: Resources and Development Tools
35
This listing has the code that will convert my source bitmaps (Icon.bmp and Intro.bmp) into the Cybiko file equivalents (Root.ico and Intro.pic) in the parent folder (Res). If I had more pictures or music (and I usually do), there would be additional lines for each resource in Makeres.bat. Some of the tools have extra switches that specify how a resource is to be made, and while these are all documented in the SDK help file, I figured I would also put them here, and give a better explanation on how to fine tune your resource building.
2mus The 2mus tool is pretty basic. The syntax for it is shown in Listing 4.3. Listing 4.3 2mus .mid
This is a pretty spartan tool. It only has one parameter, and will be the same name for both the source MIDI file and the Cybiko music file. Since you cannot direct where the music file will be created, you will either have to move it yourself or put the MIDI file in the Res subfolder of your project. I personally don’t use 2mus. I make my music files using a hex editor, so I never need to compile them.
mus2txt If you have a Cybiko music file, and you wish to convert it back to a MIDI (for whatever reason), you must use mus2txt followed by t2mf. I’m not sure why this is a two-step process. Lising 4.4 shows the syntax for using mus2txt. Listing 4.4 mus2txt .mus .txt
is the name of your music file, and is the desired name of the output text file. This text file can then be sent through t2mf to convert it to a MIDI file.
t2mf Once you have a text file that has been generated by mus2txt, you can send it through t2mf to convert it to a MIDI file. Listing 4.5 shows the syntax. Listing 4.5 t2mf .txt .mid
is the name of your source text file, and is the desired name of the destination MIDI file.
Team LRN
36
Chapter 4: Resources and Development Tools
I’m not a big fan of using MIDI file editors for making Cybiko music. MIDI files have multiple voices and instruments and tracks that can be playing simultaneously. The Cybiko only has one, so a regular MIDI editor is sort of overkill in my opinion, but it is a common enough format that you can find a nice shareware MIDI editor at www.download.com and make your own music files (if you are of a musical bent).
2pic This tool is a great little utility. It takes one or more source bitmaps and generates a Cybiko picture file which contains a bitmap sequence. A bitmap sequence contains at least one bitmap, and may contain as many as 255 bitmaps. However, with 2pic, your effective limit is about 20 to 30, since the command line can only have a limited number of characters for each command. (I’ve written a tool that makes bitmap sequences that get rid of this limit, but I’ll show you that a little later on.) With 2pic, you can make monochrome or four-color pictures, and you may specify a color to use for transparency. Listing 4.6 shows the syntax for 2pic. Listing 4.6 2pic [<mode>] [.pic] .bmp|dib|fli|flc|cel ...
This is perhaps the most complex and robust of the command-line resource conversion tools. The <mode> may be 0, 1, 2, 3, –f, or –p. These modes are shown in Table 4.2. Table 4.2 2pic modes Mode
Meaning
0
2-bit picture; use white as transparency.
1
2-bit picture; use light gray as transparency.
2
2-bit picture; use dark gray as transparency.
3
2-bit picture; use black as transparency.
–f
1-bit picture; white is transparent.
–p
1-bit picture; no transparency.
If no mode is specified, then the output will be a 2-bit picture with no transparency. Cybiko transparency is different than you might think, but I’ll be covering that in Chapter 9. is the destination picture file, i.e., ../root.ico or ../intro.pic, or whatever else your picture might be named. The (and there can be one or many) may be a bmp, dib, fli, flc, or cel format picture. Since I’m a Windows user, my primary format is bmp anyway, so this suits me just fine. In fact, I had never even heard of fli, flc, or cel, and my primary graphical tool (PaintShop Pro) does not support them, so I just use bmps. Heck, with bmps, you
Team LRN
Chapter 4: Resources and Development Tools
37
can use MS Paint, ensuring that every Windows-based computer on the planet can make graphics for the Cybiko. There are also some excellent free bitmap editors to be found on the web that will do the job just fine. CAUTION: When creating your source bitmaps, here’s something to keep in mind. The normal Windows palette contains a dark gray and a light gray, which you might be tempted to use in your images. Don’t do that, they won’t work. Instead use RGB (83,83,83) for dark gray, and RGB (163,163,163) for light gray, to ensure that the colors will come out correctly on your Cybiko. I learned this the hard way.
I would say to use 2pic for any bitmap sequence up to about ten images in size. Above that, I would suggest using the tools I’ve made, Fontmake.exe and Bseqmake.exe, which are detailed later in this chapter.
PicView PicView is the only non-command-line utility included in this list. It is a full Windows program that you can use to look at bitmap sequences. It’s not as full featured as you might like it to be (hence, there are other tools being written by third-party developers). PicView.exe is shown in Figure 4.1.
Figure 4.1: PicView.exe
Team LRN
38
Chapter 4: Resources and Development Tools
With PicView, you can look at the contents of a Cybiko picture file, add images to it, export the first image in the list, and change the colors used by the program. In other words, it doesn’t do a whole lot other than look at a .pic file and give you some statistics about it. Theoretically, you can use PicView to make bitmap sequences of whatever length you wish. In practical terms, it takes way too long to do this, so you’d be better off using Bseqmake or Fontmake.
Third-Party Resource Conversion Tools Because some of the Cybiko resource conversion tools are a little too primitive, I decided to take matters into my own hands. After trying several times to make a font file using 2pic, I created Fontmake.exe and a flexible bitmap sequence maker called Bseqmake.exe. Both of these are command-line tools, and designed to be placed in the Bin subfolder of the Cybiko SDK, so you can use them just like any of the Cybiko resource conversion tools. These tools can be found on the CD under the Tools directory. The full VC++ source is included with these tools, and you are free to use, modify, and extend them, as long as you give me due credit.
Fontmake.exe When I began trying to make fonts using 2pic, I kept getting errors because the line in my batch file was too long. Eventually, after several hours of frustration and yelling at my cats to leave me alone, I just said to heck with it, and wrote Fontmake.exe. Fontmake creates a fixed-width font that contains 96 characters (characters 32 through 127), encompassing all of the standard ASCII characters you might need for writing text. The standard Cybiko fonts have more than this, to include special characters like the (©) symbol and diacritics, but a 96-character font should be more than sufficient for general usage. The syntax for Fontmake.exe is shown in Listing 4.7. Listing 4.7 fontmake
is the input file (Fontmake supports bmp files only), and is the output .pic file (there is no default extension, but I usually use .fnt for my font files). All 96 characters of the font are placed into a single bitmap, as shown in Figure 4.2.
Team LRN
Chapter 4: Resources and Development Tools
39
Figure 4.2: A source bitmap for Fontmake.exe
The figure is blown up to 16 times its original size (the original is only 128x48), so you can see the pixels a little better. Fontmake divides an image like this up into 16 columns and 6 rows, for a total of 96 images. Notice that the first image is the space, and it follows the standard ASCII character set from there on. Each of the characters in the figure are 8x8 pixels in size (this font is an exact replica of the old 8x8 DOS font). There are other fonts located on the CD under Resources/fonts. All of these can be modified and rebuilt using Fontmake. To use Fontmake, simply make a bitmap 16 cells wide and 6 cells tall. The cell may be of any size up to 255x255 (larger than this and the picture would not be loadable on the Cybiko). In each cell, draw the character corresponding to that position. When you are done, send the file to Fontmake, and you’ve got yourself a Cybiko font, which you can use just like any of the predefined Cybiko fonts.
Bseqmake.exe Bseqmake.exe is a tool I wrote so that I could use a single bitmap as the source for an entire sequence of pictures, rather than have a long command line, and have to work with dozens of pictures. It’s a more advanced tool than Fontmake, in that it supports transparency, and it supports cells of multiple sizes in the same bitmap. The syntax for Bseqmake is shown in Listing 4.8. Listing 4.8 bseqmake
is the source bitmap (Bseqmake only supports bmp), and is the name of the destination picture file (you can use any extension you like, but I tend to stick with .pic). Figure 4.3 shows a picture of a sample source image for Bseqmake. This image can be found in the zip file that contains Bseqmake.
Team LRN
40
Chapter 4: Resources and Development Tools
Figure 4.3: Sample Bseqmake source image
You should probably find this picture (it’s called Dungeon.bmp) and open it in a graphics editor, because the explanation of how the picture is formatted discusses the colors of the pixels, but the figure above is grayscale. The first thing I would like to point out is the green border around each of the images. Each image is separated from its neighbors by this green border. Along the top and left of the picture, there are magenta pixels that correspond to the locations of the green borders. This is how Bseqmake knows where rows and columns start and stop, so they must be there. You can replace magenta and green with whatever colors you wish, and Bseqmake will still work. On the right edge of the bitmap, under the magenta pixel are four dots—black, dark gray, light gray, and white. They must be there for Bseqmake to work. These pixels are read in to control which color in the bitmap means the colors black, dark gray, light gray, and white for the Cybiko. You can use any color you wish for these, just be consistent. The magenta portions of the image specify transparency. Be careful with this. Within a cell, any column where there is a transparent pixel will make the entire column transparent. Similarly, any row with a transparent pixel will be totally transparent. Hence, the non-transparent part of the image is always rectangular. The first cell (cell#0) is the upper-left cell, and it increases to the right. Once the end of a row has been reached, the count continues on the next row. So, if you have four columns and four rows, the image numbers are as follows: Row 1: 0 1 2 3 Row 2: 4 5 6 7 Row 3: 8 9 10 11 Row 4: 12 13 14 15 You may have any number of columns or rows, and they do not all have to be the same size. Don’t put more than 255 pictures into the bitmap (17 columns by 15 rows, or vice versa), and don’t make any row or column wider than 255 pixels. Bseqmake is a good little tool, and I’ve gotten quite a bit of use out of it. I hope that you will, too.
Team LRN
Chapter 4: Resources and Development Tools
41
Adding Resources Using Filer.list Once you have all of your resources in the proper format and have placed them into the Res directory, you need to let your project know what resources you wish to use, and whether or not you would like them to be compressed. This is done in Filer.list. Filer.list is the source file for another development tool called Filer.exe, which is called by Vmake.exe when processing your makefile. You can also use Filer.exe to make archives that don’t contain any executable code (if, for instance, you wanted to make a game builder in which you simply supply an archive and the game reads all of its data from it). Full documentation for using Filer.exe can be found in the SDK help files. Each resource should be listed in Filer.list. They don’t have to be in any particular order. Since Filer.exe is called from the parent director of your project, you need to add “Res/” before the name of your resources. By default, resources sent to Filer.exe are compressed, but if you are using a different makefile than the one supplied, this might not be the default. To specify that a resource is to be compressed, you put a plus sign (+) in front of the resource, as in “+res/root.ico.” This makes the resource compressed, even if the default is uncompressed. Similarly, if you want the resource to be uncompressed, you place a “–”, as in “–res/root.ico.” This overrides any default. Usually, you’ll just use + and – in your filer.list. However, there are a few other symbols you might be interested in. The asterisk (*) stores the file but not the filename. The question mark (?) stores the filename but not the extension (i.e., “root” instead of “root.ico”). Finally, the number sign (#) starts a comment. Listing 4.9 shows a sample Filer.list file. Listing 4.9 ######################################### #root.* resources ######################################### +res/root.ico +res/root.inf +res/root.spl ######################################### #intro.pic ######################################### +res/intro.pic ######################################### #top ten file(uncompressed) ######################################### –res/topten.txt ######################################### #secret text file(no file name, compressed) ######################################### +@res/secret.txt
Team LRN
42
Chapter 4: Resources and Development Tools
So, as you can see, you have a lot of control over how your resources are stored in your application archive, whether you use it or not.
Makefiles Finally, I wanted to cover the innards of makefiles. Once upon a time, back when dinosaurs roamed the earth, using a makefile was the best way to build a project. Today, most systems have fancy IDEs (integrated development environments), in which you can build a project just by clicking a button. These IDEs still come with makefile utilities, of course, for the old-school programmers who have been programming since the late Jurassic period and don’t like IDEs. I give makefiles their due. They are an extremely flexible way to build programs without clicking on dozens of different menu items on toolbars to set up how you want your application to be made. It is also a lot easier to make a program that reads in a makefile and builds the application than it is to develop an IDE. Cybiko’s main goal is to make hardware, and games and applications to run on this hardware, not to make tools that are easy for a person to use. So we have to use makefiles until such time as someone makes an IDE for the Cybiko. I don’t blame them; I would have done the same thing. So, we have these makefiles, which to any normal human and programmers who are used to IDEs (i.e., me) look like a bunch of gibberish. I invite you to look at Listing 4.10, which contains the makefile for CyBk2_2. Listing 4.10 NAME = CyBk2_2 OBJ = src/$(NAME).o RES = res/filer.list PP CC AS LN LD RM
= = = = = =
vcpp vcc1 vas vlink filer vrm
.SUFFIXES : .c all : $(NAME).app $(NAME).app : tmp/bytecode.bin $(RES) @echo building app archive... @$(LD) a $@ @res/filer.list tmp/bytecode.bin "$(CYBIKO_SDK)"/lib/main.e tmp/bytecode.bin : $(OBJ) @echo linking ...
Team LRN
Chapter 4: Resources and Development Tools
43
@$(LN) –o $@ src/*.o .c.o : @echo compiling $<... @$(PP) –I"$(CYBIKO_SDK)"/inc $< | $(CC) | $(AS) –O –o $@ src/$(NAME).o : src/$(NAME).c clean : @echo cleaning... @$(RM) –f tmp/*.* src/*.o $(NAME).app new : clean all
Unless you are familiar with makefiles, this code listing probably looks like nonsense. That’s what it looked like to me at first. If you stare at it long enough, however, it begins to make sense. The top part of the makefile contains stuff like “NAME = CyBk2_2.” These are macros, sort of like variables, that are used later on. Once you have “NAME = something,” you can use $(NAME) to refer to it later in the script, and the makefile processor replaces it with whatever you said NAME ought to be. Make.bat runs Vmake, which is the makefile processor. The contents of Make.bat are shown in Listing 4.11. Listing 4.11 path %CYBIKO_SDK%/bin vmake new –p2 %1
The first line of Make.bat simply ensures that the Bin directory of the Cybiko SDK is in our executable path, so we don’t have to specify where each tool is all the time. The second line calls vmake, with the parameters of new, –p2, and %1. %1 is used in DOS batch files to specify “use the first parameter sent to this batch file.” We did not send any such parameters to the batch file, so this is blank. If we had a different name for our application besides the default name, we would need to have this parameter. –p2 is a switch. There are three of these, –p0, –p1, and –p2. These tell Vmake if and how we want it to pause. p0 means to never pause. p1 means to pause only if there is an error. p2 means to always pause, whether there was an error or not. The first parameter, new, specifies where in the makefile you want Vmake to start. In this makefile, new is on the last line, with a colon and “clean all” after it. If you scroll up a few lines, you will also see “clean” and “all,” both with colons after them. These are labels which Vmake uses to run the makefile. So, with Vmake new, new will be run, which will run clean first, and then all. So, as you can see this is not total gibberish, and there is more than enough documentation on makefiles and how to use them in the SDK help. In this book, we will
Team LRN
44
Chapter 4: Resources and Development Tools
just be using the makefile above and changing the NAME= macro line. If you want to get more into makefiles, I suggest looking at the SDK help.
Summary I hope you now have a better grasp on what resources are, how to make them, and how to include them in your applications. In addition, you should have a good grasp on the developer tools that can assist you with your resource creation. I know these first few chapters have been a little bit light in the code department, but the learning curve for doing things the Cybiko way is a little steep. Luckily, it will soon be over, and we can get onto the fun stuff.
Team LRN
Chapter 5
The Cybiko Way of Object-Oriented Programming Overview This chapter is about coding conventions that make the SDK documentation more readable and also demonstrate how most of the code for this book is going to be written. If you are a C++ programmer, you will find this chapter pretty easy to read, but you are going to think that doing all of this stuff is sort of silly. If you are a C programmer who has never touched C++, you should also have an easy time reading this chapter, and you probably use similar methods in your C programs. This chapter is on object-oriented programming, and how it works on the Cybiko. I’m not going to go into great detail about the theory of OOP, because it’s one of those things that you either like or you don’t. I personally am a C++ programmer, and I like OOP. I think that the equivalent C code is a little strange to look at and bulky, but I am not paid for my opinion, I am paid for content. I know that a number of you will be C programmers, and since the Cybiko only allows C, that’s what we have to use.
OOP (Object-Oriented Programming) If you’ve never been exposed to the idea of OOP, you might want to read this next bit where I explain the basic theory under which this type of programming works. If you are comfortable with OOP, feel free to skip it. I’m not going to go into long and boring graphic detail about OOP, since there are many books on the topic (really big books, usually very boring and dry) and this is a book on game programming, so I don’t wish to bore you. Instead, I’m going to give you
45
Team LRN
46
Chapter 5: The Cybiko Way of Object-Oriented Programming
the “big picture” story of OOP—enough to form a foundation, and if you later wish to explore it in greater detail, you can do so on your own. The three pillars of OOP are Encapsulation, Inheritance, and Polymorphism. These three pillars are in capital letters to appease the gods of OOP, who would strike me dead for not capitalizing them since they are so important.
Encapsulation Central to the idea of OOP is the use of objects. Objects are variables, just like any other, but they are independent of other objects (except when talking to one another), and usually incorporate aspects of an entire autonomous thing, like a car. A car is a separate entity from the road, the driver, the passenger, and the other cars, so it would be a good example of something you might make into an object. An object is usually said to be of a certain “class.” In the case of a car object, it would be of the Car class. All of the internal workings of a car are just that, internal to the car. If we were programming a car simulation program, we shouldn’t care about how the car works inside. We should simply be able to tell the car “turn left,” “turn right,” “speed up,” “slow down,” or “run over little old lady.” Now, a car has a number of things that can be considered data, such as which gear it is in, how far the accelerator has been pressed, whether or not the parking brake is activated, the orientation of the steering wheel, and so on. To incorporate all of this, we might make a struct, called Car, as shown in Listing 5.1. Listing 5.1 struct Car { int steering_wheel_orientation; int gas_in_tank; bool running; bool parking_brake_activated; bool brake_down; int accelerator_level; bool door_ajar; //and so on.... };
This example has just a scant few of the things that make up a car, but I think you get the idea. All of the aspects needed for a car should be stored in a variable of the Car struct, to make it easier. Each of these items in the Car struct is called a “field,” or in C++ parlance a “member.” This is half of encapsulation. The other half deals with the operations that can take place on a car—for example, starting the car, stopping the car, opening the door, turning the steering wheel, activating/deactivating the parking brake, stepping on the pedals, and so on.
Team LRN
Chapter 5: The Cybiko Way of Object-Oriented Programming
47
In C++, we would just make these functions part of the struct. We can’t do that in C. In normal C, we could put function pointers in for all of these functions to accomplish the same thing. Cybiko C doesn’t allow the use of function pointers. So, we are left with using functions external to the struct to allow us to perform these functions. Listing 5.2 shows what some of these functions might look like. Listing 5.2 bool Car_start(struct Car* ptr_car); bool Car_shut_off(struct Car* ptr_car); int Car_set_steering_direction(struct Car* ptr_car ,int dir); bool Car_set_parking_brake(struct Car* ptr_car ,bool value); //and so on
Each of these functions takes as the first parameter a pointer to a Car struct, which allows us to say which car we want to perform the activity on. Functions with more than one parameter allow us to say to what degree we want the activity to be performed. As you can see, it doesn’t really matter what is going on inside the Car_start function; we just want the thing to start. The return values in these examples tell us the relative success of the activity. For example, Car_start returns whether or not the car is running. If a call to Car_start does not start the car, something must be wrong with the car. Each of these functions, if they were inside of the struct, either with the C++ mechanism or function pointers, would be called “methods” or “member functions.” They are not, they are merely functions, but for the purpose of Cybiko programming I will call them member functions, because that is their intended use. And so, encapsulation is the bringing together of data and functions to better model your programming.
Inheritance So, we have a Car class, from which we can make car objects. This is good and useful. But what about a truck? A truck shares many similarities with a car, certainly, but it is not a car. Just ask anyone who owns a truck. The same thing goes for vans, recreational vehicles, tractors, riding lawn mowers, and motorcycles. One thing that we can say about all of these things is that they are automobiles. They all run on internal combustion (we’ll ignore electric cars for now), and they all move across the land using friction. So, if we are dealing with many different types of automobiles, we might want to make a struct called Automobile, with all of the members and member functions we can think of that pertain to the greater extent of the automobile family, and we would want Car to be an automobile with the special attributes pertaining to a car, and a Van to be an automobile with the special attributes pertaining to a van, and so on. In regular C, this would look like Listing 5.3.
Team LRN
48
Chapter 5: The Cybiko Way of Object-Oriented Programming
Listing 5.3 //automobile “class” struct Automobile { //automobile stuff here }; //car “class” struct Car { struct Automobile* ptr_auto;//contains information common to automobiles //more stuff here, specific to a car };
This will work, but it is clumsy. If we were calling an automobile function for a car, there would be excessive use of the –> operator, so this solution is more trouble than it is worth. It would be better if we could use a few C++ extensions and use inheritance as shown in Listing 5.4. Listing 5.4 //automobile “class” struct Automobile { //automobile stuff here }; //car “class” struct Car: public Automobile { //more stuff here, specific to a car };
I put the pertinent part of the listing in bold type. A colon after the type, with the word “public” and a structure name says, “I want to use all of the members of Automobile in Car, and in addition I want to use . . . . ” This is how C++ works. As you might guess, it comes in pretty handy. Luckily, Cybiko C isn’t pure ANSI C. It has a few C++ extensions, including the one that allows us to use the code in Listing 5.4. This ability to extend a base class is inheritance. Automobile, in this case, would be the “parent class” or “base class,” and Car would be the “child class” or “derived class.” Now we can make our Car functions, and send a struct Car* as the first parameter. We do, however, “inherit” the member functions for Automobile, but since the member functions are done in a strange way, they are better discussed under polymorphism.
Team LRN
Chapter 5: The Cybiko Way of Object-Oriented Programming
49
Polymorphism Polymorphism is the last pillar of OOP, and perhaps the most important. This is what enables us to reuse code written for other classes. For example, you might have an Automobile_start function, like the one shown in Listing 5.5. Listing 5.5 bool Automobile_start(struct Automobile* ptr_auto);
Now that we have this function, and we know that Car, a child class of Automobile, starts in exactly the same way, we don’t want to have to make a separate Car_start function; we would like to make use of the Automobile_start function, since the start procedure works in the same way. Luckily, in Cybiko C, we don’t have to write a separate function. Automobile_ start is just as happy to take the struct Car* as it is the struct Automobile*, since Car is derived from Automobile and has all of the pertinent data. This is polymorphism. Of course, we don’t want to call Automobile_start to start our car. Rather, we’d like to call Car_start. We can do this by making a simple macro, as shown in Listing 5.6. Listing 5.6 #define Car_start Automobile_start
Now, when you compile your application, the preprocessor will replace any Car_start you have with Automobile_start, so you don’t have to remember which base class has which functions.
Constructors and Destructors In OOP, there are two types of member functions that are set apart from the rest. These are the constructor and the destructor, and they each have a special purpose.
Constructors A constructor is said to “construct” an object. It fills in an object with the default values, which may or may not be supplied along with the constructor. For example, an Automobile constructor may set the steering wheel to the zero position, set the gas tank to full, set the running member to FALSE, and so on. In addition, if there are any dynamically allocated parts of the object, the constructor allocates the memory for these. An example of a constructor function is shown in Listing 5.7.
Team LRN
50
Chapter 5: The Cybiko Way of Object-Oriented Programming
Listing 5.7 void Automobile_ctor(struct Automobile* ptr_auto);//constructor for automobile
A class might have more than one way in which it can be constructed. You might, for example, want a default constructor to set the gas tank to full, and another to allow you to set the level of the gas tank yourself. To do this, you make another constructor, and name it with _Ex at the end, as shown in Listing 5.8. Listing 5.8 void Automobile_ctor_Ex(struct Automobile* ptr_auto,int fuel_level);
If you have more than two constructors, you can use _Ex1 instead of _Ex, and use _Ex2 for the third constructor, etc. Have as many constructor functions as you like. However, you probably want to make the usual constructor (the one without any _Ex suffix) take only one parameter and have it default all of the values, if you can possibly do so. This is how all of the Cybiko SDK constructors are done, and one of the goals of programming is to be consistent.
Dynamic Allocation Constructors You will not always just declare objects and construct them using the constructor functions, as shown in Listing 5.9. Listing 5.9 struct Car MyCar; Car_ctor(&MyCar);
There will be times when you will dynamically allocate your objects. To do this, you use code similar to Listing 5.10. Listing 5.10 struct Car* ptr_MyCar; ptr_MyCar=(struct Car*)malloc(sizeof(struct Car)); Car_ctor(ptr_MyCar);
As you can see in Listing 5.10, the dynamic allocation of the car is a little wordy. It might be better to have a function that you just call with no parameter that dynamically allocates one for you, constructs it, and returns the pointer to it, as shown in Listing 5.11. Listing 5.11 struct Car* ptr_MyCar; ptr_MyCar=Car_New();
The code in Listing 5.11 is not only shorter, but it better communicates to other programmers what your intent was. Your intent was to dynamically allocate a new car and
Team LRN
Chapter 5: The Cybiko Way of Object-Oriented Programming
51
construct it. For this, we use the _New member function. If you have multiple constructors, and your objects are likely to be dynamically allocated with regularity, you may wish to make some _New functions, one for each constructor. Make these functions match up with the appropriate _ctor, such as _New, _New_Ex, _New_Ex1, and so on. The code for a _New function is quite simple, as shown in Listing 5.12. Listing 5.12 struct Car* Car_New() { struct Car* ptr_car; //allocate memory for a new car object ptr_car=(struct Car*)malloc(sizeof(struct Car)); //construct the car Car_ctor(ptr_car); //return the new car return(ptr_car); }
With such a function, the code in Listing 5.11 is possible. You would make a similar _New function for every constructor for your class.
Destructors On the flip side of a constructor is a destructor, which deallocates any memory that the constructor and sequential operations might have allocated for the object. Unlike the constructor or the _New functions, there should only be one destructor, as shown in Listing 5.13. Listing 5.13 void Car_dtor(struct Car* ptr_car,int memflag);
This is what all of the Cybiko destructors look like. The first parameter is a pointer to the object, and the second is one of two values, LEAVE_MEMORY or FREE_MEMORY. If the object was dynamically allocated (either manually or by using a _New function), use FREE_MEMORY. If it was not, use LEAVE_MEMORY. Some examples are shown in Listing 5.14. Listing 5.14 struct Car car1; struct Car* ptr_car2; //construct car 1 Car_ctor(&car1); //construct car 2, dynamic allocation ptr_car2=Car_New(); //other code goes here //destruct car 1
Team LRN
52
Chapter 5: The Cybiko Way of Object-Oriented Programming
Car_dtor(&car1,LEAVE_MEMORY); //destruct car 2 Car_dtor(ptr_car2,FREE_MEMORY);
A destructor function should clean up the object, no matter which constructor was used, and no matter if it was dynamically allocated or not. Some example code of what a destructor might look like can be found in Listing 5.15. Listing 5.15 void Car_dtor(struct Car* ptr_car,int memflag) { //code to clean up car goes here //if memflag is FREE_MEMORY if(memflag==FREE_MEMORY) { //free the memory for this object free(ptr_car); } }
Summary Now you should have at your command the basics of OOP on the Cybiko. It’s a little weird at first, but it grows on you. Pretty soon, after you’ve programmed the Cybiko a while, you’ll go back to whatever other platform you program for, and you’ll find yourself doing the weird Cybiko OOP in your normal projects. I couldn’t possibly do justice to a big topic like OOP, but I certainly hope that you have found this crash course to be helpful. We have just one more stop on our way through Cybiko fundamentals, and then we can get into more interesting subject matter.
Team LRN
Chapter 6
Program Frameworks Overview In a general purpose programming language like C, there are many types of applications and games you might write. Each application has its own needs, and lends itself to a certain program framework. A program framework is nothing more than a skeleton upon which the rest of the program can work. I’ve come up with six basic frameworks upon which you might build your applications. There are undoubtedly more, but for most purposes one of these should do the job. The six frameworks are called Quick-Running, Event-Driven, Idle-Loop, Real-Time, Dialog-Based, and Multi-threaded. This chapter is going to be pretty code heavy, since I am presenting most of these frameworks in this chapter. (Dialog-Based and Multi-threaded frameworks are covered in later chapters.)
Quick-Running Framework By far, the simplest running framework is the Quick-Running framework. There is no call to init_module or cWinApp_get_message; essentially, this is just a plain main function with no extras. Normally, you would just run this program from the console. You wouldn’t make any end-user games or applications with it; it would usually just be some sort of utility. One thing you might use it for is a little utility program that you run from your own application, such as something that performs some operation on a file (perhaps a conversion utility that runs on the Cybiko). Generally, you won’t use this framework much, but I have included it in order to be more complete. The framework is shown in Listing 6.1. The workspace for this application can be found on the CD, named CyBk6_1.
53
Team LRN
54
Chapter 6: Program Frameworks
Listing 6.1 /* ******************************************* *CyBk6_1.C * *27FEB2001 * *"Quick Running" Framework ******************************************* */ //master include file for cybiko sdk #include "cywin.h" //main functions long main(int argc, char* argv[], bool start) { //code for application goes here //return 0, we're done return 0; }
As you can see, the program does almost nothing. It returns zero, but it does nothing else. The first example program in Chapter 2 (CyBk2_1) is an example of the quickrunning framework in use.
Event-Driven Framework The event-driven framework includes the use of init_module and message processing, as do the idle-loop and real-time framework. In fact, they all pretty much work in the same way, but the subtle differences make them useful for different types of applications. In the event-driven framework, the application waits patiently for a message, then handles the message, then goes back to waiting for a message. This is good for most types of non-game applications, like word processors and other tools where there is nothing happening in the background. Most turn-based strategy games and puzzle games fall into this category. Action games, where timing is important and things happen even when the messages aren’t being received, are not good candidates for the event-driven framework. Listing 6.2 shows the event-driven framework. A workspace with this code can be found on the companion CD in the file CyBk6_2. Listing 6.2 /* ******************************************* *CyBk6_2.C
Team LRN
Chapter 6: Program Frameworks
* *16FEB2001 * *Event Driven Framework ******************************************* */ //master include file for cybiko sdk #include "cywin.h" //global variables struct module_t main_module;
//main module
//forward declarations for functions bool Prog_Init(); void Prog_Done();
//initialize the program //clean up for the program
//message routing functions bool Message_pump(struct cWinApp* ptr_win_app); bool Message_handle(struct Message* ptr_message); //message handling functions //key handlers bool OnKeyDown(int scancode,int mask,char ch); bool OnKeyUp(int scancode,int mask,char ch); bool OnCharTyped(int scancode,int mask,char ch); //timer bool OnTimer(); //power down bool OnPowerDown(); //quit bool OnQuit(); //paint bool OnPaint(); //files bool OnFiles(); //focus bool OnLostFocus(); bool OnGotFocus(); //launch bool OnLaunch(); //device bool OnDevice(); //ping bool OnPing(); //shut up bool OnShutUp(); //user bool OnUser(); //main functions
Team LRN
55
56
Chapter 6: Program Frameworks
long main(int argc, char* argv[], bool start) { //declare local variable for message retrieval struct Message* ptr_message; //initialize the main module init_module(&main_module); //initialize the program if(Prog_Init()) { //pump messages Message_pump(main_module.m_process); } //clean up after the program Prog_Done(); //return 0, we're done return 0; } bool Prog_Init() { //initialization //return TRUE if program initialized, and FALSE if it did not return(TRUE); } void Prog_Done() { //cleanup } bool Message_pump(struct cWinApp* ptr_win_app) { bool quit=FALSE; struct Message* ptr_msg; //while there are still messages coming, handle them while(!quit) { ptr_msg=cWinApp_get_message(ptr_win_app,0,1,MSG_USER); quit=!Message_handle(ptr_msg); Message_delete(ptr_msg); } } bool Message_handle(struct Message* ptr_message)
Team LRN
Chapter 6: Program Frameworks
{ //if there is a message... if(ptr_message) { //...check what kind of message it is, and process it switch(ptr_message–>msgid) { case MSG_KEYDOWN: //key has been pressed { if(!OnKeyDown(Message_get_key_param(ptr_message)–>scancode, Message_get_key_param(ptr_message)–>mask, Message_get_key_param(ptr_message)–>ch)) { cWinApp_defproc(main_module.m_process, ptr_message); } }break; case MSG_KEYUP: //key has been released { if(OnKeyUp(Message_get_key_param(ptr_message)–>scancode, Message_get_key_param(ptr_message)–>mask, Message_get_key_param(ptr_message)–>ch)) { cWinApp_defproc(main_module.m_process, ptr_message); } }break; case MSG_CHARTYPED: //character has been generated { if(OnCharTyped(Message_get_key_param(ptr_message)–>scancode, Message_get_key_param(ptr_message)–>mask, Message_get_key_param(ptr_message)–>ch)) { cWinApp_defproc(main_module.m_process, ptr_message); } }break; case MSG_TIMER: //timer event has fired { if(OnTimer()) { cWinApp_defproc(main_module.m_process, ptr_message); } }break; case MSG_POWERDOWN: //a powerdown message has been received { if(OnPowerDown()) { cWinApp_defproc(main_module.m_process, ptr_message); } }break; case MSG_QUIT: //a quit message has been received {
Team LRN
57
58
Chapter 6: Program Frameworks
case
case
case
case
case
case
case
if(OnQuit()) { cWinApp_defproc(main_module.m_process, ptr_message); } return(FALSE); }break; MSG_PAINT: //a paint message has been received { if(OnPaint()) { cWinApp_defproc(main_module.m_process, ptr_message); } }break; MSG_FILES: //a filed message has been received { if(OnFiles()) { cWinApp_defproc(main_module.m_process, ptr_message); } }break; MSG_LOSTFOCUS: //the application has lost focus { if(OnLostFocus()) { cWinApp_defproc(main_module.m_process, ptr_message); } }break; MSG_GOTFOCUS: //the application has received focus { if(OnGotFocus()) { cWinApp_defproc(main_module.m_process, ptr_message); } }break; MSG_LAUNCH: //the application has received a launch message { if(OnLaunch()) { cWinApp_defproc(main_module.m_process, ptr_message); } }break; MSG_DEVICE: //the application has received a device message { if(OnDevice()) { cWinApp_defproc(main_module.m_process, ptr_message); } }break; MSG_PING: //a ping has been received {
Team LRN
Chapter 6: Program Frameworks
if(OnPing()) { cWinApp_defproc(main_module.m_process, ptr_message); } }break; case MSG_SHUTUP: //application has received a shutup message { if(OnShutUp()) { cWinApp_defproc(main_module.m_process, ptr_message); } return(FALSE); }break; case MSG_USER: //application has received a user message { if(OnUser()) { cWinApp_defproc(main_module.m_process, ptr_message); } }break; default: //unknown message { cWinApp_defproc(main_module.m_process, ptr_message); }break; } } return(TRUE); } bool OnKeyDown(int scancode,int mask,char ch) { struct Message* ptr_msg; //if the escape key has been pressed, quit if(scancode==KEY_ESC) { //create a new message ptr_msg=Message_new(sizeof(struct Message)); //make it a quit message ptr_msg–>msgid=MSG_QUIT; //send this message to the message queue Message_post(ptr_msg,cWinApp_get_name(main_module.m_process),get_own_id()); //the message has been handled, so return true return(TRUE); } //if message hasn't been handled, return FALSE return(FALSE); } bool OnKeyUp(int scancode,int mask,char ch)
Team LRN
59
60
Chapter 6: Program Frameworks
{ //if message hasn't been handled, return FALSE return(FALSE); } bool OnCharTyped(int scancode,int mask,char ch) { //if message hasn't been handled, return FALSE return(FALSE); } bool OnTimer() { //if message hasn't been handled, return FALSE return(FALSE); } bool OnPowerDown() { //if message hasn't been handled, return FALSE return(FALSE); } bool OnQuit() { //if message hasn't been handled, return FALSE return(FALSE); } bool OnPaint() { //fill the screen with white DisplayGraphics_fill_screen(main_module.m_gfx,CLR_WHITE); //show the screen DisplayGraphics_show(main_module.m_gfx); //message has been handled return(TRUE); } bool OnFiles() { //if message hasn't been handled, return FALSE return(FALSE); } bool OnLostFocus() { //if message hasn't been handled, return FALSE
Team LRN
Chapter 6: Program Frameworks
61
return(FALSE); } bool OnGotFocus() { //do the same thing as OnPaint return(OnPaint()); } bool OnLaunch() { //if message hasn't been handled, return FALSE return(FALSE); } bool OnDevice() { //if message hasn't been handled, return FALSE return(FALSE); } bool OnPing() { //if message hasn't been handled, return FALSE return(FALSE); } bool OnShutUp() { //if message hasn't been handled, return FALSE return(FALSE); } bool OnUser() { //if message hasn't been handled, return FALSE return(FALSE); }
I know this code is quite lengthy, considering it does almost nothing. However, using this code as a base, you can easily write a function for handling whatever messages may come your way. For example, a MSG_KEYDOWN is processed in OnKeyDown, a MSG_GOTFOCUS is processed in OnGotFocus, and so on. Central to how the event-driven framework operates is the Message_pump function, which reads in messages and sends them to Message_handle, which returns TRUE if the application should continue running, and FALSE if not. Message_handle routes the message based on msgid. From there, it gets sent along to the individual message handler, which returns TRUE if the message was handled, and FALSE if it was not. If the message is not handled by the individual handler
Team LRN
62
Chapter 6: Program Frameworks
function, Message_handle will send the message along to cWinApp_defproc, which will do whatever default processing might be required for the message. Additional functions in this framework are Prog_Init and Prog_Done. Prog_Init currently does nothing but return TRUE. In an application based on this framework, Prog_Init would include any code that sets up global information used by the application. On the other end is Prog_Done, which cleans up any data used by the application after the Message_pump function exits. CyBk6_2 only handles the OnPaint, OnGotFocus, and OnKeyDown messages. The rest just return FALSE, which allows default processing of the messages. During OnPaint, the screen is filled by CLR_WHITE, then shown. During OnGotFocus, OnPaint is called. During OnKeyDown, it checks to see if the Escape key was pressed, and if it was, then it sends MSG_QUIT to the application, which will shut it down.
Idle-Loop Framework In the idle-loop framework (found in CyBk6_3), very little has changed from the event-driven framework. In fact, the changes are simply the addition of a function (Prog_Loop), changing Message_pump, and adding a #define. In the event-driven framework, the program would wait indefinitely for a message to occur, then process the message. In the idle-loop framework, we specify a timeout value at the top of the program, like in Listing 6.3. Listing 6.3 #define MESSAGE_TIMOUT 100
This is used in the new Message_pump function (see Listing 6.4). The only other change is the addition of a Prog_Loop function, which is a void function with no parameters. Listing 6.4 bool Message_pump(struct cWinApp* ptr_win_app) { bool quit=FALSE; struct Message* ptr_msg; //while there are still messages coming, handle them while(!quit) { //grab a message ptr_msg=cWinApp_get_message(ptr_win_app,MESSAGE_TIMEOUT,1,MSG_USER); if(ptr_msg) { //handle the message quit=!Message_handle(ptr_msg); //delete the message Message_delete(ptr_msg);
Team LRN
64
Chapter 6: Program Frameworks
} }
In this framework, the program waits MESSAGE_TIMEOUT clock ticks for a message, and if a message has been received, it is processed through Message_handle. Whether a message is received or not, Message_pump calls Prog_Loop, so that the game appears to be operating in “real time.” One of the problems with this framework is that you can get a considerable amount of latency with user input if you are responding to MSG_KEYDOWN and MSG_KEYUP for your input. For example, you might press and hold down the KEY_UP key, which will send a series of MSG_KEYDOWN messages, and after each message, Prog_Loop will execute. When you release the KEY_UP key, there are still a number of MSG_KEYDOWN messages left in the queue that haven’t been processed, and each of these messages will be processed in the order received, so even after you have released the key, the screen will still scroll up (or whatever your program does when processing KEY_UP). This is latency—input that isn’t processed immediately. Fortunately, there are ways around this. To avoid input latency, you simply make use of the DirectKeyboard functions, which I show in a later chapter.
Dialog-Based Framework In the dialog-based framework, you make use of the Cybiko GUI (graphical user interface) objects to build your application. This winds up looking almost nothing like any of the other frameworks shown before now. The Cybiko GUI objects are complex and difficult to use for a beginner, so I will cover the dialog-based framework in a later chapter.
Multi-threaded Framework In the multi-threaded framework, you have more than one thread of execution operating at the same time. This is like having several programs operating as though it were a single program. One thread might be keeping music playing, another thread might be calculating artificial intelligence, and yet another thread might be maintaining a list of opponents playing on the local network with you. As you might imagine, creating multi-threaded programs is quite complex (since you have to have otherwise independent processes working in sync with one another), and there is no simple framework that works for all multi-threaded needs. I’ll cover multi-threading in a later chapter.
Team LRN
64
Chapter 6: Program Frameworks
} }
In this framework, the program waits MESSAGE_TIMEOUT clock ticks for a message, and if a message has been received, it is processed through Message_handle. Whether a message is received or not, Message_pump calls Prog_Loop, so that the game appears to be operating in “real time.” One of the problems with this framework is that you can get a considerable amount of latency with user input if you are responding to MSG_KEYDOWN and MSG_KEYUP for your input. For example, you might press and hold down the KEY_UP key, which will send a series of MSG_KEYDOWN messages, and after each message, Prog_Loop will execute. When you release the KEY_UP key, there are still a number of MSG_KEYDOWN messages left in the queue that haven’t been processed, and each of these messages will be processed in the order received, so even after you have released the key, the screen will still scroll up (or whatever your program does when processing KEY_UP). This is latency—input that isn’t processed immediately. Fortunately, there are ways around this. To avoid input latency, you simply make use of the DirectKeyboard functions, which I show in a later chapter.
Dialog-Based Framework In the dialog-based framework, you make use of the Cybiko GUI (graphical user interface) objects to build your application. This winds up looking almost nothing like any of the other frameworks shown before now. The Cybiko GUI objects are complex and difficult to use for a beginner, so I will cover the dialog-based framework in a later chapter.
Multi-threaded Framework In the multi-threaded framework, you have more than one thread of execution operating at the same time. This is like having several programs operating as though it were a single program. One thread might be keeping music playing, another thread might be calculating artificial intelligence, and yet another thread might be maintaining a list of opponents playing on the local network with you. As you might imagine, creating multi-threaded programs is quite complex (since you have to have otherwise independent processes working in sync with one another), and there is no simple framework that works for all multi-threaded needs. I’ll cover multi-threading in a later chapter.
Team LRN
Chapter 6: Program Frameworks
65
Summary So, as you can see, there are a number of choices as far as what framework you use as the skeleton of your programs. In most of the future program examples for this book, the framework will be either event-driven, idle-loop, or real-time, based on the nature of the application. Once you get into the GUI part of Cybiko programming, I will present the dialogbased framework again. It’s not terribly hard, but it does look strange to a person who is new to it. By now, you’ve got enough basic knowledge to be able to put together simple Cybiko applications, which means it is time to build upon this knowledge and start making some real applications and games!
Team LRN
Chapter 7
Messages Overview In Chapter 6, we took a look at the various types of program frameworks that you might commonly use for your Cybiko applications and games. Throughout, you undoubtedly noticed the use of the Message struct. However, while dumping pages upon pages of code on you, I didn’t do a whole lot in the way of explaining what these messages are and how they are used. You probably picked up that they are used for input handling. That’s good. It means you’ve been paying attention. In this chapter, I will be exploring basic message handling, with details on what makes up a message, how to retrieve messages, how to handle messages, and how to define your own messages. We aren’t going to fully cover the topic. There are some advanced aspects to the Cybiko messaging system, including sending messages to other Cybikos, and attaching blocks of information (called buffers) to a message, which allows the sending of large amounts of data from one Cybiko to another.
Event-Driven Operating Systems For the Cybiko, there is one primary method of input: the keyboard. Things can happen when you press a key, release a key, or hold down a key. The act of pressing or releasing a key is the most concrete example of what is called an “event.” In the context of the Cybiko, an event is just “something that has happened.” Events are not limited to key presses and releases, of course, but those are the easiest to demonstrate, and thus, are the best examples to use to understand what events are. In order to understand an event-driven operating system, it is customary to talk about how a non-event-driven operating system works, and that means we talk about what happens, exactly, when a key is pressed or released. Every key on the keyboard is part of a circuit. If the circuit is closed, then electricity will flow. If the circuit is open, no electricity flows. This is sort of like a light
66
Team LRN
Chapter 7: Messages
67
switch. The key acts as the switch; pressing the key turns the light on, and releasing the key turns the light off again. The natural position of a key is off. We have to actually apply force in order to turn it on and to keep it on. In the absence of force applied to the key, it will return to the “off” state. There are a number of ways we might get input from such a system. One way would be to check periodically to see if a key is currently pressed, and if it is, then do something about it. The problem with this method is that we will miss input if we take too much time between checking the state of the key. If we were, say, loading a file between checks, the user might press and release a key. When we check again, the switch will be in the off position, so it appears to the computer as though nothing has happened. So, naturally, this method of processing the keyboard just won’t do for us. We need something more reliable. Another way to get input is to have an input device interrupt the computer operation (if only for a fraction of a second) when a state change occurs. This steals a small amount of time from us, but it is much more reliable, as we get all of the state changes recorded and stored for later viewing. However, this does steal away some time from other things, and information about state changes can pile up until there is no room for anything else. The manner in which the Cybiko receives input is similar to this method. The actual method of keyboard input is not documented, but we can assume that there is a “watcher” thread running in the background that monitors key events. So, when you press a key, the Cybiko registers it immediately and places information where we can get to it later. This happens almost without our knowing it. The same thing happens after a key has been held for a period of time. We get another “key is pressed” event. After a “key is pressed” event, we also get a “character has been typed” event. This allows us to easily deal with text input without relying on key codes, which are not the same as the letters and numbers written on those keys. When we release a key, we get a “key is released” message. When any event occurs, it is our responsibility to do something about it. Taking action in response to an event takes many forms. One common example is that pressing the Esc key causes the program to exit. Another might be when pressing an arrow key, we move a cursor around the screen. The possibilities are endless. We let the operating system handle messages that we don’t have to do anything about. This has two benefits. One, we don’t have to duplicate what the operating system handles in our own code. Two, it allows us to pick and choose the events we wish to handle. The basic formula is: if this happens, then do that, where “this” is an event of some sort, and “that” is an action we are taking in response to that event. However, we need a way to represent an event, and a consistent way of doing so for all events, not just keyboard events.
Team LRN
68
Chapter 7: Messages
The Message Class The Message class is the package into which information from an event is stored. It contains not only what kind of event occurred, but may also contain extended information about the event. For example, the extra information in a keyboard event is what key is being pressed, the state of the Shift and function keys, and so on. The Message structure is shown in Listing 7.1. Listing 7.1 struct Message { struct Message* next; char* dst_name; cyid_t cyid_from; cyid_t cyid_to; bool deleted; short msgid; long param [2]; };
The member called next has to do with linking messages together. Since the operating system has no idea how many messages it might be called upon to store at any particular time, it stores them in a linked list and uses pointers to move between them. This member is not terribly important to message handling itself, but more important to message storage. The dst_name member is a char*, so it’s a string. This string stores the name of the process for which this message is bound. For the most part, this is unimportant to message handling. It only becomes important when sending messages. When you are handling messages for your application, only those intended for your process will be read, so you really don’t have to worry about this member much. The cyid_from and cyid_to members deal with the source and destination of the message. Because the Cybiko uses radio communications, your application may get messages coming from other Cybikos in the area. Each Cybiko has its own unique ID number called the CyID. I will talk more about CyIDs in a later chapter. In most cases, the cyid_from and cyid_to members of the Message struct will have the same value. The deleted member has to do with message management on the operating system side. You won’t have to deal with it. The msgid and param members are the two primary means by which you will access message data. The msgid member stores what type of message you are dealing with, and the param array has the “extended” information needed for messages. When working with messages, these are the only members you will access most of the time.
Team LRN
Chapter 7: Messages
69
Types of Messages Now that we’ve established what a message is, we need to talk about the kinds of messages we might encounter. Listing 7.2 shows all of the messages for the Cybiko. Listing 7.2 MSG_KEYDOWN MSG_KEYUP MSG_CHARTYPED MSG_TIMER MSG_POWERDOWN MSG_QUIT MSG_PAINT MSG_FILES MSG_LOSTFOCUS MSG_GOTFOCUS MSG_LAUNCH MSG_DEVICE MSG_PING MSG_SHUTUP MSG_USER
If you were to look up API reference/communications/messaging/defines in the SDK docs, you’ll see all of these messages listed, and if you looked up a particular message, you would see the lack of documentation that accompanies them. You could then scour the example programs that came with the SDK, and notice that very few of these messages are used in examples. The only well-documented messages are MSG_KEYDOWN, MSG_KEYUP, MSG_QUIT, and MSG_SHUTUP. For the rest, your guess is as good as mine. MSG_USER is for defining new messages that only your application handles. I have learned a thing or two about MSG_GOTFOCUS, and how to use it to properly respond to the help key, but that’s really about it. The rest of the messages are mostly a mystery. I will be ignoring undocumented messages. Undocumented usually means “reserved,” and their implementation can change at any time.
Retrieving Messages The first part of message processing is checking for a message, naturally. This is done with either the cWinApp_get_message or the cWinApp_peek_message function. Most of the time, you will want to use cWinApp_get_message unless you really need cWinApp_peek_message. Listing 7.3 shows the prototype for cWinApp_get_message.
Team LRN
70
Chapter 7: Messages
Listing 7.3 struct Message * cWinApp_get_message ( struct cWinApp * ptr_win_app, long timeout, int min, int max);
This function takes four parameters and returns a pointer to a Message object. The first parameter, ptr_win_app, is a pointer to a cWinApp object, or main_module.m_ process in our examples. The second parameter is a timeout value. If zero, this function will wait forever or until an event happens. If it specifies a positive number, it will wait for that many 10 ms intervals to pass, and return 0 if no event occurred in that time. The min and max parameters specify the minimum and maximum value for the messages that should be checked for. You may only wish to look for particular messages. Most of the time, you won’t, so just put 1 for min and WM_USER (or the value of the highest user-defined message) into this parameter. The cWinApp_peek_message function, on the other hand, can be used in one of two ways. Its prototype is shown in Listing 7.4. Listing 7.4 struct Message * cWinApp_peek_message ( struct cWinApp * ptr_win_app, int min, int max );
bool remove,
It has mostly the same parameter list as cWinApp_get_message, and the same return type. The difference is in the second parameter. For cWinApp_peek_message, this is a bool. If this value is TRUE and a message is found, then the message will be removed from the list of messages waiting to be processed. If FALSE, it will leave that message in the waiting list. If there is no message waiting, this function will return 0. So, there are two ways to use this function: n
Call it to determine if there are any messages currently in the queue. Call this with a remove value of FALSE. If the returned value is non-zero, there are messages waiting. This is useful for when you are doing some long task, like loading in a file or something. You can periodically check for messages in the queue; if you receive some, run a small loop that does nothing more than empty out the message queue.
n
Call it to attempt to read messages immediately, then go on to do something else. Whether a message exists or not, it will immediately return. This is not suggested for most applications. If you spend a lot of time doing other things, and not enough time looking for messages, then the messages will pile up quickly and you’ll run out of memory in short order.
Handling Messages Once you’ve read a message, from whatever method, you then have to do something about it, or do nothing about it and let the default handler process it. You will almost never care about every single message that is being received by your program. You might care about whether the Enter key is pressed, but you might not care if the J key
Team LRN
Chapter 7: Messages
71
is pressed, so you would write code for the Enter key, but let the default message handler deal with the J key.
Keyboard Messages Keyboard messages are the best documented messages in the Cybiko SDK. This is due to their great importance in applications and games. Indeed, the keyboard is the only means through which a user can interact with an application. There are three keyboard messages: MSG_KEYDOWN, MSG_CHARTYPED, and MSG_KEYUP. Each of these messages are rather similar in the information that they contain. To best make use of these messages, you’ll need a little understanding of when and how they occur, and what information they contain. Also, you’ll need to learn about a new class, the KeyParam class.
MSG_KEYDOWN There are two situations that cause a MSG_KEYDOWN to fire. First, when a key is initially pressed, one of these messages is sent. Second, after the key has been held down for a certain period of time, another MSG_KEYDOWN is fired, and so you can make use of this “key repeat” feature for entering text. You will usually respond to MSG_KEYDOWN for your own customized controls. However, you should be aware of something. Look at the configuration of your Cybiko keyboard. If it’s like mine, it looks a great deal like the QWERTY keyboard that has become common. Or maybe it looks quite different. This is my point. Since Cybiko, Inc., is an international company, not all of their keyboards will look the same. However, there are some things they all have in common, most notably the arrow keypad, the Esc key, and the five keys to the side of the arrow pad that don’t usually correspond to a particular text character (technically, Enter does, but that’s an exception). If you are using MSG_KEYDOWN to respond to the “1” key, you should probably rethink that. On one keyboard, the “1” key might be its own key. On another keyboard, to type a “1” might require a Shift+key or Fn+key combination, so your response to the “1” key won’t work on that machine. So for the “big buttons” you can feel free to use MSG_KEYDOWN without much danger of not being compatible. For the “little buttons” you are probably better off using MSG_CHARTYPED.
MSG_CHARTYPED After every MSG_KEYDOWN event, a MSG_CHARTYPED event occurs in response to it. The machine uses a keyboard driver to map the key that has been pressed and the current state of the Shift and Fn keys to generate a character. For example, Shift+= will generate a plus sign (+), at least on my keyboard.
Team LRN
72
Chapter 7: Messages
The reason for a separate message like MSG_CHARTYPED is to help counteract what I warned about in the discussion of MSG_KEYDOWN. It helps to achieve hardware independence. All languages of the world have adopted the Arabic system of representing numbers (using the digits 0 through 9), so nearly all keyboards will have some way of generating these characters. Also, most European alphabets use the Roman alphabet or some variation of it (notable exceptions—Greece and Eastern European nations that use the Cyrillic alphabet). Also, foreign keyboards don’t necessarily use the same punctuation that we do. The main idea I want to drive home here is that you cannot assume that, if you are an American or Canadian, that the other users of your application will necessarily be Americans or Canadians. The same thing if you live in Europe. The Cybiko is localized, and has a keyboard appropriate for your area. Even small items like replacing the “#” with the “£” is common for British keyboards. Also, keep in mind your primary method of distribution for your applications: the Internet. The world has gotten very small lately. I commonly talk to people all over the world about programming, and let me tell you, reading code that has been commented in Portuguese is an interesting experience. So, use the “big buttons” when at all possible, and leave the rest of the keyboard for text input only. Sometimes this is not possible, but do try. It makes it easier to distribute your application to the world.
MSG_KEYUP Finally, MSG_KEYUP occurs when a key has been released. Only one MSG_KEYUP will occur. So, even if you’ve had 50 MSG_KEYDOWN and MSG_CHARTYPED events occur, you will get one final MSG_KEYUP for that key. You will rarely, if ever, respond to the MSG_KEYUP event.
The KeyParam Struct We talked a little earlier about the extended information stored within a Message object, in the Param array. This is true of keyboard messages as well, but there is a special utility struct for accessing this information for keyboard events only. Listing 7.5 shows the structure of the KeyParam struct. Listing 7.5 struct KeyParam { int scancode; int mask; char ch; };
The scancode member contains one of the key identifiers. These all begin with KEY_, and there’s a nice long list of them in the SDK docs. Most of them correspond loosely
Team LRN
Chapter 7: Messages
73
to ASCII codes for the characters that the keys represent, but this is not a hard and fast rule. For the “big buttons,” the KEY_* identifiers are >256 (0x100). The mask member contains zero or more bit flags. These are part of an enumeration called keymask_t. There are three different bit flags: KEYMASK_SHIFT, KEYMASK_CONTROL, and KEYMASK_AUTOREPEAT. KEYMASK_SHIFT will be set if the Shift key was being held down during a MSG_KEYDOWN event, and the bit will also be set in the corresponding MSG_CHARTYPED event. KEYMASK_CONTROL is a similar idea, but is instead in response to the Fn key. KEYMASK_AUTOREPEAT is sent with MSG_KEYDOWN and MSG_CHARTYPED events, after the initial pressing of the key. This is how you can filter out the repeated key messages. The ch member is the ASCII character code corresponding to the event. It is mapped based on the character being pressed, the Shift key, and the Fn key. So, how do we grab this information out of a Message object? Quite simply, we use the Message_get_key_param function, shown in Listing 7.6. Listing 7.6 struct KeyParam* Message_get_key_param(struct Message* ptr_message);
This function takes a single parameter, a pointer to a Message object, and returns a KeyParam pointer. From here, you can check the members of the KeyParam struct as shown in Listing 7.7 Listing 7.7 //check for KEY_ESC if(Message_get_key_param(msg)–>scancode==KEY_ESC) { //do something in response to KEY_ESC } //check for status of Shift in key mask if(Message_get_key_param(msg)–>mask&KEYMASK_SHIFT) { //do something in response to shift mask } //check for a generated '0' character if(Message_get_key_param(msg)–>ch=='0') { //do something in response to a generated '0' }
Hopefully, you get the idea of how to handle keyboard messages now.
Focus Messages The focus messages (MSG_GOTFOCUS and MSG_LOSTFOCUS) are also quite important, but not nearly as important as the keyboard messages. Since CyOS is a multitasking operating system, there may be times in which your application will have
Team LRN
74
Chapter 7: Messages
to surrender control to another. Primarily, this occurs when you have called up the Cybiko help system by pressing the help key. If your application continues to draw to the screen while the help system is active, you will get garbled results. Therefore, when the help system comes up, and your application receives a MSG_LOSTFOCUS, your application should “go to sleep.” The easiest way to implement this is with a global Boolean variable that you set to TRUE. When the user exits the help system, your application will receive a MSG_GOTFOCUS, and you can set that variable back to FALSE, redraw the screen, and carry on with whatever the application was doing.
Quit and Shut Up No, I didn’t mean you... Hey! Come back! In the examples with the SDK, the MSG_QUIT and MSG_SHUTUP are given roughly equal strength. When one is received, the program should shut down as quickly as possible. MSG_QUIT generally comes as part of user input. MSG_SHUTUP, I believe, comes from other sources, although I don’t know what. However, to be safe, we should obey the conventions set before us, and treat MSG_SHUTUP and MSG_QUIT the same, i.e., get out of the program, ASAP. The manner in which you do this depends on the structure of your application. If you work on programs based on the frameworks in this book, you don’t really have to do anything, because the framework handles MSG_QUIT and MSG_SHUTUP by exiting the app. If you start making your own frameworks, then your response to these messages might be as simple as a call to the exit function, or it might set some global Boolean variable to TRUE. There are a hundred different ways to do it.
Sending Messages There are a couple of different ways to send messages, and plenty of reasons you might want to send them. The primary method is to use the send_msg function, shown in Listing 7.8. Listing 7.8 bool send_msg(char* app_name, int msgid, long d0, long d1, void* data, size_t size);
This is a pretty cool and flexible function. It will set up and send a message for you, and you just supply the important parameters. The app_name parameter corresponds to the dst_name member of the Message struct. The msgid parameter is used for the msgid member of the Message struct. The d0 and d1 correspond to param[0] and param[1]. The data and size parameters are for buffers. The data parameter is a pointer to some memory containing data you want
Team LRN
Chapter 7: Messages
75
to send with the message, and size is how many bytes are in that memory block. I talk more about buffers in a later chapter. When using send_msg, the rest of the members of the Message struct are taken care of for you. This is a nice, simple way to send messages to your own app. The most commonly sent message will be MSG_QUIT. Listing 7.9 shows an example of how you might send it. Listing 7.9 send_msg(cWinApp_get_name(main_module.m_process),MSG_QUIT,0,0,0,0);//send a quit message
Don’t let the cWinApp_get_name function call throw you. This is just a function that, given a pointer to a cWinApp (i.e., main_module.m_process), will spit out the name of that application. That way, you don’t have to worry about what the application’s name is, and you will save time in coding.
User-Defined Messages The predefined messages for the Cybiko will serve you in good stead. However, at some point, you will probably want to define your own messages. For this, Cybiko has given us MSG_USER. It has a value of 0x2000. Below this value, the msgids are reserved for use by Cybiko, Inc. Above this number, we are free to define them for ourselves as we wish. Creating new messages is no big deal. You can simply make a number of defines, like the one in Listing 7.10. Listing 7.10 #define MSG_MYMSG (MSG_USER) #define MSG_YOURMSG (MSG_USER+1)
You can start with the value of MSG_USER, and go from there. Once you start doing this, however, you will probably want to have an extra #define in there, called MSG_LAST, so that you can use this value in your calls to cWinApp_get_message and only have to update the #define when new message IDs are created. The meaning of the values in param[0] and param[1] for your new messages are entirely up to you. A lot of messages don’t need any sort of extra parameters, such as MSG_QUIT. Others do, like the keyboard messages.
Summary In this chapter, we have explored the basics of Cybiko message handling. This is perhaps the most fundamental aspect of Cybiko programming. Without it, there is hardly a program at all. (This is not to say that those utilities that don’t process messages aren’t programming, but they are not interactive in any sort of meaningful way.)
Team LRN
76
Chapter 7: Messages
This ends the topic of basic message handling. Naturally, there’s a lot more to it than what I have presented here. Indeed, we will have more to cover later on. But you should now have the gist of it, at least, and be able to work with messages.
Team LRN
Chapter 8
Basic Graphics Overview Now that you have the fundamentals of Cybiko programming down, it is time for something a little more fun and productive, namely, graphics. By far, the most noticeable part of any Cybiko application is what is shown on the screen. The screen is the primary method by which a program gets information to the user. Whether those graphics are in the form of text, icons, lines, pixels, or rectangles is immaterial. As long as the program is successful in giving the user feedback on what he is doing (whether he is writing an e-mail or playing a game), then graphics have served their purpose. This chapter serves as an introduction into Cybiko graphics. Mainly, we will be doing simple stuff like clearing the screen and drawing simple graphical primitives like pixels, lines, and rectangles. In the next chapter, we get to bitmaps and fonts.
TGraph, Graphics, and DisplayGraphics The Cybiko graphics system, like everything else, is an object-oriented, class-based system, like the ones we discussed in Chapter 5. There are three classes for dealing with graphics: TGraph, Graphics, and DisplayGraphics. These are shown in Table 8.1, along with a brief description of what these classes encompass. Table 8.1 Cybiko graphics classes Class
Purpose
TGraph
Base implementation of raster/2d graphics (abstract class).
Graphics
Implementation for drawing on Bitmap objects.
DisplayGraphics
Implementation for drawing on the main display.
77
Team LRN
78
Chapter 8: Basic Graphics
As noted in the table, TGraph is an abstract class, which means it isn’t actually useful. You will never have a variable of type TGraph. Its purpose is to provide base functionality for its derived classes, Graphics and DisplayGraphics. The Graphics class is the first non-abstract, or “concrete,” class in the graphics hierarchy. We won’t be using it in this chapter, but we will later on when we get into drawing bitmaps. The DisplayGraphics class is the main class we are concerned with in this chapter, since it allows us to write onto the Cybiko’s display. It is derived from Graphics, and contains all of the functionality from both TGraph and Graphics.
Creating a DisplayGraphics Object You don’t really “create” a DisplayGraphics object. One always exists, and it is shared by all applications running on the Cybiko. Because of this, there is no DisplayGraphics_ctor or DisplayGraphics_dtor. Instead, you just grab it from the module you initialize using init_module. Since we are using the variable main_module, we can access the DisplayGraphics object through main_module.m_gfx. This is a pointer to the DisplayGraphics object. Another way we might grab the DisplayGraphics pointer is to call cWinApp_ get_display. This function takes no parameters and returns a pointer to the DisplayGraphics object. This would really only be useful in a program that was run from the console that, for example, saved a screen shot of whatever application is running.
Clearing the Screen Now that you’ve got the DisplayGraphics object’s pointer, you can begin to do things with it. The simplest operation you’d want to do is to clear the screen. Before we get to that, however, I need to tell you just a little bit about Cybiko colors.
color_t Within the include file cyber-types.h, there are a number of type aliases (typedefs). One of these is the color_t typedef, shown in Listing 8.1. Listing 8.1 typedef int color_t
This isn’t particularly significant in itself. I just wanted to show you that in all of the functions that take a color_t as a parameter, you can use an int just as easily. There are lots of functions that take color_t parameters, and I wanted to save you the hassle of thinking to yourself, what the heck is a color_t?
Team LRN
Chapter 8: Basic Graphics
79
In the include file cyber-graph.h, there are four #defines, one for each of the colors that can be shown on the Cybiko. These #defines are shown in Listing 8.2. Listing 8.2 #define #define #define #define
CLR_WHITE CLR_LTGRAY CLR_DKGRAY CLR_BLACK
0 85 171 255
There are a few things to note here. First, Cybiko colors increase from white to black, which is opposite of how graphics are done on most other platforms. Second, these values are not sequential, and using values between these cause unpredictable results. As for the reason that these values are opposite of other platforms, consider how an LCD display works versus how a cathode ray tube (a monitor) works. On an LCD, electricity is used to darken a given pixel, which is “white” when no energy is supplied. On a monitor, energy is taken to lighten a pixel, which is black without any energy. As for why the values are non-sequential, I’m not sure. I theorize that at some point in the future, there will be more colors on the Cybiko, and because of the need to be backward compatible with older software, these values were chosen.
DisplayGraphics_fill_screen Once you’ve got a handle on color_t, filling the screen is a piece of cake. The function for this is DisplayGraphics_fill_screen, and the syntax for it is shown in Listing 8.3. Listing 8.3 void DisplayGraphics_fill_screen ( struct DisplayGraphics * ptr_gfx, color_t fc );
This function takes two parameters and returns no value. The first parameter is the pointer to your DisplayGraphics object (i.e., main_module.m_gfx), and the second parameter is a color_t value, i.e., CLR_WHITE.
DisplayGraphics_show After you have performed all of the operations that you wish to on the DisplayGraphics object, you must then send it to the actual display, using DisplayGraphics_show. The syntax for this function is shown in Listing 8.4. Listing 8.4 void DisplayGraphics_show ( struct DisplayGraphics * );
ptr_gfx
Team LRN
80
Chapter 8: Basic Graphics
This function takes a single parameter (main_module.m_gfx), and returns no value. This function updates the display. The reason you have to call this function is so that the user of your application doesn’t have to see the graphics actually being drawn on the screen, which means that any animations shown will be smooth.
Screen Filling Example Example CyBk8_1 is the screen filling example. It can be found on the companion CD in the Examples folder. This example is built using the event-driven framework, so you can refer back to CyBk6_2 for details on how that framework operates. Only two of the many functions from the event-driven framework need to be modified to create CyBk8_1: OnGotFocus (shown in Listing 8.5.1) and OnKeyDown(shown in Listing 8.5.2). Listing 8.5.1 bool OnGotFocus() { //clear the screen white DisplayGraphics_fill_screen(main_module.m_gfx,CLR_WHITE); //show the screen DisplayGraphics_show(main_module.m_gfx); //handled, return true return(TRUE); }
OnGotFocus simply clears the screen to white, so that there are no remnants of the Intro.pic or Root.spl files left on the display. (I consider leaving artifacts unprofessional.) Listing 8.5.2 bool OnKeyDown(int scancode,int mask,char ch) { struct Message* ptr_msg; switch(scancode) { case KEY_ESC://escape key { //create a new message ptr_msg=Message_new(sizeof(struct Message)); //make it a quit message ptr_msg–>msgid=MSG_QUIT; //send this message to the message queue Message_post(ptr_msg,cWinApp_get_name(main_module.m_process),get_own_id() );
Team LRN
Chapter 8: Basic Graphics
//the message has been handled, so return true return(TRUE); }break; case KEY_1: { //fill the screen DisplayGraphics_fill_screen(main_module.m_gfx,CLR_WHITE); //show the screen DisplayGraphics_show(main_module.m_gfx); //the message has been handled, so return true return(TRUE); }break; case KEY_2: { //fill the screen DisplayGraphics_fill_screen(main_module.m_gfx,CLR_LTGRAY); //show the screen DisplayGraphics_show(main_module.m_gfx); //the message has been handled, so return true return(TRUE); }break; case KEY_3: { //fill the screen DisplayGraphics_fill_screen(main_module.m_gfx,CLR_DKGRAY); //show the screen DisplayGraphics_show(main_module.m_gfx); //the message has been handled, so return true return(TRUE); }break; case KEY_4: { //fill the screen DisplayGraphics_fill_screen(main_module.m_gfx,CLR_BLACK); //show the screen DisplayGraphics_show(main_module.m_gfx); //the message has been handled, so return true return(TRUE); }break; }
Team LRN
81
82
Chapter 8: Basic Graphics
//if message hasn't been handled, return FALSE return(FALSE); }
In the OnKeyDown function, depending on the value of scancode, different things occur. If the scancode is KEY_ESC, MSG_QUIT is posted to the queue. If the number 1, 2, 3, or 4 is pressed, then the screen is cleared to the appropriate color, and the screen is updated with DisplayGraphics_show. This application may be extremely simple, but it demonstrates one of the uses of the event-driven framework. The application responds to user input by giving visual feedback. Also, it took very little code to change the framework into an actual example that does something.
Plotting Pixels Pixel is short for picture element. At least, that’s what all of the books on graphics say. I’ve never been sure how the “x” got in there, but so it goes. It is the smallest unit of graphics, making it the equivalent of the atom as far as graphics are concerned. The basic idea here is that if you can plot a pixel, you can do anything graphically. This is true, sort of. In more advanced graphical operations, doing everything by plotting the individual pixels would be too inefficient. Often you will plot multiple pixels at the same time, but that doesn’t change the fact that you can do anything if you can plot a pixel. The pixel plotting function is called DisplayGraphics_set_pixel, and the syntax for it is shown in Listing 8.6. Listing 8.6 void DisplayGraphics_set_pixel ( struct DisplayGraphics * ptr_gfx, int fx, int fy, color_t fc );
This function takes four parameters and returns no value. The first parameter is the pointer to the DisplayGraphics object. The next two parameters are the x and y location for the pixel. The last parameter is the color.
Pixel Plotting Example For the pixel plotting demo, I started with an idle-loop framework (see example CyBk6_3). I chose this framework because, in the absence of user input, I wanted random pixels to be displayed on the screen. The pixel plotting demo can be found on the CD in CyBk8_2. The only function I had to change for this example was Prog_Loop, which is shown in Listing 8.7.
Team LRN
Chapter 8: Basic Graphics
83
Listing 8.7 void Prog_Loop() { int x; int y; color_t col; //random x position x=(int)random(160); //random y position y=(int)random(100); //random color col=(color_t)random(4); //convert to cybiko color switch(col) { case 0: col=CLR_WHITE; break; case 1: col=CLR_LTGRAY; break; case 2: col=CLR_DKGRAY; break; case 3: col=CLR_BLACK; break; } //plot the pixel DisplayGraphics_set_pixel(main_module.m_gfx,x,y,col); //show the screen DisplayGraphics_show(main_module.m_gfx); }
Figure 8.1 shows the output of this application, as seen on the Cybiko. I placed a black border around the image, so that it would stand out against this white page.
Team LRN
84
Chapter 8: Basic Graphics
Figure 8.1: Output of CyBk8_2
The code in Prog_Loop is pretty simple. A random (x,y) value is chosen, and then a random color 0 through 3, which is converted into the Cybiko equivalent color by the switch. The pixel is then written and the screen is shown. One function that I used in Prog_Loop that I hadn’t covered prior to now is the random function. In other versions of C and C++, the function for generating “random” numbers is called rand, and it takes no parameters. On the Cybiko, the function is called random, and it takes a single parameter, the number that is the highest value you want from the function plus one. The lowest random number is zero. So, if you wanted a random value from 0 to 9, you would call random(10).
Retrieving Pixels On the flip side of DisplayGraphics_set_pixel is DisplayGraphics_get_pixel, which retrieves the value of a pixel on the screen. The syntax for this function is shown in Listing 8.8. Listing 8.8 color_t DisplayGraphics_get_pixel( struct DisplayGraphics * ptr_gfx, int fx, int fy );
This function takes three parameters, and returns a color_t. The first parameter is the pointer to the DisplayGraphics object. The second and third parameter are the x and y coordinate of the pixel that you wish to retrieve. I don’t have an example program for DisplayGraphics_get_pixel, but I wanted to include it around the same time as DisplayGraphics_set_pixel, so that you have it at your disposal should you need it.
Team LRN
Chapter 8: Basic Graphics
85
Drawing Lines One step up from plotting pixels is line drawing. A line is an approximation of the inifinitely thin mathematical line between two (x,y) coordinates. Lines can be used together to create more complicated shapes, like triangles and rectangles, and can even be used to approximate circles. Because of the way that a graphical display is laid out, some types of lines are easier to draw than others, easier meaning faster and with fewer calculations. The easiest lines are horizontal and vertical, since in a horizontal line, the y value remains constant and the x value changes, and in a vertical line, the x remains constant while the y changes. In other lines, the x and y values both change, so there are more calculations that the line drawing function has to do to make it look right. Because of this, there are two special case functions for horizontal and vertical lines for the Cybiko, DisplayGraphics_draw_hline and DisplayGraphics_draw_vline.
Setting the Current Color Before we draw any lines, we first must inform Cybiko of which color we intend to use for line drawing. This is done with DisplayGraphics_set_color. The syntax is shown in Listing 8.9. Listing 8.9 void DisplayGraphics_set_color( struct DisplayGraphics * ptr_gfx, color_t fc );
This function takes two parameters and returns no value. The first parameter is the pointer to the DisplayGraphics object, and the second is a color_t. So, if you wanted to write black lines, you would use CLR_BLACK as the second parameter.
Horizontal Lines As stated earlier, horizontal lines are much easier to draw than diagonals, since you can leave y constant and make an x loop that sets the pixels. For this reason, Cybiko has a special function called DisplayGraphics_draw_hline for drawing horizontal lines. The syntax for this function is shown in Listing 8.10. Listing 8.10 void DisplayGraphics_draw_hline( struct DisplayGraphics * ptr_gfx, int x, int y, int xx );
Team LRN
86
Chapter 8: Basic Graphics
This function takes four parameters and returns no value. The first parameter is the pointer to the DisplayGraphics object, and the next two parameters are x and y values indicating where to start the horizontal line. The last parameter is the x coordinate of the other end of the line. This function draws a horizontal line between (x,y) and (xx,y).
Vertical Lines Similar to horizontal lines, vertical lines are easy to draw, since you can just loop the y value while keeping the x value constant. The vertical line function is called DisplayGraphics_draw_vline, and the syntax is shown in Listing 8.11. Listing 8.11 void DisplayGraphics_draw_vline( struct DisplayGraphics * ptr_gfx, int x, int y, int yy );
Like DisplayGraphics_draw_hline, this function takes four parameters and returns no value. The only difference between this function and the horizontal line function (other than the name of the function, of course) is the meaning of the last parameter, which in this function is the y coordinate of the other end of the line. This function draws a vertical line between (x,y) and (x,yy).
Free-Form Lines The final line drawing function applies to all lines that are neither horizontal nor vertical. It is called DisplayGraphics_draw_line. The syntax for this function is shown in Listing 8.12. Listing 8.12 void DisplayGraphics_draw_line( struct DisplayGraphics * ptr_gfx, int x, int y, int xx, int yy );
This function takes five parameters and returns no value. The first parameter is the pointer to the DisplayGraphics object. The next two parameters are the values of the starting (x,y) coordinate. The last two parameters are the values of the ending (x,y) coordinate. This function draws a line from (x,y) to (xx,yy).
Team LRN
Chapter 8: Basic Graphics
87
Random Lines Example Now that you’ve got a handle on lines, it is time for another example. CyBk8_3 on the companion CD contains the code for the line drawing demo. Like the pixel plotting demo, this example is built using the idle-loop framework, so the only function that has changed is Prog_Loop, which is shown in Listing 8.13. Listing 8.13 void Prog_Loop() { int x; int y; int xx; int yy; color_t col; //starting position //random x position x=(int)random(160); //random y position y=(int)random(100); //ending position //random x position xx=(int)random(160); //random y position yy=(int)random(100); //random color col=(color_t)random(4); //convert to cybiko color switch(col) { case 0: col=CLR_WHITE; break; case 1: col=CLR_LTGRAY; break; case 2: col=CLR_DKGRAY; break; case 3: col=CLR_BLACK; break; }
Team LRN
88
Chapter 8: Basic Graphics
//set the color DisplayGraphics_set_color(main_module.m_gfx,col); //draw the line DisplayGraphics_draw_line(main_module.m_gfx,x,y,xx,yy); //show the screen DisplayGraphics_show(main_module.m_gfx); }
If you’re thinking this looks a lot like the pixel plotting demo, you’re right. I took the code for CyBk8_2 and just adapted it into CyBk8_3. The only real differences are the addition of another (x,y) coordinate pair and which functions are called to actually draw the line. Figure 8.2 shows the output of CyBk8_3. Figure 8.2: Output of CyBk8_3
That’s all there is to line drawing. It’s not really that much more difficult than pixel plotting. Most of the time, line drawing is unimportant (games and applications tend to be bitmap based rather than line based), but it is still a good introduction into drawing primitives.
Rectangles The last primitive type for the chapter is the rectangle. Rectangles on the Cybiko come in two flavors, framed and filled. A framed rectangle just draws the border (i.e., the horizontal and vertical lines that make up the outside of the rectangle. A filled rectangle fills in all of the pixels inside as well. Like lines, you need to call DisplayGraphics_set_color before drawing a rectangle of a certain color.
Framed Rectangles A framed rectangle just draws the border pixels of a rectangle. The function for doing this is DisplayGraphics_draw_rect, and the syntax is shown in Listing 8.14.
Team LRN
Chapter 8: Basic Graphics
89
Listing 8.14 void DisplayGraphics_draw_rect( struct DisplayGraphics * ptr_gfx, int fx, int fy, int fw, int fh );
This function takes five parameters and returns no value. The first parameter is the pointer to the DisplayGraphics object. The next two parameters are the values of the (x,y) coordinate for the upper-left corner of the rectangle. The last two parameters are the width and height of the rectangle (not the position of the lower-right corner, as you might expect). Many times when drawing a rectangle, you know the lower-right corner, but you don’t know what the width and height are, and you don’t have a piece of scrap paper or a calculator handy. For example, you might want to draw a rectangle from (40,40) to (80,80). There is a nice simple formula for calculating the width and height shown in Listing 8.15. Listing 8.15 //left and top are the left and top values //right and bottom are the right and bottom values //width and height are self explanatory. //calc width and height width=right+1–left; height=bottom+1–top; //draw rectangle DisplayGraphics_draw_rect(main_module.m_gfx,left,top,width,height);
Filled Rectangles The function used for filling rectangles is called DisplayGraphics_fill_rect. The syntax is shown in Listing 8.16. Listing 8.16 void DisplayGraphics_fill_rect( struct DisplayGraphics * ptr_gfx, int fx, int fy, int fw, int fh );
The parameter list is exactly the same as DisplayGraphics_draw_rect, so I won’t repeat it here. The same set of calculations for width and height can be used here as well as for drawing a framed rectangle.
Team LRN
90
Chapter 8: Basic Graphics
rect_t Besides the functions DisplayGraphics_draw_rect and DisplayGraphics_fill_rect, there are two other functions that you can use to draw rectangles. These are the _Ex functions DisplayGraphics_draw_rect_Ex and DisplayGraphics_fill_rect_Ex. The syntax for both of these functions is shown in Listing 8.17. Listing 8.17 void DisplayGraphics_draw_rect_Ex( struct DisplayGraphics * ptr_gfx, struct rect_t * ptr_rectangle ); void DisplayGraphics_fill_rect_Ex( struct DisplayGraphics * ptr_gfx, struct rect_t * ptr_rectangle );
Both of these functions return no values and have two parameters. The first parameter is the pointer to the DisplayGraphics object, and the second parameters is a pointer to a rect_t. A rect_t is nothing more than a simple struct. It is shown in Listing 8.18. Listing 8.18 struct rect_t { short x short y short w short h };
As you might imagine, rect_t is just a shorthand way of describing a rectangle. If you had many rectangles that you needed to draw, you might be better off with a rect_t array to keep track of them. The four data members of rect_t are the x, y pair for the upper-left corner, and the width (w) and height (h) of the rectangle.
The rect_t Functions The rect_t struct can come in quite handy, and Cybiko C has a few functions to help you make the best use of them. There are only three: rect_set, rect_and, and rect_or.
rect_set This function is really great for setting up the dimensions of a rectangle without having to do it manually on four different lines. For example, to manually set up a rect_t to encompass the entire screen, you would have to use the code in Listing 8.19.
Team LRN
Chapter 8: Basic Graphics
91
Listing 8.19 rect_t rcScreen; rcScreen.x=0; rcScreen.y=0; rcScreen.w=160; rcScreen.h=100;
But if you use rect_set, all of this can be done on a single line, and it makes the intent of your code much easier to see. An example of rect_set is shown in Listing 8.20. Listing 8.20 rect_t rcScreen; rect_set(&rcScreen,0,0,160,100);
The parameters for rect_set should be pretty obvious: a pointer to a rect_t followed by x, y, w, and h. The function returns no value. Using rect_set can save you quite a bit of typing.
rect_and This function is good for collision detection. If you had two objects in a game and were keeping track of them using rect_t’s, you can use rect_and to determine not only if those rectangles overlap, but by how much they overlap. The syntax for rect_and is shown in Listing 8.21. Listing 8.21 bool rect_and( struct rect_t * ptr_rectangle, struct rect_t * ptr_rectangle_1, struct rect_t * ptr_rectangle_2 );
This function returns TRUE if an intersection exists, and FALSE if no intersection exists. The first parameter is a pointer to a rect_t in which the intersection will be stored. The second and third parameters are the two rect_t’s that you are testing for intersection.
rect_or The rect_or function figures out the smallest rectangle into which two source rectangles can be joined. This function has its uses, especially for creating update regions. The syntax is shown in Listing 8.22. Listing 8.22 bool rect_or( struct rect_t * ptr_rectangle, struct rect_t * ptr_rectangle_1, struct rect_t * ptr_rectangle_2 );
Team LRN
92
Chapter 8: Basic Graphics
Similar to rect_and, this function returns TRUE if the union exists, and FALSE if it does not. The first parameter is filled in with details of the resulting union, and the other two parameters are the source rect_t’s.
Rectangle Drawing Example Naturally, a discussion of rectangles would not be complete without a rectangle drawing demo. This example can be found in CyBk8_4 on the companion CD. This example was created with the idle-loop framework, and has the same code base as CyBk8_2 and CyBk8_3. The only function that changed was Prog_Loop, which is shown in Listing 8.23. Listing 8.23 void Prog_Loop() { int x; int y; int w; int h; color_t col; //starting position //random x position x=(int)random(160); //random y position y=(int)random(100); //width/height //random width w=(int)random(160–x); //random height h=(int)random(100–y);
//159+1–x //99+1–y
//random color col=(color_t)random(4); //convert to cybiko color switch(col) { case 0: col=CLR_WHITE; break; case 1: col=CLR_LTGRAY; break; case 2: col=CLR_DKGRAY; break; case 3:
Team LRN
Chapter 8: Basic Graphics
93
col=CLR_BLACK; break; } //set the color DisplayGraphics_set_color(main_module.m_gfx,col); //draw the line DisplayGraphics_draw_rect(main_module.m_gfx,x,y,w,h); //show the screen DisplayGraphics_show(main_module.m_gfx); }
By now, this code should be pretty easy to follow. It simply picks a random x and y coordinate, and based on them, it picks a random width and height for the rectangle. The color selection function is the same as in the line drawing demo. Figure 8.3 shows a screen shot of CyBk8_4 in action. Figure 8.3: Output of CyBk8_4
If you are interested in seeing a filled rectangle demo, you can replace the draw function with a fill function, and remake the project. Similarly, you could adapt the program to use rect_t and the draw_rect_Ex function, rather than the normal draw_rect function.
Summary That’s all there is to drawing simple primitives on the screen of the Cybiko. You should now have a good grasp of the DisplayGraphics object, and how to use it to draw pixels, lines, and rectangles. Admittedly, the examples in this chapter aren’t very fancy, but do play around with them a bit. Make a demo that does all three types of primitives. Play around with it, and gain some Verstehen. Next up, we’re moving on to bitmaps and fonts, or at least the rudiments of them.
Team LRN
Chapter 9
Bitmap and Font Basics Overview Pixels, lines, and rectangles are swell and all that, but they aren’t well suited to communicate with the user, at least, not all by themselves. In the modern age, users are accustomed to pictograms and text. Not too long ago, communication with the user was performed strictly through text interfaces, and still is on some systems. However, with the popularization of icon-based user interfaces, text has become less important, although you will still use it quite a bit. Whether you are using text or graphical icons, you are simply using a pattern of pixels which approximate something, be it the letter “F” or a picture of a pencil. These are all glyphs—pixellated approximations of real-world symbols or objects that (in theory) have meaning to you. On the Cybiko, all of these are bitmap objects. Even letters are bitmap objects (or rather, a series of bitmap objects representing letters).
Bitmap Objects If you’ve worked with bitmaps before on other platforms, feel free to skip down to “Creating a Bitmap Resource.” This is the bit where I explain what bitmaps are. A bitmap is an array of bit data that represents pixel data. It is simply a block of memory that is treated as though it were a two-dimensional array of pixel colors. On the Cybiko, there are two types of bitmaps, monochrome and four-color (xpic is a totally different story). A monochrome bitmap has one bit for every pixel, and a four-color bitmap has two bits for every pixel. The number of bits required for each pixel is called the bpp (bits per pixel) or, the color depth. In this text, I will use bpp. When I refer to a 1 bpp image, I will call it a monochrome bitmap or a mono bitmap. When I speak of a 2 bpp image, I will just use the word “bitmap.” In other words, you can assume I’m talking about the four-color bitmap, unless I specify otherwise.
94
Team LRN
Chapter 9: Bitmap and Font Basics
95
You’ve already been working with bitmaps, in the form of Root.ico and Intro.pic. However, you haven’t been loading and manipulating these yourself, and that’s what you’re here to learn.
Creating a Bitmap Resource In order to use a bitmap on the Cybiko, you must first have it on the Cybiko. This should go without saying. In order to get it onto your Cybiko, usually in the company of a game or application that uses that bitmap, you must make it into a resource of that application. Most of the time, I just make normal Windows .bmp files and use 2pic to convert them to the Cybiko format. From there, I put the name of the resource into Filer.list, and from there, it gets compressed and stored in my application archive. All of this stuff is covered back in Chapter 4. The code for loading in a bitmap resource is pretty simple. First, you must have a Bitmap object variable in your program, as in Listing 9.1. Listing 9.1 struct Bitmap bmp1;
The Bitmap struct is just another class we use to abstract objects. The actual struct is mostly hidden to us, and more importantly, we do not and should not care that much about the actual way that the Bitmap class is implemented. The Bitmap class has four constructors, named Bitmap_ctor, Bitmap_ctor_ Ex1, Bitmap_ctor_Ex2, and Bitmap_ctor_Ex3. The names aren’t particularly helpful in telling you which individual constructor you should use for what purpose, but it is a good example of the interface standard for constructors.
Bitmap_ctor This is the simplest constructor. The syntax is shown in Listing 9.2. Listing 9.2 struct Bitmap * Bitmap_ctor( struct Bitmap * ptr_bitmap );
This function takes a pointer to a Bitmap object that has already been allocated and returns the same pointer. This function creates an empty bitmap. Why in the world you would use it is beyond me. I provide it here for completeness only.
Bitmap_ctor_Ex1 Unlike Bitmap_ctor, Bitmap_ctor_Ex1 actually does something useful, and you will wind up using this function a great deal in your code. The syntax is shown in Listing 9.3.
Team LRN
96
Chapter 9: Bitmap and Font Basics
Listing 9.3 struct Bitmap * Bitmap_ctor_Ex1( struct Bitmap * ptr_bitmap, char * filename );
This function returns a pointer to the newly constructed bitmap object. It takes two parameters. The first is a pointer to a Bitmap object, and the second is the name of the resource you wish to load into that bitmap. When using resources that contain only a single bitmap, this is the function I use. I’ve gotten a lot of mileage out of it.
Bitmap_ctor_Ex2 The third constructor, _Ex2, isn’t quite as commonly used as _Ex1, although it still comes in pretty handy, so it’s a good function to have. The syntax for it is shown in Listing 9.4. Listing 9.4 struct Bitmap * Bitmap_ctor_Ex2( struct Bitmap * ptr_bitmap, int width, int height, int bpp );
Like the other constructors, this function returns a pointer to the newly constructed bitmap. It has four parameters, which are listed and explained in Table 9.1. Table 9.1 Bitmap_ctor_Ex2 parameters Parameter
Purpose
ptr_bitmap
A pointer to a Bitmap object that you are constructing.
width
The desired width of the bitmap.
height
The desired height of the bitmap.
bpp
The desired bits per pixel of the bitmap.
This function creates a blank bitmap with all color bits set to zero. This is quite useful for creating temporary bitmap storage areas in memory, for use as a double buffer or a dozen other reasons. There will be more on this in Chapter 14.
Bitmap_ctor_Ex3 The last constructor, _Ex3, can be pretty handy as well. It makes a duplicate of an already existing bitmap. The syntax for this function is shown in Listing 9.5.
Team LRN
Chapter 9: Bitmap and Font Basics
97
Listing 9.5 struct Bitmap * Bitmap_ctor_Ex3( struct Bitmap * ptr_bitmap, struct Bitmap * templ );
Like the other constructors, this function returns a pointer to the newly constructed Bitmap object. The two parameters are the pointer to the bitmap that is going to be constructed, and a Bitmap object pointer to have the information copied from.
Drawing a Bitmap on Screen Once you’ve constructed a Bitmap object all you need to do is draw it on the screen, and then show the screen using DisplayGraphics_show. The function to use here is DisplayGraphics_draw_bitmap. The syntax is shown in Listing 9.6. Listing 9.6 void DisplayGraphics_draw_bitmap( struct DisplayGraphics * ptr_gfx, struct Bitmap * bmp, int left, int top, int fm );
This function returns no value, and takes five parameters, which are listed and explained in Table 9.2. Table 9.2 DisplayGraphics_draw_bitmap parameters Parameter
Purpose
ptr_gfx
The pointer to the DisplayGraphics object.
bmp
A pointer to a bitmap that you wish to draw.
left
The x coordinate for the left of the bitmap.
top
The y coordinate for the top of the bitmap.
fm
A bitmap writing mode.
The bitmap drawing function is pretty simple: you essentially just say what you want drawn, where you want it drawn, and how you want it drawn. The “how” part is the fm parameter. If you just want to draw the Bitmap object as it appears, you use BM_NORMAL. However, there are some special effects you can achieve using different BM_* constants. These constants are listed and explained in Table 9.3.
Team LRN
98
Chapter 9: Bitmap and Font Basics
Table 9.3 BM_* constants Constant
Value
Meaning
BM_NORMAL
0
Write the bitmap as normal.
BM_INVERSE
1
Invert the colors of the bitmap.
BM_FLIPX
2
Mirror the bitmap horizontally (draw it backward).
BM_FLIPY
4
Mirror the bitmap vertically (draw it upsidedown).
NOTE: The BM_* constants, other than BM_NORMAL, represent individual bits, so you can combine these values to achieve more than one effect at the same time. You can, for example, use BM_FLIPX | BM_INVERSE, to get a backward, color-inverted bitmap drawn on the screen.
Draw Modes Another thing you have to think about when creating bitmaps is what your current draw mode is. Up until now, I haven’t made mention of draw modes, but since you can use them to create special effects with bitmaps, they bear mentioning during a Bitmap object discussion. drawmode is a property of the DisplayGraphics object, which by now you should be pretty familiar with. There are two functions dealing with drawmode, DisplayGraphics_set_draw_mode and DisplayGraphics_get_draw_mode. The syntax for these functions are shown in Listings 9.7.1 and 9.7.2, respectively. Listing 9.7.1 void DisplayGraphics_set_draw_mode( struct DisplayGraphics * ptr_gfx, drawmode_t dm );
Listing 9.7.2 drawmode_t DisplayGraphics_get_draw_mode( struct DisplayGraphics * ptr_gfx );
These functions are pretty simple to understand just by looking at them, so I won’t insult your intelligence by giving you a parameter breakdown. You may, however, notice the use of drawmode_t. This is just a typedef of int, like color_t. The drawmode_t type is used only for the two functions above. There are three different draw modes, and each has its own peculiar properties. The three draw modes are DM_PUT, DM_OR, and DM_XOR. I’m going to explain them now, but I’ll be returning to them in Chapter 14.
Team LRN
Chapter 9: Bitmap and Font Basics
99
DM_PUT In DM_PUT mode, the source pixel of the bitmap is written to the destination without regard to what is already on the destination. This means that however your Bitmap object looks in the file is how it will show up on the display. You’ll use this quite a bit for backgrounds. For now, this is the only draw mode we will use. DM_OR In DM_OR mode, the source pixel of the bitmap is checked against the destination’s background color (set using DisplayGraphics_set_bkcolor and retrieved using DisplayGraphics_get_bkcolor, which you can look up in the SDK; they are simple functions). If the source pixel matches the background color, nothing is written. If it does not match, the source pixel is written. This give the effect of transparency, but requires you to give up a color. There is a way to have transparency without giving up any colors, but we won’t get into that until Chapter 17. DM_XOR DM_XOR is a non-destructive way to write a bitmap onto a destination. The cool part about DM_XOR is that if you write the same bitmap in the same position twice while using DM_XOR, it will appear as though the bitmap was never there. Also, DM_XOR guarantees that the bitmap will contrast with whatever is on the display, making it useful for cursors and other things of that nature. Being “Draw-Mode Friendly” I’ll add this final note about draw modes, and then I’ll shut up about them until later. In a real game or application, you are likely going to need to change draw modes and background colors frequently. To keep glitches to a minimum, I recommend that when you are changing either the draw mode or the background color, you should first store the old value of those properties, and restore them after you are finished drawing. An example of this is shown in Listing 9.8. Listing 9.8 color_t old_bkcolor; drawmode_t old_drawmode; //retrieve current settings old_bkcolor=DisplayGraphics_get_bkcolor(main_module.m_gfx); old_drawmode=DisplayGraphics_get_draw_mode(main_module.m_gfx); //set new settings DisplayGraphics_set_bkcolor(main_module.m_gfx,new_bkcolor); DisplayGraphics_set_draw_mode(main_module.m_gfx,new_drawmode); //do whatever //restore settings DisplayGraphics_set_bkcolor(main_module.m_gfx,old_bkcolor); DisplayGraphics_set_draw_mode(main_module.m_gfx,old_drawmode);
Team LRN
100
Chapter 9: Bitmap and Font Basics
Doing this ensures that your changing the draw mode or background color won’t adversely affect another part of the application. Prior planning prevents poor performance.
Cleaning Up after a Bitmap The Bitmap object has a standard destructor, Bitmap_dtor. The syntax is shown in Listing 9.9. Listing 9.9 void Bitmap_dtor( struct Bitmap* ptr_bitmap, int memflag );
This function returns no value. The first parameter is the pointer to the bitmap that is being destructed. The second parameter is either LEAVE_MEMORY or FREE_ MEMORY, which depends on how you created the bitmap.
Bitmap Example I’ve thrown a lot of stuff at you, without any really solid examples to go along with it. Well, now I’m going to correct that situation. CyBk9_1 on the companion CD contains the workspace for a simple bitmap demo. Unlike all of the previous examples, this one actually interacts with the user, even if it still doesn’t do a whole lot. The basic idea of the bitmap demo is a small 10x10 picture of a person (named Dude.pic in the Res folder, and Dude.bmp in Res/src) that moves around the screen in response to the arrow keys. I based CyBk9_1 on CyBk6_3, the idle-loop framework, although the real-time or event-driven framework would have been just as good. Most of the code remains the same as in CyBk6_3. There are a few extra globals (Listing 9.10.1), and Prog_Init (Listing 9.10.2), Prog_Done (Listing 9.10.3), and Prog_Loop (Listing 9.10.4) have changed. In addition, OnKeyUp (Listing 9.10.5) has the code to move the dude around. Listing 9.10.1 struct Bitmap bmp; int dude_x,dude_y;
//bitmap for the dude //position of the dude
The additional globals in Listing 9.10.1 simply add what we need to make the program work, i.e., a Bitmap object named bmp, and two integers to keep track of the dude’s position (dude_x and dude_y). Listing 9.10.2 bool Prog_Init() { //initialization
Team LRN
Chapter 9: Bitmap and Font Basics
101
//construct the bitmap from a resource Bitmap_ctor_Ex1(&bmp,"dude.pic"); //start dude at 0,0 dude_x=0; dude_y=0; //return TRUE if program initialized, and FALSE if it did not return(TRUE); }
Prog_Init, shown in Listing 9.10.2, initializes all of our global data (that’s its job, after all). So, a call to Bitmap_ctor_Ex1 constructs our bitmap and loads into it the data stored in the resource named dude.pic. After that, dude_x and dude_y are initialized to zero, setting up our dude to be in the upper-left corner of the display. Listing 9.10.3 void Prog_Done() { //cleanup //destroy the bitmap Bitmap_dtor(&bmp,LEAVE_MEMORY); }
During Prog_Done, shown in Listing 9.10.3, we clean up the Bitmap object by calling Bitmap_dtor, using LEAVE_MEMORY as the memory flag, since we did not dynamically allocate the space for our Bitmap object. Listing 9.10.4 void Prog_Loop() { //idle loop //clear the screen white DisplayGraphics_fill_screen(main_module.m_gfx,CLR_WHITE); //draw the dude DisplayGraphics_draw_bitmap(main_module.m_gfx,&bmp, dude_x*10,dude_y*10,BM_NORMAL); //show the screen DisplayGraphics_show(main_module.m_gfx); }
Prog_Loop, in Listing 9.10.4, performs the showing of our display. Since this is a simple demo, Prog_Loop clears the screen to white, draws the bitmap at the proper position using DisplayGraphics_draw_bitmap, and shows the screen. See Figure 9.1.
Team LRN
102
Chapter 9: Bitmap and Font Basics
Figure 9.1
Listing 9.10.5 bool OnKeyUp(int scancode,int mask,char ch) { //switch on the scan code switch(scancode) { case KEY_UP: //move up { if(dude_y>0) dude_y—; return(TRUE); }break; case KEY_DOWN: //move down { if(dude_y<9) dude_y++; return(TRUE); }break; case KEY_LEFT: //move left { if(dude_x>0) dude_x—; return(TRUE); }break; case KEY_RIGHT: //move right { if(dude_x<15) dude_x++; return(TRUE); }break; } //if message hasn't been handled, return FALSE return(FALSE); }
The OnKeyUp function (Listing 9.10.5) does the work of moving the dude whenever one of the arrow keys is released. I could have put this in the OnKeyDown function, and the behavior of the little person would have been a bit different. In this example, however, the dude doesn’t move until you release the arrow key. This example is still pretty simple at this point, but I thought you might appreciate something where you aren’t just watching things being drawn on the screen.
Team LRN
Chapter 9: Bitmap and Font Basics
103
Font Objects Bitmap objects are pretty cool, and you are going to use them a great deal in your programs. However, they are not the only way to give information to the user. You will also make use of text, and to use text, you must make use of fonts. The word “font” has a long history behind it, going all the way back to the Gutenberg Bible printing. A font is nothing more than a collection of letters, numbers, and symbols used for some sort of textual output. On a computer (Cybiko included) a letter is represented as a monochrome bitmap as a general rule, so on the Cybiko, a font is nothing more than a series of bitmaps that represent letters, numbers, and symbols.
Global Fonts You can, if you wish, make your own fonts. However, when starting out with writing text on the Cybiko, you might want to start out with the fonts already there. Cybiko provides you with four general purpose fonts: cool_normal_font, cool_bold_font, mini_normal_font, and mini_bold_font. These fonts are listed in Table 9.4, along with the width and height of the characters, and the numer of characters in these built-in fonts. Table 9.4 Built-in Cybiko fonts Font Name
Width
Height
Characters
cool_normal_font
10
12
221
cool_bold_font
11
12
221
mini_normal_font
8
9
221
mini_bold_font
9
9
221
Keep in mind that most of the characters in the font don’t take up all of the full width and height, and many characters in these fonts are blank. These fonts are shown in Figures 9.2.1 through 9.2.4.
Figure 9.2.1: “Cool Normal” font
Team LRN
Figure 9.2.2: “Cool Bold” font
104
Chapter 9: Bitmap and Font Basics
Figure 9.2.4: “Mini Bold” font
Figure 9.2.3: “Mini Normal” font
Setting the Current Font In order to draw text on the DisplayGraphics object, you must first select which font you want to use. To do this, you use DisplayGraphics_set_font, which is shown in Listing 9.11. Listing 9.11 void DisplayGraphics_set_font( struct DisplayGraphics * ptr_gfx, struct Font * font );
This function returns no value and takes two parameters. The first parameter is the pointer to the DisplayGraphics object, and the second parameter is a pointer to the font you wish to use. To retrieve the font currently in use, you use DisplayGraphics_get_font, shown in Listing 9.12. Listing 9.12 struct Font * DisplayGraphics_get_font( struct DisplayGraphics * ptr_gfx );
This function takes a single parameter, the pointer to the DisplayGraphics object, and returns a pointer to the current font in use. It is good practice to be “font friendly,” so before switching fonts, save the old font pointer somewhere and restore it when you are done. This helps avoid problems in other parts of the program that may use different fonts.
Team LRN
Chapter 9: Bitmap and Font Basics
105
Writing Text Once you have the proper font selected, you simply set the color using DisplayGraphics_set_color and draw the text. There are two text drawing functions, DisplayGraphics_draw_text and DisplayGraphics_draw_text_Ex. These are shown in Listings 9.13.1 and 9.13.2 respectively. Listing 9.13.1 void DisplayGraphics_draw_text( struct DisplayGraphics * ptr_gfx, char * text, int left, int top );
Listing 9.13.2 void DisplayGraphics_draw_text_Ex( struct DisplayGraphics * ptr_gfx, char * text, int left, int top, int flen );
Neither function returns a value. The only difference in the parameter list is that the _Ex function has an extra one. These parameters are listed and explained in Table 9.5. Table 9.5 DisplayGraphics_draw_text(_Ex) parameters Parameter
Purpose
ptr_gfx
Pointer to the DisplayGraphics object.
text
A character pointer to the string you wish to write.
left
x coordinate of the left of the text.
top
y coordinate of the top of the text.
flen
(_Ex only) The maximum length (in pixels) of the string that you wish to write.
If you recall Chapter 2, we used DisplayGraphics_draw_text to write “Hello, world!” onto the screen in the upper-left corner.
Formatting Text There is more to presentation than simply drawing text, of course. We may wish to center a string on the screen, or have it flush against the right side or against the bottom, or have it positioned within a rectangle. For this, we need to know how tall a
Team LRN
106
Chapter 9: Bitmap and Font Basics
string is, how wide a string is, and so on. Luckily, Cybiko C has functions for this. These functions are shown in Listing 9.14. Listing 9.14 int int int int
DisplayGraphics_get_char_height (struct DisplayGraphics* ptr_gfx) ; DisplayGraphics_get_char_width (struct DisplayGraphics* ptr_gfx); DisplayGraphics_string_width (struct DisplayGraphics* ptr_gfx, char *string); DisplayGraphics_string_width_Ex (struct DisplayGraphics* ptr_gfx, char *string, int flen);
DisplayGraphics_get_char_height and DisplayGraphics_get_char_width are pretty obvious. They return the width and height of the currently selected font of the DisplayGraphics object. DisplayGraphics_string_width and DisplayGraphics_string_width_Ex both return the width (in pixels) of a string (the second parameter). In the case of DisplayGraphics_string_width_Ex, only the first flen number of characters are used for calculating this width. To left justify or top justify (i.e., have your text flush against the left or top of some rectangle), you simply use the left and/or top coordinate for x and y. To center something horizontally, you take the leftmost x coordinate of the area in which you are centering, add half of the width of the area you are centering in, and subtract half of the string’s width. Similarly, to center vertically take the top y value, add half of the height of the area, and subtract half of the character height. To right justify something, you take the rightmost x value and subtract the width of the string. To bottom justify, you take the bottommost y value, and subtract the character height. Ergo, if you had four values, left, top, width, and height (i.e., the same information as a rect_t), you can do any text justification you wish using the formulas shown in Listing 9.15. Listing 9.15 //left,top,width, and height are given values //textx and texty is where the text should be drawn //text is a character pointer to the desired string //left justify textx=left; //horizontal center justify textx=left+width/2–DisplayGraphics_string_width(main_module.m_gfx,text)/2; //right justify textx=left+width–DisplayGraphics_string_width(main_module.m_gfx,text); //top justify texty=top;
Team LRN
Chapter 9: Bitmap and Font Basics
107
//vertical center justify texty=top+height/2–DisplayGraphics_get_char_height(main_module.m_gfx)/2; //bottom justify texty=top+height/–DisplayGraphics_get_char_height(main_module.m_gfx);
Naturally, you can combine any horizontal (left, center, right) with any vertical (top, center, bottom) justification to suit your needs.
Font Demo CyBk9_2 on the companion CD contains the workspace for the font demo. This demo is based on the idle-loop framework (CyBk6_3). There was quite a bit that I needed to add for this demo, so be prepared for several code listings. First off, I needed a few constants for the justifications (Listing 9.16.1). Next, I needed some extra global variables for printing text (Listing 9.16.2). The functions that needed modification were Prog_Init (Listing 9.16.3), Prog_Loop (Listing 9.16.4) and finally, OnKeyUp (Listing 9.16.5). Listing 9.16.1 //horizontal justification #define J_LEFT 0 #define J_CENTER 1 #define J_RIGHT 2 //vertical justification #define J_TOP 0 #define J_VCENTER 1 #define J_BOTTOM 2
Listing 9.16.1 shows all of the #defines I needed for the font demo. I made three for horizontal (left, center, right) and three for vertical (top, vcenter, bottom). The meanings should be relatively clear. Listing 9.16.2 //current font struct Font* ptr_current_font; //justification int justify_h; //horizontal int justify_v; //vertical //justification rectangle struct rect_t justify_rect; //text buffer char text[20];
I don’t like to hard code anything (it’s bad code, and it’s hard to read). So, in Listing 9.16.2, I added a number of globals. Since this font demo works with all four of the Cybiko fonts, I decided to have a global store the font that is currently being used (ptr_current_font). Also, since I’m using justification to format the font, I made two little variables to keep track of that: justify_h and justify_v. Then, I made a rect_t
Team LRN
108
Chapter 9: Bitmap and Font Basics
variable named justify_rect, which stores the rectangle in which we are justifying the text. Last, I created a buffer for text, called text. Listing 9.16.3 bool Prog_Init() { //initialization //set the current font ptr_current_font=cool_normal_font; //set the text sprintf(text,"%s","cool_normal_font"); //set the current justification justify_h=J_LEFT; justify_v=J_TOP; //set the justification rect rect_set(&justify_rect,0,0,160,100); //return TRUE if program initialized, and FALSE if it did not return(TRUE); }
Listing 9.16.3 shows the Prog_Init for the font demo. This function does nothing more than initialize the global variables to their starting values. The font is set to cool_normal_font, the text is set to “cool_normal_font”, justification is set to left and top, and the justify rectangle is set to the entire screen. Listing 9.16.4 void Prog_Loop() { //idle loop int textx; int texty; //clear the screen DisplayGraphics_fill_screen(main_module.m_gfx,CLR_WHITE); //set the font DisplayGraphics_set_font(main_module.m_gfx,ptr_current_font); //set the color DisplayGraphics_set_color(main_module.m_gfx,CLR_BLACK); //calculate textx and texty switch(justify_h) { case J_LEFT: //left justify { textx=justify_rect.x; }break; case J_RIGHT: //right justify { textx=justify_rect.x+justify_rect.w–DisplayGraphics_string_width (main_module.m_gfx,text); }break;
Team LRN
Chapter 9: Bitmap and Font Basics
109
case J_CENTER: //center justify { textx=justify_rect.x+justify_rect.w/2–DisplayGraphics_string_width (main_module.m_gfx,text)/2; }break; } switch(justify_v) { case J_TOP: //top justify { texty=justify_rect.y; }break; case J_BOTTOM: //bottom justify { texty=justify_rect.y+justify_rect.h–DisplayGraphics_get_char_height (main_module.m_gfx); }break; case J_VCENTER: //vertically center justify { texty=justify_rect.y+justify_rect.h/2–DisplayGraphics_get_char_height (main_module.m_gfx)/2; }break; } //draw the text DisplayGraphics_draw_text(main_module.m_gfx,text,textx,texty); //show the screen DisplayGraphics_show(main_module.m_gfx); }
Listing 9.16.4 shows the Prog_Loop function of the font demo. It does all of the drawing for the program. It clears the screen to white, calculates where to place the text using the calculations I talked about earlier, and finally, it draws the text and shows the screen. Listing 9.16.5 bool OnKeyUp(int scancode,int mask,char ch) { //switch on the scancode switch(scancode) { case KEY_1: //set font to cool_normal_font { sprintf(text,"%s","cool_normal_font"); ptr_current_font=cool_normal_font; return(TRUE); }break; case KEY_2: //set font to cool_bold_font { sprintf(text,"%s","cool_bold_font"); ptr_current_font=cool_bold_font;
Team LRN
110
Chapter 9: Bitmap and Font Basics
case
case
case
case
case
case
case
case
return(TRUE); }break; KEY_3: //set font to mini_normal_font { sprintf(text,"%s","mini_normal_font"); ptr_current_font=mini_normal_font; return(TRUE); }break; KEY_4: //set font to mini_bold_font { sprintf(text,"%s","mini_bold_font"); ptr_current_font=mini_bold_font; return(TRUE); }break; KEY_T: //top justify { justify_v=J_TOP; return(TRUE); }break; KEY_V: //vertical center justify { justify_v=J_VCENTER; return(TRUE); }break; KEY_B: //bottom justify { justify_v=J_BOTTOM; return(TRUE); }break; KEY_L: //left justify { justify_h=J_LEFT; return(TRUE); }break; KEY_C: //center justify { justify_h=J_CENTER; return(TRUE); }break; KEY_R: //right justify { justify_h=J_RIGHT; return(TRUE); }break;
} //if message hasn't been handled, return FALSE return(FALSE); }
Team LRN
Chapter 9: Bitmap and Font Basics
111
Listing 9.16.5 shows the OnKeyUp function, which is the longest function of the bunch because it does all of the work. Depending on what key was pressed, the program changes fonts or changes justifications. The number keys 1 through 4 change the fonts. The L, C, and R keys change the horizontal justification, and the T, V, and B keys change the vertical justification. The OnKeyUp function is just there to make these changes. You might want to experiment with the font demo a little bit, since it demonstrates most of what you would want to do with a font. You could, for example, change the values sent to the justify_rect, and have the justifications be elsewhere on the screen. We will return to fonts in greater detail in a later chapter.
Summary Bitmaps and fonts give real meaning to your graphical displays. You almost can’t make a program without one or both of these (sure, you might have a text-only program, or you might have a bitmap-only program, but usually you will use both). As of right now, you have enough knowledge to make yourself a game. Of course, you wouldn’t have any sounds yet, and you wouldn’t be able to save your top ten score list, and a handful of other little details that make a program feature rich. However, the visual component is 70%, with the other senses making up the other 30%, so you are well on your way. This is by no means the final word on bitmaps and fonts. This is just the basics. There is a lot more you can do and will do with bitmaps than the simple examples we have here, but that’s a little bit later.
Team LRN
Chapter 10
Sounds, Music, and Vibration Overview If 70% of our input is from sight, i.e., the display, I would say about 20% is from hearing, so while not as important as the visual display, good sounds and music are important. Unfortunately, the sound hardware of the Cybiko isn’t exactly topnotch. It is a small speaker that can make little beeps and boops. Despite its lack of quality, it’s all we’ve got, so we should make the best use of it that we can.
Beeps The simplest way to make sounds on the Cybiko is to use one of the predefined “beeps” that Cybiko provides with CyOS. This is done, to no one’s surprise, with a function named beep, shown in Listing 10.1. Listing 10.1 void beep( int beep_type );
This function returns no value, and has one parameter. The parameter takes one of the predefined BEEP_* constants, listed in Table 10.1.
112
Team LRN
Chapter 10: Sounds, Music, and Vibration
113
Table 10.1 BEEP_* Constants Constant
Use
BEEP_OK
A generic beep for when things are OK.
BEEP_INFO
A generic beep for information dialog boxes.
BEEP_QUESTION
A generic beep for when you need to confirm something.
BEEP_ERROR
A generic beep for when you report an error to the user.
I made a simple beep demo in CyBk10_1 on the companion CD. In this simple little demo, you can hit the 1, 2, 3, or 4 key to get the different beeps. I won’t bother with the code. The only function that changed was the OnKeyUp function.
Tone Generation Beeps are nice, I suppose, but I’m certain that at some point you will want more than just the four tones that the beep function makes available to you. On the Cybiko, there are 68 chromatic tones available to you through a function called play_tone. This function is shown in Listing 10.2. Listing 10.2 void play_tone( int index );
This function returns no value, and takes a single parameter. The index parameter is the number of the tone you wish to play (0 through 67), or a negative number to turn off the currently playing tone. This begs the question of what do these tones mean? Well, without a long diatribe on music theory, these tone indexes are musical notes. The number 0 is an E, the number 1 is an F, the number 2 is an F-sharp/G-flat, and so on, all the way up to 67, which is a B. Table 10.2 shows these tones, split into octaves. Table 10.2 Note equivalents of play_tone indices Octave Note
Octave2
Octave3
Octave4
Octave5
Octave6
C
8
20
32
44
56
C#/Db
9
21
33
45
57
D
10
22
34
46
58
D#/Eb
11
23
35
47
59
12
24
36
48
60
E
Octave1
0
Team LRN
114
Chapter 10: Sounds, Music, and Vibration
Octave Note
Octave1
Octave2
Octave3
Octave4
Octave5
Octave6
F
1
13
25
37
49
61
F#/Gb
2
14
26
38
50
62
G
3
15
27
39
51
63
G#/Ab
4
16
28
40
52
64
A
5
17
29
41
53
65
A#/Bb
6
18
30
42
54
66
B
7
19
31
43
55
67
With this in mind, you can generate any of these notes with a simple call to play_tone. To stop tones, you can use the stop_tone function, which returns no value and takes no parameter. Using stop_tone() has the same effect as using play_tone(–1). I wrote a little example of using play_tone that can be found in CyBk10_2 on the companion CD. This program is based on the event-driven framework (CyBk6_2). This little example turns your Cybiko into a mini-musical keyboard. Three complete octaves are located on the keyboard. The row starting with the “1” key is a row of “black keys,” the row starting with “Q” is a row of “white keys,” the row starting with “A” is another row of black keys, and the row starting with “`” is another row of white keys. The keys are situated (to the best of my ability) as a piano would be. Full instructions can be found in the Root.spl file. With this example, I’m not going to bother with the code. Essentially, all it does is respond to the OnKeyDown and OnKeyUp messages. During an OnKeyDown, depending on the key, a tone is played, and when a key is released (during OnKeyUp), all tones are stopped. You can take a look at the code on your own, but there isn’t that much to it.
Raw Tone Generation The third method of generating tones on the Cybiko is to use the play_raw function, shown in Listing 10.3. Listing 10.3 void play_raw( int divisor );
This function returns no value and takes a single parameter. The divisor is a little difficult to explain, and has to do with how speaker technology works. The speaker is nothing more than a little magnet that moves back and forth, causing the air in the area to vibrate, which travels to your ear and vibrates your eardrum, which moves little bones inside your inner ear, which compress liquid, which is changed to electrical signals that are read by your brain as sound. The sound wave generated depends on
Team LRN
Chapter 10: Sounds, Music, and Vibration
115
how quickly the magnet is moved back and forth. That’s what the divisor does. It is based on the internal timer of the Cybiko. If you were to use 1 as the divisor, you would have the magnet move as fast as the timer, in theory. This would produce a sound audible only to rodents and bats. The hardware can’t actually handle this, of course, so the range for the divisor is anywhere from 1356 (producing a sound at 4075Hz) through 6505 (producing a sound at 85Hz). The higher the divisor, the lower the tone generated. A lower divisor will generate a higher sound. What good is this? Well, using play_raw, you get the full (albeit a bit limited) capabilities of the Cybiko sound hardware at your disposal. To stop raw tones, you can use the function stop_tone. CyBk10_3 on the companion CD contains an example workspace that makes use of play_raw. Try not to run it around anybody who you would like to remain friends with. The code is pretty simple, as only Prog_Loop and Prog_Done have changed, and only one line was added to each, so you should be able to understand it without me placing all of the code here.
MSequence The M in MSequence stands for “music.” An MSequence object is little more than a series of tones and durations that make up a piece of music. You can make MSequences from MIDI files using the 2mus utility in the Bin directory of the SDK. I personally use a hex editor to make mine, since I do not have a MIDI editor, but that’s just me. Music files are stored in .mus files, and most of the time, you’ll add them into your .app archive using Filer. Once you’ve got a music sequence as a resource, your job becomes a great deal easier (making the music is the hard part).
MSequence_ctor An MSequence object, like every other Cybiko object, must first be constructed using a constructor function. MSequence has only one constructor, MSequence_ctor, which is shown in Listing 10.4. Listing 10.4 struct MSequence* MSequence_ctor( struct MSequence* ptr_msequence, char* sz_file_name );
This function returns a pointer to the newly constructed MSequence object. It takes two parameters. The first is a pointer to the MSequence object that you wish to construct, and the second is the name of the resource that you wish the MSequence to be loaded from. You can construct your MSequence object at any time, although you will
Team LRN
116
Chapter 10: Sounds, Music, and Vibration
usually do this either at the beginning of a program or at the beginning of a level (if, for example, different levels in your game have different music).
MSequence_dtor On the flip side of MSequence_ctor is MSequence_dtor, shown in Listing 10.5. Listing 10.5 void MSequence_dtor( struct MSequence* ptr_msequence, int memory_flag );
This destructor looks and behaves just like any other destructor. You pass the pointer of the object you wish to destroy, along with either LEAVE_MEMORY or FREE_ MEMORY, depending on whether or not you dynamically allocated the object in question. You would normally destroy an MSequence object at the end of the program or the end of the level (i.e., whenever you no longer need that MSequence).
Playing and Stopping Now that you can construct and destruct this object, how about playing it? There are actually two different ways to play an MSequence on the Cybiko. One way is to play it in the foreground, using MSequence_play, which is shown in Listing 10.6. Listing 10.6 void MSequence_play( struct MSequence* ptr_msequence );
This function returns no value and takes a single parameter, a pointer to the MSequence object that you wish to play. The other way to play an MSequence object is in the background, using the MSequence_play_background function shown in Listing 10.7. Listing 10.7 void MSequence_play_background( struct MSequence* ptr_msequence );
Like MSequence_play, this function returns no value and takes a pointer to the MSequence object you wish to play. The difference between MSequence_play and MSequence_play_background is mostly a matter of priority. Whenever an MSequence is playing in the foreground, the background MSequence will not be heard. Other sounds, such as the system alarm, have an even higher priority, and will override any MSequence you may have playing at the time, foreground or background.
Team LRN
Chapter 10: Sounds, Music, and Vibration
117
To stop an MSequence, you use MSequence_stop. This function is shown in Listing 10.8. Listing 10.8 void MSequence_stop( struct MSequence* ptr_msequence );
This function returns no value and takes as a parameter the MSequence object you wish to stop playing. MSequence_stop does not differentiate between foreground and background MSequence objects, it just stops it no matter what.
Information Functions The MSequence class also provides a couple of functions for retrieving information about a playing MSequence object. These functions are MSequence_is_playing (shown in Listing 10.9) and MSequence_get_curr_pos (shown in Listing 10.10). Listing 10.9 bool MSequence_is_playing( struct MSequence* ptr_msequence );
This function returns TRUE if the MSequence object in question is playing, and FALSE if it is not. This function doesn’t care whether the MSequence object is playing in the foreground or the background. Listing 10.10 int MSequence_get_curr_pos( struct MSequence* ptr_msequence );
This function returns how far into the MSequence object the playing has progressed. The value 0xFFFF(–1) is returned if it is right at the beginning, before the first note. The MSequence_is_playing function is of great use for looping MSequence objects (if you want to have a song playing in the background all the time). The code for this is pretty simple, and is shown in Listing 10.11. Listing 10.11 //mseq is an MSequence object if(!MSequence_is_playing(&mseq)) MSequence_play_background(&mseq);
Just make sure this code gets called often enough so that the MSequence doesn’t get to the end and just stop.
Team LRN
118
Chapter 10: Sounds, Music, and Vibration
Muting You can mute (or unmute) background, foreground, or both types of MSequence objects, by using a set of functions that I’m lumping together as the muting functions. The three functions, MSequence_global_mute, MSequence_mute_foreground, and MSequence_mute_background, are all shown in Listing 10.12. Listing 10.12 void MSequence_global_mute(bool mute_flag); void MSequence_mute_foreground(bool mute_flag); void MSequence_mute_background(bool mute_flag);
All of these functions return no value and take a single parameter, TRUE or FALSE, specifying whether or not you want muting on or off.
MSequence Example CyBk10_4 on the companion CD contains a workspace with the MSequence demo. In this simple demo, an MSequence is constructed during Prog_Init, destroyed during Prog_Done, and played if not already playing during Prog_Loop. It’s a pretty simple demo, but it does illustrate how you make use of the MSequence object. I’m not going to bother with the code here.
The Voice of Sanity I’ll show you one last little function you might want to use for MSequences, and then we’re moving on. It is entirely possible to make a .mus file that is completely unplayable. By the time you are ready to distribute your game or application, you should ensure that all of your .mus files contain valid information (preferably by actually playing them and testing them out first). However, during development, you may well wind up with an unplayable .mus file. The SDK has a function to test whether a given MSequence is “sane” or not. This function is called MSequence_is_sane, and is shown in Listing 10.13. Listing 10.13 bool MSequence_is_sane(struct MSequence* ptr_msequence);
This function returns TRUE if the sequence is valid, and FALSE if it is not. The parameter is a pointer to the MSequence object whose sanity is in question.
Enabling and Disabling Tone Generation Now that you can add sounds, you will probably want to add some sort of sounds to all of your applications and games, even if you just have a beep or two. However, you will probably at some point want to be able to check to see if a sound is playing, check to
Team LRN
Chapter 10: Sounds, Music, and Vibration
119
see if sounds are enabled, and possibly even enable or disable sounds programmatically. This isn’t strictly required. There is, after all, a key combination used by Cybiko to enable or disable sounds, but it’s good stuff to know anyway, just in case.
is_tone_playing If you are using play_tone or play_raw, you may wish to check to see if a tone is playing. To do this, you use the is_tone_playing function, shown in Listing 10.14. Listing 10.14 bool is_tone_playing();
This function takes no parameters. It returns TRUE if a tone is playing, and FALSE if there are no tones playing.
get_sounds_enabled and enable_sounds There are times when you might want to provide an alternate key command to turn on and off the sounds in your game or application. (Hitting the Fn key and one of the Section keys is something of a pain, and I never remember which Section key does what, and for some reason, I always wind up changing the contrast of my display when I intend to toggle sounds). To retrieve whether or not sounds are currently enabled, you use the get_sounds_ enabled function, shown in Listing 10.15. To set whether or not sounds should be enabled or disabled, you use the enable_sounds function, shown in Listing 10.16. Listing 10.15 bool get_sounds_enabled();
This function takes no parameters. It returns TRUE if sounds are enabled, and FALSE if they are disabled. Listing 10.16 void enable_sounds(bool enable_flag);
This function returns no value, and takes either TRUE or FALSE, to enable or disable sounds respectively. Listing 10.17 shows a very simple line of code that will toggle sound from off to on, or on to off, depending on the initial state of sound enabling. Listing 10.17 enable_sounds(!get_sounds_enabled());
Team LRN
120
Chapter 10: Sounds, Music, and Vibration
Key Clicks Unless you have some of the older Cybiko hardware (those with the actual on/off switch rather than the reset button), your device has the capability of beeping when a key is pressed, and probably does so unless you have your sound turned off. This feature is known as “key clicking.” You can control, programmatically, whether or not the Cybiko on which your program is running beeps when a key is clicked, and what kind of beep is emitted when a key is pressed. Personally, I find key clicks to be distracting and somewhat annoying.
Enabling and Disabling Key Clicks To check whether or not key clicks are enabled, you use the function get_clicks_ enabled, which is shown in Listing 10.18. To set whether or not you want key clicks enabled, you use function set_clicks_enabled, shown in Listing 10.19. Listing 10.18 bool get_clicks_enabled (void)
This function takes no parameters and returns either TRUE or FALSE, indicating whether or not key clicks are enabled on the Cybiko device. Listing 10.19 void set_clicks_enabled (bool enable)
This function takes a bool, which specifies whether or not you want key clicks to be enabled on the Cybiko device. These two functions are rather similar to the get_sounds_enabled and enable_sounds functions, which is why they are covered here, rather than in the chapter on keyboard input.
Advanced Disables There may be a time when you would like some keys that have key clicks, and some keys that don’t. The Cybiko SDK has a function that allows you to do this, called disable_key_click, shown in Listing 10.20. Listing 10.20 void disable_key_click (int* ptr_key_list, int key_count)
This function returns no value and takes two parameters. The ptr_key_list parameter is a pointer to an int, which points to an array of keys that you wish to disable, and key_count is the number of keys in that array. This function isn’t quite as intuitive as some of the others, so I’ve provided a small snippet of code that shows how to disable key clicks for the arrow keys. This snippet can be found in Listing 10.21.
Team LRN
Chapter 10: Sounds, Music, and Vibration
121
Listing 10.21 int Arrows[4]; //fill in the array Arrows[0]=KEY_LEFT; Arrows[1]=KEY_RIGHT; Arrows[2]=KEY_UP; Arrows[3]=KEY_DOWN; disable_key_click(Arrows,4);
//there are four arrow keys
//disable key clicks for the arrows
Unfortunately, there is no function to retrieve what keys have the key click disabled. To turn key clicks back on for all keys, you use the code shown in Listing 10.22. Listing 10.22 disable_key_click(0,0);
//turns all key clicks back on
Kinds of Clicks Besides whether or not key clicks are enabled, and for which keys the key click is enabled, you may also set what kind of key click occurs when a key is pressed. This is done through the function set_click_kind, shown in Listing 10.23. Listing 10.23 void set_click_kind (click_kind_t kind)
This function returns no value, and takes a click_kind_t value called kind. The click_kind_t type is nothing more than a typedeffed int. There are three valid values for click_kind_t, which are shown in Table 10.3. Table 10.3 click_kind_t values Constant
Meaning
CK_NO
No beep
CK_BEEP
Long beep
CK_BEEP_SHORT
Short beep
As you can see, there aren’t many options here. The key click isn’t exactly a complicated part of the SDK. An alternate way of turning off key clicks is just to set the click kind to CK_NO. To retrieve what kind of key click is currently set, you use the get_click_kind function, shown in Listing 10.24. Listing 10.24 click_kind_t get_click_kind (void)
This function takes no parameters and returns the kind of key click that is currently selected.
Team LRN
122
Chapter 10: Sounds, Music, and Vibration
Key clicks are pretty simple, so I’ll leave you to experiment with them on your own.
Vibration The last topic of the chapter is vibration. Built into every Cybiko device, there is a little motor that is connected to an off-balance weight. When it is given power, it spins the weight around in circles, causing a vibration effect. The vibration section of the SDK is the simplest of all. It consists of two functions, vibrate (shown in Listing 10.25) and enable_vibration (shown in Listing 10.26). Listing 10.25 void vibrate (int index)
This function returns no value and takes a number between 0 and 255 as a parameter. The number indicates the strength of vibration you desire, with a higher number meaning a harder vibration. Listing 10.26 void enable_vibration (bool enable)
This function returns no value and takes either TRUE or FALSE as a parameter, indicating whether or not you wish for vibrations to be enabled. There is no function for determining whether or not vibration is enabled.
Summary The section of the SDK for sounds, key clicks, and vibrations is pretty simple to understand and use, which is why I didn’t spend a lot of time on it. All of the information you need is here in this chapter, and we won’t need to revisit this topic. The sound generating capabilities of the Cybiko are by today’s standard rather primitive. With a little creativity, though, you should be able to incorporate these features to enhance gameplay.
Team LRN
Chapter 11
Basic Dialogs Overview What we have looked at thus far in the Cybiko SDK has been rather simple. Starting simple is a good way to present anything that is unfamiliar, and hopefully you now have a solid foundation of how things are done on the Cybiko. The Cybiko SDK is not altogether simple like this. Indeed, the part that I’ve come to call the user interface, or UI, section, is rather complicated and difficult to understand at a glance. Taken in pieces, however, it’s not incomprehensible. We’re going to take it slow. In this chapter, I’m going to present you with the simplest component of the Cybiko UI, cDialog. cDialog is pretty easy to learn, and it packs a lot of functionality. You can make message boxes and input boxes similar in style to those in Win32. That, however, is the limit of what cDialog can do, as we shall see shortly.
Cybiko Dialogs The cDialog class is based on the cCustomForm class, which in turn is based on the cClip class, which is in turn based on the cObject class. Translation: cDialog is a pretty high-level user interface element. If you were to look up the cDialog class in the SDK help files, you would see a big list of constants and functions dealing with cDialog. This list might seem daunting at first. Don’t worry; getting started with cDialog only requires a handful of those constants, and a mere five of the functions.
cDialog_ctor The first of the functions we are concerned with here is cDialog_ctor, which, naturally enough, constructs a new cDialog. This function is shown in Listing 11.1.
123
Team LRN
124
Chapter 11: Basic Dialogs
Listing 11.1 struct cDialog * cDialog_ctor ( struct cDialog * ptr_dialog, char * caption, char * text, long style, int edit_size, struct cWinApp * ptr_win_app )
This function returns a pointer to the newly created cDialog object. The parameters are listed and explained in Table 11.1. Table 11.1 cDialog_ctor parameters Parameter
Purpose
ptr_dialog
Pointer to the cDialog object being constructed.
caption
Caption for the cDialog object.
text
Prompt to use in the cDialog object.
style
Style of the dialog (see section on styles below).
edit_size
Size of the edit box buffer.
ptr_win_app
Pointer to a cWinApp (use main_module.m_process).
Most of these parameters are self-explanatory. Your dialogs can have title bars (with the caption parameter) and text prompts (with the text parameter). A cDialog object needs a message queue (such as the ptr_win_app parameter) from which it receives input. The only mysterious parameters are style and edit_size.
cDialog Styles The fourth parameter of cDialog_ctor, style, specifies how you want the dialog to look. There are a limited number of options, and more complicated forms will require a more complicated user interface element than cDialog can provide. For most simple cases, however, cDialog has what you need. The style parameter consists of a number of flags, that specify how the dialog should look. These are all members of the tDialogStyle enum. For convenience and ease of presentation, I have divided these flags into several groups of related flags. These groups are button flags, sound flags, edit box flags, and other flags. Button Flags The first group of flags specifies which buttons you want to appear on the dialog. There are 16 different buttons you can have on your dialogs. The flag constants and what button appears when each flag is used are shown in Table 11.2.
Team LRN
Chapter 11: Basic Dialogs
125
Table 11.2 Button flags Flag
Button Text
mbNone
No buttons
mbOk
OK button
mbYes
YES button
mbNo
NO button
mbDraw
DRAW button
mbChat
CHAT button
mbQuit
QUIT button
mbNew
NEW button
mbUpload
UPLOAD button
mbRename
RENAME button
mbDelete
DELETE button
mbView
VIEW button
mbPlay
PLAY button
mbRestart
RESTART button
mbSet
SET button
mbLater
LATER button
mbCancel
CANCEL button
mbReverseOrder
Reverses the order of the buttons in the dialog
There is one oddball flag thrown into this group, mbReverseOrder. Normally, when you show a dialog, it will display a lower numbered flag, like mbOk, to the left of a higher numbered flag, like mbCancel. Using mbReverseOrder switches this around so that the CANCEL button will appear to the left of the OK button. Keep in mind that while there are 16 different buttons you can choose from, only two of them can appear on a dialog, so your grand plans for a 16-button dialog box will not come to be using the cDialog class. You would instead have to use a cCustomForm to do that. Sound Flags Besides buttons, you can also specify what sound you want to play when a dialog comes up. All of these flags start with the letters “mbs.” They are shown in Table 11.3.
Team LRN
126
Chapter 11: Basic Dialogs
Table 11.3 Dialog sound style flags Flag
Meaning
mbsDefault
Play default music (same as mbs0)
mbsNone
Play no music (same as mbs0)
mbs0
Play music 0
mbs1
Play music 1
mbs2
Play music 2
mbs3
Play music 3
mbs4
Play music 4
mbs5
Play music 5
mbs6
Play music 6
mbs7
Play music 7
mbsAbout
Same as mbs6
mbsDraw
Same as mbs4
mbsEsc
Same as mbs5
mbsLinkOff
Same as mbs1
mbsNoDraw
Same as mbs7
mbsWelcome
Same as mbs2
There are eight different pieces of music that can be played when your dialog is first shown. mbs0, mbsDefault, and mbsNone are all the same, indicating that no music is to be played. You can only use one of the eight pieces of music. Mixing these flags will likely not play the music you request. Edit Box Flags Table 11.4 shows the edit box flags. You use these when you wish to have an edit box appear on your form so that you can retrieve a textual response from the user. Table 11.4 Edit box flags Flag
Meaning
mbEdit
You wish to have an edit box on the dialog.
mbPasswd
The edit box is for passwords, so all text will show as *.
If you want a password dialog, both flags must be specified. Using the mbEdit flag means that you must put a non-zero number in the edit_size parameter of cDialog_ctor.
Team LRN
Chapter 11: Basic Dialogs
127
Other Flags Table 11.5 shows the rest of the flags. These flags affect the appearance or behavior of the dialog. Table 11.5 Other flags Flag
Meaning
mbNoEsc
The dialog must ignore the Esc key.
mbLeft
The dialog’s text will be left justified rather than centered.
mbNoShutup
The dialog will ignore MSG_SHUTUP.
Normally, hitting Esc during a dialog will cause the dialog to close, and a result of mrCancel (which we’ll talk about a little later) will be returned. Specifying the mbNoEsc flag in your call to cDialog_ctor will prevent this behavior from happening. Also, a dialog’s text is usually centered. Using the mbLeft flag will cause the text to be left justified. And finally, when you want your dialog to ignore the MSG_SHUTUP message, use mbNoShutup. While I can’t think of a reason for using this flag, I’m sure one will come up eventually.
cDialog_dtor Like any other Cybiko SDK object, you must call cDialog’s destructor, which in this case is named cDialog_dtor (shown in Listing 11.2). Listing 11.2 void cDialog_dtor(struct cDialog* ptr_dialog,int mem_flag);
Like all destructor functions, this one takes two parameters (the pointer to the object being destroyed and a memory flag with either the value LEAVE_MEMORY or FREE_MEMORY) and returns no value.
cDialog_ShowModal The function responsible for getting all of the work done for a cDialog object is cDialog_ShowModal. This function is shown in Listing 11.3. Listing 11.3 int cDialog_ShowModal (
struct cDialog * ptr_dialog );
This function takes a pointer to the cDialog object you wish to show modally, and returns an int, which specifies the state in which the cDialog object was exited. Something that might be a little confusing to you is the term “modal.” It does kind of sound like a word from an alien language. Dialogs come in two flavors: modal and modeless. In a modal dialog, you can do nothing else in the program until the dialog
Team LRN
128
Chapter 11: Basic Dialogs
has been taken care of (i.e., push a button or cancel the dialog by pressing Esc). In a modeless dialog, you can do other things outside of the dialog while it is up. Most of the time, you will want simple message boxes and input boxes to be modal. The return value of cDialog_ShowModal is one of a number of mr* constants. The “mr” stands for “modal result.” Table 11.6 lists the predefined modal result constants. Table 11.6 Modal result constants Value
Meaning
mrNone
No result available
mrOk
OK button pressed
mrYes
YES button pressed
mrNo
NO button pressed
mrDraw
DRAW button pressed
mrChat
CHAT button pressed
mrQuit
QUIT button pressed
mrNew
NEW button pressed
mrUpload
UPLOAD button pressed
mrRename
RENAME button pressed
mrDelete
DELETE button pressed
mrView
VIEW button pressed
mrPlay
PLAY button pressed
mrRestart
RESTART button pressed
mrSet
SET button pressed
mrLater
LATER button pressed
mrCancel
CANCEL button pressed
mrMessage
Message received
mrUser
Beginning of the user’s definitions
As you can see, most of these constants correspond to the mb* flags, like mbOk and mrOk, and mbCancel and mrCancel. Each button has its own modal result constant. For now, we aren’t going to worry about mrMessage or mrUser.
cDialog_GetEditText and cDialog_SetEditText If you use the mbEdit flag to construct your dialog, there will be an edit box on it, with a buffer allocated for a string equal to the value passed in the edit_size parameter. Once you have constructed your dialog, you can initialize the string stored along with
Team LRN
Chapter 11: Basic Dialogs
129
the dialog. After you have called cDialog_ShowModal, you can then move whatever is stored in that string into another buffer before destroying the dialog. To set the text in the edit box, you use the function cDialog_SetEditText. This function is shown in Listing 11.4. To retrieve the text from the edit box, you use the function cDialog_GetEditText, shown in Listing 11.5. Listing 11.4 void
cDialog_SetEditText (struct cDialog* ptr_dialog, char* text)
This function returns no value and takes two parameters. The first parameter is a pointer to the cDialog object for which you are setting the edit text. The second parameter is a pointer to a string that you wish to be copied into the cDialog’s edit box. Listing 11.5 void
cDialog_GetEditText (struct cDialog* ptr_dialog, char* ptr_buffer)
This function returns no value and takes two parameters. The first parameter is a pointer to the cDialog object from which you are retrieving the edit text. The second parameter is a pointer to a string buffer into which you want the edit text to be copied.
Simple Message Box Now that we have spent some time becoming familiar with the cDialog class, it is time to put our knowledge into effect. We shall start by making a simple message box. Since we might make a message box for many different occasions, we will use the ubiquitous “Are you sure you want to quit (y/n)?” message box that seems to be the standard on every application written since time began. I’m going to present this task two ways. The first way is the “Cybiko way,” and is the way you will see it done in every sample Cybiko application in the SDK. The second way is “My Way,” which really isn’t that different other than I wrap it up inside a function so you only have to write one line instead of several. Either way, the steps are still the same: 1.
Construct a dialog with the appropriate values for parameters.
2.
Show the dialog modally and save the return value.
3.
Destroy the dialog.
4.
Take appropriate action based on the value returned from cDialog_ShowModal.
The Cybiko Way The message box demo can be found on the companion CD in CyBk11_1. This program is based on CyBk6_2; the only thing I changed was the OnKeyDown function, which is shown in Listing 11.6.
Team LRN
130
Chapter 11: Basic Dialogs
Listing 11.6 bool OnKeyDown(int scancode,int mask,char ch) { struct Message* ptr_msg; //pointer to a message struct cDialog* ptr_dlg; //pointer to a dialog int mrResult; //modal result //if the escape key has been pressed, quit if(scancode==KEY_ESC) { //allocate dialog ptr_dlg=(struct cDialog*)malloc(sizeof(struct cDialog)); //construct the dialog cDialog_ctor(ptr_dlg,NULL,"Are you sure you want to quit?",mbYes | mbNo,0,main_module.m_process); //show the dialog modally mrResult=cDialog_ShowModal(ptr_dlg); //destroy the dialog cDialog_dtor(ptr_dlg,FREE_MEMORY); //examine the result returned by the dialog if(mrResult==mrYes) //check for mrYes { //create a new message ptr_msg=Message_new(sizeof(struct Message)); //make it a quit message ptr_msg–>msgid=MSG_QUIT; //send this message to the message queue Message_post(ptr_msg,cWinApp_get_name(main_module.m_process), get_own_id()); } //repaint the screen OnPaint(); //the message has been handled, so return true return(TRUE); } //if message hasn't been handled, return FALSE return(FALSE); }
The code should be pretty easy to follow. I just went through each of the steps I outlined earlier. If the result stored in mrResult is equal to mrYes, I send a MSG_QUIT to the application, which shuts it down. In any other case, I call OnPaint, which restores
Team LRN
Chapter 11: Basic Dialogs
131
the old image to the screen (otherwise, there would be a residual dialog image still on the screen, since the program still does essentially nothing). Figure 11.1 shows what this message box looks like. Figure 11.1: A simple message box
My Way The downside (at least in my opinion) to creating dialogs the Cybiko way is that it takes three lines of code, and two of them are exactly the same no matter what your message box looks like. The only difference is in the call to the constructor. It seems to me that we would be much better off just having a single function with the necessary parameters to make a simple message box that will create a cDialog object and return whatever value we retrieve from it. That way, we can do a message box with a single line of code, and worry about the return value afterward. So, submitted for your approval, I present you with the MessageBox function, shown in Listing 11.7. Listing 11.7 int MessageBox( char *title, //(in)title of the message box char *message, //(in)message for this message box long style, //(in)style (combination of mbXXXX constants) struct cWinApp *ptr_win_app //(in)pointer to application(main_module.m_process) ) { //pointer only, cut down on stack space struct cDialog* pDialog; //return value(modal result) int mr; //allocate dialog pDialog=(struct cDialog*)malloc(sizeof(struct cDialog)); //construct dialog cDialog_ctor(pDialog,title,message,style,0,ptr_win_app); //show the dialog modally mr=cDialog_ShowModal(pDialog);
Team LRN
132
Chapter 11: Basic Dialogs
//destroy dialog cDialog_dtor(pDialog,FREE_MEMORY); //return the modal result return(mr); }
This function takes four parameters: the title, the message, the style, and a pointer to an application for message reading. It returns whatever modal result is returned from the dialog that is created within the function. Notice that edit_size is not one of the parameters. With just a simple message box, there will never be an edit box so this parameter is unnecessary. (In the function itself, the value of zero is always passed to cDialog_ctor for this parameter.)
Simple Input Box The other primary use for the cDialog class is for creating simple input boxes. A simple input box is just like a simple message box, except for the inclusion of an edit box for retrieving some sort of textual response from the user. There are plenty of uses for input boxes, including logins, passwords, and any other small piece of text information. For more involved input, you would want to use a different kind of form, which we will explore in a later chapter.
The Cybiko Way The input box example can be found in CyBk11_2 on the companion CD. This program is based on CyBk11_1. I added functionality so that when the N key is pressed and released, an input box asking for your name is displayed. You can change the name in the edit box. When you hit the OK button, it will be saved in a global variable called szName. If you hit the Esc key or press the CANCEL button, the name will not be saved. To add this input box, the only function I changed was the OnKeyUp function, which is shown in Listing 11.8. Listing 11.8 bool OnKeyUp(int scancode,int mask,char ch) { struct cDialog* ptr_dlg;//pointer to a dialog int mrResult;//modal result if(scancode==KEY_N) { //allocate dialog ptr_dlg=(struct cDialog*)malloc(sizeof(struct cDialog));
Team LRN
Chapter 11: Basic Dialogs
133
//construct the dialog cDialog_ctor(ptr_dlg,NULL,"What is your name?",mbOk | mbCancel | mbEdit,20,main_module.m_process); //set the edit text of dialog cDialog_SetEditText(ptr_dlg,szName); //show the dialog modally mrResult=cDialog_ShowModal(ptr_dlg); //check the modal result for mrOk if(mrResult==mrOk) { //copy the edit text cDialog_GetEditText(ptr_dlg,szName); } //destroy the dialog cDialog_dtor(ptr_dlg,FREE_MEMORY); //repaint the display OnPaint(); //message handled, so return TRUE return(TRUE); } //if message hasn't been handled, return FALSE return(FALSE); }
This code is rather similar to the code for a simple message box with a few additions. First, calls to cDialog_SetEditText and cDialog_GetEditText occur before and after the call to cDialog_ShowModal, respectively. Second, the code checks the value of mrResult before the destructor is called, and the edit text is only copied into the buffer if cDialog_ShowModal returns mrOk. Figure 11.2 shows a snapshot of the input box in action. Figure 11.2: A simple input box
My Way Again, in my opinion, the Cybiko way takes too many lines of code, so I wrap this up into a single function called InputBox. This function is shown in Listing 11.9.
Team LRN
134
Chapter 11: Basic Dialogs
Listing 11.9 //input box function(returns a modal result (mrXXXX constant) int InputBox( char* title, //(in)title of the input box char* message, //(in)message for this input box long style, //(in)style (combination of mbXXXX constants) int edit_size, //(in)max length of the string for input box char* edit_text, //(in/out)input box text struct cWinApp *ptr_win_app //(in)pointer to application(main_module.m_process) ) { //pointer only, cut down on stack space struct cDialog* pDialog; //return value(modal result) int mr; //allocate dialog pDialog=(struct cDialog*)malloc(sizeof(struct cDialog)); //construct dialog cDialog_ctor(pDialog,title,message,style | mbEdit,edit_size,ptr_win_app); //set the edit text cDialog_SetEditText(pDialog,edit_text); //show the dialog modally mr=cDialog_ShowModal(pDialog); //retrieve the edit text cDialog_GetEditText(pDialog,edit_text); //destroy dialog cDialog_dtor(pDialog,FREE_MEMORY); //return the modal result return(mr); }
This function is a lot like my MessageBox function. You specify the title, message, and style in the first three parameters. The next two parameters are a text buffer for initializing and saving the results of the edit box text and the size of that buffer. The last parameter is a pointer to an application (main_module.m_process) so the input box can retrieve messages. The function returns the mr* constant returned from the cDialog_ShowModal call.
Team LRN
Chapter 11: Basic Dialogs
135
Interface Standards Now for a word about interface standards. Cybiko, Inc., has drawn up a number of standards, including messages, dialog boxes, and input boxes that should be used for many common tasks, to keep the same look and feel across all Cybiko applications and games. These are listed in the Cybiko SDK help files, and you should give them a good read. Neither I nor Cybiko, Inc., can make you follow these standards, but I strongly suggest that you use them.
Summary At this point, you should now be able to make message boxes and input boxes for any occasion. These tasks may seem trivial right now, but believe me, they are very important when it comes to polishing up your applications and games. Later on, we will be revisiting the Cybiko UI classes in greater detail. I just wanted you to be familiar with the cDialog class because it is used with such frequency that you practically cannot avoid using it. Next up, we’re going to take a look at a few miscellaneous Cybiko programming basics. Then, we’re going to make an actual game with just the basic stuff we’ve covered thus far.
Team LRN
Chapter 12
Some Miscellaneous Basics Overview At this moment, you are very close to having enough knowledge to make a simple Cybiko application or game. There are just a couple of little things that don’t really belong in any other category that need to be covered just to round out the body of knowledge we have already discussed. This will be a short chapter, and then I promise we’ll make a game.
Input Files We have talked about bitmaps and music sequences, and how to load them from resources. Later, we will talk about more things dealing with loading and saving these objects to files, but just being able to load them in is enough to get started with them. However, not all information your program will need will necessarily be in the form of a bitmap or music sequence. You will have level files, text files that are shown between levels, and various other types of miscellaneous files that your program needs to read. In order to do that, we need to be able to generically open a resource or external file and read them in. There are two different classes dealing with binary input. The classes are Input and FileInput. Both of these classes will work for most of what you want to do. FileInput just adds some functionality to allow you to specify filenames in the constructor, and also gives a function to open files. However, Input does all of the actual reading, and the corresponding FileInput functions are nothing more than #defines that use the Input functions. To read information from resources, we will make use of the Input class. To read from external files, we will use the FileInput class. There is really very little difference in the code for each other than what class is used.
136
Team LRN
Chapter 12: Some Miscellaneous Basics
137
Opening a Resource For opening resources, use the Input class. There are two functions that you can use to open a resource and return a pointer to an Input object. There is no Input constructor, so these functions are all you have to open up resources for input. The functions are shown in Listing 12.1. Listing 12.1 struct Input* struct Input*
open_resource (int index) ; open_resource_Ex (char* sz_file_name);
Both of these functions return a pointer to an Input object. The open_resource function takes an index into the resource list. Indices start at 0 for the first resource in the app file, and go up from there. The open_resource_Ex function takes the name of the resource you wish to open. In most cases, I wouldn’t suggest using open_resource since the resource number can change from one build to another and it makes maintaining your code more difficult. The only time you would want to use it is if you had many resources and did not store the filenames in the application archive (using some of the more advanced features of Filer.exe). Each resource’s name is stored in your application archive, and having many resources will cause more space to be taken up, and not storing the name might just shave off enough bytes in the archive to allow you to fit some more stuff in there.
Opening an External File For opening external files, use the FileInput class. Unlike the Input class, FileInput has constructors. These constructors are shown in Listing 12.2. Listing 12.2 struct FileInput* struct FileInput*
FileInput_ctor (struct FileInput* ptr_file_input) ; FileInput_ctor_Ex (struct FileInput* ptr_file_input, char* sz_file_name);
Both of these functions return pointers to the newly constructed FileInput object. The first parameter (the only parameter in the case of FileInput_ctor) is a pointer to the object you wish to construct. The second parameter of FileInput_ctor_Ex is a string that tells the constructor which file you wish to open. FileInput_ctor constructs a FileInput object, but does not open a file. If you use this function to construct your FileInput object, you will need to use the FileInput_ open function (shown in Listing 12.3) to actually open the file. Listing 12.3 bool FileInput_open (struct FileInput* ptr_file_input, char* sz_file_name);
This function returns TRUE or FALSE, indicating whether or not the file was successfully opened. The first parameter is a pointer to a FileInput object, and the second parameter is a string that tells what filename you wish to open.
Team LRN
138
Chapter 12: Some Miscellaneous Basics
Destroying an Input or FileInput Object To destroy an Input or FileInput object, you use the destructor Input_dtor or FileInput_dtor, respectively. These destructors are just like any other destructor, and you should be used to using them by now. In all cases, opening an Input object with open_resource or open_resource_Ex will require the FREE_MEMORY flag to be passed to the destructor. The FileInput object may or may not be dynamically allocated, so you should use the appropriate memory flag when destroying them.
Retrieving Information about an Input Stream There are plenty of times when you need some information about an Input or FileInput object, including how big it is, what position it is at, whether you are at the end of the stream, if the stream is bad, and so on. The information retrieval functions for the Input class are shown in Listing 12.4. The information retrieval functions for FileInput are shown in Listing 12.5. Listing 12.4 long Input_tellg (struct Input* ptr_input); long Input_get_size (struct Input* ptr_input); int Input_get_flags (struct Input* ptr_input) ; bool Input_is_eof (struct Input* ptr_input) ; bool Input_is_bad (struct Input* ptr_input) ; bool Input_is_good (struct Input* ptr_input);
Listing 12.5 long FileInput_tell (struct FileInput* ptr_file_input); long FileInput_tellg (struct FileInput* ptr_file_input); long FileInput_get_size (struct FileInput* ptr_file_input); int FileInput_get_flags (struct FileInput* ptr_file_input); bool FileInput_is_eof (struct FileInput* ptr_file_input); bool FileInput_is_bad (struct FileInput* ptr_file_input); bool FileInput_is_good (struct FileInput* ptr_file_input);
Even though the function names are pretty self-explanatory, I’m going to explain them anyway. Input_tellg, FileInput_tellg, and FileInput_tell all return the current position within the input stream. If the stream’s position cannot be determined, it returns –1. Input_get_size and FileInput_get_size both return the size of their respective objects. If the size cannot be determined, it returns a –1. Input_get_flags and FileInput_get_flags return an int that contains a number of flags that give information about the file. There are three different flags, FLAG_EOF, FLAG_BAD, and FLAG_EXCEPTIONS. You won’t have to worry about FLAG_EXCEPTIONS, and retrieving the values of FLAG_EOF and FLAG_BAD can be done through other functions. Input_is_eof and FileInput_is_eof check the flags to see if FLAG_EOF is set. This indicates that you are at the end of the stream.
Team LRN
Chapter 12: Some Miscellaneous Basics
139
Input_is_bad and FileInput_is_bad check the flags to see if FLAG_BAD is set. A stream is bad if it is invalid or otherwise corrupted. You probably won’t ever use this function. Input_is_good and FileInput_is_good check to make sure that FLAG_BAD is not set. Again, you are unlikely to use this function.
Reading from an Input Stream It wouldn’t be an input stream unless we wanted to read something from it, now would it? Each of the Input and FileInput classes can read data in four ways. The four functions are shown in Listing 12.6. Listing 12.6 long Input_read (struct Input* ptr_input, void* buffer, long length); int Input_read_byte (struct Input* ptr_input); short Input_read_word (struct Input* ptr_input); long Input_read_dword (struct Input* ptr_input);
The functions for FileInput are the same, except FileInput replaces Input. Technically, the Input functions will work for a FileInput object, but mixing names like this tends to make code more confusing, so when using a FileInput object, use the FileInput version of the functions. With Input_read_byte, you can read a single byte. With Input_read_word, you can read a word, or two bytes. With Input_read_dword, you can read a double word, or four bytes. For sizes other than 1, 2, and 4 bytes, you can just use Input_read, which allows you to read a variable number of bytes (specified by the length parameter) into a buffer (specified by the buffer parameter). Input_read returns the number of bytes actually read from the file.
Maneuvering through an Input Stream Many times, you will want to input from a stream sequentially, meaning you read it in once, from start to end, without skipping over parts or moving back to other parts of the file. Other times, you may wish to move to a specific part of the file or resource, and read data from there. This is called random access, which is rather a misnomer, since it has nothing to do with randomness. You can move to any part of the file or resource at any time, using Input_seekg, FileInput_seekg, or FileInput_seek. These three functions are exactly the same and can be used interchangeably. The syntax for Input_seekg is shown in Listing 12.7. Listing 12.7 long
Input_seekg (struct Input* ptr_input, long pos, seek_t mode);
The syntax for the other two functions is exactly the same other than the name and the first parameter, so I will narrow my discussion to just Input_seekg, but keep in mind that everything I say here applies to the other functions as well.
Team LRN
140
Chapter 12: Some Miscellaneous Basics
The first parameter is the Input or FileInput object of which you are changing the stream position. The second parameter is either an absolute or relative position to which you wish the stream position to move. The third parameter is a “seek mode,” which changes the meaning of pos depending on its value. There are three seek modes: SEEK_SET, SEEK_CUR, and SEEK_END. If you use SEEK_SET, the stream position is changed to be the absolute position in the stream based on the beginning of the file, and you should only specify positive positions. If, for example, you read the 10th byte of a file, you would use 10 as pos and SEEK_SET as the seek mode, and then read from there. If you use SEEK_CUR, the stream position is changed relative to the current position. If pos is a positive value, it moves the current position toward the end of the stream. If pos is negative, the position moves closer to the beginning of the file. If you wanted to move 10 bytes ahead of the current position, you would use a pos of 10 and a seek mode of SEEK_CUR. If you wanted to move 10 bytes backward, you would instead use –10 in the pos parameter. Finally, SEEK_END references the end of the file, and only non-positive values should be used. If you wanted to move to the last 10 bytes of a stream, you would put a 10 in pos and use SEEK_END. Input_seekg returns a long. This is the new absolute position in the file, or –1 if the operation for some reason failed. There is now nothing you can’t do as far as reading in files to a Cybiko program. I have covered every single function dealing with the Input and FileInput classes. Later, when we get to Output and FileOutput, you will be reminded of Input and FileInput, because the output stream functions are just the opposite of the input stream functions.
The Wait Icon You have, I’m certain, noticed the spinning Cybiko icon that shows up whenever a lengthy process has begun, such as loading in a file or starting an application. You can also make use of this feature, with a simple function call to set_hourglass, shown in Listing 12.8. Listing 12.8 void set_hourglass (
bool enable );
To turn on the wait icon, you call set_hourglass with TRUE. To turn it off, call it with FALSE. Be warned: using the wait icon starts a special thread that takes care of rendering and spinning, so there is a slight performance hit when using it. However, having your Cybiko do nothing and look like it is locked up during a long operation isn’t a good idea. Anytime something takes longer than a second or two, you probably want to use the wait icon, regardless of the performance implications.
Team LRN
Chapter 12: Some Miscellaneous Basics
141
Summary Now you’ve got the goods on input streams and wait icons. You have enough knowledge at this point to make a halfway decent Cybiko application or game, as we shall see in the next chapter. There is still quite a bit left to learn, of course, but you now have enough of a solid foundation to get started with some actual fun stuff.
Team LRN
Chapter 13
A Simple Cybiko Game Overview So! Let’s make a game! That is what we’re all here for, after all. In this chapter, I’m going to take you through all of the steps required to make a game, just in case you’ve never made one before. It’s not like any other kind of programming on the planet. The game I’m going to show you is rather simple, but it does have all of the elements required in a game of any size.
Game Theory It is said that the human race should not be judged by its acts of good or evil, but by the games it plays, i.e., what we do in our leisure time. Indeed, games have fascinated many people for millenia. Every culture plays games, from tribes in Africa playing mancala to someone playing Quake III. The Cybiko was built for the primary purpose of playing games. Sure, there are other applications that you can find for this hand-held little wonder, but by and large, it’s the games you want. So, what is a game? What purpose do they serve?
What is a Game? A game consists of two things: game states and game mechanics. These are interrelated concepts. A game state is just a set of information that describes the current configuration of the game. For example, in chess, the initial game state is where the pieces are set up on an 8x8 grid in the appropriate positions. If you start out with the pieces in any other configuration, you are not playing chess. You are, at most, playing a variation of chess.
142
Team LRN
Chapter 13: A Simple Cybiko Game
143
A game mechanic (also known as a rule) allows you to move from one game state into another, or to remain at the current game state. Game mechanics specify what moves are legal in a given game state and manage things like changing players in a multi-player game. There are a few game states that are special. One is the initial game state, which exists whenever you start a new game. The other is the end game state. In the end game state, the game is either in a state where you can no longer use a game mechanic to move to another state or there is no point in doing so (like a stalemate). Please notice that I have made no mention of “winning” or “losing” yet, because the presence of these states depends on the game you are playing. Not all games have a “win” condition, although many do. All games have a “lose” condition, however. Winning depends on whether the game you are playing is “finite” or “infinite.” An infinite game can theoretically be played forever, with no players ever winning. This is true of most arcade-type games. A finite game will, at some point, end. A good example of this is Reversi. There are 64 squares on a Reversi board; four of them are occupied during the initial game state. During each player’s turn, if possible, another square is occupied. When no more moves are possible (usually when the board is filled up), the game is over. So, Reversi lasts at most 60 turns, and can end sooner. One last category I’m going to talk about is “semi-finite.” Chess is a good example of this. In some circumstances, a game of chess could go on forever, for example when each player only has his king left. Sure, you could both move the king around until kingdom come, but you would never reach an end game state. However, in that circumstance, it is obvious that the game will continue forever with neither player winning, so there are provisions made for such an occurrence—the stalemate or draw, where both players agree that neither of them are going to win or lose.
What Purpose Do Games Serve? This is a tricky question. There have been many pundits who have suggested that people play games to relax. If this is so, why are many games frustrating? We can say that game playing is generally a leisure-time activity, although not in all cases. There are professional football and basketball players who get paid to play the game. There are also tournaments for chess and Reversi and other classic games that have cash prizes. In addition, there are game shows on television where money can be won. Our culture is so inundated with games of various types that they must serve some sort of purpose (according to one theory of sociology). My own theory on this matter is that a game serves the same purpose as a book or a TV show—escapism. Your life might be completely filled with stress from your job, your family, your debts, and so on, but when you play a game, you can forget about all of your concerns and just play a game, or watch a game being played. So, it is entertainment.
Team LRN
144
Chapter 13: A Simple Cybiko Game
Where Do Games Come From? For the most part, modern games are usually just a variation on a theme. They are based on some other game that already exists. Very few games are totally and completely original. As a creator of games, I can tell you that most of my games are either “covers” or “re-dos” of older games, or a variation on an older game where I ask a few “what-if” questions. Game creation is perhaps the most interesting activity that you could ever do. It requires both logic and creativity, and requires that you be creatively logical and logically creative at the same time. Both hemispheres of your brain are engaged in this process. Unfortunately, no one has figured out how to teach creativity (I sure haven’t), so you’re on your own in that respect. A few tips, however: challenge conventional wisdom, think outside of the box, and try to look at things in a completely different way.
Game Design Once you have an idea for a game, you have taken your first small step into the game creation process. I accent the word “small” in the prior sentence because an idea for a game is not a game. It isn’t half of a game. It isn’t even a fourth of a game. The idea is no more than 1% of the game. It is a kernel, a seed, something that you process and work on and make into a game. Take, for example, a nugget of iron ore. A nugget of iron ore is not a sword. First you have to smelt it and purify it, then you need to take the iron and fashion it into something usable, like a sword, and finally, you have to test it to make sure it doesn’t have flaws. Game creation is much like this process. If the idea for a game is the nugget of iron ore, then game design is the smelting. You take your idea, and flesh it out into something that might be usable. Most games fit into some sort of genre: arcade, action, strategy, etc. Determine what genre your game idea best fits into, and look at other games in the same genre. This means comparing and contrasting your idea with other ideas. Look critically at these other games. What do they do that you like or dislike? Ask your friends what they like or dislike about these games. Break the games down into features. Determine whether your game needs those features; if you find yourself adding features to your game just because they are in other games of the same genre, challenge that! Just because game X has a certain feature in it doesn’t mean your game necessarily should.
Game Analysis Case Study: Let us say you are going to do an arcadish game similar to Pac-Man. This is in the arcade/action genre. I’m going to take apart the game of Pac-Man and analyze its features to show you what I mean.
Team LRN
Chapter 13: A Simple Cybiko Game
145
Pac-Man: Most noticably, Pac-Man has its namesake, the little yellow guy who eats dots. Naturally, this guy could be of any color and look like anything you want. This is the “main character,” the avatar for the player of the game. Is he necessary? Well, in order to be playable, the player has to control something, although it need not be the little yellow guy. So, yes, we need the player to control something, but we’re just not sure what yet. Monsters: The next most obvious feature is the monsters. The monsters attempt to eat the Pac-Man. Are the monsters necessary? Not as such, but we do need some sort of adversary that tries to keep the main character from achieving his goal. However, these need not take the form of monsters. The dots: Pac-Man must eat all of the dots on the screen in order to complete the level (we’ll get to the concept of levels in a bit). This is Pac-Man’s main objective, to eat all of the dots. Without a need for Pac-Man to do this, there would be nothing for Pac-Man to do, and no point in playing the game. The objective of the main character need not be dot-eating, but there should be something for the main character to do. Power pellets: On each level, there are four power pellets. When Pac-Man eats one, for a short period of time the tables are turned on the monsters, and instead of them eating him, he can eat them. The idea of power pellets is not essential to the game of Pac-Man. Indeed, the game is playable without them (albeit much more difficult). The main concept behind the power pellets is that Pac-Man gets a brief respite from the monsters. Bonuses: In Pac-Man, you can eat fruit, which gives a boost to your score. We haven’t talked about score yet, but we will in a bit. The fruits are not strictly necessary to the game play. They do, however, give that “little something extra” that enhances the game playing experience, and takes some skill and cunning to acquire, especially when monsters are chasing you. Score: The score in Pac-Man is your measure of success. Pac-Man is an infinite game. With enough skill, you could play it forever, although I think you would die of hunger and dehydration and sleep deprivation first, but it is possible. In an infinite game, you generally do want some sort of success metric like a score. However, it need not actually be a score. You might have a success metric of how long the game lasted, or how many levels you surpassed. Without a success metric, the player doesn’t know how well he did, so he is not interested in doing better next time, since he doesn’t know what “better” means. Levels: The Pac-Man levels are mazes filled with dots, with power pellets at the four corners. Pac-Man must quickly and efficiently navigate this environment while avoiding the monsters. Once a level is completed, he moves on to the next level. This brings up a topic I have not yet discussed: episodic versus progressive games. PacMan is an episodic game. You complete one level, then move on to another level, then another, etc. After a level is complete, you get a small break while the next level is loaded. In a progressive game, like Centipede, there is no break in the action. The screen changes color, the mushrooms move down, and you keep playing. A Pac-Mantype game does not need to be episodic; it could be designed to be progressive.
Team LRN
146
Chapter 13: A Simple Cybiko Game
Lives: The concept of “lives” or “tries” is pretty prevalent in arcade video games. At least one “life” is required. I’m going to talk about the concept of lives not in the context of “should the player have a life” but rather “should the player have multiple lives and should he be able to earn extras.” The style of play is quite different if the player has only one life. He will be less likely to take risks, less likely to go for bonuses, and so on. In a multiple-life scenario, he is more likely to do these things, especially if he can earn extra lives under certain circumstances. So, that’s about it for breaking down Pac-Man. Here’s a list of features that I think make Pac-Man the game it is: 1.
A main character that the player controls (the Pac-Man)
2.
Adversaries that attempt to thwart the objective of the main character (the monsters)
3.
An objective of some kind (dots)
4.
Something that gives a respite from/turns the tables on the adversaries (power pellets)
5.
The bonus fruits, which gives the player an optional objective to demonstrate his skill of playing
6.
A success metric (score)
7.
Episodic play (levels)
8.
Multiple attempts, with extra attempts attainable (lives)
Of these, I rank features 1, 2, 3, and 6 to be essential for any Pac-Manish game. Without a main character, adversaries, an objective, and a success metric, there is no game. The rest of the list is negotiable and/or optional. Here’s my reasoning for both groups. Essential components: n
Without a main character that the player controls, there is no point to have a player, and thus, no game.
n
Without adversaries, the main character can achieve his objective unopposed, ergo no challenge, and therefore no game.
n
Without an objective, the main character has nothing to do, and there is no point to playing the game.
n
Without some sort of success metric, the player does not know how well he did, and therefore cannot do “better,” and this diminishes the sense of achievement, which makes the game pointless.
Non-essential components: n
The game can be played without a respite from the adversaries; it just makes the game more challenging/frustrating.
n
The game can be played without bonuses, although bonuses do add a challenging factor that many players will find enjoyable.
Team LRN
Chapter 13: A Simple Cybiko Game
147
n
The game can be designed to be played progressively rather than being episodic.
n
The game can be played with only a single try rather than multiple tries. This would make the game more challenging/frustrating.
You’ll notice I have used the words “challenging” and “frustrating” several times above. I am now going to speak of game balance. A game that no one wants to play may as well not be a game at all. Players and potential players have to want to play your game, for whatever reason: fun, challenge, etc. In order to keep people playing your game, you must not make the game too difficult or too easy. If the game is too easy, the players will become bored, and stop playing. If the game is too hard, they will become frustrated, and again, stop playing. So, as a game designer, you must make your game challenging but not too challenging, and easy enough but not too easy. This is a hard thing to do, and unfortunately, you cannot do this in the design phase. For this, you have to wait until later in the process. Despite the fact that you cannot make a balanced game in the design phase, you can identify at this point what factors you need to watch that may later turn out to be a problem.
Fleshing Out the Design Once you have a rough idea of what features you want your game to have (like the rather abstract features I talked about with Pac-Man), you can start to detail them. I’m going to continue with the Pac-Man example for now. We’ve determined that we need a main character, adversaries, an objective, and a success metric. What form do these take? What does the main character look like? What actions can he perform? What do the adversaries look like? How numerous are they? What actions can they perform? What is the main character’s objective? How can he use the actions available to him to reach that objective? How will the adversaries try to prevent him from achieving that objective? How do we measure the success of the main character? The “what does X look like” questions aren’t really ones that have to be answered right now. You can wait until later, but it helps if you can visualize the main character and the adversaries. You can just pick something for now and change it later. The “what actions can X perform” should be answered after the “what is the objective” question, since the objective will help make deciding what actions can be performed a little easier. The number of adversaries should be chosen initially, but will probably change throughout the course of the rest of the creation process since it is a balance issue. Too many adversaries will make it too hard, and too few adversaries will make it too easy. Identify potential balance issues as early as you can!
Simulation Make a mockup of the game on some sort of board or graph paper, and test out the major concepts. You can identify a number of balance issues in this step. Alternately,
Team LRN
148
Chapter 13: A Simple Cybiko Game
you can make a quick-and-dirty version of the game (nothing more than a couple of hours should be spent on this) and try it out, with the primary goal not of making the game complete, but testing out whether the game design is solid. Something that sounds good on paper isn’t necessarily going to make the transition to a game. Also, some game designs are just unworkable, so don’t be afraid to trash something or go back and rethink it.
Making the Game When you get through all of the design and simulation stuff, your game concept should be a great deal more specific than when you entered the process. That is, it should be a lot more complicated than, “I want to make a game like Pac-Man.” You should at least have several pages of scribbled notes and little drawings of what you intend to make, if not a formalized design document. Now you have the features you want, all that is left is to implement them. But where to start? This is perhaps one of the hardest things about game programming; it is often not immediately obvious. Unless you have an established base of classes from previous games you have made, you start with nothing. You could start with one of the template applications from Chapter 6, but all that does is give you a blank screen. Bringing that blank screen to life is your task, and it isn’t easy. The first thing you might think to do is make the main character. Fair enough. That was the first thing that occurred to me as well. Let us examine our main character. First, he can move in four directions—up, down, left, and right. I tend to use north, south, west, and east for these directions, but either one will do. I will use the cardinal directions rather than the relative directions because I’m more comfortable doing so. Second, the main character is animated. For each direction, there is a picture with him open mouthed and closed mouthed. Since the main character is just a circle with a piece of pie cut out, the art will be pretty simple. Third, he moves around the screen in whatever direction he is facing until he runs into a wall. These three items tell us a lot about the main character of the game. Here’s a short list of the properties I feel are important to the main character. 1.
Direction he is facing—north, east, south, or west
2.
Position on screen
3.
Mouth open or closed
4.
Images for each of the directions for each of the mouth states
So, to abstract this data, we might declare the code in Listing 13.1.
Team LRN
Chapter 13: A Simple Cybiko Game
149
Listing 13.1 //directions #define DIR_NORTH 0 #define DIR_EAST 1 #define DIR_SOUTH 2 #define DIR_WEST 3 #define DIR_COUNT 4 //mouth constants #define MOUTH_OPEN 0 #define MOUTH_CLOSED 1 #define MOUTH_COUNT 2 //main character struct struct MainCharacter { //direction he is facing int Direction; //position int X,Y; //mouth state int MouthState; //bitmaps struct Bitmap* bmpArray[DIR_COUNT][2]; };
This is a good start. We have all of the required knowledge for our main character represented here. But what about functions for dealing with this stuff? Check out Listing 13.2, which has a number of functions for generically creating, destroying, and manipulating the MainCharacter struct. Listing 13.2 //constructors struct MainCharacter* MainCharacter_ctor(struct MainCharacter* ptr_maincharacter); struct MainCharacter* MainCharacter_ctor_Ex(struct MainCharacter* ptr_maincharacter,int dir,int x,int y,int mouthstate); //destructor struct MainCharacter* Maincharacter_dtor(struct MainCharacter* ptr_maincharacter,int mem_flag); //getters int MainCharacter_get_direction(struct Maincharacter* ptr_maincharacter); int MainCharacter_get_x(struct Maincharacter* ptr_maincharacter); int MainCharacter_get_y(struct Maincharacter* ptr_maincharacter); int MainCharacter_get_mouthstate(struct Maincharacter* ptr_maincharacter);
Team LRN
150
Chapter 13: A Simple Cybiko Game
struct Bitmap* MainCharacter_get_bitmap(struct MainCharacter* ptr_maincharacter,int dir,int mouthstate); //setters void MainCharacter_set_direction(struct MainCharacter* ptr_maincharacter,int dir); void MainCharacter_set_x(struct MainCharacter* ptr_maincharacter,int x); void MainCharacter_set_y(struct MainCharacter* ptr_maincharacter,int y); void MainCharacter_set_mouthstate(struct MainCharacter* ptr_maincharacter,int mouthstate); void MainCharacter_set_bitmap(struct MainCharacter* ptr_maincharacter,int dir,int mouthstate,struct Bitmap* ptr_bitmap);
As you can see, I made two constructors, a destructor, and functions to set and get each of the properties of the MainCharacter object. This is a bare minimum for any class you create. There should always be functions to set and get every property of the object with which you are working. Why? Well, the setters are important for validation reasons. For example, setting a direction other than the ones defined above itsmeaningless. The same is true for the mouth state. At some point, the x and y values will be limited to a given range. For the bitmap setter, we must make certain that the parameters dir and mouthstate are valid values before we assign a bitmap pointer to the array. Similarly, with the getters, we may need validation. In most of the cases here, we do not, except for MainCharacter_get_bitmap, in which we have to validate dir and mouthstate again. For the others that require no validation, we can use a “faux function” instead. NOTE: Technically, even all of the getters need validation, since we might be passing it a bad MainCharacter pointer. We can handle this validation inside of our faux function instead.
Faux Functions Those functions that I am terming “faux functions” are not really functions, but they look like them and are used just like them. Consider the four functions in Listing 13.3. Listing 13.3 int int int int
MainCharacter_get_direction(struct Maincharacter* ptr_maincharacter); MainCharacter_get_x(struct Maincharacter* ptr_maincharacter); MainCharacter_get_y(struct Maincharacter* ptr_maincharacter); MainCharacter_get_mouthstate(struct Maincharacter* ptr_maincharacter);
There is virtually no need for validation here since the only parameter is the pointer to the object of which we are retrieving the value. Instead of using MainCharacter_ get_direction (pMainCharacter), we may as well use pMainCharacter–>Direction since using an actual function gives us the added overhead of a function call, and it is less typing to boot! However, one of the pillars of OOP is encapsulation and data
Team LRN
Chapter 13: A Simple Cybiko Game
151
hiding, so we generally do not want to be accessing members of objects in any form other than functions whenever possible. But, since it is less efficient to use a function to retrieve this data, how can we as programmers properly do data hiding? Well, in a constrained environment like the Cybiko, you don’t want to have more functions than you need, so you make a #define that will fake a function. This is what I mean by “faux function.” Consider Listing 13.4, which shows the four faux function equivalents of the functions in Listing 13.3. Listing 13.4 #define #define #define #define
MainCharacter_get_direction(ptr) ( (ptr) != NULL : (ptr)–>Direction : –1 ) MainCharacter_get_x(ptr) ( (ptr) != NULL : (ptr)–>X : –1 ) MainCharacter_get_y(ptr) ( (ptr) != NULL : (ptr)–>Y : –1 ) MainCharacter_get_mouthstate(ptr) ( (ptr) != NULL : (ptr)–>MouthState : –1 )
There we go! We’ve got all of our getter functions without adding the overhead of an actual function call. In each of these, if the pointer we pass into the function is NULL, we will get a negative one, so we have a limited amount of validation in effect. Plus, we are four functions fewer now. This is a mixed blessing. If these faux functions get used a great deal, the application will be larger since the code in them is placed anywhere they are used, making the application larger than it needs to be. On the plus side, since we are not calling an actual function, we will get a small speed increase, although probably not enough to be noticable.
Extending the MainCharacter Class While we can now do any operations on MainCharacter objects that we would ever want, it really doesn’t help us, because nothing is really very automated. In order to move a MainCharacter object, we must first find out where he currently is, move him, check his mouth state, and change the mouth state. Like I said . . . not very helpful. Also, while we have a nice array of bitmaps, we still have to retrieve his direction and mouth states, then we must retrieve the Bitmap object for that condition, then retrieve his x and y position, then render the bitmap. Listing 13.5 shows another list of functions that you will probably find useful for the MainCharacter class. Listing 13.5 //retrieves the next x and y coordinates of the main character int MainCharacter_get_next_x(struct MainCharacter* ptr_maincharacter); int MainCharacter_get_next_y(struct MainCharacter* ptr_maincharacter); //moves the main character void MainCharacter_move(struct MainCharacter* ptr_maincharacter,bool togglemouth,bool updateposition); //toggles the mouth state int MainCharacter_toggle_mouth(struct MainCharacter* ptr_maincharacter); //draws the main character
Team LRN
152
Chapter 13: A Simple Cybiko Game
void Graphics_draw_maincharacter(struct Graphics* ptr_gfx,struct Maincharacter* ptr_maincharacter); #define DisplayGraphics_draw_maincharacter Graphics_draw_maincharacter
Some explanation is in order. I’ve got two functions here that will tell me the next x and y position of the main character, based on his current direction. This is because I’m thinking ahead. In some circumstances, we may need this information to determine whether or not the main character is about to collide with something, like the walls, or a monster, or a dot, or a power pellet. Also, you’ll notice the last two functions, which are functions dealing with the Graphics class and the DisplayGraphics class, as well as the MainCharacter class. Why did I choose to make a Graphics_draw_maincharacter class rather than a MainCharacter_draw class? For this, I looked to other, already existing Cybiko classes, namely the Bitmap class. There is no Bitmap_draw function, but there is a Graphics_draw_bitmap. So, I have concluded that anything that should be drawn should be a Graphics function, not a function of the object being drawn. I focus on the destination, not the source, to keep my own code base consistent with how the Cybiko SDK works.
The Monster Class I’m going to leave the MainCharacter class alone for a while. Other than a few faux functions, there is no implementation for its various functions at this point. This is because I know something that will cause me to change this later. I’ll be getting to it momentarily. Now we move on to the Monster class. We give the monsters the same sort of consideration we gave the main character, picking out properties that we think are important to have in a monster. First, a monster can move in four directions. This is normally indicated somehow on the image being displayed to represent the monster. In the original, his eyes pointed in the direction he was going. Second, a monster is animated. In the original, the lower edge of the monster would move a bit. This makes the monster seem alive, and it’s probably something we want to do here. Third, a monster moves around the screen, usually attempting to eat the main character. Fourth, in reaction to the main character eating a power pellet, the monster will move away from the main character. Fifth, if he is eaten by the main character, the image changes to just his eyes, and he seeks to move to home base as quickly as possible. The image of the eyes still points in the direction he is going. Based on these items, here is a list of the properties that a monster class will need. 1.
Direction of motion
Team LRN
Chapter 13: A Simple Cybiko Game
153
2.
Position on the screen
3.
Current animation frame
4.
Some sort of indication that a power pellet has been eaten, as well as a timer for how much longer the power pellet will be in effect.
5.
Whether or not the monster has been “eaten,” and must now seek home base.
6.
Images for both animation frames as well as the directions of the eyes.
You should notice some similarities between the monster and the main character. Both of these have a direction and a position. They also both have animation, although this animation takes a slightly different form. In Listing 13.6, there is a quick struct to contain all of the information for a Monster object (except for the power pellet status, which I’ll handle outside of the class). Listing 13.6 struct Monster { int Direction; int X,Y; int Frame; bool Eaten; struct Bitmap* bmpEyes[DIR_COUNT]; struct Bitmap* bmpIcon; };
//direction monster is facing //position of the monster //current animation frame of the monster //whether or not the monster has been “eaten” //images for the eyes //bitmap for the image, used when not eaten
We could continue on from here, making all of the functions for dealing with the Monster class, but since there is a significant overlap between Monster and MainCharacter (namely Direction, X, and Y), we definitely want a base class.
Base Class for Monster and MainCharacter Since both monsters and the main character have a position and a direction, it only makes sense that they come from the same base class. I talked about this a bit in Chapter 5, but now I’m actually going to give an example of doing it. First, we are dealing with only the properties common to both classes: Direction, X, and Y. No other information will be used, and no other code should be made. Listing 13.7 shows the struct and functions for what I am calling the Character class. Listing 13.7 struct Character { int Direction;//direction the character is facing int X,Y;//position of the character }; //constructors struct Character* Character_ctor(struct Character* ptr_chr);
Team LRN
154
Chapter 13: A Simple Cybiko Game
struct Character* Character_ctor_Ex(struct Character* ptr_chr,int dir,int x,int y); //destructor void Character_dtor(struct Character* ptr_chr,int mem_flag); //getters int Character_get_direction(struct Character* ptr_chr); int Character_get_x(struct Character* ptr_chr); int Character_get_y(struct Character* ptr_chr); //setters void Character_set_direction(struct Character* ptr_chr,int dir); void Character_set_x(struct Character* ptr_chr,int x); void Character_set_y(struct Character* ptr_chr,int y);
Since this class is abstract, all of the getters and setters should be made into faux functions, since we cannot tell what values are valid for Direction, X, or Y for this class. That is up to derived classes to determine. In fact, we aren’t even going to use validation for direction, because then we could use the Character class as a base class for objects that may have four directions, six direction, eight directions, or even more. We won’t be making any objects of the Character class anyway.
Deriving MainCharacter from Character Now that we’ve got a base class, we can redesign our MainCharacter class and Monster class to make use of this. Listing 13.8 shows the new declarations for the MainCharacter class, including all functions. Listing 13.8 //main character struct struct MainCharacter: public Character { //mouth state int MouthState; //bitmaps struct Bitmap* bmpArray[DIR_COUNT][2]; }; //constructors struct MainCharacter* MainCharacter_ctor(struct MainCharacter* ptr_maincharacter); struct MainCharacter* MainCharacter_ctor_Ex(struct MainCharacter* ptr_maincharacter,int dir,int x,int y,int mouthstate); //destructor struct MainCharacter* Maincharacter_dtor(struct MainCharacter* ptr_maincharacter,int mem_flag); //getters #define MainCharacter_get_direction Character_get_direction
Team LRN
Chapter 13: A Simple Cybiko Game
155
#define MainCharacter_get_x Character_get_x #define MainCharacter_get_y Character_get_y int MainCharacter_get_mouthstate(struct Maincharacter* ptr_maincharacter); struct Bitmap* MainCharacter_get_bitmap(struct MainCharacter* ptr_maincharacter,int dir,int mouthstate); //setters void MainCharacter_set_direction(struct MainCharacter* ptr_maincharacter,int dir); void MainCharacter_set_x(struct MainCharacter* ptr_maincharacter,int x); void MainCharacter_set_y(struct MainCharacter* ptr_maincharacter,int y); void MainCharacter_set_mouthstate(struct MainCharacter* ptr_maincharacter,int mouthstate); void MainCharacter_set_bitmap(struct MainCharacter* ptr_maincharacter,int dir,int mouthstate,struct Bitmap* ptr_bitmap); //retrieves the next x and y coordinates of the main character int MainCharacter_get_next_x(struct MainCharacter* ptr_maincharacter); int MainCharacter_get_next_y(struct MainCharacter* ptr_maincharacter); //moves the main character void MainCharacter_move(struct MainCharacter* ptr_maincharacter,bool togglemouth,bool updateposition); //toggles the mouth state int MainCharacter_toggle_mouth(struct MainCharacter* ptr_maincharacter); //draws the main character void Graphics_draw_maincharacter(struct Graphics* ptr_gfx,struct Maincharacter* ptr_maincharacter); #define DisplayGraphics_draw_maincharacter Graphics_draw_maincharacter
I put in bold some of the changes so that you can pick them out a bit better. Notice the use of “: public Character” on the line where we declare the struct MainCharacter. This is an object-oriented extension of the Cybiko C compiler that makes it act in some ways like C++. If you are not familiar with C++, this little piece of code just tells the Cybiko compiler that struct MainCharacter has all of the same data members as struct Character in addition to those we are adding in the remainder of the definition of MainCharacter. Also, this allows us to use a struct MainCharacter* any place where we can use a struct Character*, which means we can get away with fewer functions, since we will reuse as many of the Character functions as we can, and I did just that with all of the getter functions.
MainCharacter Implementation Check out the program found in CyBk13_1 on the companion CD. In this example, I have implemented a portion of the functionality need