<5 Min BASIC #12 - Machine Learning
Most games would be pretty one-sided without some form of Artificial Intelligence (A.I.). Here, I've cooked up a little Sinclair BASIC listing that keeps track of the player's decisions and in turn tries to outdo the player by predicting his or her next move.
1 REM Under 5 min BASIC#12 2 REM Machine Learning 3 REM Ste Nichol/Loading Screech 4 REM 19th Aug 2018 5 LET a=0: LET b=0: LET c=0 10 CLS : INPUT "Choose 0 or 1 (2=quit)",a 15 IF a=2 THEN STOP 20 PRINT AT 0,0;"You" 30 IF a=0 THEN LET b=b+1 40 IF a=1 THEN LET c=c+1 50 PRINT AT 1,0;"0=";b 60 PRINT AT 2,0;"1=";c 70 IF b>c THEN PRINT AT 20,0;"Computer chooses 0" 80 IF b<c THEN PRINT AT 20,0;"Computer chooses 1" 90 PAUSE 0 100 GO TO 10
Explanation/Refresher Lines 1 to 4 are REMarks, comments that do not affect the running of the program. Line 5 sets up the three variables we are using a,b,and c. Line 10 clears the screen then prompts the player to choose either 0 or 1. Choosing a 2 STOPs the program. Note that this variable a (number) and not a$ which would be a text string. Line 15 STOPs the program if you chose 2 in line 10. Line 20 PRINTS "You" at the top of the screen. Line 30 increases variable b, by 1 if you chose 0. Line 40 increases variable c, by 1 if you chose 0. Lines 50 and 60 PRINT your choices so far. Lines 70 and 80 PRINT the computers choice. If you chose 0 more than 1 the computer will choose 0 and likewise it will choose 1 if you chose 1 more often. Line 90 waits for any keypress before proceeding. Line 100 returns to the top of the program loop (Line 10 in this program).
Exercise 1. At the moment the computer does nothing if the number of 0's and 1's are equal to each other. Add a line between lines 80 and 90 to make it do something, perhaps a compromise, or a third action.
Thanks for reading!
Stephen