------------------------------------------------------------"Let's Play Miniature Golf!" from December, 1989------------------------------------------------------------ Several years ago, the editors of ONE THOUSAND magazineasked me to write a monthly column on BASIC. On one hand, Iwas excited by the possibilities. I would have a chance towrite the kind of BASIC column that I had only dreamed of.On the other, I was worried; how in the world would I comeup with new programming ideas month after month? Well,after three years of columns, it is obvious that the wellhas not run dry yet. In fact, I have discovered thatinspiration turns up in the most unexpected places! Take this month's program, for example. The BASIC programlisting found on the following pages allows you to "play"miniature golf on your Tandy 1000 computer. I got the ideafor that program as I was driving my five-year-old daughterhome from a birthday party. And where was that party held?At the local miniature golf course, of course! Think for a moment about the game of miniature golf; what anatural it is for an entertaining program on our Grandycomputers. Miniature golf courses are bright and colorful.The carpet, the golf balls, and the obstacles present arainbow of colors. Of course, Grandy graphics and colorsare second to none. The path of the ball can be describedusing a relatively simple yet accurate set of calculations.A computer can handle those calculations easily. Andfinally, the rules are simple and universally known. Thecomputer game will be one that the whole family can sit downand play instinctively. An Historical Perspective ------------------------- How much do you know about the history of miniature golf?Did you know that it was invented by a lady named FreidaCarter? According to an article in the August 4th issue ofthe Wall Street Journal, Mrs. Carter patented the concept in1929, calling it "Tom Thumb Golf". In less than one year,the entire nation was caught up in the fad. Over fourmillion people played the game -- every day! There wereover 25,000 courses offering fantastically exotic andimaginative holes. Not only were there the familiarwindmills and drawbridges, but also spinning roulette wheelsand even a live bear trained to snatch golf balls! The fad spawned a popular song ("I've Gone Goofy OverMiniature Golf"), a monthly magazine, and textbooks ontechnique. However, like all fads, it quickly fizzled andalmost died. Some claimed that the game had corrupted ouryouth; others feared that it had been infiltrated byorganized crime. Many courses stayed open all night, andtheir sleepless neighbors fought to have those businessesclosed. Although miniature golf enjoyed a brief revival inthe 1950's, there are only 1,500 courses left today -- lessthan one tenth the number in 1930. Although it costs aminimum of $5,000 to construct an 18-hole course today, youcan have your own just by investing an hour or so of yourtime typing in this month's program! Game Strategy ------------- How does one go about simulating the game of miniature golfon a computer? Ask a dozen BASIC authors, and you willprobably get a dozen different answers -- but here is how Idid it. As you play the game, you will see an "overhead"view of each hole. You will see the outline of the course,the obstacles, your ball, and of course, the hole. On yourturn, you use the keyboard's arrow keys to indicate thedirection you wish to hit the ball. Next, you press one ofthe number keys from "1" to "9"; press "1" for a gentle tap,or "9" for a hard stroke. After hitting the ball, all youcan do is sit back and watch as the ball rolls along,bouncing off the side boards and obstacles, hopefullyfalling into the hole eventually. The game obviously requires that we use one of the Grandy'sgraphics display modes. But which one? Screen mode 0 isout, since it is text only. Obviously, color is important.In fact, we need at least six colors -- one each for theforeground, the background, the carpet, the ball, theobstacles, and the hole. Thus, screen modes 1, 2, 4, and 6are out, too, since they do not allow the use of enoughdifferent colors (only 2 to 4 colors). That leaves onlymodes 3 and 5. Graphics in screen mode 3 are rather coarse;that mode is decidedly low-resolution. So, by default, weare left with screen mode 5 -- a medium resolution graphicsscreen that allows as many as 16 colors. Next problem: how does one create a smooth, flicker-freegraphical representation of a rolling golf ball? The GETand PUT statements will handle that situation nicely. TheGET statement is used to grab a picture off of the screenand store it in a dimensioned variable. In effect, we willuse the GET statement to make a "rubber stamp" of thepicture of the golf ball. Once that "rubber stamp" has been created using the GETstatement, the PUT statement can be used to display the ballat any point on the screen. The interesting thing about PUTis that if you "rubber stamp" a second copy exactly on topof the first, then the picture will disappear! PUT willdisplay the ball, another PUT in the same location willerase it. Do you see how useful that feature is? We canPUT the ball on the screen to display it in the first place,then PUT another copy on top of the first to make itdisappear, calculate where the ball would move in the nextinstant, then PUT a copy in that new location to give theillusion of movement. Speed and Direction ------------------- How does one calculate the ball's movement? Since thescreen is divided into rows and columns, I decided to handleball movement as changes in the horizontal and verticaldirections, also. If the ball is moving at a forty-fivedegree angle (toward the northeast for example), then itmight be moving one pixel to the right and one pixel upduring each adjustment. (A pixel is one "dot" on the videoscreen.) Calculating the number of pixels of movement fordifferent angles is a simple matter of trigonometry. (Andyou thought there would never be a practical use for thetrigonometry you learned in high school!) What about bounces? Eventually the ball will run intoeither an obstacle or the edge of the fairway (and we willassume there are bumper boards all around). According tothe laws of physics, in this situation the angle ofincidence is equal to the angle of reflection. That is, ifthe angle between the path of the ball and the obstacle itstrikes is equal to 35 degrees, then the ball will leave atan angle of 145 (or 180 minus 35) degrees. Although this law of physics is rigorous enough to describeany bounce, the mathematics are somewhat intimidating --especially if the reflecting surface is at an odd angle. Ifall of the reflecting surfaces are either horizontal orvertical, then the calculations are much simpler. With thatsimplification, only two simple checks are required. If thehorizontal movement of the ball would cause it to enter anobstacle or leave the playing field, then the ball mustreverse its movement in the horizontal direction. That is,if it is moving one pixel to the right and it is about toover-run an obstacle, then it must turn and travel one pixelto the left. The same thing applies for movement in the verticaldirection. If the vertical movement of the ball would causeit to strike an obstacle, then the ball must reverse itsmovement in that direction. And that is all there is to it!Remember, these simple rules only apply if all the obstaclesare aligned in the horizontal and vertical direction. Thus,I limited myself to simple rectangular fairways with squareor rectangular obstacles. (Well, to be honest, I did sneakin a few rounded corners here and there. You will see whatI mean when you play the game. During my own testing, Ifound that most of the bounces off those rounded edgeslooked realistic. Every once in a while you will get a realstrange bounce, though. But, hey! That just makes itinteresting, right?) Rules of the Game ----------------- Almost no explanation of rules is necessary, but we will gothrough them quickly anyway. Once you start the program,you must first specify the number of players, then entereach player's name. With that bit of recordkeeping out ofthe way, play begins. An overhead view of each hole isdrawn on the screen. The playing field is blue, the ball isyellow, the hole is white, and the obstacles are a varietyof colors. An arrow will be shown radiating out from theball; on his or her turn, each player must use one or moreof the four arrow keys to move that on-screen arrow toindicate the direction he or she wishes to hit the ball. [Note: Those of you with the new enhanced keyboard -- andthat includes all SL and TL owners -- will have trouble withthe up arrow. There is a bug in either Tandy BASIC or thatkeyboard which makes it impossible for BASIC to detect theup arrow. On that keyboard, you can use the PAGE UP key asan alternative to the up arrow.] Once the on-screen arrowhead is aligned correctly, theplayer must press one of the digits from "1" to "9".Pressing "1" gives the ball a little tap; pressing "9" givesit a strong stroke. (You can use the numeric keypad, but besure to press NUM LOCK first.) You will have to develop a"feel" for this yourself, but as a hint, remember that "5"is usually enough to send the ball from one side of thescreen to the other in the absence of any obstacles. If youaim carefully and have a little bit of luck, the ball willeventually fall into the hole. If more than one person isplaying, then the other players will have a chance at thesame hole. Once every player has taken a shot a the hole, ascoreboard will present all players' scores. This procedurewill continue through all eighteen holes, after which thewinner is announced. Program Theory -------------- BASIC automatically sets aside 16,384 bytes of memory forthe video display. Every letter, number, and punctuationmark displayed requires a byte of memory. The foregroundand background color information stored for each characterrequires even more memory. Normally, those 16,384 bytes areenough. However, screen mode 5 is especially memoryintensive; it requires twice the default amount (or 32,768bytes) of memory. The CLEAR statement of line 150 takescare of that special requirement. The DIM statement in line 160 sets aside space for theplayers names in WHO$, their scores in SCORE, a picture ofthe ball in BALL, a holding area called HOLD, and a pictureof the direction arrow in ARROW. Lines 210 through 270handle the housekeeping chores. The number of players isstored in variable NP, and the players' names are stored inarray variable WHO$. Play begins in line 310. Notice that the FOR-NEXT loopwhich starts in line 310 increments the variable HOLE fromone to eighteen. The variables X and Y calculated in lines310 and 320 are used in lines 320 through 370 to select thencall one of the eighteen subroutines located after line1090. Each of those eighteen subroutines draws the playingfield on the screen, sets the initial screen coordinates ofthe ball in BX and BY, sets the screen coordinates of thehole in HX and HY, and sets the PAR for the hole. After returning from the subroutine, the cumulative totalpar is calculated in SCORE(0). Line 420 begins a FOR-NEXTloop involving variable PL which allows all NP players totake their turn on the hole. Lines 430 through 470 presentsome scoreboard information, while line 480 draws the balland the hole on the field. Arrow and Movement ------------------ The GET statement in line 520 makes a temporary copy of theupper left-hand corner of the screen and places it invariable HOLD; the PUT which immediately follows erases thatcorner. The DRAW statement of line 530 draws an arrow inthat area, which is copied by the GET statement of 540 intovariable ARROW. The first PUT statement of line 540 erasesthe arrow; the second PUT restores the original screencontents. Finally, the PUT statement of line 550 "rubberstamps" variable ARROW over the ball, indicating thedirection of movement. Lines 560 and 570 check for a valid keystroke. If an arrowkey is pressed, then the angle used to draw the arrow ismodified, and the whole arrow-drawing process in lines 520through 550 is repeated. If a number key is pressed, thevariable SPEED is calculated; SPEED represents the number ofball movements which will occur during this stroke.Variables DX and DY represent the changes in horizontal andvertical position per move, respectively. Lines 720 and 730update the scoreboard. The ball begins moving in line 740;variable SPEED is decremented by one until it reaches zero.Lines 750 and 760 look forward to find where the ball willroll on its next move. If the next move puts it in thehole, then the program jumps to line 850. If it strikes anobstacle or the wall, then variables DX and/or DY areadjusted, and the SOUND statement issues an audible click.The ball is erased in line 800, its position isrecalculated, it is redisplayed in line 810, and controlloops back to line 740. Lines 850 through 880 move the ball into the center of thehole. After a three second delay in line 890, the nextplayer takes his turn. Lines 900 through 960 show all theplayers scores along with the par score for a few secondsbefore the next hole is drawn and play continues. Lines1000 through 1050 show the final scores and congratulate theplayer with the lowest score. As discussed earlier, thecollection of subroutines beginning with line 1090 drawseach of the eighteen holes. Of particular interest aresubroutines 1090, 1110, and 1140. Those three generic holesare used over and over by the other fifteen subroutines. Wrapping Up ----------- If this game sounds interesting, go ahead and type it in!You have nothing to lose but about an hour of time. By theway, here is something interesting to remember: since thisprogram uses screen mode 5, it will not work on most PCcompatible computers. In fact, it will not even work on anIBM PC (although I believe it will on a PCjr). Screen mode5 is one of the exciting innovations that Tandy brought tothe field of PC compatibles -- and no other brand of PCclones can do what our Grandy can do graphically. So enjoythe program, thank your lucky stars you bought a Grandy, andbe sure to write to me in care of ONE THOUSAND magazine withyour questions and comments. See you next month!