Quantcast
Channel: Small Basic
Viewing all articles
Browse latest Browse all 669

Small Basic Game Programming - Let's start with RPS game

$
0
0

I'm going to write about game programming in Small Basic for several weeks on this blog.  For the first time, I'd like to pick up simple text base RPS (Rock-Paper-Scissors) game.

Main loop

This code is the main loop of this game.  Lines 4-6 are one game.  And While condition is always "True", so this is endless loop to repeat games.

 1.' Rock Paper Scissors
 2.Init()
 3.While "True"
 4.  CPU()
 5.  You()
 6.  Judge()
 7.EndWhile

Initialization

Subroutine Init is to initialize for arrays.  These arrays need only one time initialization out of the main loop.  The array hand is to input numbers.  The 2-D array judge is for game judge.

 8.Sub Init
 9.  hand = "1=Rock;2=Paper;3=Scissors;"
10.  judge["Rock"] = "Rock=Draw;Paper=Win;Scissors=Lose;"
11.  judge["Paper"] = "Rock=Lose;Paper=Draw;Scissors=Win;"
12.  judge["Scissors"] = "Rock=Win;Paper=Lose;Scissors=Draw;"
13.EndSub

Random number

In game programs, we call game AI (Artificial Intelligence) for the strategic routine for CPU side.  In game AI, random number is used sometimes.  In Small Basic, Math.GetRandomNumber() operation generates a random number.  In following subroutine, a number from 1 to 3 is generated and set into a variable n. 

14.Sub CPU
15.  n = Math.GetRandomNumber(3)
16.  cpu = hand[n]
17.EndSub

Input number

Following routine is for human side.  Te make it easier, this requires only number input for your hand.  For displaying input number just after the prompt, TextWindow.Write() operation is used instead of TextWindow.WriteLine() operation.  And to ensure the input is a number, TextWindow.ReadNumber() operation is used instead of Text.Window.Read() operation.  In line 23, if n is not from 1 to 3, null text "" is set to the variable you.

18.Sub You
19.  error = "True"
20.  While error
21.    TextWindow.Write("1(Rock), 2(Paper), 3(Scissors)? ")
22.    n = TextWindow.ReadNumber()
23.    you = hand[n]
24.    If you <> "" Then
25.      error = "False"
26.    EndIf
27.  EndWhile
28.EndSub

Judge the game

Judgement is very easy.  That is just referring an array judge.

29.Sub Judge
30.  ' param you - your hand
31.  ' param cpu - CPU's hand
32.  TextWindow.WriteLine("CPU:" + cpu)
33.  TextWindow.WriteLine("You:" + you)
34.  TextWindow.WriteLine(judge[cpu][you])
35.EndSub

Whole program is published as GXP440-0.  This game has only 35 lines.  Using technique introduced here, you may create new games something like rolling dice or so.  Let's start game programming!


Viewing all articles
Browse latest Browse all 669

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>