1. Trang chủ
  2. » Khoa Học Tự Nhiên

Creating games in c++ a step by step guide (2006)

697 150 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 697
Dung lượng 3,05 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Virtually every beginning game programming book I've everseen assumes you know a programming language like C or C++.. It Teaches You Real Game Programming Skills There are a few, very ra

Trang 1

By David Conger, Ron Little

Publisher: New Riders Pub Date: February 21, 2006 Print ISBN-10: 0-7357-1434-7 Print ISBN-13: 978-0-7357-1434-2 Pages: 464

Table of Contents | Index

Do you love video games? Ever wondered if you could create one of your own, with all the bells and whistles? It's not as complicated as you'd think, and you don't need to be a math whiz or a programming genius to do it In fact, everything you need to create your first game, "Invasion of the Slugwroths," is included in this book and CD-ROM Author David Conger starts at square one, introducing the tools of the trade and all the basic concepts for getting started programming with C++, the language that powers most current

commercial games Plus, he's put a wealth of top-notch (and free) tools on the CD-ROM, including the Dev-C++ compiler, linker, and debugger and his own LlamaWorks2D game engine Step-by-step instructions and ample illustrations take you through game program structure, integrating sound and music into games, floating-point math, C++ arrays, and much more Using the sample programs and the source code to run them, you can follow along as you learn Bio: David Conger has been programming professionally for over 23 years Along with countless custom business applications, he has written several PC and online games Conger also worked on graphics firmware for military aircraft, and taught computer science at the university level for four years Conger has written numerous books on C, C++, and other computer-related topics He lives in western Washington State and has also published a collection of Indian folk tales.

Trang 2

By David Conger, Ron Little

Publisher: New Riders Pub Date: February 21, 2006 Print ISBN-10: 0-7357-1434-7 Print ISBN-13: 978-0-7357-1434-2 Pages: 464

Trang 6

Project Editors: Davina Baum, Kristin Kalning

Development Editors: Davina Baum, Denise Santoro LincolnProduction Editor: Myrna Vladic

Trang 7

permission for reprints and excerpts, contact

permissions@peachpit.com

Notice of Liability

The information in this book is distributed on an "As Is" basiswithout warranty While every precaution has been taken in thepreparation of the book, neither the author nor Peachpit shallhave any liability to any person or entity with respect to anyloss or damage caused or alleged to be caused directly or

indirectly by the instructions contained in this book or by thecomputer software and hardware products described in it

Trademarks

Many of the designations used by manufacturers and sellers todistinguish their products are claimed as trademarks Wherethose designations appear in this book, and Peachpit was aware

of a trademark claim, the designations appear as requested bythe owner of the trademark All other product names and

services identified throughout this book are used in editorialfashion only and for the benefit of such companies with no

intention of infringement of the trademark No such use, or theuse of any trade name, is intended to convey endorsement orother affiliation with this book

9 8 7 6 5 4 3 2 1

Printed and bound in the United States of America

Dedication

Trang 8

This book is dedicated to my mother, Jan Conger, for all the good that she has done and still does.

Thanks, Mom.

Trang 9

Owen Wolfson, Eric Geoffroy, Aren Howell, and Denise Lincoln

I especially want to thank Ron Little His technical edits wereexcellent And without his help on the sample programs for thelast five chapters, I'd probably still be working on this book

Trang 10

The first video game I ever played (at age 13) was Pong It was

a very simple ping-pong simulation During my teenage years, afew, more advanced games appeared on the market Most

notable were the Atari games such as Missile Command, a

nuclear warfare simulator When I was 19, I went to live for acouple of years in Japan There I discovered a whole new

worldseveral, in fact

Around the time I arrived in Japan, the game Space Invadershad just crested its phenomenal wave of popularity I had neverseen anything so cool By the time I returned to the United

States, video games were everywhere

In the fall of 1981, I started college Keith, a longtime friendand roommate, pointed to a class in the university's catalog andtold me, "You have to take this programming class I know

you'll love it." He was right By the time two weeks had passed,

Trang 11

And what did I specialize in? Graphics and games, of course

When I started writing games in college, it was a long anddifficult task The only people who had a prayer of writingdecent games were complete geeks (like me)

A lot has changed since then With the tools available now,nearly anyone can write an original and inventive game

Trang 12

There are lots of beginning game programming books In theend, the question everyone asks is, "What's special about thisbook in particular?"

I'm glad you asked

The short answer to your question is that this book is unlike 99percent of all beginning game programming books in severalrespects

It Doesn't Assume You Know How to Program Computers

Most people who want to get started in game programming

don't know how to program at all They are bright, creative, andinnovativeand they like games But they can't yet write

computer programs

Virtually every beginning game programming book I've everseen assumes you know a programming language like C or

C++ That means that most beginning game programmers have

to spend months or years learning to program before they caneven start a game

What a waste

If you want to be a game programmer, but you have little or noprogramming experience, this book is for you As I mentionedearlier, the tools available for writing games make the whole

experience much easier than when I started in the industry

more than 25 years ago There's no reason that a bright andcreative person like you should have to jump through a lot of

Trang 13

You can learn to program computers and write games at the same time Unfortunately, that thought hasn't occurred to

most authors of beginning game programming books

It Teaches You Real Game Programming Skills

There are a few, very rare, beginning game programming booksthat are written for nonprogrammers To try and make thingseasy, they teach you to write games in a programming

language called Basic Unfortunately, no games are written inBasic It's far too slow for real games Instead, game

programmers use a language called C++ (pronounced see-plus-plus) So if you read one of these books, you'll have to start

from scratch in a new programming language if you want towrite a real game

Unlike any other book on the market, this book teaches

nonprogrammers how to write games in C++ When you finishreading this book, you'll be reasonably proficient with the

programming language that real game programmers use.

Also, I explain and demonstrate the techniques used by

professional game programmers for animation and sound Inaddition, I demonstrate that it is surprisingly easy to add

essential physics to your games

It Teaches You How to Build A Real Game

Many beginning programming books give you lots of nifty littlesample programs that demonstrate the concepts they're

teaching However, very few show you how to pull all of thoseconcepts into a complete game That's a skill in itself And theprocess of building a complete game often stumps people who

Trang 14

By the end of this book, you'll see how to write a complete

game The game we'll be building is called "Invasion of the

Slugwroths." It's a simple side-scroller (I'll explain that termlater) similar to many games that were popular in the 1980sand '90s

Aren't most games today written in 3D?

Well, yes But writing 3D games is much harder If you startwith a side-scroller like Invasion of the Slugwroths, you'll learnfundamentals of game programming before you have to dealwith 3D concepts It makes the learning process much easierand much more fun

It Provides Everything You Need to Write Games

Not only does this book teach you everything you need to getstarted in game programming, it provides you with all of thetools as well To write computer programs, you need a compiler,linker, and debugger These can easily cost $500 Have no fear.You don't need to cough up your hard-earned cash You'll findthem all on the CD that comes with this book, at no extra cost

To save themselves from having to write program code thatnearly every game uses, many game programmers use a gameengine A game engine supplies program code that performsthe most common tasks in games Professional game enginestypically start at about $100 But don't go out and buy one I'vesupplied one for you for free on the CD

In addition, I've provided programs for making music, creating

a game's graphics, and testing your animations With the

development tools and the game engine you get on the CD, the

CD alone is well worth the cost of the book

Trang 15

I have been asked for years by parents what book they shouldbuy to get their teenaged son or daughter started in game

programming Adults in their twenties and thirties also oftenask me how they can get started I have difficulty

recommending most books because they are really too

technical They're often too hard to understand for people whodon't have a college degree in math, engineering, or computers

Although this book is not written specifically for teens, it is

usable by everyone If you're 15 or over, you can use this book.Both teens and adults will find everything they need right here.This book explains the terms and ideas it uses It provides youwith a lot of the essential program code (programs are builtfrom program code) you need to write games It teaches

programming, computer graphics, and games It's one-stopshopping

Trang 16

This book is divided into five main parts

Part 1 gives an overview of the tools and skills you'll need

to write games It also covers the most basic programmingconcepts

Part 2 dives into object-oriented programming, which is astyle of programming used by all professional game

programmers

Part 3 shows how game programs are constructed Here,you'll write your first gamePing, a clone of the ancient Ponggame You'll also learn to add sounds to your games

Part 4 raises your C++ skills to a level that enables you towrite real games

Part 5 enables you to pull everything you've learned

together to write the game Invasion of the Slugwroths, andleaves you fully equipped to go on and write your own

games

In addition, I provide you with a glossary that explains all of thetechnical terms presented in the book I've also compiled anextensive list of books that I recommend you read after youfinish reading this one That will help you move forward intotopics like 3D graphics You'll find the list of recommended

reading on the CD that comes with this book

Trang 17

To use the tools included with this book and to run the sampleprograms you compile as you read the chapters, you'll need acomputer with at least the following:

500 MHz Pentium III computer

Minimum 128 MB of system RAM

Windows 98 Second Edition or later operating system

OpenGL-compatible video adapter card Virtually all videocards today are compatible with OpenGL

300MB of free space on your computer's hard drive so

that you can install all of the tools and source code Youmight not need this much space if you choose not to

install some of the tools

Trang 18

information on them by inserting the CD into your CD- or DVD-display That page contains a list of everything on the CD Inthat list is an item called Tools, Tools, Tools That item provides

a link to a page in the CD that explains what the tools are andhow to install them

LlamaWorks2D This is the game engine you'll use to

write your games I wrote this version of LlamaWorks2Despecially for this book Building games with

LlamaWorks2D will save you many hours of programming

In addition, it handles many of the repetitive and tedioustasks you have to do in order to get a game up and

running Using LlamaWorks2D, you'll spend less time withthe mechanics of Windows programs and more time on

games

Dev-CPP The free Dev-C++ compiler is a combination of

a compiler, linker, debugger, and program editor You need

Trang 20

This book contains numerous sample programs that

demonstrate the concepts it teaches In order to view the

programs, you must first compile them The instructions forcompiling them are slightly different for each program To makethings more convenient for you, I've written instructions forhow to compile every program You'll find the compilation

instructions on the CD To see them, insert the CD into yourCD/DVD-ROM drive On the HTML page that appears, you'll find

a list item called Compilation Instructions Click that link

At this point, an HTML page appears called Compiling the

Sample Programs This page contains a list of all of the sampleprograms grouped by chapter To see how to compile a

particular program, click on its link in the list The compilationinstructions for that program will appear

In addition, I've provided a compiled version of each program.They're in the Bin (short for binary) folder for their respectivechapters You'll see a link for each Bin folder on the Compilingthe Sample Programs page

Trang 21

Hi, I'm David Conger I've been in the computer industry since

1981, when I took my first professional programming contractshortly after entering college Most of my career has been

focused on graphics, games, and network programming Aftergraduating from college, I wrote firmware for graphics displaycontrollers used on military aircraft After that, I taught college-level programming classes for several years My next careerchange enabled me to attain my long-standing goal of

becoming a professional game programmer I wrote games forAmerican Laser Games, For Her Interactive Inc., and MicrosoftCorporation

I started writing books in 1987 My first book was a collection offolktales from the Far East and India retold for Western

children Since then, I've written a fairly steady stream of

computer books

I play way too many games If it wasn't for my wife and kids, Iwould hardly ever visit reality

I have a lot of experience in computer graphics, games, writing,and teaching I want to help you to get into game programming

as fast and painlessly as possible Game programming lets youget paid for being a programmer, designer, artist, composer,and general nutcase

So read on and have fun That's what games are for

Trang 22

Chapter 1 What it Takes to be a Game ProgrammerChapter 2 Writing C++ Programs

Trang 23

Programmer

You're reading this book because you want to be a game

programmer You may not have any programming experience atall That doesn't matter This book shows you everything youneed to know to get started Before you finish reading this

book, you'll see how to develop your own innovative games

So what does it take to be a game programmer?

Game programming can include a wide range of skills To be agame programmer, you must, of course, know a bit about

programming You should also know the basics of computergraphics In addition, it helps to know how to design games.You'll learn all of these skills right here

It also helps to be a musician and an artist That's not reallyrequired However, you do have to know how art and music are

Trang 24

basics of creating art on a computer If you know how to ripMP3s, you know how to prepare music for games But if you'venever done either of these, don't worry I'll teach you how tohandle both art and music for your games

This chapter presents a brief overview of the most essentialskills you'll need: programming, computer graphics, game

design, art, and the ability to use sound and music Because it's

an overview, don't worry if you run across something that youdon't understand Everything discussed in this chapter is

presented again in greater detail in later chapters

Trang 25

People are often fearful of learning to program computers

Programming can get pretty hairy at times, but learning to

program proficiently is not as difficult as it may seem In fact, ifyou like to tinker with things and find out how they work,

programming often seems like play

The first step in learning to program is to understand what aprogram is

cookbook and find a recipe The recipe is a set of instructions Ifyou follow the instructions exactly, you get a cake If not, youmay wind up with a foul-tasting mess

A computer program is like a recipe It's a set of instructions.The instructions in a program tell the computer how to be agame machine If you write the instructions properly, you get agame If not, you get a mess

Each instruction in a computer program is made up of one or

Trang 26

A what?

Computers don't understand human languages like English orJapanese In fact, they don't really "understand" anything at all.But the computer's microprocessor, which is also called its

101, 110, 111, 1000, and so forth You really don't have to

know the details of using binary in order to program computers.All you have to know is that a binary number is a group of 0sand 1s All instructions you give to a microprocessor must be 0sand 1s, or the microprocessor won't be able to execute them

When a program is running, all of its binary instructions arestored as bits in your computer's memory A bit is simply a

binary 0 or 1 Therefore, the binary number 10 is 2 bits long Incomputers, the bits in memory or on a disk are grouped

Trang 27

10011100 is 8 bits long so it fits in 1 byte A group of 1024bytes is a kilobyte; 1024 kilobytes is a megabyte; 1024

megabytes is a gigabyte; 1024 gigabytes is a terabyte This isillustrated in Table 1.1

in a language called C++ (pronounced see-plus-plus).

The C++ programming language enables you to write

statements that let you control all parts of a computer, such asthe display, sound card, or joystick With C++ statements, you

Trang 28

C++ programs start as C++ instructions that we store in text files A text file is just what it sounds like: It's a file on the diskthat contains textletters and numbers C++ text files are alsocalled source files The entire collection of C++ instructions iscalled the source code of the program

Tools of the Trade

Recall that microprocessors only execute commands that arebinary numbers C++ is not binary; it's more like English How

Trang 29

on the CD that comes with this book The instructions for

installing it are in the Introduction

Linkers

Trang 30

called object code Object code is binary, but it is not

executable Object code must be converted to executable code,

which is an actual program that you can run on your computer.The tool that converts object code to executable code is a

linker

You'll need a linker to create your games A linker is includedwith the Dev-C++ compiler on the CD and it's installed whenyou install Dev-C++ Whenever you compile your program withDev-C++, the linker runs automatically, so your program isboth compiled and linked in one step

Trang 31

C++ with only minimal changes.

Trang 32

As a result of the mistakes we make, you and I need a tool tohelp us find and fix bugs Appropriately enough, that tool is

called a debugger You get a debugger for free with Dev-C++.Like the linker, it's installed automatically

Trang 33

of very smart people had to think for a long time to learn how

to do these tasks efficiently The methods they use are veryadvanced and very involved This stuff is not easy, and it used

to be the case that every game programmer had to know how

to do it all

Fortunately, you no longer have to bother with learning how to

do these basic tasks When you write your games, you'll use atool called a graphics library A graphics library contains codethat does all the basic graphics tasks such as drawing lines andcircles, or displaying pictures on a screen The library uses allthe best methods and techniques that were developed by all thesmart people I mentioned in the preceding paragraph As a

result, you already have code for the basic tasks you'll do whenyou write games You don't have to write it yourself

By the way, the graphics library you'll use is called OpenGL

OpenGL is used in high-powered games such as Quake and

Doom from id Software There is a version of the OpenGL

graphics library for Dev-C++ The instructions for installing itare in the Introduction

Microsoft also provides a graphics library called DirectX

Graphics (more commonly called Direct3D) Like OpenGL,

Direct3D is used for professional games Direct3D is part of

DirectX, which contains libraries for adding sound, music, andnetworking to games

Whether you use OpenGL or Direct3D is largely a matter of

preference They both will get you where you need to go

Although this book primarily uses OpenGL, I've also providedthe Microsoft DirectX Software Development Kit (SDK) on theDVD that comes with this book It's in the folder\Tools\MicrosoftDirectX SDK

Tip

Trang 34

To make game programmers' lives easier, other programmersoften develop game engines A game engine performs the mostcommon tasks that a particular type of game does For

instance, a game engine for first-person shooters handles all ofthe tasks associated with displaying scenery, drawing bad guys,and so forth You have to insert your own scenery, code for yourweapons, and any other code that is specific to your game Thegame engine handles displaying buildings, trees, and things likethat Figure 1.2 shows how game engines are used

Figure 1.2 Games are built in layers of code.

Trang 35

it saves you from writing a tremendous amount of code All youhave to do is add your game code on top of the game engine.That's the only part of the game that you have to write Take

my word for it; that's all you want to worry about You'll findwriting your game code challenging enough

simulators, and so on The best game engines are generic

enough to be used for more than one type of game Many

excellent game engines are available commercially The people

Trang 36

There are also outstanding game engines you can get for free

In fact, I've written one for you and provided it on the CD thataccompanies this book It's called LlamaWorks2D Throughoutthe rest of this book, I'll show you how to use it and how to addyour own code to it to produce many types of games

If you have not installed the LlamaWorks2D game engine onyour computer, please turn to the Introduction and do that now

Trang 37

From the name LlamaWorks2D, you've probably figured out that this game engine does 2D rather than 3D games You may also be wondering why I don't teach you how to do 3D games The answer is simple: It's hard.

This book teaches the essential skills every professional game programmer must have It does so by teaching you to write games in 2D, which is considerably simpler than doing 3D However, don't think that your game programming skills will be anything less than professional when you get done Many games today are written in 2D Command and Conquer by Westwood Studios and SimCity by Maxis are two examples They are both top-selling games that are written with 2D graphics.

Also, many 3D game programming techniques require that you first understand 2D game programming You would be surprised how much 2D programming there is in 3D games Therefore, the best way to start learning to write games is with 2D graphics It gives you the fundamentals, which makes learning 3D game programming much easier.

Trang 38

In addition to programming skills, you'll need to understandhow computer graphics work If you want to become a guru incomputer graphics, be prepared to do almost nothing but thatfor the rest of your career However, you don't have to be aguru to start writing games You just need to know a few

fundamental concepts

The Basics of Computer Graphics

The tool you'll use for displaying graphics in your games is amonitor, which is also commonly called a screen, or display Anunderstanding of monitors is the starting point for developingcomputer graphics skills

How Computer Monitors Work

The internals of monitors aren't as complex as you might think

Figure 1.3 How computer monitors work.

Trang 39

phosphorus coating, the phosphorus glows The color that thephosphorus emits depends on what chemicals you add to it Thephosphorus coating on the front of your screen is made up of

Trang 40

a pixel Every pixel has a red, green, and blue dot in it To make

a pixel turn a particular color on your screen, you mix differentamounts of red, green, and blue

As you can see from Figure 1.3, all of the pixels on the screenare arranged in rows The rows are called scan lines The

electron guns fire at each pixel, one after the other They start

at the top scan line and work their way down to the bottom.When they reach the end of the last scan line, they start again

at the top of the screen The time that it takes for the electronguns to hit every pixel on the screen is called the screen's

refresh rate

Ngày đăng: 25/03/2019, 17:12

TỪ KHÓA LIÊN QUAN

TÀI LIỆU CÙNG NGƯỜI DÙNG

TÀI LIỆU LIÊN QUAN