mirror of
https://github.com/coding-horror/basic-computer-games.git
synced 2025-12-23 07:29:02 -08:00
@@ -5,3 +5,7 @@ https://www.atariarchives.org/basicgames/showpage.php?page=2
|
||||
|
||||
Downloaded from Vintage Basic at
|
||||
http://www.vintage-basic.net/games.html
|
||||
|
||||
#### Other languages:
|
||||
|
||||
- [Pascal/Object Pascal](https://github.com/gcarreno/basic-computer-games-in-pascal/tree/main/01%20Acey%20Ducey)
|
||||
8
03 Animal/csharp/Animal.csproj
Normal file
8
03 Animal/csharp/Animal.csproj
Normal file
@@ -0,0 +1,8 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net5.0</TargetFramework>
|
||||
</PropertyGroup>
|
||||
|
||||
</Project>
|
||||
25
03 Animal/csharp/Animal.sln
Normal file
25
03 Animal/csharp/Animal.sln
Normal file
@@ -0,0 +1,25 @@
|
||||
|
||||
Microsoft Visual Studio Solution File, Format Version 12.00
|
||||
# Visual Studio Version 16
|
||||
VisualStudioVersion = 16.0.30907.101
|
||||
MinimumVisualStudioVersion = 10.0.40219.1
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Animal", "Animal.csproj", "{D9A8DAB5-1B29-44A9-B13F-CED17B5A22B9}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
Release|Any CPU = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
||||
{D9A8DAB5-1B29-44A9-B13F-CED17B5A22B9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{D9A8DAB5-1B29-44A9-B13F-CED17B5A22B9}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{D9A8DAB5-1B29-44A9-B13F-CED17B5A22B9}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{D9A8DAB5-1B29-44A9-B13F-CED17B5A22B9}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
EndGlobalSection
|
||||
GlobalSection(ExtensibilityGlobals) = postSolution
|
||||
SolutionGuid = {064879D3-A288-4980-8DC4-59653D5EE2DD}
|
||||
EndGlobalSection
|
||||
EndGlobal
|
||||
18
03 Animal/csharp/Branch.cs
Normal file
18
03 Animal/csharp/Branch.cs
Normal file
@@ -0,0 +1,18 @@
|
||||
namespace Animal
|
||||
{
|
||||
public class Branch
|
||||
{
|
||||
public string Text { get; set; }
|
||||
|
||||
public bool IsEnd => Yes == null && No == null;
|
||||
|
||||
public Branch Yes { get; set; }
|
||||
|
||||
public Branch No { get; set; }
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
return $"{Text} : IsEnd {IsEnd}";
|
||||
}
|
||||
}
|
||||
}
|
||||
152
03 Animal/csharp/Program.cs
Normal file
152
03 Animal/csharp/Program.cs
Normal file
@@ -0,0 +1,152 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
|
||||
using Animal;
|
||||
|
||||
Console.WriteLine(new string(' ', 32) + "ANIMAL");
|
||||
Console.WriteLine(new string(' ', 15) + "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY");
|
||||
Console.WriteLine();
|
||||
Console.WriteLine();
|
||||
Console.WriteLine();
|
||||
Console.WriteLine("PLAY 'GUESS THE ANIMAL'");
|
||||
Console.WriteLine();
|
||||
Console.WriteLine("THINK OF AN ANIMAL AND THE COMPUTER WILL TRY TO GUESS IT.");
|
||||
Console.WriteLine();
|
||||
|
||||
// Root of the question and answer tree
|
||||
Branch rootBranch = new Branch
|
||||
{
|
||||
Text = "DOES IT SWIM",
|
||||
Yes = new Branch { Text = "FISH" },
|
||||
No = new Branch { Text = "BIRD" }
|
||||
};
|
||||
|
||||
string[] TRUE_INPUTS = { "Y", "YES", "T", "TRUE" };
|
||||
string[] FALSE_INPUTS = { "N", "NO", "F", "FALSE" };
|
||||
|
||||
|
||||
while (true)
|
||||
{
|
||||
MainGameLoop();
|
||||
}
|
||||
|
||||
void MainGameLoop()
|
||||
{
|
||||
// Wait fora YES or LIST command
|
||||
string input = null;
|
||||
while (true)
|
||||
{
|
||||
input = GetInput("ARE YOU THINKING OF AN ANIMAL");
|
||||
if (IsInputListCommand(input))
|
||||
{
|
||||
ListKnownAnimals(rootBranch);
|
||||
}
|
||||
else if (IsInputYes(input))
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Walk through the tree following the YES and NO
|
||||
// branches based on user input.
|
||||
Branch currentBranch = rootBranch;
|
||||
while (!currentBranch.IsEnd)
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
input = GetInput(currentBranch.Text);
|
||||
if (IsInputYes(input))
|
||||
{
|
||||
currentBranch = currentBranch.Yes;
|
||||
break;
|
||||
}
|
||||
else if (IsInputNo(input))
|
||||
{
|
||||
currentBranch = currentBranch.No;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Was the answer correct?
|
||||
input = GetInput($"IS IT A {currentBranch.Text}");
|
||||
if (IsInputYes(input))
|
||||
{
|
||||
Console.WriteLine("WHY NOT TRY ANOTHER ANIMAL?");
|
||||
return;
|
||||
}
|
||||
|
||||
// Interview the user to add a new question and answer
|
||||
// branch to the tree
|
||||
string newAnimal = GetInput("THE ANIMAL YOU WERE THINKING OF WAS A");
|
||||
string newQuestion = GetInput($"PLEASE TYPE IN A QUESTION THAT WOULD DISTINGUISH A {newAnimal} FROM A {currentBranch.Text}");
|
||||
string newAnswer = null;
|
||||
while (true)
|
||||
{
|
||||
newAnswer = GetInput($"FOR A {newAnimal} THE ANSWER WOULD BE");
|
||||
if (IsInputNo(newAnswer))
|
||||
{
|
||||
currentBranch.No = new Branch { Text = newAnimal };
|
||||
currentBranch.Yes = new Branch { Text = currentBranch.Text };
|
||||
currentBranch.Text = newQuestion;
|
||||
break;
|
||||
}
|
||||
else if (IsInputYes(newAnswer))
|
||||
{
|
||||
currentBranch.Yes = new Branch { Text = newAnimal };
|
||||
currentBranch.No = new Branch { Text = currentBranch.Text };
|
||||
currentBranch.Text = newQuestion;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
string GetInput(string prompt)
|
||||
{
|
||||
Console.Write($"{prompt}? ");
|
||||
string result = Console.ReadLine();
|
||||
if (string.IsNullOrWhiteSpace(result))
|
||||
{
|
||||
return GetInput(prompt);
|
||||
}
|
||||
|
||||
return result.Trim().ToUpper();
|
||||
}
|
||||
|
||||
bool IsInputYes(string input) => TRUE_INPUTS.Contains(input.ToUpperInvariant().Trim());
|
||||
|
||||
bool IsInputNo(string input) => FALSE_INPUTS.Contains(input.ToUpperInvariant().Trim());
|
||||
|
||||
bool IsInputListCommand(string input) => input.ToUpperInvariant().Trim() == "LIST";
|
||||
|
||||
string[] GetKnownAnimals(Branch branch)
|
||||
{
|
||||
List<string> result = new List<string>();
|
||||
if (branch.IsEnd)
|
||||
{
|
||||
return new[] { branch.Text };
|
||||
}
|
||||
else
|
||||
{
|
||||
result.AddRange(GetKnownAnimals(branch.Yes));
|
||||
result.AddRange(GetKnownAnimals(branch.No));
|
||||
return result.ToArray();
|
||||
}
|
||||
}
|
||||
|
||||
void ListKnownAnimals(Branch branch)
|
||||
{
|
||||
string[] animals = GetKnownAnimals(branch);
|
||||
for (int x = 0; x < animals.Length; x++)
|
||||
{
|
||||
int column = (x % 4);
|
||||
if (column == 0)
|
||||
{
|
||||
Console.WriteLine();
|
||||
}
|
||||
|
||||
Console.Write(new string(' ', column == 0 ? 0 : 15) + animals[x]);
|
||||
}
|
||||
Console.WriteLine();
|
||||
}
|
||||
@@ -51,7 +51,7 @@
|
||||
800 D=-99:H=13
|
||||
805 FOR I=0 TO 13:G(I)=B(I):NEXT I
|
||||
810 FOR J=7 TO 12:IF B(J)=0 THEN 885
|
||||
815 G=0:M=J:GOSUB 600
|
||||
815 Q=0:M=J:GOSUB 600
|
||||
820 FOR I=0 TO 5:IF B(I)=0 THEN 845
|
||||
825 L=B(I)+I:R=0
|
||||
830 IF L>13 THEN L=L-14:R=1:GOTO 830
|
||||
|
||||
9
04 Awari/javascript/awari.html
Normal file
9
04 Awari/javascript/awari.html
Normal file
@@ -0,0 +1,9 @@
|
||||
<html>
|
||||
<head>
|
||||
<title>AWARI</title>
|
||||
</head>
|
||||
<body>
|
||||
<pre id="output" style="font-size: 12pt;"></pre>
|
||||
<script src="awari.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
259
04 Awari/javascript/awari.js
Normal file
259
04 Awari/javascript/awari.js
Normal file
@@ -0,0 +1,259 @@
|
||||
// AWARI
|
||||
//
|
||||
// Converted from BASIC to Javascript by Oscar Toledo G. (nanochess)
|
||||
//
|
||||
|
||||
function print(str)
|
||||
{
|
||||
document.getElementById("output").appendChild(document.createTextNode(str));
|
||||
}
|
||||
|
||||
function input()
|
||||
{
|
||||
var input_element;
|
||||
var input_str;
|
||||
|
||||
return new Promise(function (resolve) {
|
||||
input_element = document.createElement("INPUT");
|
||||
|
||||
print("? ");
|
||||
input_element.setAttribute("type", "text");
|
||||
input_element.setAttribute("length", "50");
|
||||
document.getElementById("output").appendChild(input_element);
|
||||
input_element.focus();
|
||||
input_str = undefined;
|
||||
input_element.addEventListener("keydown", function (event) {
|
||||
if (event.keyCode == 13) {
|
||||
input_str = input_element.value;
|
||||
document.getElementById("output").removeChild(input_element);
|
||||
print(input_str);
|
||||
print("\n");
|
||||
resolve(input_str);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function tab(space)
|
||||
{
|
||||
var str = "";
|
||||
while (space-- > 0)
|
||||
str += " ";
|
||||
return str;
|
||||
}
|
||||
|
||||
print(tab(34) + "AWARI\n");
|
||||
print(tab(15) + "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY\n");
|
||||
|
||||
n = 0;
|
||||
|
||||
b = [0,0,0,0,0,0,0,0,0,0,0,0,0,0];
|
||||
g = [0,0,0,0,0,0,0,0,0,0,0,0,0,0];
|
||||
f = [];
|
||||
for (i = 0; i <= 50; i++) {
|
||||
f[i] = 0;
|
||||
}
|
||||
|
||||
function show_number(number)
|
||||
{
|
||||
if (number < 10)
|
||||
print(" " + number + " ");
|
||||
else
|
||||
print(" " + number + " ");
|
||||
}
|
||||
|
||||
function show_board()
|
||||
{
|
||||
var i;
|
||||
|
||||
print("\n");
|
||||
print(" ");
|
||||
for (i = 12; i >= 7; i--)
|
||||
show_number(b[i]);
|
||||
print("\n");
|
||||
i = 13;
|
||||
show_number(b[i]);
|
||||
print(" " + b[6] + "\n");
|
||||
print(" ");
|
||||
for (i = 0; i <= 5; i++)
|
||||
show_number(b[i]);
|
||||
print("\n");
|
||||
print("\n");
|
||||
}
|
||||
|
||||
function do_move()
|
||||
{
|
||||
k = m;
|
||||
adjust_board();
|
||||
e = 0;
|
||||
if (k > 6)
|
||||
k -= 7;
|
||||
c++;
|
||||
if (c < 9)
|
||||
f[n] = f[n] * 6 + k
|
||||
for (i = 0; i <= 5; i++) {
|
||||
if (b[i] != 0) {
|
||||
for (i = 7; i <= 12; i++) {
|
||||
if (b[i] != 0) {
|
||||
e = 1;
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function adjust_board()
|
||||
{
|
||||
p = b[m];
|
||||
b[m] = 0;
|
||||
while (p >= 1) {
|
||||
m++;
|
||||
if (m > 13)
|
||||
m -= 14;
|
||||
b[m]++;
|
||||
p--;
|
||||
}
|
||||
if (b[m] == 1) {
|
||||
if (m != 6 && m != 13) {
|
||||
if (b[12 - m] != 0) {
|
||||
b[h] += b[12 - m] + 1;
|
||||
b[m] = 0;
|
||||
b[12 - m] = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function computer_move()
|
||||
{
|
||||
d = -99;
|
||||
h = 13;
|
||||
for (i = 0; i<= 13; i++) // Backup board
|
||||
g[i] = b[i];
|
||||
for (j = 7; j <= 12; j++) {
|
||||
if (b[j] == 0)
|
||||
continue;
|
||||
q = 0;
|
||||
m = j;
|
||||
adjust_board();
|
||||
for (i = 0; i <= 5; i++) {
|
||||
if (b[i] == 0)
|
||||
continue;
|
||||
l = b[i] + i;
|
||||
r = 0;
|
||||
while (l > 13) {
|
||||
l -= 14;
|
||||
r = 1;
|
||||
}
|
||||
if (b[l] == 0) {
|
||||
if (l != 6 && l != 13)
|
||||
r = b[12 - l] + r;
|
||||
}
|
||||
if (r > q)
|
||||
q = r;
|
||||
}
|
||||
q = b[13] - b[6] - q;
|
||||
if (c < 8) {
|
||||
k = j;
|
||||
if (k > 6)
|
||||
k -= 7;
|
||||
for (i = 0; i <= n - 1; i++) {
|
||||
if (f[n] * 6 + k == Math.floor(f[i] / Math.pow(7 - c, 6) + 0.1))
|
||||
q -= 2;
|
||||
}
|
||||
}
|
||||
for (i = 0; i <= 13; i++) // Restore board
|
||||
b[i] = g[i];
|
||||
if (q >= d) {
|
||||
a = j;
|
||||
d = q;
|
||||
}
|
||||
}
|
||||
m = a;
|
||||
print(m - 6);
|
||||
do_move();
|
||||
}
|
||||
|
||||
// Main program
|
||||
async function main()
|
||||
{
|
||||
while (1) {
|
||||
print("\n");
|
||||
print("\n");
|
||||
e = 0;
|
||||
for (i = 0; i <= 12; i++)
|
||||
b[i] = 3;
|
||||
|
||||
c = 0;
|
||||
f[n] = 0;
|
||||
b[13] = 0;
|
||||
b[6] = 0;
|
||||
|
||||
while (1) {
|
||||
show_board();
|
||||
print("YOUR MOVE");
|
||||
while (1) {
|
||||
m = parseInt(await input());
|
||||
if (m < 7) {
|
||||
if (m > 0) {
|
||||
m--;
|
||||
if (b[m] != 0)
|
||||
break;
|
||||
}
|
||||
}
|
||||
print("ILLEGAL MOVE\n");
|
||||
print("AGAIN");
|
||||
}
|
||||
h = 6;
|
||||
do_move();
|
||||
show_board();
|
||||
if (e == 0)
|
||||
break;
|
||||
if (m == h) {
|
||||
print("AGAIN");
|
||||
while (1) {
|
||||
m = parseInt(await input());
|
||||
if (m < 7) {
|
||||
if (m > 0) {
|
||||
m--;
|
||||
if (b[m] != 0)
|
||||
break;
|
||||
}
|
||||
}
|
||||
print("ILLEGAL MOVE\n");
|
||||
print("AGAIN");
|
||||
}
|
||||
h = 6;
|
||||
do_move();
|
||||
show_board();
|
||||
}
|
||||
if (e == 0)
|
||||
break;
|
||||
print("MY MOVE IS ");
|
||||
computer_move();
|
||||
if (e == 0)
|
||||
break;
|
||||
if (m == h) {
|
||||
print(",");
|
||||
computer_move();
|
||||
}
|
||||
if (e == 0)
|
||||
break;
|
||||
}
|
||||
print("\n");
|
||||
print("GAME OVER\n");
|
||||
d = b[6] - b[13];
|
||||
if (d < 0)
|
||||
print("I WIN BY " + -d + " POINTS\n");
|
||||
else if (d == 0) {
|
||||
n++;
|
||||
print("DRAWN GAME\n");
|
||||
} else {
|
||||
n++;
|
||||
print("YOU WIN BY " + d + " POINTS\n");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
main();
|
||||
@@ -3,7 +3,7 @@
|
||||
15 REM *** BAGLES NUMBER GUESSING GAME
|
||||
20 REM *** ORIGINAL SOURCE UNKNOWN BUT SUSPECTED TO BE
|
||||
25 REM *** LAWRENCE HALL OF SCIENCE, U.C. BERKELY
|
||||
30 DIM A1(6),A(3),B(3)
|
||||
30 DIM A1(3),A(3),B(3)
|
||||
40 Y=0:T=255
|
||||
50 PRINT:PRINT:PRINT
|
||||
70 INPUT "WOULD YOU LIKE THE RULES (YES OR NO)";A$
|
||||
@@ -66,7 +66,7 @@
|
||||
600 PRINT
|
||||
605 NEXT I
|
||||
610 PRINT "OH WELL."
|
||||
615 PRINT "THAT'S TWNETY GUESSES. MY NUMBER WAS";100*A(1)+10*A(2)+A(3)
|
||||
615 PRINT "THAT'S TWENTY GUESSES. MY NUMBER WAS";100*A(1)+10*A(2)+A(3)
|
||||
620 GOTO 700
|
||||
630 PRINT "TRY GUESSING A THREE-DIGIT NUMBER.":GOTO 230
|
||||
650 PRINT "OH, I FORGOT TO TELL YOU THAT THE NUMBER I HAVE IN MIND"
|
||||
@@ -74,7 +74,7 @@
|
||||
680 PRINT "YOU GOT IT!!!":PRINT
|
||||
690 Y=Y+1
|
||||
700 INPUT "PLAY AGAIN (YES OR NO)";A$
|
||||
720 IF LEFT$(A$,1)="YES" THEN 150
|
||||
720 IF LEFT$(A$,1)="Y" THEN 150
|
||||
730 IF Y=0 THEN 750
|
||||
740 PRINT:PRINT "A";Y;"POINT BAGELS BUFF!!"
|
||||
750 PRINT "HOPE YOU HAD FUN. BYE."
|
||||
|
||||
9
05 Bagels/javascript/bagels.html
Normal file
9
05 Bagels/javascript/bagels.html
Normal file
@@ -0,0 +1,9 @@
|
||||
<html>
|
||||
<head>
|
||||
<title>BAGELS</title>
|
||||
</head>
|
||||
<body>
|
||||
<pre id="output" style="font-size: 12pt;"></pre>
|
||||
<script src="bagels.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
160
05 Bagels/javascript/bagels.js
Normal file
160
05 Bagels/javascript/bagels.js
Normal file
@@ -0,0 +1,160 @@
|
||||
// BAGELS
|
||||
//
|
||||
// Converted from BASIC to Javascript by Oscar Toledo G. (nanochess)
|
||||
//
|
||||
|
||||
function print(str)
|
||||
{
|
||||
document.getElementById("output").appendChild(document.createTextNode(str));
|
||||
}
|
||||
|
||||
function input()
|
||||
{
|
||||
var input_element;
|
||||
var input_str;
|
||||
|
||||
return new Promise(function (resolve) {
|
||||
input_element = document.createElement("INPUT");
|
||||
|
||||
print("? ");
|
||||
input_element.setAttribute("type", "text");
|
||||
input_element.setAttribute("length", "50");
|
||||
document.getElementById("output").appendChild(input_element);
|
||||
input_element.focus();
|
||||
input_str = undefined;
|
||||
input_element.addEventListener("keydown", function (event) {
|
||||
if (event.keyCode == 13) {
|
||||
input_str = input_element.value;
|
||||
document.getElementById("output").removeChild(input_element);
|
||||
print(input_str);
|
||||
print("\n");
|
||||
resolve(input_str);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function tab(space)
|
||||
{
|
||||
var str = "";
|
||||
while (space-- > 0)
|
||||
str += " ";
|
||||
return str;
|
||||
}
|
||||
|
||||
print(tab(33) + "BAGELS\n");
|
||||
print(tab(15) + "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY\n");
|
||||
|
||||
// *** Bagles number guessing game
|
||||
// *** Original source unknown but suspected to be
|
||||
// *** Lawrence Hall of Science, U.C. Berkeley
|
||||
|
||||
a1 = [0,0,0,0];
|
||||
a = [0,0,0,0];
|
||||
b = [0,0,0,0];
|
||||
|
||||
y = 0;
|
||||
t = 255;
|
||||
|
||||
print("\n");
|
||||
print("\n");
|
||||
print("\n");
|
||||
|
||||
// Main program
|
||||
async function main()
|
||||
{
|
||||
while (1) {
|
||||
print("WOULD YOU LIKE THE RULES (YES OR NO)");
|
||||
str = await input();
|
||||
if (str.substr(0, 1) != "N") {
|
||||
print("\n");
|
||||
print("I AM THINKING OF A THREE-DIGIT NUMBER. TRY TO GUESS\n");
|
||||
print("MY NUMBER AND I WILL GIVE YOU CLUES AS FOLLOWS:\n");
|
||||
print(" PICO - ONE DIGIT CORRECT BUT IN THE WRONG POSITION\n");
|
||||
print(" FERMI - ONE DIGIT CORRECT AND IN THE RIGHT POSITION\n");
|
||||
print(" BAGELS - NO DIGITS CORRECT\n");
|
||||
}
|
||||
for (i = 1; i <= 3; i++) {
|
||||
do {
|
||||
a[i] = Math.floor(Math.random() * 10);
|
||||
for (j = i - 1; j >= 1; j--) {
|
||||
if (a[i] == a[j])
|
||||
break;
|
||||
}
|
||||
} while (j >= 1) ;
|
||||
}
|
||||
print("\n");
|
||||
print("O.K. I HAVE A NUMBER IN MIND.\n");
|
||||
for (i = 1; i <= 20; i++) {
|
||||
while (1) {
|
||||
print("GUESS #" + i);
|
||||
str = await input();
|
||||
if (str.length != 3) {
|
||||
print("TRY GUESSING A THREE-DIGIT NUMBER.\n");
|
||||
continue;
|
||||
}
|
||||
for (z = 1; z <= 3; z++)
|
||||
a1[z] = str.charCodeAt(z - 1);
|
||||
for (j = 1; j <= 3; j++) {
|
||||
if (a1[j] < 48 || a1[j] > 57)
|
||||
break;
|
||||
b[j] = a1[j] - 48;
|
||||
}
|
||||
if (j <= 3) {
|
||||
print("WHAT?");
|
||||
continue;
|
||||
}
|
||||
if (b[1] == b[2] || b[2] == b[3] || b[3] == b[1]) {
|
||||
print("OH, I FORGOT TO TELL YOU THAT THE NUMBER I HAVE IN MIND\n");
|
||||
print("HAS NO TWO DIGITS THE SAME.\n");
|
||||
continue;
|
||||
}
|
||||
break;
|
||||
}
|
||||
c = 0;
|
||||
d = 0;
|
||||
for (j = 1; j <= 2; j++) {
|
||||
if (a[j] == b[j + 1])
|
||||
c++;
|
||||
if (a[j + 1] == b[j])
|
||||
c++;
|
||||
}
|
||||
if (a[1] == b[3])
|
||||
c++;
|
||||
if (a[3] == b[1])
|
||||
c++;
|
||||
for (j = 1; j <= 3; j++) {
|
||||
if (a[j] == b[j])
|
||||
d++;
|
||||
}
|
||||
if (d == 3)
|
||||
break;
|
||||
for (j = 0; j < c; j++)
|
||||
print("PICO ");
|
||||
for (j = 0; j < d; j++)
|
||||
print("FERMI ");
|
||||
if (c + d == 0)
|
||||
print("BAGELS");
|
||||
print("\n");
|
||||
}
|
||||
if (i <= 20) {
|
||||
print("YOU GOT IT!!!\n");
|
||||
print("\n");
|
||||
} else {
|
||||
print("OH WELL.\n");
|
||||
print("THAT'S A TWENTY GUESS. MY NUMBER WAS " + a[1] + a[2] + a[3]);
|
||||
}
|
||||
y++;
|
||||
print("PLAY AGAIN (YES OR NO)");
|
||||
str = await input();
|
||||
if (str.substr(0, 1) != "Y")
|
||||
break;
|
||||
}
|
||||
if (y == 0)
|
||||
print("HOPE YOU HAD FUN. BYE.\n");
|
||||
else
|
||||
print("\nA " + y + " POINT BAGELS BUFF!!\n");
|
||||
|
||||
}
|
||||
|
||||
main();
|
||||
9
06 Banner/javascript/banner.html
Normal file
9
06 Banner/javascript/banner.html
Normal file
@@ -0,0 +1,9 @@
|
||||
<html>
|
||||
<head>
|
||||
<title>BANNER</title>
|
||||
</head>
|
||||
<body>
|
||||
<pre id="output" style="font-size: 12pt;"></pre>
|
||||
<script src="banner.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
168
06 Banner/javascript/banner.js
Normal file
168
06 Banner/javascript/banner.js
Normal file
@@ -0,0 +1,168 @@
|
||||
// BANNER
|
||||
//
|
||||
// Converted from BASIC to Javascript by Oscar Toledo G. (nanochess)
|
||||
//
|
||||
|
||||
function print(str)
|
||||
{
|
||||
document.getElementById("output").appendChild(document.createTextNode(str));
|
||||
}
|
||||
|
||||
function input()
|
||||
{
|
||||
var input_element;
|
||||
var input_str;
|
||||
|
||||
return new Promise(function (resolve) {
|
||||
input_element = document.createElement("INPUT");
|
||||
|
||||
print("? ");
|
||||
input_element.setAttribute("type", "text");
|
||||
input_element.setAttribute("length", "50");
|
||||
document.getElementById("output").appendChild(input_element);
|
||||
input_element.focus();
|
||||
input_str = undefined;
|
||||
input_element.addEventListener("keydown", function (event) {
|
||||
if (event.keyCode == 13) {
|
||||
input_str = input_element.value;
|
||||
document.getElementById("output").removeChild(input_element);
|
||||
print(input_str);
|
||||
print("\n");
|
||||
resolve(input_str);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function tab(space)
|
||||
{
|
||||
var str = "";
|
||||
while (space-- > 0)
|
||||
str += " ";
|
||||
return str;
|
||||
}
|
||||
|
||||
var letters = [" ",0,0,0,0,0,0,0,
|
||||
"A",505,37,35,34,35,37,505,
|
||||
"G",125,131,258,258,290,163,101,
|
||||
"E",512,274,274,274,274,258,258,
|
||||
"T",2,2,2,512,2,2,2,
|
||||
"W",256,257,129,65,129,257,256,
|
||||
"L",512,257,257,257,257,257,257,
|
||||
"S",69,139,274,274,274,163,69,
|
||||
"O",125,131,258,258,258,131,125,
|
||||
"N",512,7,9,17,33,193,512,
|
||||
"F",512,18,18,18,18,2,2,
|
||||
"K",512,17,17,41,69,131,258,
|
||||
"B",512,274,274,274,274,274,239,
|
||||
"D",512,258,258,258,258,131,125,
|
||||
"H",512,17,17,17,17,17,512,
|
||||
"M",512,7,13,25,13,7,512,
|
||||
"?",5,3,2,354,18,11,5,
|
||||
"U",128,129,257,257,257,129,128,
|
||||
"R",512,18,18,50,82,146,271,
|
||||
"P",512,18,18,18,18,18,15,
|
||||
"Q",125,131,258,258,322,131,381,
|
||||
"Y",8,9,17,481,17,9,8,
|
||||
"V",64,65,129,257,129,65,64,
|
||||
"X",388,69,41,17,41,69,388,
|
||||
"Z",386,322,290,274,266,262,260,
|
||||
"I",258,258,258,512,258,258,258,
|
||||
"C",125,131,258,258,258,131,69,
|
||||
"J",65,129,257,257,257,129,128,
|
||||
"1",0,0,261,259,512,257,257,
|
||||
"2",261,387,322,290,274,267,261,
|
||||
"*",69,41,17,512,17,41,69,
|
||||
"3",66,130,258,274,266,150,100,
|
||||
"4",33,49,41,37,35,512,33,
|
||||
"5",160,274,274,274,274,274,226,
|
||||
"6",194,291,293,297,305,289,193,
|
||||
"7",258,130,66,34,18,10,8,
|
||||
"8",69,171,274,274,274,171,69,
|
||||
"9",263,138,74,42,26,10,7,
|
||||
"=",41,41,41,41,41,41,41,
|
||||
"!",1,1,1,384,1,1,1,
|
||||
"0",57,69,131,258,131,69,57,
|
||||
".",1,1,129,449,129,1,1];
|
||||
|
||||
f = [];
|
||||
j = [];
|
||||
s = [];
|
||||
|
||||
// Main program
|
||||
async function main()
|
||||
{
|
||||
print("HORIZONTAL");
|
||||
x = parseInt(await input());
|
||||
print("VERTICAL");
|
||||
y = parseInt(await input());
|
||||
print("CENTERED");
|
||||
ls = await input();
|
||||
g1 = 0;
|
||||
if (ls > "P")
|
||||
g1 = 1;
|
||||
print("CHARACTER (TYPE 'ALL' IF YOU WANT CHARACTER BEING PRINTED)");
|
||||
ms = await input();
|
||||
print("STATEMENT");
|
||||
as = await input();
|
||||
print("SET PAGE"); // This means to prepare printer, just press Enter
|
||||
os = await input();
|
||||
|
||||
for (t = 0; t < as.length; t++) {
|
||||
ps = as.substr(t, 1);
|
||||
for (o = 0; o < 50 * 8; o += 8) {
|
||||
if (letters[o] == ps) {
|
||||
for (u = 1; u <= 7; u++)
|
||||
s[u] = letters[o + u];
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (o == 50 * 8) {
|
||||
ps = " ";
|
||||
o = 0;
|
||||
}
|
||||
// print("Doing " + o + "\n");
|
||||
if (o == 0) {
|
||||
for (h = 1; h <= 7 * x; h++)
|
||||
print("\n");
|
||||
} else {
|
||||
xs = ms;
|
||||
if (ms == "ALL")
|
||||
xs = ps;
|
||||
for (u = 1; u <= 7; u++) {
|
||||
// An inefficient way of extracting bits
|
||||
// but good enough in BASIC because there
|
||||
// aren't bit shifting operators.
|
||||
for (k = 8; k >= 0; k--) {
|
||||
if (Math.pow(2, k) >= s[u]) {
|
||||
j[9 - k] = 0;
|
||||
} else {
|
||||
j[9 - k] = 1;
|
||||
s[u] -= Math.pow(2, k);
|
||||
if (s[u] == 1) {
|
||||
f[u] = 9 - k;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
for (t1 = 1; t1 <= x; t1++) {
|
||||
str = tab((63 - 4.5 * y) * g1 / xs.length + 1);
|
||||
for (b = 1; b <= f[u]; b++) {
|
||||
if (j[b] == 0) {
|
||||
for (i = 1; i <= y; i++)
|
||||
str += tab(xs.length);
|
||||
} else {
|
||||
for (i = 1; i <= y; i++)
|
||||
str += xs;
|
||||
}
|
||||
}
|
||||
print(str + "\n");
|
||||
}
|
||||
}
|
||||
for (h = 1; h <= 2 * x; h++)
|
||||
print("\n");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
main();
|
||||
123
06 Banner/python/banner.py
Normal file
123
06 Banner/python/banner.py
Normal file
@@ -0,0 +1,123 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
# BANNER
|
||||
#
|
||||
# Converted from BASIC to Python by Trevor Hobson
|
||||
|
||||
letters = {
|
||||
" ": [0, 0, 0, 0, 0, 0, 0],
|
||||
"A": [505, 37, 35, 34, 35, 37, 505],
|
||||
"G": [125, 131, 258, 258, 290, 163, 101],
|
||||
"E": [512, 274, 274, 274, 274, 258, 258],
|
||||
"T": [2, 2, 2, 512, 2, 2, 2],
|
||||
"W": [256, 257, 129, 65, 129, 257, 256],
|
||||
"L": [512, 257, 257, 257, 257, 257, 257],
|
||||
"S": [69, 139, 274, 274, 274, 163, 69],
|
||||
"O": [125, 131, 258, 258, 258, 131, 125],
|
||||
"N": [512, 7, 9, 17, 33, 193, 512],
|
||||
"F": [512, 18, 18, 18, 18, 2, 2],
|
||||
"K": [512, 17, 17, 41, 69, 131, 258],
|
||||
"B": [512, 274, 274, 274, 274, 274, 239],
|
||||
"D": [512, 258, 258, 258, 258, 131, 125],
|
||||
"H": [512, 17, 17, 17, 17, 17, 512],
|
||||
"M": [512, 7, 13, 25, 13, 7, 512],
|
||||
"?": [5, 3, 2, 354, 18, 11, 5],
|
||||
"U": [128, 129, 257, 257, 257, 129, 128],
|
||||
"R": [512, 18, 18, 50, 82, 146, 271],
|
||||
"P": [512, 18, 18, 18, 18, 18, 15],
|
||||
"Q": [125, 131, 258, 258, 322, 131, 381],
|
||||
"Y": [8, 9, 17, 481, 17, 9, 8],
|
||||
"V": [64, 65, 129, 257, 129, 65, 64],
|
||||
"X": [388, 69, 41, 17, 41, 69, 388],
|
||||
"Z": [386, 322, 290, 274, 266, 262, 260],
|
||||
"I": [258, 258, 258, 512, 258, 258, 258],
|
||||
"C": [125, 131, 258, 258, 258, 131, 69],
|
||||
"J": [65, 129, 257, 257, 257, 129, 128],
|
||||
"1": [0, 0, 261, 259, 512, 257, 257],
|
||||
"2": [261, 387, 322, 290, 274, 267, 261],
|
||||
"*": [69, 41, 17, 512, 17, 41, 69],
|
||||
"3": [66, 130, 258, 274, 266, 150, 100],
|
||||
"4": [33, 49, 41, 37, 35, 512, 33],
|
||||
"5": [160, 274, 274, 274, 274, 274, 226],
|
||||
"6": [194, 291, 293, 297, 305, 289, 193],
|
||||
"7": [258, 130, 66, 34, 18, 10, 8],
|
||||
"8": [69, 171, 274, 274, 274, 171, 69],
|
||||
"9": [263, 138, 74, 42, 26, 10, 7],
|
||||
"=": [41, 41, 41, 41, 41, 41, 41],
|
||||
"!": [1, 1, 1, 384, 1, 1, 1],
|
||||
"0": [57, 69, 131, 258, 131, 69, 57],
|
||||
".": [1, 1, 129, 449, 129, 1, 1],
|
||||
}
|
||||
|
||||
|
||||
def print_banner():
|
||||
"""Print the banner"""
|
||||
|
||||
f = [0] * 7
|
||||
j = [0] * 9
|
||||
|
||||
while True:
|
||||
try:
|
||||
x = int(input("Horizontal "))
|
||||
if x < 1:
|
||||
raise ValueError("Horizontal must be greater than zero")
|
||||
break
|
||||
|
||||
except ValueError:
|
||||
print("Please enter a number greater than zero")
|
||||
while True:
|
||||
try:
|
||||
y = int(input("Vertical "))
|
||||
if y < 1:
|
||||
raise ValueError("Vertical must be greater than zero")
|
||||
break
|
||||
|
||||
except ValueError:
|
||||
print("Please enter a number greater than zero")
|
||||
g1 = 0
|
||||
if input("Centered ").lower().startswith("y"):
|
||||
g1 = 1
|
||||
mStr = input(
|
||||
"Character (type 'ALL' if you want character being printed) ").upper()
|
||||
aStr = input("Statement ")
|
||||
# This means to prepare printer, just press Enter
|
||||
oStr = input("Set page ")
|
||||
for lStr in aStr:
|
||||
s = letters[lStr].copy()
|
||||
xStr = mStr
|
||||
if mStr == "ALL":
|
||||
xStr = lStr
|
||||
if xStr == " ":
|
||||
print("\n" * (7 * x))
|
||||
else:
|
||||
for u in range(0, 7):
|
||||
for k in range(8, -1, -1):
|
||||
if 2 ** k >= s[u]:
|
||||
j[8 - k] = 0
|
||||
else:
|
||||
j[8 - k] = 1
|
||||
s[u] = s[u] - 2 ** k
|
||||
if s[u] == 1:
|
||||
f[u] = 8 - k
|
||||
break
|
||||
for t1 in range(1, x + 1):
|
||||
lineStr = " " * int((63 - 4.5 * y) * g1 / len(xStr) + 1)
|
||||
for b in range(0, f[u] + 1):
|
||||
if j[b] == 0:
|
||||
for i in range(1, y + 1):
|
||||
lineStr = lineStr + " " * len(xStr)
|
||||
else:
|
||||
lineStr = lineStr + xStr * y
|
||||
print(lineStr)
|
||||
print("\n" * (2 * x - 1))
|
||||
# print("\n" * 75) # Feed some more paper from the printer
|
||||
|
||||
|
||||
def main():
|
||||
"""Main"""
|
||||
|
||||
print_banner()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
372
11 Bombardment/java/src/Bombardment.java
Normal file
372
11 Bombardment/java/src/Bombardment.java
Normal file
@@ -0,0 +1,372 @@
|
||||
import java.util.HashSet;
|
||||
import java.util.Scanner;
|
||||
|
||||
/**
|
||||
* Game of Bombardment
|
||||
*
|
||||
* Based on the Basic game of Bombardment here
|
||||
* https://github.com/coding-horror/basic-computer-games/blob/main/11%20Bombardment/bombardment.bas
|
||||
*
|
||||
* Note: The idea was to create a version of this 1970's Basic game in Java, without introducing
|
||||
* new features - no additional text, error checking, etc has been added.
|
||||
*/
|
||||
public class Bombardment {
|
||||
|
||||
public static final int MAX_GRID_SIZE = 25;
|
||||
public static final int PLATOONS = 4;
|
||||
|
||||
private enum GAME_STATE {
|
||||
STARTING,
|
||||
DRAW_BATTLEFIELD,
|
||||
GET_PLAYER_CHOICES,
|
||||
PLAYERS_TURN,
|
||||
COMPUTER_TURN,
|
||||
PLAYER_WON,
|
||||
PLAYER_LOST,
|
||||
GAME_OVER
|
||||
}
|
||||
|
||||
private GAME_STATE gameState;
|
||||
|
||||
public static final String[] PLAYER_HIT_MESSAGES = { "ONE DOWN, THREE TO GO.",
|
||||
"TWO DOWN, TWO TO GO.", "THREE DOWN, ONE TO GO." };
|
||||
|
||||
public static final String[] COMPUTER_HIT_MESSAGES = {"YOU HAVE ONLY THREE OUTPOSTS LEFT.",
|
||||
"YOU HAVE ONLY TWO OUTPOSTS LEFT.", "YOU HAVE ONLY ONE OUTPOST LEFT." };
|
||||
|
||||
private HashSet<Integer> computersPlatoons;
|
||||
private HashSet<Integer> playersPlatoons;
|
||||
|
||||
private HashSet<Integer> computersGuesses;
|
||||
|
||||
// Used for keyboard input
|
||||
private final Scanner kbScanner;
|
||||
|
||||
public Bombardment() {
|
||||
|
||||
this.gameState = GAME_STATE.STARTING;
|
||||
|
||||
// Initialise kb scanner
|
||||
kbScanner = new Scanner(System.in);
|
||||
}
|
||||
|
||||
/**
|
||||
* Main game loop
|
||||
*/
|
||||
public void play() {
|
||||
|
||||
do {
|
||||
switch (this.gameState) {
|
||||
|
||||
// Show an introduction the first time the game is played.
|
||||
case STARTING:
|
||||
init();
|
||||
intro();
|
||||
this.gameState = GAME_STATE.DRAW_BATTLEFIELD;
|
||||
break;
|
||||
|
||||
// Enter the players name
|
||||
case DRAW_BATTLEFIELD:
|
||||
drawBattlefield();
|
||||
this.gameState = GAME_STATE.GET_PLAYER_CHOICES;
|
||||
break;
|
||||
|
||||
// Get the players 4 locations for their platoons
|
||||
case GET_PLAYER_CHOICES:
|
||||
String playerChoices = displayTextAndGetInput("WHAT ARE YOUR FOUR POSITIONS? ");
|
||||
|
||||
// Store the 4 player choices that were entered separated with commas
|
||||
for(int i=0; i<PLATOONS; i++) {
|
||||
playersPlatoons.add(getDelimitedValue(playerChoices,i));
|
||||
}
|
||||
|
||||
this.gameState = GAME_STATE.PLAYERS_TURN;
|
||||
break;
|
||||
|
||||
// Players turn to pick a location
|
||||
case PLAYERS_TURN:
|
||||
|
||||
int firePosition = getDelimitedValue(
|
||||
displayTextAndGetInput("WHERE DO YOU WISH TO FIRE YOUR MISSILE? "),0);
|
||||
|
||||
if(didPlayerHitComputerPlatoon(firePosition)) {
|
||||
// Player hit a player platoon
|
||||
int hits = updatePlayerHits(firePosition);
|
||||
// How many hits has the player made?
|
||||
if(hits != PLATOONS) {
|
||||
showPlayerProgress(hits);
|
||||
this.gameState = GAME_STATE.COMPUTER_TURN;
|
||||
} else {
|
||||
// Player has obtained 4 hits, they win
|
||||
this.gameState = GAME_STATE.PLAYER_WON;
|
||||
}
|
||||
} else {
|
||||
// Player missed
|
||||
System.out.println("HA, HA YOU MISSED. MY TURN NOW:");
|
||||
System.out.println();
|
||||
this.gameState = GAME_STATE.COMPUTER_TURN;
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
// Computers time to guess a location
|
||||
case COMPUTER_TURN:
|
||||
|
||||
// Computer takes a guess of a location
|
||||
int computerFirePosition = uniqueComputerGuess();
|
||||
if(didComputerHitPlayerPlatoon(computerFirePosition)) {
|
||||
// Computer hit a player platoon
|
||||
int hits = updateComputerHits(computerFirePosition);
|
||||
// How many hits has the computer made?
|
||||
if(hits != PLATOONS) {
|
||||
showComputerProgress(hits, computerFirePosition);
|
||||
this.gameState = GAME_STATE.PLAYERS_TURN;
|
||||
} else {
|
||||
// Computer has obtained 4 hits, they win
|
||||
System.out.println("YOU'RE DEAD. YOUR LAST OUTPOST WAS AT " + computerFirePosition
|
||||
+ ". HA, HA, HA.");
|
||||
this.gameState = GAME_STATE.PLAYER_LOST;
|
||||
}
|
||||
} else {
|
||||
// Computer missed
|
||||
System.out.println("I MISSED YOU, YOU DIRTY RAT. I PICKED " + computerFirePosition
|
||||
+ ". YOUR TURN:");
|
||||
System.out.println();
|
||||
this.gameState = GAME_STATE.PLAYERS_TURN;
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
// The player won
|
||||
case PLAYER_WON:
|
||||
System.out.println("YOU GOT ME, I'M GOING FAST. BUT I'LL GET YOU WHEN");
|
||||
System.out.println("MY TRANSISTO&S RECUP%RA*E!");
|
||||
this.gameState = GAME_STATE.GAME_OVER;
|
||||
break;
|
||||
|
||||
case PLAYER_LOST:
|
||||
System.out.println("BETTER LUCK NEXT TIME.");
|
||||
this.gameState = GAME_STATE.GAME_OVER;
|
||||
break;
|
||||
|
||||
// GAME_OVER State does not specifically have a case
|
||||
}
|
||||
} while (this.gameState != GAME_STATE.GAME_OVER);
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate computer guess. Make that the computer does not guess the same
|
||||
* location twice
|
||||
*
|
||||
* @return location of the computers guess that has not been guessed previously
|
||||
*/
|
||||
private int uniqueComputerGuess() {
|
||||
|
||||
boolean validGuess = false;
|
||||
int computerGuess;
|
||||
do
|
||||
{
|
||||
computerGuess = randomNumber();
|
||||
|
||||
if(!computersGuesses.contains(computerGuess)) {
|
||||
validGuess = true;
|
||||
}
|
||||
} while(!validGuess);
|
||||
|
||||
computersGuesses.add(computerGuess);
|
||||
|
||||
return computerGuess;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create four unique platoons locations for the computer
|
||||
* We are using a hashset which guarantees uniqueness so
|
||||
* all we need to do is keep trying to add a random number
|
||||
* until all four are in the hashset
|
||||
*
|
||||
* @return 4 locations of computers platoons
|
||||
*
|
||||
*/
|
||||
private HashSet<Integer> computersChosenPlatoons() {
|
||||
|
||||
// Initialise contents
|
||||
HashSet<Integer> tempPlatoons = new HashSet<>();
|
||||
|
||||
boolean allPlatoonsAdded = false;
|
||||
|
||||
do {
|
||||
tempPlatoons.add(randomNumber());
|
||||
|
||||
// All four created?
|
||||
if(tempPlatoons.size() == PLATOONS) {
|
||||
// Exit when we have created four
|
||||
allPlatoonsAdded = true;
|
||||
}
|
||||
|
||||
} while(!allPlatoonsAdded);
|
||||
|
||||
return tempPlatoons;
|
||||
}
|
||||
/**
|
||||
* Shows a different message for each number of hits
|
||||
*
|
||||
* @param hits total number of hits by player on computer
|
||||
*/
|
||||
private void showPlayerProgress(int hits) {
|
||||
|
||||
System.out.println("YOU GOT ONE OF MY OUTPOSTS!");
|
||||
showProgress(hits, PLAYER_HIT_MESSAGES);
|
||||
}
|
||||
|
||||
/**
|
||||
* Shows a different message for each number of hits
|
||||
*
|
||||
* @param hits total number of hits by computer on player
|
||||
*/
|
||||
private void showComputerProgress(int hits, int lastGuess) {
|
||||
|
||||
System.out.println("I GOT YOU. IT WON'T BE LONG NOW. POST " + lastGuess + " WAS HIT.");
|
||||
showProgress(hits, COMPUTER_HIT_MESSAGES);
|
||||
}
|
||||
|
||||
/**
|
||||
* Prints a message from the passed array based on the value of hits
|
||||
|
||||
* @param hits - number of hits the player or computer has made
|
||||
* @param messages - an array of string with messages
|
||||
*/
|
||||
private void showProgress(int hits, String[] messages) {
|
||||
System.out.println(messages[hits-1]);
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* Update a player hit - adds a hit the player made on the computers platoon.
|
||||
* @param fireLocation - computer location that got hit
|
||||
* @return number of hits the player has inflicted on the computer in total
|
||||
*/
|
||||
private int updatePlayerHits(int fireLocation) {
|
||||
|
||||
// N.B. only removes if present, so its redundant to check if it exists first
|
||||
this.computersPlatoons.remove(fireLocation);
|
||||
|
||||
// return number of hits in total
|
||||
return PLATOONS - this.computersPlatoons.size();
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* Update a computer hit - adds a hit the computer made on the players platoon.
|
||||
* @param fireLocation - player location that got hit
|
||||
* @return number of hits the player has inflicted on the computer in total
|
||||
*/
|
||||
private int updateComputerHits(int fireLocation) {
|
||||
|
||||
// N.B. only removes if present, so its redundant to check if it exists first
|
||||
this.playersPlatoons.remove(fireLocation);
|
||||
|
||||
// return number of hits in total
|
||||
return PLATOONS - this.playersPlatoons.size();
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if the player hit one of the computers platoons
|
||||
*
|
||||
* @param fireLocation the players choice of location to fire on
|
||||
* @return true if a computer platoon was at that position
|
||||
*/
|
||||
private boolean didPlayerHitComputerPlatoon(int fireLocation) {
|
||||
return this.computersPlatoons.contains(fireLocation);
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if the computer hit one of the players platoons
|
||||
*
|
||||
* @param fireLocation the computers choice of location to fire on
|
||||
* @return true if a players platoon was at that position
|
||||
*/
|
||||
private boolean didComputerHitPlayerPlatoon(int fireLocation) {
|
||||
return this.playersPlatoons.contains(fireLocation);
|
||||
}
|
||||
|
||||
/**
|
||||
* Draw the battlefield grid
|
||||
*
|
||||
*/
|
||||
private void drawBattlefield() {
|
||||
for(int i=1; i<MAX_GRID_SIZE+1; i+= 5) {
|
||||
System.out.printf("%-2s %-2s %-2s %-2s %-2s %n", i, i+1, i+2, i+3, i+4);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Basic information about the game
|
||||
*
|
||||
*/
|
||||
private void intro() {
|
||||
System.out.println("BOMBARDMENT");
|
||||
System.out.println("CREATIVE COMPUTING MORRISTOWN, NEW JERSEY");
|
||||
System.out.println();
|
||||
System.out.println("YOU ARE ON A BATTLEFIELD WITH 4 PLATOONS AND YOU");
|
||||
System.out.println("HAVE 25 OUTPOSTS AVAILABLE WHERE THEY MAY BE PLACED.");
|
||||
System.out.println("YOU CAN ONLY PLACE ONE PLATOON AT ANY ONE OUTPOST.");
|
||||
System.out.println("THE COMPUTER DOES THE SAME WITH ITS FOUR PLATOONS.");
|
||||
System.out.println();
|
||||
System.out.println("THE OBJECT OF THE GAME IS TO FIRE MISSILES AT THE");
|
||||
System.out.println("OUTPOSTS OF THE COMPUTER. IT WILL DO THE SAME TO YOU.");
|
||||
System.out.println("THE ONE WHO DESTROYS ALL FOUR OF THE ENEMY'S PLATOONS");
|
||||
System.out.println("FIRST IS THE WINNER.");
|
||||
System.out.println();
|
||||
System.out.println("GOOD LUCK... AND TELL US WHERE YOU WANT THE BODIES SENT!");
|
||||
System.out.println();
|
||||
System.out.println("TEAR OFF MATRIX AND USE IT TO CHECK OFF THE NUMBERS.");
|
||||
System.out.println();
|
||||
System.out.println();
|
||||
}
|
||||
|
||||
private void init() {
|
||||
|
||||
// Create four locations for the computers platoons.
|
||||
this.computersPlatoons = computersChosenPlatoons();
|
||||
|
||||
// Players platoons.
|
||||
this.playersPlatoons = new HashSet<>();
|
||||
|
||||
this.computersGuesses = new HashSet<>();
|
||||
}
|
||||
|
||||
/**
|
||||
* Accepts a string delimited by comma's and returns the nth delimited
|
||||
* value (starting at count 0).
|
||||
*
|
||||
* @param text - text with values separated by comma's
|
||||
* @param pos - which position to return a value for
|
||||
* @return the int representation of the value
|
||||
*/
|
||||
private int getDelimitedValue(String text, int pos) {
|
||||
String[] tokens = text.split(",");
|
||||
return Integer.parseInt(tokens[pos]);
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* Print a message on the screen, then accept input from Keyboard.
|
||||
*
|
||||
* @param text message to be displayed on screen.
|
||||
* @return what was typed by the player.
|
||||
*/
|
||||
private String displayTextAndGetInput(String text) {
|
||||
System.out.print(text);
|
||||
return kbScanner.next();
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate random number
|
||||
*
|
||||
* @return random number
|
||||
*/
|
||||
private int randomNumber() {
|
||||
return (int) (Math.random()
|
||||
* (MAX_GRID_SIZE) + 1);
|
||||
}
|
||||
}
|
||||
8
11 Bombardment/java/src/BombardmentGame.java
Normal file
8
11 Bombardment/java/src/BombardmentGame.java
Normal file
@@ -0,0 +1,8 @@
|
||||
public class BombardmentGame {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
Bombardment bombardment = new Bombardment();
|
||||
bombardment.play();
|
||||
}
|
||||
}
|
||||
@@ -16,7 +16,7 @@
|
||||
150 R=R+1: PRINT: PRINT "ROUND";R:PRINT "---------"
|
||||
160 FOR I=1 TO N
|
||||
170 PRINT: PRINT A$(I)"'S THROW";: INPUT T
|
||||
180 IF T<0 OR T>3 THEN PRINT "INPUT 1, 2, OR 3!": GOTO 170
|
||||
180 IF T<1 OR T>3 THEN PRINT "INPUT 1, 2, OR 3!": GOTO 170
|
||||
190 ON T GOTO 200, 210, 200
|
||||
200 P1=.65: P2=.55: P3=.5: P4=.5: GOTO 230
|
||||
210 P1=.99: P2=.77: P3=.43: P4=.01: GOTO 230
|
||||
|
||||
248
18 Bullseye/java/src/Bullseye.java
Normal file
248
18 Bullseye/java/src/Bullseye.java
Normal file
@@ -0,0 +1,248 @@
|
||||
import java.util.ArrayList;
|
||||
import java.util.Scanner;
|
||||
|
||||
public class Bullseye {
|
||||
|
||||
public static final int FIRST_IDENT = 10;
|
||||
public static final int SECOND_IDENT = 30;
|
||||
public static final int THIRD_INDENT = 30;
|
||||
|
||||
public static final double[] SHOT_ONE = new double[] { .65, .55, .5, .5};
|
||||
public static final double[] SHOT_TWO = new double[] { .99, .77, .43,.01};
|
||||
public static final double[] SHOT_THREE = new double[] { .95, .75, .45, .05 };
|
||||
|
||||
private enum GAME_STATE {
|
||||
STARTING,
|
||||
START_GAME,
|
||||
PLAYING,
|
||||
GAME_OVER
|
||||
}
|
||||
|
||||
private GAME_STATE gameState;
|
||||
|
||||
private ArrayList<Player> players;
|
||||
|
||||
private Shot[] shots;
|
||||
|
||||
// Used for keyboard input
|
||||
private Scanner kbScanner;
|
||||
|
||||
private int numberOfPlayers;
|
||||
|
||||
private int round;
|
||||
|
||||
public Bullseye() {
|
||||
|
||||
gameState = GAME_STATE.STARTING;
|
||||
players = new ArrayList<>();
|
||||
|
||||
// Save the random chances of points based on shot type
|
||||
|
||||
shots = new Shot[3];
|
||||
shots[0] = new Shot(SHOT_ONE);
|
||||
shots[1] = new Shot(SHOT_TWO);
|
||||
shots[2] = new Shot(SHOT_THREE);
|
||||
|
||||
// Initialise kb scanner
|
||||
kbScanner = new Scanner(System.in);
|
||||
}
|
||||
|
||||
/**
|
||||
* Main game loop
|
||||
*
|
||||
*/
|
||||
public void play() {
|
||||
|
||||
do {
|
||||
switch (gameState) {
|
||||
|
||||
// Show an introduction the first time the game is played.
|
||||
case STARTING:
|
||||
intro();
|
||||
gameState = GAME_STATE.START_GAME;
|
||||
break;
|
||||
|
||||
// Start the game, set the number of players, names and round
|
||||
case START_GAME:
|
||||
|
||||
this.numberOfPlayers = chooseNumberOfPlayers();
|
||||
|
||||
for(int i=0; i<this.numberOfPlayers; i++) {
|
||||
String name = displayTextAndGetInput("NAME OF PLAYER #" + (i+1) + "? ");
|
||||
Player player = new Player(name);
|
||||
this.players.add(player);
|
||||
}
|
||||
|
||||
this.round = 1;
|
||||
|
||||
gameState = GAME_STATE.PLAYING;
|
||||
break;
|
||||
|
||||
// Playing round by round until we have a winner
|
||||
case PLAYING:
|
||||
System.out.println();
|
||||
System.out.println("ROUND " + this.round);
|
||||
System.out.println("=======");
|
||||
|
||||
// Each player takes their turn
|
||||
for(int i=0; i<players.size(); i++) {
|
||||
Player player = players.get(i);
|
||||
int playerThrow = getPlayersThrow(player);
|
||||
int points = calculatePlayerPoints(playerThrow);
|
||||
player.addScore(points);
|
||||
System.out.println("TOTAL SCORE = " + player.getScore());
|
||||
}
|
||||
|
||||
boolean foundWinner = false;
|
||||
|
||||
// Check if any player won
|
||||
for(int i=0; i<players.size(); i++) {
|
||||
Player thePlayer = players.get(i);
|
||||
int score = thePlayer.getScore();
|
||||
if(score >=200) {
|
||||
if(!foundWinner) {
|
||||
System.out.println("WE HAVE A WINNER!!");
|
||||
System.out.println();
|
||||
foundWinner = true;
|
||||
}
|
||||
System.out.println(thePlayer.getName() + " SCORED "
|
||||
+ thePlayer.getScore() + " POINTS");
|
||||
}
|
||||
}
|
||||
|
||||
if(foundWinner) {
|
||||
System.out.println("THANKS FOR THE GAME.");
|
||||
gameState = GAME_STATE.GAME_OVER;
|
||||
} else {
|
||||
// No winner found, continue on with the next round
|
||||
this.round++;
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
} while(gameState != GAME_STATE.GAME_OVER);
|
||||
}
|
||||
|
||||
/**
|
||||
* Display info about the game
|
||||
*
|
||||
*/
|
||||
private void intro() {
|
||||
System.out.println("BULLSEYE");
|
||||
System.out.println("CREATIVE COMPUTING MORRISTOWN, NEW JERSEY");
|
||||
System.out.println();
|
||||
System.out.println("IN THIS GAME, UP TO 20 PLAYERS THROW DARTS AT A TARGET");
|
||||
System.out.println("WITH 10, 20, 30, AND 40 POINT ZONES. THE OBJECTIVE IS");
|
||||
System.out.println("TO GET 200 POINTS.");
|
||||
System.out.println();
|
||||
System.out.println(paddedString("THROW", "DESCRIPTION", "PROBABLE SCORE"));
|
||||
System.out.println(paddedString("1", "FAST OVERARM","BULLSEYE OR COMPLETE MISS"));
|
||||
System.out.println(paddedString("2", "CONTROLLED OVERARM", "10, 20 OR 30 POINTS"));
|
||||
System.out.println(paddedString("3", "UNDERARM", "ANYTHING"));
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate the players score
|
||||
* Score is based on the type of shot plus a random factor
|
||||
*
|
||||
* @param playerThrow 1,2, or 3 indicating the type of shot
|
||||
* @return player score
|
||||
*/
|
||||
private int calculatePlayerPoints(int playerThrow) {
|
||||
|
||||
// -1 is because of 0 base Java array
|
||||
double p1 = this.shots[playerThrow-1].getShot(0);
|
||||
double p2 = this.shots[playerThrow-1].getShot(1);
|
||||
double p3 = this.shots[playerThrow-1].getShot(2);
|
||||
double p4 = this.shots[playerThrow-1].getShot(3);
|
||||
|
||||
double random = Math.random();
|
||||
|
||||
int points;
|
||||
|
||||
if(random >= p1) {
|
||||
System.out.println("BULLSEYE!! 40 POINTS!");
|
||||
points = 40;
|
||||
// If the throw was 1 (bullseye or missed, then make it missed
|
||||
// N.B. This is a fix for the basic code which for shot type 1
|
||||
// allowed a bullseye but did not make the score zero if a bullseye
|
||||
// was not made (which it should have done).
|
||||
} else if (playerThrow == 1) {
|
||||
System.out.println("MISSED THE TARGET! TOO BAD.");
|
||||
points = 0;
|
||||
} else if(random >= p2) {
|
||||
System.out.println("30-POINT ZONE!");
|
||||
points = 30;
|
||||
} else if(random >= p3) {
|
||||
System.out.println("20-POINT ZONE");
|
||||
points = 20;
|
||||
} else if(random >= p4) {
|
||||
System.out.println("WHEW! 10 POINTS.");
|
||||
points = 10;
|
||||
} else {
|
||||
System.out.println("MISSED THE TARGET! TOO BAD.");
|
||||
points = 0;
|
||||
}
|
||||
|
||||
return points;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get players shot 1,2, or 3 - ask again if invalid input
|
||||
*
|
||||
* @param player
|
||||
* @return 1,2, or 3 indicating the players shot
|
||||
*/
|
||||
private int getPlayersThrow(Player player) {
|
||||
boolean inputCorrect = false;
|
||||
String theThrow;
|
||||
do {
|
||||
theThrow = displayTextAndGetInput(player.getName() + "'S THROW ");
|
||||
if(theThrow.equals("1") || theThrow.equals("2") || theThrow.equals("3")) {
|
||||
inputCorrect = true;
|
||||
} else {
|
||||
System.out.println("INPUT 1, 2, OR 3!");
|
||||
}
|
||||
|
||||
} while(!inputCorrect);
|
||||
|
||||
return Integer.valueOf(theThrow);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Get players guess from kb
|
||||
*
|
||||
* @return players guess as an int
|
||||
*/
|
||||
private int chooseNumberOfPlayers() {
|
||||
|
||||
return Integer.valueOf((displayTextAndGetInput("HOW MANY PLAYERS? ")));
|
||||
}
|
||||
/*
|
||||
* Print a message on the screen, then accept input from Keyboard.
|
||||
*
|
||||
* @param text message to be displayed on screen.
|
||||
* @return what was typed by the player.
|
||||
*/
|
||||
private String displayTextAndGetInput(String text) {
|
||||
System.out.print(text);
|
||||
return kbScanner.next();
|
||||
}
|
||||
|
||||
/**
|
||||
* Format three strings to a given number of spaces
|
||||
* Replacing the original basic code which used tabs
|
||||
*
|
||||
* @param first String to print in pos 1
|
||||
* @param second String to print in pos 2
|
||||
* @param third String to print in pos 3
|
||||
* @return formatted string
|
||||
*/
|
||||
private String paddedString(String first, String second, String third) {
|
||||
String output = String.format("%1$" + FIRST_IDENT + "s", first);
|
||||
output += String.format("%1$" + SECOND_IDENT + "s", second);
|
||||
output += String.format("%1$" + THIRD_INDENT + "s", third);
|
||||
return output;
|
||||
}
|
||||
}
|
||||
8
18 Bullseye/java/src/BullseyeGame.java
Normal file
8
18 Bullseye/java/src/BullseyeGame.java
Normal file
@@ -0,0 +1,8 @@
|
||||
public class BullseyeGame {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
Bullseye bullseye = new Bullseye();
|
||||
bullseye.play();
|
||||
}
|
||||
}
|
||||
26
18 Bullseye/java/src/Player.java
Normal file
26
18 Bullseye/java/src/Player.java
Normal file
@@ -0,0 +1,26 @@
|
||||
/**
|
||||
* A Player in the game - consists of name and score
|
||||
*
|
||||
*/
|
||||
public class Player {
|
||||
|
||||
private String name;
|
||||
private int score;
|
||||
|
||||
Player(String name) {
|
||||
this.name = name;
|
||||
this.score = 0;
|
||||
}
|
||||
|
||||
public void addScore(int score) {
|
||||
this.score += score;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public int getScore() {
|
||||
return score;
|
||||
}
|
||||
}
|
||||
21
18 Bullseye/java/src/Shot.java
Normal file
21
18 Bullseye/java/src/Shot.java
Normal file
@@ -0,0 +1,21 @@
|
||||
/**
|
||||
* This class records the percentage chance of a given type of shot
|
||||
* scoring specific points
|
||||
* see Bullseye class points calculation method where its used
|
||||
*/
|
||||
public class Shot {
|
||||
|
||||
double[] chances;
|
||||
|
||||
// Array of doubles are passed for a specific type of shot
|
||||
Shot(double[] shots) {
|
||||
chances = new double[shots.length];
|
||||
for(int i=0; i<shots.length; i++) {
|
||||
chances[i] = shots[i];
|
||||
}
|
||||
}
|
||||
|
||||
public double getShot(int index) {
|
||||
return chances[index];
|
||||
}
|
||||
}
|
||||
9
18 Bullseye/javascript/bullseye.html
Normal file
9
18 Bullseye/javascript/bullseye.html
Normal file
@@ -0,0 +1,9 @@
|
||||
<html>
|
||||
<head>
|
||||
<title>BULLSEYE</title>
|
||||
</head>
|
||||
<body>
|
||||
<pre id="output" style="font-size: 12pt;"></pre>
|
||||
<script src="bullseye.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
142
18 Bullseye/javascript/bullseye.js
Normal file
142
18 Bullseye/javascript/bullseye.js
Normal file
@@ -0,0 +1,142 @@
|
||||
// BULLSEYE
|
||||
//
|
||||
// Converted from BASIC to Javascript by Oscar Toledo G. (nanochess)
|
||||
//
|
||||
|
||||
function print(str)
|
||||
{
|
||||
document.getElementById("output").appendChild(document.createTextNode(str));
|
||||
}
|
||||
|
||||
function input()
|
||||
{
|
||||
var input_element;
|
||||
var input_str;
|
||||
|
||||
return new Promise(function (resolve) {
|
||||
input_element = document.createElement("INPUT");
|
||||
|
||||
print("? ");
|
||||
input_element.setAttribute("type", "text");
|
||||
input_element.setAttribute("length", "50");
|
||||
document.getElementById("output").appendChild(input_element);
|
||||
input_element.focus();
|
||||
input_str = undefined;
|
||||
input_element.addEventListener("keydown", function (event) {
|
||||
if (event.keyCode == 13) {
|
||||
input_str = input_element.value;
|
||||
document.getElementById("output").removeChild(input_element);
|
||||
print(input_str);
|
||||
print("\n");
|
||||
resolve(input_str);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function tab(space)
|
||||
{
|
||||
var str = "";
|
||||
while (space-- > 0)
|
||||
str += " ";
|
||||
return str;
|
||||
}
|
||||
|
||||
var as = [];
|
||||
var s = [];
|
||||
var w = [];
|
||||
|
||||
// Main program
|
||||
async function main()
|
||||
{
|
||||
print(tab(32) + "BULLSEYE\n");
|
||||
print(tab(15) + "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY\n");
|
||||
print("\n");
|
||||
print("\n");
|
||||
print("\n");
|
||||
print("IN THIS GAME, UP TO 20 PLAYERS THROW DARTS AT A TARGET\n");
|
||||
print("WITH 10, 20, 30, AND 40 POINT ZONES. THE OBJECTIVE IS\n");
|
||||
print("TO GET 200 POINTS.\n");
|
||||
print("\n");
|
||||
print("THROW\t\tDESCRIPTION\t\tPROBABLE SCORE\n");
|
||||
print("1\t\tFAST OVERARM\t\tBULLSEYE OR COMPLETE MISS\n");
|
||||
print("2\t\tCONTROLLED OVERARM\t10, 20 OR 30 POINTS\n");
|
||||
print("3\t\tUNDERARM\t\tANYTHING\n");
|
||||
print("\n");
|
||||
m = 0;
|
||||
r = 0;
|
||||
for (i = 1; i <= 20; i++)
|
||||
s[i] = 0;
|
||||
print("HOW MANY PLAYERS");
|
||||
n = parseInt(await input());
|
||||
print("\n");
|
||||
for (i = 1; i <= n; i++) {
|
||||
print("NAME OF PLAYER #" + i);
|
||||
as[i] = await input();
|
||||
}
|
||||
do {
|
||||
r++;
|
||||
print("\n");
|
||||
print("ROUND " + r + "\n");
|
||||
print("---------\n");
|
||||
for (i = 1; i <= n; i++) {
|
||||
do {
|
||||
print("\n");
|
||||
print(as[i] + "'S THROW");
|
||||
t = parseInt(await input());
|
||||
if (t < 1 || t > 3)
|
||||
print("INPUT 1, 2, OR 3!\n");
|
||||
} while (t < 1 || t > 3) ;
|
||||
if (t == 1) {
|
||||
p1 = 0.65;
|
||||
p2 = 0.55;
|
||||
p3 = 0.5;
|
||||
p4 = 0.5;
|
||||
} else if (t == 2) {
|
||||
p1 = 0.99;
|
||||
p2 = 0.77;
|
||||
p3 = 0.43;
|
||||
p4 = 0.01;
|
||||
} else {
|
||||
p1 = 0.95;
|
||||
p2 = 0.75;
|
||||
p3 = 0.45;
|
||||
p4 = 0.05;
|
||||
}
|
||||
u = Math.random();
|
||||
if (u >= p1) {
|
||||
print("BULLSEYE!! 40 POINTS!\n");
|
||||
b = 40;
|
||||
} else if (u >= p2) {
|
||||
print("30-POINT ZONE!\n");
|
||||
b = 30;
|
||||
} else if (u >= p3) {
|
||||
print("20-POINT ZONE\n");
|
||||
b = 20;
|
||||
} else if (u >= p4) {
|
||||
print("WHEW! 10 POINT.\n");
|
||||
b = 10;
|
||||
} else {
|
||||
print("MISSED THE TARGET! TOO BAD.\n");
|
||||
b = 0;
|
||||
}
|
||||
s[i] += b;
|
||||
print("TOTAL SCORE = " + s[i] + "\n");
|
||||
}
|
||||
for (i = 1; i <= n; i++) {
|
||||
if (s[i] >= 200) {
|
||||
m++;
|
||||
w[m] = i;
|
||||
}
|
||||
}
|
||||
} while (m == 0) ;
|
||||
print("\n");
|
||||
print("WE HAVE A WINNER!!\n");
|
||||
print("\n");
|
||||
for (i = 1; i <= m; i++)
|
||||
print(as[w[i]] + " SCORED " + s[w[i]] + " POINTS.\n");
|
||||
print("\n");
|
||||
print("THANKS FOR THE GAME.\n");
|
||||
}
|
||||
|
||||
main();
|
||||
@@ -2,7 +2,7 @@
|
||||
20 PRINT TAB(15);"CREATIVE COMPUTING MORRISTOWN, NEW JERSEY"
|
||||
30 PRINT:PRINT:PRINT
|
||||
40 PRINT "THIS PROGRAM PRINTS HIGHLY ACCEPTABLE PHRASES IN"
|
||||
50 PRINT "'EDUCATOR-SPEAK'THAT YOU CAN WORK INTO REPORTS"
|
||||
50 PRINT "'EDUCATOR-SPEAK' THAT YOU CAN WORK INTO REPORTS"
|
||||
60 PRINT "AND SPEECHES. WHENEVER A QUESTION MARK IS PRINTED,"
|
||||
70 PRINT "TYPE A 'Y' FOR ANOTHER PHRASE OR 'N' TO QUIT."
|
||||
80 PRINT:PRINT:PRINT "HERE'S THE FIRST PHRASE:"
|
||||
|
||||
9
20 Buzzword/javascript/buzzword.html
Normal file
9
20 Buzzword/javascript/buzzword.html
Normal file
@@ -0,0 +1,9 @@
|
||||
<html>
|
||||
<head>
|
||||
<title>BUZZWORD</title>
|
||||
</head>
|
||||
<body>
|
||||
<pre id="output" style="font-size: 12pt;"></pre>
|
||||
<script src="buzzword.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
83
20 Buzzword/javascript/buzzword.js
Normal file
83
20 Buzzword/javascript/buzzword.js
Normal file
@@ -0,0 +1,83 @@
|
||||
// BUZZWORD
|
||||
//
|
||||
// Converted from BASIC to Javascript by Oscar Toledo G. (nanochess)
|
||||
//
|
||||
|
||||
function print(str)
|
||||
{
|
||||
document.getElementById("output").appendChild(document.createTextNode(str));
|
||||
}
|
||||
|
||||
function input()
|
||||
{
|
||||
var input_element;
|
||||
var input_str;
|
||||
|
||||
return new Promise(function (resolve) {
|
||||
input_element = document.createElement("INPUT");
|
||||
|
||||
print("? ");
|
||||
input_element.setAttribute("type", "text");
|
||||
input_element.setAttribute("length", "50");
|
||||
document.getElementById("output").appendChild(input_element);
|
||||
input_element.focus();
|
||||
input_str = undefined;
|
||||
input_element.addEventListener("keydown", function (event) {
|
||||
if (event.keyCode == 13) {
|
||||
input_str = input_element.value;
|
||||
document.getElementById("output").removeChild(input_element);
|
||||
print(input_str);
|
||||
print("\n");
|
||||
resolve(input_str);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function tab(space)
|
||||
{
|
||||
var str = "";
|
||||
while (space-- > 0)
|
||||
str += " ";
|
||||
return str;
|
||||
}
|
||||
|
||||
var a = ["",
|
||||
"ABILITY","BASAL","BEHAVIORAL","CHILD-CENTERED",
|
||||
"DIFFERENTIATED","DISCOVERY","FLEXIBLE","HETEROGENEOUS",
|
||||
"HOMOGENEOUS","MANIPULATIVE","MODULAR","TAVISTOCK",
|
||||
"INDIVIDUALIZED","LEARNING","EVALUATIVE","OBJECTIVE",
|
||||
"COGNITIVE","ENRICHMENT","SCHEDULING","HUMANISTIC",
|
||||
"INTEGRATED","NON-GRADED","TRAINING","VERTICAL AGE",
|
||||
"MOTIVATIONAL","CREATIVE","GROUPING","MODIFICATION",
|
||||
"ACCOUNTABILITY","PROCESS","CORE CURRICULUM","ALGORITHM",
|
||||
"PERFORMANCE","REINFORCEMENT","OPEN CLASSROOM","RESOURCE",
|
||||
"STRUCTURE","FACILITY","ENVIRONMENT",
|
||||
];
|
||||
|
||||
// Main program
|
||||
async function main()
|
||||
{
|
||||
print(tab(26) + "BUZZWORD GENERATOR\n");
|
||||
print(tab(15) + "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY\n");
|
||||
print("\n");
|
||||
print("\n");
|
||||
print("\n");
|
||||
print("THIS PROGRAM PRINTS HIGHLY ACCEPTABLE PHRASES IN\n");
|
||||
print("'EDUCATOR-SPEAK' THAT YOU CAN WORK INTO REPORTS\n");
|
||||
print("AND SPEECHES. WHENEVER A QUESTION MARK IS PRINTED,\n");
|
||||
print("TYPE A 'Y' FOR ANOTHER PHRASE OR 'N' TO QUIT.\n");
|
||||
print("\n");
|
||||
print("\n");
|
||||
print("HERE'S THE FIRST PHRASE:\n");
|
||||
do {
|
||||
print(a[Math.floor(Math.random() * 13 + 1)] + " ");
|
||||
print(a[Math.floor(Math.random() * 13 + 14)] + " ");
|
||||
print(a[Math.floor(Math.random() * 13 + 27)] + "\n");
|
||||
print("\n");
|
||||
y = await input();
|
||||
} while (y == "Y") ;
|
||||
print("COME BACK WHEN YOU NEED HELP WITH ANOTHER REPORT!\n");
|
||||
}
|
||||
|
||||
main();
|
||||
101
20 Buzzword/ruby/buzzword.rb
Normal file
101
20 Buzzword/ruby/buzzword.rb
Normal file
@@ -0,0 +1,101 @@
|
||||
######################################################################
|
||||
#
|
||||
# Buzzword Generator
|
||||
#
|
||||
# From: BASIC Computer Games (1978)
|
||||
# Edited by David H. Ahl
|
||||
#
|
||||
# "This program is an invaluable aid for preparing speeches and
|
||||
# briefings about education technology. This buzzword generator
|
||||
# provides sets of three highly-acceptable words to work into your
|
||||
# material. Your audience will never know that the phrases don't
|
||||
# really mean much of anything because they sound so great! Full
|
||||
# instructions for running are given in the program.
|
||||
#
|
||||
# "This version of Buzzword was written by David Ahl."
|
||||
#
|
||||
#
|
||||
# Ruby port by Leslie Viljoen, 2021
|
||||
#
|
||||
######################################################################
|
||||
|
||||
WORDS = [["Ability", "Basal", "Behavioral", "Child-centered",
|
||||
"Differentiated", "Discovery", "Flexible", "Heterogeneous",
|
||||
"Homogenous", "Manipulative", "Modular", "Tavistock",
|
||||
"Individualized"],
|
||||
|
||||
["learning", "evaluative", "objective", "cognitive",
|
||||
"enrichment", "scheduling", "humanistic", "integrated",
|
||||
"non-graded", "training", "vertical age", "motivational",
|
||||
"creative"] ,
|
||||
|
||||
["grouping", "modification", "accountability", "process",
|
||||
"core curriculum", "algorithm", "performance",
|
||||
"reinforcement", "open classroom", "resource", "structure",
|
||||
"facility","environment"]]
|
||||
|
||||
|
||||
# Display intro text
|
||||
|
||||
puts "\n Buzzword Generator"
|
||||
puts "Creative Computing Morristown, New Jersey"
|
||||
puts "\n\n"
|
||||
puts "This program prints highly acceptable phrases in"
|
||||
puts "'educator-speak' that you can work into reports"
|
||||
puts "and speeches. Whenever a question mark is printed,"
|
||||
puts "type a 'Y' for another phrase or 'N' to quit."
|
||||
puts "\n\nHere's the first phrase:"
|
||||
|
||||
loop do
|
||||
phrase = []
|
||||
|
||||
prefix, body, postfix = WORDS
|
||||
|
||||
phrase << prefix[rand(prefix.length)]
|
||||
phrase << body[rand(body.length)]
|
||||
phrase << postfix[rand(postfix.length)]
|
||||
|
||||
puts phrase.join(' ')
|
||||
puts "\n"
|
||||
|
||||
print "?"
|
||||
response = gets
|
||||
|
||||
break unless response.upcase.start_with?('Y')
|
||||
end
|
||||
|
||||
puts "Come back when you need help with another report!\n"
|
||||
|
||||
|
||||
######################################################################
|
||||
#
|
||||
# Porting Notes
|
||||
#
|
||||
# The original program stored all 39 words in one array, then
|
||||
# built the buzzword phrases by randomly sampling from each of the
|
||||
# three regions of the array (1-13, 14-26, and 27-39).
|
||||
#
|
||||
# Instead, we're storing the words for each section in three
|
||||
# separate arrays. That makes it easy to loop through the sections
|
||||
# to stitch the phrase together, and it easily accomodates adding
|
||||
# (or removing) elements from any section. They don't all need to
|
||||
# be the same length.
|
||||
#
|
||||
# The author of this program (and founder of Creative Computing
|
||||
# magazine) first started working at DEC--Digital Equipment
|
||||
# Corporation--as a consultant helping the company market its
|
||||
# computers as educational products. He later was editor of a DEC
|
||||
# newsletter named "EDU" that focused on using computers in an
|
||||
# educational setting. No surprise, then, that the buzzwords in
|
||||
# this program were targeted towards educators!
|
||||
#
|
||||
#
|
||||
# Ideas for Modifications
|
||||
#
|
||||
# Try adding more/different words. Better yet, add a third
|
||||
# array to the WORDS array to add new sets of words that
|
||||
# might pertain to different fields. What would business buzzwords
|
||||
# be? Engineering buzzwords? Art/music buzzwords? Let the user
|
||||
# choose a field and pick the buzzwords accordingly.
|
||||
#
|
||||
######################################################################
|
||||
9
22 Change/javascript/change.html
Normal file
9
22 Change/javascript/change.html
Normal file
@@ -0,0 +1,9 @@
|
||||
<html>
|
||||
<head>
|
||||
<title>CHANGE</title>
|
||||
</head>
|
||||
<body>
|
||||
<pre id="output" style="font-size: 12pt;"></pre>
|
||||
<script src="change.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
107
22 Change/javascript/change.js
Normal file
107
22 Change/javascript/change.js
Normal file
@@ -0,0 +1,107 @@
|
||||
// CHANGE
|
||||
//
|
||||
// Converted from BASIC to Javascript by Oscar Toledo G. (nanochess)
|
||||
//
|
||||
|
||||
function print(str)
|
||||
{
|
||||
document.getElementById("output").appendChild(document.createTextNode(str));
|
||||
}
|
||||
|
||||
function input()
|
||||
{
|
||||
var input_element;
|
||||
var input_str;
|
||||
|
||||
return new Promise(function (resolve) {
|
||||
input_element = document.createElement("INPUT");
|
||||
|
||||
print("? ");
|
||||
input_element.setAttribute("type", "text");
|
||||
input_element.setAttribute("length", "50");
|
||||
document.getElementById("output").appendChild(input_element);
|
||||
input_element.focus();
|
||||
input_str = undefined;
|
||||
input_element.addEventListener("keydown", function (event) {
|
||||
if (event.keyCode == 13) {
|
||||
input_str = input_element.value;
|
||||
document.getElementById("output").removeChild(input_element);
|
||||
print(input_str);
|
||||
print("\n");
|
||||
resolve(input_str);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function tab(space)
|
||||
{
|
||||
var str = "";
|
||||
while (space-- > 0)
|
||||
str += " ";
|
||||
return str;
|
||||
}
|
||||
|
||||
// Main program
|
||||
async function main()
|
||||
{
|
||||
print(tab(33) + "CHANGE\n");
|
||||
print(tab(15) + "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY\n");
|
||||
print("\n");
|
||||
print("\n");
|
||||
print("\n");
|
||||
print("I, YOUR FRIENDLY MICROCOMPUTER, WILL DETERMINE\n");
|
||||
print("THE CORRECT CHANGE FOR ITEMS COSTING UP TO $100.\n");
|
||||
print("\n");
|
||||
print("\n");
|
||||
while (1) {
|
||||
print("COST OF ITEM");
|
||||
a = parseFloat(await input());
|
||||
print("AMOUNT OF PAYMENT");
|
||||
p = parseFloat(await input());
|
||||
c = p - a;
|
||||
m = c;
|
||||
if (c == 0) {
|
||||
print("CORRECT AMOUNT, THANK YOU.\n");
|
||||
} else {
|
||||
print("YOUR CHANGE, $" + c + "\n");
|
||||
d = Math.floor(c / 10);
|
||||
if (d)
|
||||
print(d + " TEN DOLLAR BILL(S)\n");
|
||||
c -= d * 10;
|
||||
e = Math.floor(c / 5);
|
||||
if (e)
|
||||
print(e + " FIVE DOLLAR BILL(S)\n");
|
||||
c -= e * 5;
|
||||
f = Math.floor(c);
|
||||
if (f)
|
||||
print(f + " ONE DOLLAR BILL(S)\n");
|
||||
c -= f;
|
||||
c *= 100;
|
||||
g = Math.floor(c / 50);
|
||||
if (g)
|
||||
print(g + " ONE HALF DOLLAR(S)\n");
|
||||
c -= g * 50;
|
||||
h = Math.floor(c / 25);
|
||||
if (h)
|
||||
print(h + " QUARTER(S)\n");
|
||||
c -= h * 25;
|
||||
i = Math.floor(c / 10);
|
||||
if (i)
|
||||
print(i + " DIME(S)\n");
|
||||
c -= i * 10;
|
||||
j = Math.floor(c / 5);
|
||||
if (j)
|
||||
print(j + " NICKEL(S)\n");
|
||||
c -= j * 5;
|
||||
k = Math.floor(c + 0.5);
|
||||
if (k)
|
||||
print(k + " PENNY(S)\n");
|
||||
print("THANK YOU, COME AGAIN.\n");
|
||||
print("\n");
|
||||
print("\n");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
main();
|
||||
9
23 Checkers/javascript/checkers.html
Normal file
9
23 Checkers/javascript/checkers.html
Normal file
@@ -0,0 +1,9 @@
|
||||
<html>
|
||||
<head>
|
||||
<title>CHECKERS</title>
|
||||
</head>
|
||||
<body>
|
||||
<pre id="output" style="font-size: 12pt;"></pre>
|
||||
<script src="checkers.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
300
23 Checkers/javascript/checkers.js
Normal file
300
23 Checkers/javascript/checkers.js
Normal file
@@ -0,0 +1,300 @@
|
||||
// CHECKERS
|
||||
//
|
||||
// Converted from BASIC to Javascript by Oscar Toledo G. (nanochess)
|
||||
//
|
||||
|
||||
function print(str)
|
||||
{
|
||||
document.getElementById("output").appendChild(document.createTextNode(str));
|
||||
}
|
||||
|
||||
function input()
|
||||
{
|
||||
var input_element;
|
||||
var input_str;
|
||||
|
||||
return new Promise(function (resolve) {
|
||||
input_element = document.createElement("INPUT");
|
||||
|
||||
print("? ");
|
||||
input_element.setAttribute("type", "text");
|
||||
input_element.setAttribute("length", "50");
|
||||
document.getElementById("output").appendChild(input_element);
|
||||
input_element.focus();
|
||||
input_str = undefined;
|
||||
input_element.addEventListener("keydown", function (event) {
|
||||
if (event.keyCode == 13) {
|
||||
input_str = input_element.value;
|
||||
document.getElementById("output").removeChild(input_element);
|
||||
print(input_str);
|
||||
print("\n");
|
||||
resolve(input_str);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function tab(space)
|
||||
{
|
||||
var str = "";
|
||||
while (space-- > 0)
|
||||
str += " ";
|
||||
return str;
|
||||
}
|
||||
|
||||
// x,y = origin square
|
||||
// a,b = movement direction
|
||||
function try_computer()
|
||||
{
|
||||
u = x + a;
|
||||
v = y + b;
|
||||
if (u < 0 || u > 7 || v < 0 || v > 7)
|
||||
return;
|
||||
if (s[u][v] == 0) {
|
||||
eval_move();
|
||||
return;
|
||||
}
|
||||
if (s[u][v] < 0) // Cannot jump over own pieces
|
||||
return;
|
||||
u += a;
|
||||
u += b;
|
||||
if (u < 0 || u > 7 || v < 0 || v > 7)
|
||||
return;
|
||||
if (s[u][v] == 0)
|
||||
eval_move();
|
||||
}
|
||||
|
||||
// x,y = origin square
|
||||
// u,v = target square
|
||||
function eval_move()
|
||||
{
|
||||
if (v == 0 && s[x][y] == -1)
|
||||
q += 2;
|
||||
if (Math.abs(y - v) == 2)
|
||||
q += 5;
|
||||
if (y == 7)
|
||||
q -= 2;
|
||||
if (u == 0 || u == 7)
|
||||
q++;
|
||||
for (c = -1; c <= 1; c += 2) {
|
||||
if (u + c < 0 || u + c > 7 || v + g < 0)
|
||||
continue;
|
||||
if (s[u + c][v + g] < 0) { // Computer piece
|
||||
q++;
|
||||
continue;
|
||||
}
|
||||
if (u - c < 0 || u - c > 7 || v - g > 7)
|
||||
continue;
|
||||
if (s[u + c][v + g] > 0 && (s[u - c][v - g] == 0 || (u - c == x && v - g == y)))
|
||||
q -= 2;
|
||||
}
|
||||
if (q > r[0]) { // Best movement so far?
|
||||
r[0] = q; // Take note of score
|
||||
r[1] = x; // Origin square
|
||||
r[2] = y;
|
||||
r[3] = u; // Target square
|
||||
r[4] = v;
|
||||
}
|
||||
q = 0;
|
||||
}
|
||||
|
||||
function more_captures() {
|
||||
u = x + a;
|
||||
v = y + b;
|
||||
if (u < 0 || u > 7 || v < 0 || v > 7)
|
||||
return;
|
||||
if (s[u][v] == 0 && s[x + a / 2][y + b / 2] > 0)
|
||||
eval_move();
|
||||
}
|
||||
|
||||
var r = [-99, 0, 0, 0, 0];
|
||||
var s = [];
|
||||
|
||||
for (x = 0; x <= 7; x++)
|
||||
s[x] = [];
|
||||
|
||||
var g = -1;
|
||||
var data = [1, 0, 1, 0, 0, 0, -1, 0, 0, 1, 0, 0, 0, -1, 0, -1, 15];
|
||||
var p = 0;
|
||||
var q = 0;
|
||||
|
||||
// Main program
|
||||
async function main()
|
||||
{
|
||||
print(tab(32) + "CHECKERS\n");
|
||||
print(tab(15) + "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY\n");
|
||||
print("\n");
|
||||
print("\n");
|
||||
print("\n");
|
||||
print("THIS IS THE GAME OF CHECKERS. THE COMPUTER IS X,\n");
|
||||
print("AND YOU ARE O. THE COMPUTER WILL MOVE FIRST.\n");
|
||||
print("SQUARES ARE REFERRED TO BY A COORDINATE SYSTEM.\n");
|
||||
print("(0,0) IS THE LOWER LEFT CORNER\n");
|
||||
print("(0,7) IS THE UPPER LEFT CORNER\n");
|
||||
print("(7,0) IS THE LOWER RIGHT CORNER\n");
|
||||
print("(7,7) IS THE UPPER RIGHT CORNER\n");
|
||||
print("THE COMPUTER WILL TYPE '+TO' WHEN YOU HAVE ANOTHER\n");
|
||||
print("JUMP. TYPE TWO NEGATIVE NUMBERS IF YOU CANNOT JUMP.\n");
|
||||
print("\n");
|
||||
print("\n");
|
||||
print("\n");
|
||||
for (x = 0; x <= 7; x++) {
|
||||
for (y = 0; y <= 7; y++) {
|
||||
if (data[p] == 15)
|
||||
p = 0;
|
||||
s[x][y] = data[p];
|
||||
p++;
|
||||
}
|
||||
}
|
||||
while (1) {
|
||||
|
||||
// Search the board for the best movement
|
||||
for (x = 0; x <= 7; x++) {
|
||||
for (y = 0; y <= 7; y++) {
|
||||
if (s[x][y] > -1)
|
||||
continue;
|
||||
if (s[x][y] == -1) { // Piece
|
||||
for (a = -1; a <= 1; a += 2) {
|
||||
b = g; // Only advances
|
||||
try_computer();
|
||||
}
|
||||
} else if (s[x][y] == -2) { // King
|
||||
for (a = -1; a <= 1; a += 2) {
|
||||
for (b = -1; b <= 1; b += 2) {
|
||||
try_computer();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (r[0] == -99) {
|
||||
print("\n");
|
||||
print("YOU WIN.\n");
|
||||
break;
|
||||
}
|
||||
print("FROM " + r[1] + "," + r[2] + " TO " + r[3] + "," + r[4]);
|
||||
r[0] = -99;
|
||||
while (1) {
|
||||
if (r[4] == 0) { // Computer reaches the bottom
|
||||
s[r[3]][r[4]] = -2; // King
|
||||
break;
|
||||
}
|
||||
s[r[3]][r[4]] = s[r[1]][r[2]]; // Move
|
||||
s[r[1]][r[2]] = 0;
|
||||
if (Math.abs(r[1] - r[3]) == 2) {
|
||||
s[(r[1] + r[3]) / 2][(r[2] + r[4]) / 2] = 0; // Capture
|
||||
x = r[3];
|
||||
y = r[4];
|
||||
if (s[x][y] == -1) {
|
||||
b = -2;
|
||||
for (a = -2; a <= 2; a += 4) {
|
||||
more_captures();
|
||||
}
|
||||
} else if (s[x][y] == -2) {
|
||||
for (a = -2; a <= 2; a += 4) {
|
||||
for (b = -2; b <= 2; b += 4) {
|
||||
more_captures();
|
||||
}
|
||||
}
|
||||
}
|
||||
if (r[0] != -99) {
|
||||
print(" TO " + r[3] + "," + r[4]);
|
||||
r[0] = -99;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
print("\n");
|
||||
print("\n");
|
||||
print("\n");
|
||||
for (y = 7; y >= 0; y--) {
|
||||
str = "";
|
||||
for (x = 0; x <= 7; x++) {
|
||||
if (s[x][y] == 0)
|
||||
str += ".";
|
||||
if (s[x][y] == 1)
|
||||
str += "O";
|
||||
if (s[x][y] == -1)
|
||||
str += "X";
|
||||
if (s[x][y] == -2)
|
||||
str += "X*";
|
||||
if (s[x][y] == 2)
|
||||
str += "O*";
|
||||
while (str.length % 5)
|
||||
str += " ";
|
||||
}
|
||||
print(str + "\n");
|
||||
print("\n");
|
||||
}
|
||||
print("\n");
|
||||
z = 0;
|
||||
t = 0;
|
||||
for (l = 0; l <= 7; l++) {
|
||||
for (m = 0; m <= 7; m++) {
|
||||
if (s[l][m] == 1 || s[l][m] == 2)
|
||||
z = 1;
|
||||
if (s[l][m] == -1 || s[l][m] == -2)
|
||||
t = 1;
|
||||
}
|
||||
}
|
||||
if (z != 1) {
|
||||
print("\n");
|
||||
print("I WIN.\n");
|
||||
break;
|
||||
}
|
||||
if (t != 1) {
|
||||
print("\n");
|
||||
print("YOU WIN.\n");
|
||||
break;
|
||||
}
|
||||
do {
|
||||
print("FROM");
|
||||
e = await input();
|
||||
h = parseInt(e.substr(e.indexOf(",") + 1));
|
||||
e = parseInt(e);
|
||||
x = e;
|
||||
y = h;
|
||||
} while (s[x][y] <= 0) ;
|
||||
do {
|
||||
print("TO");
|
||||
a = await input();
|
||||
b = parseInt(a.substr(a.indexOf(",") + 1));
|
||||
a = parseInt(a);
|
||||
x = a;
|
||||
y = b;
|
||||
if (s[x][y] == 0 && Math.abs(a - e) <= 2 && Math.abs(a - e) == Math.abs(b - h))
|
||||
break;
|
||||
print("WHAT?\n");
|
||||
} while (1) ;
|
||||
i = 46;
|
||||
do {
|
||||
s[a][b] = s[e][h]
|
||||
s[e][h] = 0;
|
||||
if (Math.abs(e - a) != 2)
|
||||
break;
|
||||
s[(e + a) / 2][(h + b) / 2] = 0;
|
||||
while (1) {
|
||||
print("+TO");
|
||||
a1 = await input();
|
||||
b1 = parseInt(a1.substr(a1.indexOf(",") + 1));
|
||||
a1 = parseInt(a1);
|
||||
if (a1 < 0)
|
||||
break;
|
||||
if (s[a1][b1] == 0 && Math.abs(a1 - a) == 2 && Math.abs(b1 - b) == 2)
|
||||
break;
|
||||
}
|
||||
if (a1 < 0)
|
||||
break;
|
||||
e = a;
|
||||
h = b;
|
||||
a = a1;
|
||||
b = b1;
|
||||
i += 15;
|
||||
} while (1);
|
||||
if (b == 7) // Player reaches top
|
||||
s[a][b] = 2; // Convert to king
|
||||
}
|
||||
}
|
||||
|
||||
main();
|
||||
25
24 Chemist/csharp/Chemist/Chemist.sln
Normal file
25
24 Chemist/csharp/Chemist/Chemist.sln
Normal file
@@ -0,0 +1,25 @@
|
||||
|
||||
Microsoft Visual Studio Solution File, Format Version 12.00
|
||||
# Visual Studio Version 16
|
||||
VisualStudioVersion = 16.0.31005.135
|
||||
MinimumVisualStudioVersion = 10.0.40219.1
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Chemist", "Chemist\Chemist.csproj", "{8CC70F80-F2D6-47B6-8976-079352AC6C85}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
Release|Any CPU = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
||||
{8CC70F80-F2D6-47B6-8976-079352AC6C85}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{8CC70F80-F2D6-47B6-8976-079352AC6C85}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{8CC70F80-F2D6-47B6-8976-079352AC6C85}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{8CC70F80-F2D6-47B6-8976-079352AC6C85}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
EndGlobalSection
|
||||
GlobalSection(ExtensibilityGlobals) = postSolution
|
||||
SolutionGuid = {4AFDA581-82B1-42C7-9C9C-26F6B4288584}
|
||||
EndGlobalSection
|
||||
EndGlobal
|
||||
8
24 Chemist/csharp/Chemist/Chemist/Chemist.csproj
Normal file
8
24 Chemist/csharp/Chemist/Chemist/Chemist.csproj
Normal file
@@ -0,0 +1,8 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net5.0</TargetFramework>
|
||||
</PropertyGroup>
|
||||
|
||||
</Project>
|
||||
49
24 Chemist/csharp/Chemist/Chemist/Program.cs
Normal file
49
24 Chemist/csharp/Chemist/Chemist/Program.cs
Normal file
@@ -0,0 +1,49 @@
|
||||
using System;
|
||||
const int maxLives = 9;
|
||||
|
||||
WriteCentred("Chemist");
|
||||
WriteCentred("Creative Computing, Morristown, New Jersey");
|
||||
Console.WriteLine(@"
|
||||
|
||||
|
||||
The fictitious chemical kryptocyanic acid can only be
|
||||
diluted by the ratio of 7 parts water to 3 parts acid.
|
||||
If any other ratio is attempted, the acid becomes unstable
|
||||
and soon explodes. Given the amount of acid, you must
|
||||
decide who much water to add for dilution. If you miss
|
||||
you face the consequences.
|
||||
");
|
||||
|
||||
var random = new Random();
|
||||
int livesUsed = 0;
|
||||
while (livesUsed < maxLives)
|
||||
{
|
||||
int krypto = random.Next(1, 50);
|
||||
double water = krypto * 7.0 / 3.0;
|
||||
|
||||
Console.WriteLine($"{krypto} Liters of kryptocyanic acid. How much water?");
|
||||
double answer = double.Parse(Console.ReadLine());
|
||||
|
||||
double diff = Math.Abs(answer - water);
|
||||
if (diff <= water / 20)
|
||||
{
|
||||
Console.WriteLine("Good job! You may breathe now, but don't inhale the fumes"!);
|
||||
Console.WriteLine();
|
||||
}
|
||||
else
|
||||
{
|
||||
Console.WriteLine("Sizzle! You have just been desalinated into a blob\nof quivering protoplasm!");
|
||||
Console.WriteLine();
|
||||
livesUsed++;
|
||||
|
||||
if (livesUsed < maxLives)
|
||||
Console.WriteLine("However, you may try again with another life.");
|
||||
}
|
||||
}
|
||||
Console.WriteLine($"Your {maxLives} lives are used, but you will be long remembered for\nyour contributions to the field of comic book chemistry.");
|
||||
|
||||
static void WriteCentred(string text)
|
||||
{
|
||||
int indent = (Console.WindowWidth + text.Length) / 2;
|
||||
Console.WriteLine($"{{0,{indent}}}", text);
|
||||
}
|
||||
9
24 Chemist/javascript/chemist.html
Normal file
9
24 Chemist/javascript/chemist.html
Normal file
@@ -0,0 +1,9 @@
|
||||
<html>
|
||||
<head>
|
||||
<title>CHEMIST</title>
|
||||
</head>
|
||||
<body>
|
||||
<pre id="output" style="font-size: 12pt;"></pre>
|
||||
<script src="chemist.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
82
24 Chemist/javascript/chemist.js
Normal file
82
24 Chemist/javascript/chemist.js
Normal file
@@ -0,0 +1,82 @@
|
||||
// CHEMIST
|
||||
//
|
||||
// Converted from BASIC to Javascript by Oscar Toledo G. (nanochess)
|
||||
//
|
||||
|
||||
function print(str)
|
||||
{
|
||||
document.getElementById("output").appendChild(document.createTextNode(str));
|
||||
}
|
||||
|
||||
function input()
|
||||
{
|
||||
var input_element;
|
||||
var input_str;
|
||||
|
||||
return new Promise(function (resolve) {
|
||||
input_element = document.createElement("INPUT");
|
||||
|
||||
print("? ");
|
||||
input_element.setAttribute("type", "text");
|
||||
input_element.setAttribute("length", "50");
|
||||
document.getElementById("output").appendChild(input_element);
|
||||
input_element.focus();
|
||||
input_str = undefined;
|
||||
input_element.addEventListener("keydown", function (event) {
|
||||
if (event.keyCode == 13) {
|
||||
input_str = input_element.value;
|
||||
document.getElementById("output").removeChild(input_element);
|
||||
print(input_str);
|
||||
print("\n");
|
||||
resolve(input_str);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function tab(space)
|
||||
{
|
||||
var str = "";
|
||||
while (space-- > 0)
|
||||
str += " ";
|
||||
return str;
|
||||
}
|
||||
|
||||
// Main program
|
||||
async function main()
|
||||
{
|
||||
print(tab(33) + "CHEMIST\n");
|
||||
print(tab(15) + "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY\n");
|
||||
print("\n");
|
||||
print("\n");
|
||||
print("\n");
|
||||
print("THE FICTITIOUS CHECMICAL KRYPTOCYANIC ACID CAN ONLY BE\n");
|
||||
print("DILUTED BY THE RATIO OF 7 PARTS WATER TO 3 PARTS ACID.\n");
|
||||
print("IF ANY OTHER RATIO IS ATTEMPTED, THE ACID BECOMES UNSTABLE\n");
|
||||
print("AND SOON EXPLODES. GIVEN THE AMOUNT OF ACID, YOU MUST\n");
|
||||
print("DECIDE WHO MUCH WATER TO ADD FOR DILUTION. IF YOU MISS\n");
|
||||
print("YOU FACE THE CONSEQUENCES.\n");
|
||||
t = 0;
|
||||
while (1) {
|
||||
a = Math.floor(Math.random() * 50);
|
||||
w = 7 * a / 3;
|
||||
print(a + " LITERS OF KRYPTOCYANIC ACID. HOW MUCH WATER");
|
||||
r = parseFloat(await input());
|
||||
d = Math.abs(w - r);
|
||||
if (d > w / 20) {
|
||||
print(" SIZZLE! YOU HAVE JUST BEEN DESALINATED INTO A BLOB\n");
|
||||
print(" OF QUIVERING PROTOPLASM!\n");
|
||||
t++;
|
||||
if (t == 9)
|
||||
break;
|
||||
print(" HOWEVER, YOU MAY TRY AGAIN WITH ANOTHER LIFE.\n");
|
||||
} else {
|
||||
print(" GOOD JOB! YOU MAY BREATHE NOW, BUT DON'T INHALE THE FUMES!\n");
|
||||
print("\n");
|
||||
}
|
||||
}
|
||||
print(" YOUR 9 LIVES ARE USED, BUT YOU WILL BE LONG REMEMBERED FOR\n");
|
||||
print(" YOUR CONTRIBUTIONS TO THE FIELD OF COMIC BOOK CHEMISTRY.\n");
|
||||
}
|
||||
|
||||
main();
|
||||
@@ -47,5 +47,5 @@
|
||||
450 PRINT:PRINT"#########################":PRINT
|
||||
470 PRINT "I HOPE YOU BELIEVE ME NOW, FOR YOUR SAKE!!"
|
||||
480 GOTO 520
|
||||
510 PRINT "BYE!!!"
|
||||
500 PRINT "BYE!!!"
|
||||
520 END
|
||||
|
||||
196
25 Chief/java/src/Chief.java
Normal file
196
25 Chief/java/src/Chief.java
Normal file
@@ -0,0 +1,196 @@
|
||||
import java.util.Arrays;
|
||||
import java.util.Scanner;
|
||||
|
||||
public class Chief {
|
||||
|
||||
private enum GAME_STATE {
|
||||
STARTING,
|
||||
READY_TO_START,
|
||||
ENTER_NUMBER,
|
||||
CALCULATE_AND_SHOW,
|
||||
END_GAME,
|
||||
GAME_OVER
|
||||
}
|
||||
|
||||
private GAME_STATE gameState;
|
||||
|
||||
private double calculatedNumber;
|
||||
|
||||
// Used for keyboard input
|
||||
private final Scanner kbScanner;
|
||||
|
||||
public Chief() {
|
||||
|
||||
gameState = GAME_STATE.STARTING;
|
||||
|
||||
// Initialise kb scanner
|
||||
kbScanner = new Scanner(System.in);
|
||||
}
|
||||
|
||||
/**
|
||||
* Main game loop
|
||||
*/
|
||||
public void play() {
|
||||
|
||||
do {
|
||||
switch (gameState) {
|
||||
|
||||
// Show an introduction the first time the game is played.
|
||||
case STARTING:
|
||||
intro();
|
||||
gameState = GAME_STATE.READY_TO_START;
|
||||
break;
|
||||
|
||||
// show an message to start
|
||||
case READY_TO_START:
|
||||
if(!yesEntered(displayTextAndGetInput("ARE YOU READY TO TAKE THE TEST YOU CALLED ME OUT FOR? "))) {
|
||||
System.out.println("SHUT UP, PALE FACE WITH WISE TONGUE.");
|
||||
}
|
||||
|
||||
instructions();
|
||||
gameState = GAME_STATE.ENTER_NUMBER;
|
||||
break;
|
||||
|
||||
// Enter the number to be used to calculate
|
||||
case ENTER_NUMBER:
|
||||
double playerNumber = Double.parseDouble(
|
||||
displayTextAndGetInput(" WHAT DO YOU HAVE? "));
|
||||
|
||||
// Exact same formula used in the original game to calculate the players original number
|
||||
this.calculatedNumber = (playerNumber +1-5)*5/8*5-3;
|
||||
|
||||
this.gameState = GAME_STATE.CALCULATE_AND_SHOW;
|
||||
break;
|
||||
|
||||
// Enter the number to be used to calculate
|
||||
case CALCULATE_AND_SHOW:
|
||||
if(yesEntered(
|
||||
displayTextAndGetInput("I BET YOUR NUMBER WAS " + this.calculatedNumber
|
||||
+ ". AM I RIGHT? "))) {
|
||||
this.gameState = GAME_STATE.END_GAME;
|
||||
|
||||
} else {
|
||||
// Player did not agree, so show the breakdown
|
||||
double number = Double.parseDouble(
|
||||
displayTextAndGetInput(" WHAT WAS YOUR ORIGINAL NUMBER? "));
|
||||
double f = number + 3;
|
||||
double g = f / 5;
|
||||
double h = g * 8;
|
||||
double i = h/5 + 5;
|
||||
double j = i -1;
|
||||
System.out.println("SO YOU THINK YOU'RE SO SMART, EH?");
|
||||
System.out.println("NOW WATCH.");
|
||||
System.out.println(number +" PLUS 3 EQUALS " + f + ". THIS DIVIDED BY 5 EQUALS " + g);
|
||||
System.out.println("THIS TIMES 8 EQUALS " + h + ". IF WE DIVIDE BY 5 AND ADD 5,");
|
||||
System.out.println("WE GET " + i + ", WHICH, MINUS 1, EQUALS " + j + ".");
|
||||
if(yesEntered(displayTextAndGetInput("NOW DO YOU BELIEVE ME? "))) {
|
||||
this.gameState = GAME_STATE.END_GAME;
|
||||
} else {
|
||||
// Time for a lightning bolt.
|
||||
System.out.println("YOU HAVE MADE ME MAD!!!");
|
||||
System.out.println("THERE MUST BE A GREAT LIGHTNING BOLT!");
|
||||
System.out.println();
|
||||
for(int x=30; x>=22; x--) {
|
||||
System.out.println(tabbedSpaces(x) + "X X");
|
||||
}
|
||||
System.out.println(tabbedSpaces(21) + "X XXX");
|
||||
System.out.println(tabbedSpaces(20) + "X X");
|
||||
System.out.println(tabbedSpaces(19) + "XX X");
|
||||
for(int y=20; y>=13; y--) {
|
||||
System.out.println(tabbedSpaces(y) + "X X");
|
||||
}
|
||||
System.out.println(tabbedSpaces(12) + "XX");
|
||||
System.out.println(tabbedSpaces(11) + "X");
|
||||
System.out.println(tabbedSpaces(10) + "*");
|
||||
System.out.println();
|
||||
System.out.println("#########################");
|
||||
System.out.println();
|
||||
System.out.println("I HOPE YOU BELIEVE ME NOW, FOR YOUR SAKE!!");
|
||||
this.gameState = GAME_STATE.GAME_OVER;
|
||||
}
|
||||
|
||||
}
|
||||
break;
|
||||
|
||||
// Sign off message for cases where the Chief is not upset
|
||||
case END_GAME:
|
||||
System.out.println("BYE!!!");
|
||||
this.gameState = GAME_STATE.GAME_OVER;
|
||||
break;
|
||||
|
||||
// GAME_OVER State does not specifically have a case
|
||||
}
|
||||
} while (gameState != GAME_STATE.GAME_OVER);
|
||||
}
|
||||
|
||||
/**
|
||||
* Simulate tabs by building up a string of spaces
|
||||
*
|
||||
* @param spaces how many spaces are there to be
|
||||
* @return a string with the requested number of spaces
|
||||
*/
|
||||
private String tabbedSpaces(int spaces) {
|
||||
char[] repeat = new char[spaces];
|
||||
Arrays.fill(repeat, ' ');
|
||||
return new String(repeat);
|
||||
}
|
||||
private void instructions() {
|
||||
System.out.println(" TAKE A NUMBER AND ADD 3. DIVIDE THIS NUMBER BY 5 AND");
|
||||
System.out.println("MULTIPLY BY 8. DIVIDE BY 5 AND ADD THE SAME. SUBTRACT 1.");
|
||||
}
|
||||
|
||||
/**
|
||||
* Basic information about the game
|
||||
*
|
||||
*/
|
||||
private void intro() {
|
||||
System.out.println("CHIEF");
|
||||
System.out.println("CREATIVE COMPUTING MORRISTOWN, NEW JERSEY");
|
||||
System.out.println();
|
||||
System.out.println("I AM CHIEF NUMBERS FREEK, THE GREAT INDIAN MATH GOD.");
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if a given string is equal to at least one of the values specified in the call
|
||||
* to the stringIsAnyValue method
|
||||
*
|
||||
* @param text string to search
|
||||
* @return true if string is equal to one of the varargs
|
||||
*/
|
||||
private boolean yesEntered(String text) {
|
||||
return stringIsAnyValue(text, "Y", "YES");
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if a given string contains at least one of the varargs (2nd parameter).
|
||||
* Note: Case insensitive comparison.
|
||||
*
|
||||
* @param text string to search
|
||||
* @param values varargs of type string containing values to compare
|
||||
* @return true if one of the varargs arguments was found in text
|
||||
*/
|
||||
private boolean stringIsAnyValue(String text, String... values) {
|
||||
|
||||
// Cycle through the variable number of values and test each
|
||||
for(String val:values) {
|
||||
if(text.equalsIgnoreCase(val)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
// no matches
|
||||
return false;
|
||||
}
|
||||
|
||||
/*
|
||||
* Print a message on the screen, then accept input from Keyboard.
|
||||
*
|
||||
* @param text message to be displayed on screen.
|
||||
* @return what was typed by the player.
|
||||
*/
|
||||
private String displayTextAndGetInput(String text) {
|
||||
System.out.print(text);
|
||||
return kbScanner.next();
|
||||
}
|
||||
|
||||
}
|
||||
8
25 Chief/java/src/ChiefGame.java
Normal file
8
25 Chief/java/src/ChiefGame.java
Normal file
@@ -0,0 +1,8 @@
|
||||
public class ChiefGame {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
Chief chief = new Chief();
|
||||
chief.play();
|
||||
}
|
||||
}
|
||||
9
25 Chief/javascript/chief.html
Normal file
9
25 Chief/javascript/chief.html
Normal file
@@ -0,0 +1,9 @@
|
||||
<html>
|
||||
<head>
|
||||
<title>CHIEF</title>
|
||||
</head>
|
||||
<body>
|
||||
<pre id="output" style="font-size: 12pt;"></pre>
|
||||
<script src="chief.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
105
25 Chief/javascript/chief.js
Normal file
105
25 Chief/javascript/chief.js
Normal file
@@ -0,0 +1,105 @@
|
||||
// CHIEF
|
||||
//
|
||||
// Converted from BASIC to Javascript by Oscar Toledo G. (nanochess)
|
||||
//
|
||||
|
||||
function print(str)
|
||||
{
|
||||
document.getElementById("output").appendChild(document.createTextNode(str));
|
||||
}
|
||||
|
||||
function input()
|
||||
{
|
||||
var input_element;
|
||||
var input_str;
|
||||
|
||||
return new Promise(function (resolve) {
|
||||
input_element = document.createElement("INPUT");
|
||||
|
||||
print("? ");
|
||||
input_element.setAttribute("type", "text");
|
||||
input_element.setAttribute("length", "50");
|
||||
document.getElementById("output").appendChild(input_element);
|
||||
input_element.focus();
|
||||
input_str = undefined;
|
||||
input_element.addEventListener("keydown", function (event) {
|
||||
if (event.keyCode == 13) {
|
||||
input_str = input_element.value;
|
||||
document.getElementById("output").removeChild(input_element);
|
||||
print(input_str);
|
||||
print("\n");
|
||||
resolve(input_str);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function tab(space)
|
||||
{
|
||||
var str = "";
|
||||
while (space-- > 0)
|
||||
str += " ";
|
||||
return str;
|
||||
}
|
||||
|
||||
// Main program
|
||||
async function main()
|
||||
{
|
||||
print(tab(30) + "CHIEF\n");
|
||||
print(tab(15) + "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY\n");
|
||||
print("\n");
|
||||
print("\n");
|
||||
print("\n");
|
||||
print("I AM CHIEF NUMBERS FREEK, THE GREAT INDIAN MATH GOD.\n");
|
||||
print("ARE YOU READY TO TAKE THE TEST YOU CALLED ME OUT FOR");
|
||||
a = await input();
|
||||
if (a.substr(0, 1) != "Y")
|
||||
print("SHUT UP, PALE FACE WITH WIE TONGUE.\n");
|
||||
print(" TAKE A NUMBER AND ADD 3. DIVIDE THIS NUMBER BY 5 AND\n");
|
||||
print("MULTIPLY BY 8. DIVIDE BY 5 AND ADD THE SAME. SUBTRACT 1.\n");
|
||||
print(" WHAT DO YOU HAVE");
|
||||
b = parseFloat(await input());
|
||||
c = (b + 1 - 5) * 5 / 8 * 5 - 3;
|
||||
print("I BET YOUR NUMBER WAS " + Math.floor(c + 0.5) + ". AM I RIGHT");
|
||||
d = await input();
|
||||
if (d.substr(0, 1) != "Y") {
|
||||
print("WHAT WAS YOUR ORIGINAL NUMBER");
|
||||
k = parseFloat(await input());
|
||||
f = k + 3;
|
||||
g = f / 5;
|
||||
h = g * 8;
|
||||
i = h / 5 + 5;
|
||||
j = i - 1;
|
||||
print("SO YOU THINK YOU'RE SO SMART, EH?\n");
|
||||
print("NOW WATCH.\n");
|
||||
print(k + " PLUS 3 EQUALS " + f + ". THIS DIVIDED BY 5 EQUALS " + g + ";\n");
|
||||
print("THIS TIMES 8 EQUALS " + h + ". IF WE DIVIDE BY 5 AND ADD 5,\n");
|
||||
print("WE GET " + i + ", WHICH, MINUS 1, EQUALS " + j + ".\n");
|
||||
print("NOW DO YOU BELIEVE ME");
|
||||
z = await input();
|
||||
if (z.substr(0, 1) != "Y") {
|
||||
print("YOU HAVE MADE ME MAD!!!\n");
|
||||
print("THERE MUST BE A GREAT LIGHTNING BOLT!\n");
|
||||
print("\n");
|
||||
print("\n");
|
||||
for (x = 30; x >= 22; x--)
|
||||
print(tab(x) + "X X\n");
|
||||
print(tab(21) + "X XXX\n");
|
||||
print(tab(20) + "X X\n");
|
||||
print(tab(19) + "XX X\n");
|
||||
for (y = 20; y >= 13; y--)
|
||||
print(tab(y) + "X X\n");
|
||||
print(tab(12) + "XX\n");
|
||||
print(tab(11) + "X\n");
|
||||
print(tab(10) + "*\n");
|
||||
print("\n");
|
||||
print("#########################\n");
|
||||
print("\n");
|
||||
print("I HOPE YOU BELIEVE ME NOW, FOR YOUR SAKE!!\n");
|
||||
return;
|
||||
}
|
||||
}
|
||||
print("BYE!!!\n");
|
||||
}
|
||||
|
||||
main();
|
||||
217
44 Hangman/python/hangman.py
Executable file
217
44 Hangman/python/hangman.py
Executable file
@@ -0,0 +1,217 @@
|
||||
#!/usr/bin/env python3
|
||||
# HANGMAN
|
||||
#
|
||||
# Converted from BASIC to Python by Trevor Hobson and Daniel Piron
|
||||
|
||||
import random
|
||||
|
||||
|
||||
class Canvas:
|
||||
""" For drawing text-based figures """
|
||||
|
||||
def __init__(self, width=12, height=12, fill=" "):
|
||||
self._buffer = []
|
||||
for _ in range(height):
|
||||
line = []
|
||||
for _ in range(width):
|
||||
line.append("")
|
||||
self._buffer.append(line)
|
||||
|
||||
self.clear()
|
||||
|
||||
def clear(self, fill=" "):
|
||||
for row in self._buffer:
|
||||
for x in range(len(row)):
|
||||
row[x] = fill
|
||||
|
||||
def render(self):
|
||||
lines = []
|
||||
for line in self._buffer:
|
||||
# Joining by the empty string ("") smooshes all of the
|
||||
# individual characters together as one line.
|
||||
lines.append("".join(line))
|
||||
return "\n".join(lines)
|
||||
|
||||
def put(self, s, x, y):
|
||||
# In an effort to avoid distorting the drawn image, only write the
|
||||
# first character of the given string to the buffer.
|
||||
self._buffer[y][x] = s[0]
|
||||
|
||||
|
||||
def init_gallows(canvas):
|
||||
for i in range(12):
|
||||
canvas.put("X", 0, i)
|
||||
for i in range(7):
|
||||
canvas.put("X", i, 0)
|
||||
canvas.put("X", 6, 1)
|
||||
|
||||
|
||||
def draw_head(canvas):
|
||||
canvas.put("-", 5, 2)
|
||||
canvas.put("-", 6, 2)
|
||||
canvas.put("-", 7, 2)
|
||||
canvas.put("(", 4, 3)
|
||||
canvas.put(".", 5, 3)
|
||||
canvas.put(".", 7, 3)
|
||||
canvas.put(")", 8, 3)
|
||||
canvas.put("-", 5, 4)
|
||||
canvas.put("-", 6, 4)
|
||||
canvas.put("-", 7, 4)
|
||||
|
||||
|
||||
def draw_body(canvas):
|
||||
for i in range(5, 9, 1):
|
||||
canvas.put("X", 6, i)
|
||||
|
||||
|
||||
def draw_right_arm(canvas):
|
||||
for i in range(3, 7):
|
||||
canvas.put("\\", i - 1, i)
|
||||
|
||||
|
||||
def draw_left_arm(canvas):
|
||||
canvas.put("/", 10, 3)
|
||||
canvas.put("/", 9, 4)
|
||||
canvas.put("/", 8, 5)
|
||||
canvas.put("/", 7, 6)
|
||||
|
||||
|
||||
def draw_right_leg(canvas):
|
||||
canvas.put("/", 5, 9)
|
||||
canvas.put("/", 4, 10)
|
||||
|
||||
|
||||
def draw_left_leg(canvas):
|
||||
canvas.put("\\", 7, 9)
|
||||
canvas.put("\\", 8, 10)
|
||||
|
||||
|
||||
def draw_left_hand(canvas):
|
||||
canvas.put("\\", 10, 2)
|
||||
|
||||
|
||||
def draw_right_hand(canvas):
|
||||
canvas.put("/", 2, 2)
|
||||
|
||||
|
||||
def draw_left_foot(canvas):
|
||||
canvas.put("\\", 9, 11)
|
||||
canvas.put("-", 10, 11)
|
||||
|
||||
|
||||
def draw_right_foot(canvas):
|
||||
canvas.put("-", 2, 11)
|
||||
canvas.put("/", 3, 11)
|
||||
|
||||
|
||||
PHASES = (
|
||||
("First, we draw a head", draw_head),
|
||||
("Now we draw a body.", draw_body),
|
||||
("Next we draw an arm.", draw_right_arm),
|
||||
("this time it's the other arm.", draw_left_arm),
|
||||
("Now, let's draw the right leg.", draw_right_leg),
|
||||
("This time we draw the left leg.", draw_left_leg),
|
||||
("Now we put up a hand.", draw_left_hand),
|
||||
("Next the other hand.", draw_right_hand),
|
||||
("Now we draw one foot", draw_left_foot),
|
||||
("Here's the other foot -- you're hung!!", draw_right_foot)
|
||||
)
|
||||
|
||||
|
||||
words = ["GUM", "SIN", "FOR", "CRY", "LUG", "BYE", "FLY",
|
||||
"UGLY", "EACH", "FROM", "WORK", "TALK", "WITH", "SELF",
|
||||
"PIZZA", "THING", "FEIGN", "FIEND", "ELBOW", "FAULT", "DIRTY",
|
||||
"BUDGET", "SPIRIT", "QUAINT", "MAIDEN", "ESCORT", "PICKAX",
|
||||
"EXAMPLE", "TENSION", "QUININE", "KIDNEY", "REPLICA", "SLEEPER",
|
||||
"TRIANGLE", "KANGAROO", "MAHOGANY", "SERGEANT", "SEQUENCE",
|
||||
"MOUSTACHE", "DANGEROUS", "SCIENTIST", "DIFFERENT", "QUIESCENT",
|
||||
"MAGISTRATE", "ERRONEOUSLY", "LOUDSPEAKER", "PHYTOTOXIC",
|
||||
"MATRIMONIAL", "PARASYMPATHOMIMETIC", "THIGMOTROPISM"]
|
||||
|
||||
|
||||
def play_game(guess_target):
|
||||
"""Play one round of the game"""
|
||||
wrong_guesses = 0
|
||||
guess_progress = ["-"] * len(guess_target)
|
||||
guess_list = []
|
||||
|
||||
gallows = Canvas()
|
||||
init_gallows(gallows)
|
||||
|
||||
guess_count = 0
|
||||
while True:
|
||||
print("Here are the letters you used:")
|
||||
print(",".join(guess_list) + "\n")
|
||||
print("".join(guess_progress) + "\n")
|
||||
guess_letter = ""
|
||||
guess_word = ""
|
||||
while guess_letter == "":
|
||||
|
||||
guess_letter = input("What is your guess? ").upper()[0]
|
||||
if not guess_letter.isalpha():
|
||||
guess_letter = ""
|
||||
print("Only letters are allowed!")
|
||||
elif guess_letter in guess_list:
|
||||
guess_letter = ""
|
||||
print("You guessed that letter before!")
|
||||
|
||||
guess_list.append(guess_letter)
|
||||
guess_count += 1
|
||||
if guess_letter in guess_target:
|
||||
indices = [i for i, letter in enumerate(guess_target) if letter == guess_letter]
|
||||
for i in indices:
|
||||
guess_progress[i] = guess_letter
|
||||
if guess_progress == guess_target:
|
||||
print("You found the word!")
|
||||
break
|
||||
else:
|
||||
print("\n" + "".join(guess_progress) + "\n")
|
||||
while guess_word == "":
|
||||
guess_word = input("What is your guess for the word? ").upper()
|
||||
if not guess_word.isalpha():
|
||||
guess_word = ""
|
||||
print("Only words are allowed!")
|
||||
if guess_word == guess_target:
|
||||
print("Right!! It took you", guess_count, "guesses!")
|
||||
break
|
||||
else:
|
||||
comment, draw_bodypart = PHASES[wrong_guesses]
|
||||
|
||||
print(comment)
|
||||
draw_bodypart(gallows)
|
||||
print(gallows.render())
|
||||
|
||||
wrong_guesses += 1
|
||||
print("Sorry, that letter isn't in the word.")
|
||||
|
||||
if wrong_guesses == 10:
|
||||
print("Sorry, you lose. The word was " + guess_target)
|
||||
break
|
||||
|
||||
|
||||
def main():
|
||||
print(" " * 32 + "HANGMAN")
|
||||
print(" " * 15 + "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY\n")
|
||||
|
||||
random.shuffle(words)
|
||||
current_word = 0
|
||||
word_count = len(words)
|
||||
|
||||
keep_playing = True
|
||||
while keep_playing:
|
||||
|
||||
play_game(words[current_word])
|
||||
current_word += 1
|
||||
|
||||
if current_word == word_count:
|
||||
print("You did all the words!!")
|
||||
keep_playing = False
|
||||
else:
|
||||
keep_playing = input("Want another word? (yes or no) ").lower().startswith("y")
|
||||
|
||||
print("It's been fun! Bye for now.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
214
47 Hi-Lo/java/src/HiLo.java
Normal file
214
47 Hi-Lo/java/src/HiLo.java
Normal file
@@ -0,0 +1,214 @@
|
||||
import java.util.Scanner;
|
||||
|
||||
/**
|
||||
* Game of HiLo
|
||||
*
|
||||
* Based on the Basic game of Hi-Lo here
|
||||
* https://github.com/coding-horror/basic-computer-games/blob/main/47%20Hi-Lo/hi-lo.bas
|
||||
*
|
||||
* Note: The idea was to create a version of this 1970's Basic game in Java, without introducing
|
||||
* new features - no additional text, error checking, etc has been added.
|
||||
*/
|
||||
public class HiLo {
|
||||
|
||||
public static final int LOW_NUMBER_RANGE = 1;
|
||||
public static final int HIGH_NUMBER_RANGE = 100;
|
||||
public static final int MAX_GUESSES = 6;
|
||||
|
||||
private enum GAME_STATE {
|
||||
STARTING,
|
||||
START_GAME,
|
||||
GUESSING,
|
||||
PLAY_AGAIN,
|
||||
GAME_OVER
|
||||
}
|
||||
|
||||
// Used for keyboard input
|
||||
private Scanner kbScanner;
|
||||
|
||||
// Current game state
|
||||
private GAME_STATE gameState;
|
||||
|
||||
// Players Winnings
|
||||
private int playerAmountWon;
|
||||
|
||||
// Players guess count;
|
||||
private int playersGuesses;
|
||||
|
||||
// Computers random number
|
||||
private int computersNumber;
|
||||
|
||||
public HiLo() {
|
||||
|
||||
this.gameState = GAME_STATE.STARTING;
|
||||
this.playerAmountWon = 0;
|
||||
|
||||
// Initialise kb scanner
|
||||
kbScanner = new Scanner(System.in);
|
||||
}
|
||||
|
||||
/**
|
||||
* Main game loop
|
||||
*
|
||||
*/
|
||||
public void play() {
|
||||
|
||||
do {
|
||||
switch (gameState) {
|
||||
|
||||
// Show an introduction the first time the game is played.
|
||||
case STARTING:
|
||||
intro();
|
||||
gameState = GAME_STATE.START_GAME;
|
||||
break;
|
||||
|
||||
// Generate computers number for player to guess, etc.
|
||||
case START_GAME:
|
||||
init();
|
||||
System.out.println("O.K. I HAVE A NUMBER IN MIND.");
|
||||
this.gameState = GAME_STATE.GUESSING;
|
||||
break;
|
||||
|
||||
// Player guesses the number until they get it or run out of guesses
|
||||
case GUESSING:
|
||||
int guess = playerGuess();
|
||||
|
||||
// Check if the player guessed the number
|
||||
if(validateGuess(guess)) {
|
||||
System.out.println("GOT IT!!!!!!!!!! YOU WIN " + this.computersNumber
|
||||
+ " DOLLARS.");
|
||||
this.playerAmountWon += this.computersNumber;
|
||||
System.out.println("YOUR TOTAL WINNINGS ARE NOW "
|
||||
+ this.playerAmountWon + " DOLLARS.");
|
||||
this.gameState = GAME_STATE.PLAY_AGAIN;
|
||||
} else {
|
||||
// incorrect guess
|
||||
this.playersGuesses++;
|
||||
// Ran out of guesses?
|
||||
if (this.playersGuesses == MAX_GUESSES) {
|
||||
System.out.println("YOU BLEW IT...TOO BAD...THE NUMBER WAS "
|
||||
+ this.computersNumber);
|
||||
this.playerAmountWon = 0;
|
||||
this.gameState = GAME_STATE.PLAY_AGAIN;
|
||||
}
|
||||
}
|
||||
break;
|
||||
|
||||
// Play again, or exit game?
|
||||
case PLAY_AGAIN:
|
||||
System.out.println();
|
||||
if(yesEntered(displayTextAndGetInput("PLAY AGAIN (YES OR NO) "))) {
|
||||
this.gameState = GAME_STATE.START_GAME;
|
||||
} else {
|
||||
// Chose not to play again
|
||||
System.out.println("SO LONG. HOPE YOU ENJOYED YOURSELF!!!");
|
||||
this.gameState = GAME_STATE.GAME_OVER;
|
||||
}
|
||||
}
|
||||
} while (gameState != GAME_STATE.GAME_OVER);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks the players guess against the computers randomly generated number
|
||||
*
|
||||
* @param theGuess
|
||||
* @return true if the player guessed correctly, false otherwise
|
||||
*/
|
||||
private boolean validateGuess(int theGuess) {
|
||||
|
||||
// Correct guess?
|
||||
if(theGuess == this.computersNumber) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if(theGuess > this.computersNumber) {
|
||||
System.out.println("YOUR GUESS IS TOO HIGH.");
|
||||
} else {
|
||||
System.out.println("YOUR GUESS IS TOO LOW.");
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private void init() {
|
||||
this.playersGuesses = 0;
|
||||
this.computersNumber = randomNumber();
|
||||
}
|
||||
|
||||
public void intro() {
|
||||
System.out.println("HI LO");
|
||||
System.out.println("CREATIVE COMPUTING MORRISTOWN, NEW JERSEY");
|
||||
System.out.println();
|
||||
System.out.println();
|
||||
System.out.println("THIS IS THE GAME OF HI LO.");
|
||||
System.out.println();
|
||||
System.out.println("YOU WILL HAVE 6 TRIES TO GUESS THE AMOUNT OF MONEY IN THE");
|
||||
System.out.println("HI LO JACKPOT, WHICH IS BETWEEN 1 AND 100 DOLLARS. IF YOU");
|
||||
System.out.println("GUESS THE AMOUNT, YOU WIN ALL THE MONEY IN THE JACKPOT!");
|
||||
System.out.println("THEN YOU GET ANOTHER CHANCE TO WIN MORE MONEY. HOWEVER,");
|
||||
System.out.println("IF YOU DO NOT GUESS THE AMOUNT, THE GAME ENDS.");
|
||||
}
|
||||
|
||||
/**
|
||||
* Get players guess from kb
|
||||
*
|
||||
* @return players guess as an int
|
||||
*/
|
||||
private int playerGuess() {
|
||||
return Integer.valueOf((displayTextAndGetInput("YOUR GUESS? ")));
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether player entered Y or YES to a question.
|
||||
*
|
||||
* @param text player string from kb
|
||||
* @return true of Y or YES was entered, otherwise false
|
||||
*/
|
||||
private boolean yesEntered(String text) {
|
||||
return stringIsAnyValue(text, new String[] {"Y", "YES"});
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether a string equals one of a variable number of values
|
||||
* Useful to check for Y or YES for example
|
||||
* Comparison is case insensitive.
|
||||
*
|
||||
* @param text source string
|
||||
* @param values a range of values to compare against the source string
|
||||
* @return true if a comparison was found in one of the variable number of strings passed
|
||||
*/
|
||||
private boolean stringIsAnyValue(String text, String... values) {
|
||||
|
||||
// Cycle through the variable number of values and test each
|
||||
for(String val:values) {
|
||||
if(text.equalsIgnoreCase(val)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
// no matches
|
||||
return false;
|
||||
}
|
||||
|
||||
/*
|
||||
* Print a message on the screen, then accept input from Keyboard.
|
||||
*
|
||||
* @param text message to be displayed on screen.
|
||||
* @return what was typed by the player.
|
||||
*/
|
||||
private String displayTextAndGetInput(String text) {
|
||||
System.out.print(text);
|
||||
return kbScanner.next();
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate random number
|
||||
* Used as a single digit of the computer player
|
||||
*
|
||||
* @return random number
|
||||
*/
|
||||
private int randomNumber() {
|
||||
return (int) (Math.random()
|
||||
* (HIGH_NUMBER_RANGE - LOW_NUMBER_RANGE + 1) + LOW_NUMBER_RANGE);
|
||||
}
|
||||
}
|
||||
8
47 Hi-Lo/java/src/HiLoGame.java
Normal file
8
47 Hi-Lo/java/src/HiLoGame.java
Normal file
@@ -0,0 +1,8 @@
|
||||
public class HiLoGame {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
HiLo hiLo = new HiLo();
|
||||
hiLo.play();
|
||||
}
|
||||
}
|
||||
186
51 Hurkle/java/src/Hurkle.java
Normal file
186
51 Hurkle/java/src/Hurkle.java
Normal file
@@ -0,0 +1,186 @@
|
||||
import java.util.ArrayList;
|
||||
import java.util.Scanner;
|
||||
|
||||
public class Hurkle {
|
||||
|
||||
public static final int GRID_SIZE = 10;
|
||||
public static final int MAX_GUESSES = 5;
|
||||
|
||||
private enum GAME_STATE {
|
||||
STARTING,
|
||||
START_GAME,
|
||||
GUESSING,
|
||||
PLAY_AGAIN,
|
||||
GAME_OVER
|
||||
}
|
||||
|
||||
private GAME_STATE gameState;
|
||||
|
||||
// Used for keyboard input
|
||||
private Scanner kbScanner;
|
||||
|
||||
private int guesses;
|
||||
|
||||
// hurkle position
|
||||
private int hurkleXPos;
|
||||
private int hurkleYPos;
|
||||
|
||||
// player guess
|
||||
private int playerGuessXPos;
|
||||
private int playerGuessYPos;
|
||||
|
||||
public Hurkle() {
|
||||
|
||||
gameState = GAME_STATE.STARTING;
|
||||
|
||||
// Initialise kb scanner
|
||||
kbScanner = new Scanner(System.in);
|
||||
}
|
||||
|
||||
/**
|
||||
* Main game loop
|
||||
*/
|
||||
public void play() {
|
||||
|
||||
do {
|
||||
switch (gameState) {
|
||||
|
||||
// Show an introduction the first time the game is played.
|
||||
case STARTING:
|
||||
intro();
|
||||
gameState = GAME_STATE.START_GAME;
|
||||
break;
|
||||
|
||||
// Start the game, set the number of players, names and round
|
||||
case START_GAME:
|
||||
|
||||
this.hurkleXPos = randomNumber();
|
||||
this.hurkleYPos = randomNumber();
|
||||
System.out.println("HURKLE AT : " + this.hurkleXPos + "," + this.hurkleYPos);
|
||||
|
||||
this.guesses = 1;
|
||||
gameState = GAME_STATE.GUESSING;
|
||||
|
||||
break;
|
||||
|
||||
// Guess an x,y position of the hurkle
|
||||
case GUESSING:
|
||||
String guess = displayTextAndGetInput("GUESS #" + this.guesses + "? ");
|
||||
this.playerGuessXPos = getDelimitedValue(guess, 0);
|
||||
this.playerGuessYPos = getDelimitedValue(guess, 1);
|
||||
if (foundHurkle()) {
|
||||
this.gameState = GAME_STATE.PLAY_AGAIN;
|
||||
} else {
|
||||
showDirectionOfHurkle();
|
||||
this.guesses++;
|
||||
if(this.guesses > MAX_GUESSES) {
|
||||
System.out.println("SORRY, THAT'S "
|
||||
+ MAX_GUESSES + " GUESSES.");
|
||||
System.out.println("THE HURKLE IS AT "
|
||||
+ this.hurkleXPos + "," + this.hurkleYPos);
|
||||
System.out.println();
|
||||
this.gameState = GAME_STATE.PLAY_AGAIN;
|
||||
}
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
case PLAY_AGAIN:
|
||||
System.out.println("LET'S PLAY AGAIN, HURKLE IS HIDING.");
|
||||
System.out.println();
|
||||
this.gameState = GAME_STATE.START_GAME;
|
||||
break;
|
||||
}
|
||||
// Effectively an endless loop because the game never quits as per
|
||||
// the original basic code.
|
||||
} while (gameState != GAME_STATE.GAME_OVER);
|
||||
}
|
||||
|
||||
private void showDirectionOfHurkle() {
|
||||
System.out.print("GO ");
|
||||
if(this.playerGuessYPos == this.hurkleYPos) {
|
||||
// don't print North or South because the player has chosen the
|
||||
// same y grid pos as the hurkle
|
||||
} else if (this.playerGuessYPos < this.hurkleYPos) {
|
||||
System.out.print("NORTH");
|
||||
} else if(this.playerGuessYPos > this.hurkleYPos) {
|
||||
System.out.print("SOUTH");
|
||||
}
|
||||
|
||||
if(this.playerGuessXPos == this.hurkleXPos) {
|
||||
// don't print East or West because the player has chosen the
|
||||
// same x grid pos as the hurkle
|
||||
} else if(this.playerGuessXPos < this.hurkleXPos) {
|
||||
System.out.print("EAST");
|
||||
} else if(this.playerGuessXPos > this.hurkleXPos) {
|
||||
System.out.print("WEST");
|
||||
}
|
||||
System.out.println();
|
||||
return;
|
||||
}
|
||||
|
||||
private boolean foundHurkle() {
|
||||
if ((this.playerGuessXPos - this.hurkleXPos)
|
||||
- (this.playerGuessYPos - this.hurkleYPos) == 0) {
|
||||
System.out.println("YOU FOUND HIM IN " + this.guesses + " GUESSES.");
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Display info about the game
|
||||
*/
|
||||
private void intro() {
|
||||
System.out.println("HURKLE");
|
||||
System.out.println("CREATIVE COMPUTING MORRISTOWN, NEW JERSEY");
|
||||
System.out.println();
|
||||
System.out.println("A HURKLE IS HIDING ON A " + GRID_SIZE + " BY "
|
||||
+ GRID_SIZE + " GRID. HOMEBASE");
|
||||
System.out.println("ON THE GRID IS POINT 0,0 IN THE SOUTHWEST CORNER,");
|
||||
System.out.println("AND ANY POINT ON THE GRID IS DESIGNATED BY A");
|
||||
System.out.println("PAIR OF WHOLE NUMBERS SEPERATED BY A COMMA. THE FIRST");
|
||||
System.out.println("NUMBER IS THE HORIZONTAL POSITION AND THE SECOND NUMBER");
|
||||
System.out.println("IS THE VERTICAL POSITION. YOU MUST TRY TO");
|
||||
System.out.println("GUESS THE HURKLE'S GRIDPOINT. YOU GET "
|
||||
+ MAX_GUESSES + " TRIES.");
|
||||
System.out.println("AFTER EACH TRY, I WILL TELL YOU THE APPROXIMATE");
|
||||
System.out.println("DIRECTION TO GO TO LOOK FOR THE HURKLE.");
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate random number
|
||||
* Used to create one part of an x,y grid position
|
||||
*
|
||||
* @return random number
|
||||
*/
|
||||
private int randomNumber() {
|
||||
return (int) (Math.random()
|
||||
* (GRID_SIZE) + 1);
|
||||
}
|
||||
|
||||
/*
|
||||
* Print a message on the screen, then accept input from Keyboard.
|
||||
*
|
||||
* @param text message to be displayed on screen.
|
||||
* @return what was typed by the player.
|
||||
*/
|
||||
private String displayTextAndGetInput(String text) {
|
||||
System.out.print(text);
|
||||
return kbScanner.next();
|
||||
}
|
||||
|
||||
/**
|
||||
* Accepts a string delimited by comma's and returns the pos'th delimited
|
||||
* value (starting at count 0).
|
||||
*
|
||||
* @param text - text with values separated by comma's
|
||||
* @param pos - which position to return a value for
|
||||
* @return the int representation of the value
|
||||
*/
|
||||
private int getDelimitedValue(String text, int pos) {
|
||||
String[] tokens = text.split(",");
|
||||
return Integer.parseInt(tokens[pos]);
|
||||
}
|
||||
}
|
||||
7
51 Hurkle/java/src/HurkleGame.java
Normal file
7
51 Hurkle/java/src/HurkleGame.java
Normal file
@@ -0,0 +1,7 @@
|
||||
public class HurkleGame {
|
||||
|
||||
public static void main(String[] args) {
|
||||
Hurkle hurkle = new Hurkle();
|
||||
hurkle.play();
|
||||
}
|
||||
}
|
||||
308
69 Pizza/java/src/Pizza.java
Normal file
308
69 Pizza/java/src/Pizza.java
Normal file
@@ -0,0 +1,308 @@
|
||||
import java.util.Scanner;
|
||||
|
||||
public class Pizza {
|
||||
|
||||
private final int MAX_DELIVERIES = 5;
|
||||
|
||||
private enum GAME_STATE {
|
||||
STARTING,
|
||||
ENTER_NAME,
|
||||
DRAW_MAP,
|
||||
MORE_DIRECTIONS,
|
||||
START_DELIVER,
|
||||
DELIVER_PIZZA,
|
||||
TOO_DIFFICULT,
|
||||
END_GAME,
|
||||
GAME_OVER
|
||||
}
|
||||
|
||||
// houses that can order pizza
|
||||
private final char[] houses = new char[] { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I',
|
||||
'J', 'K', 'L', 'M', 'N', 'O', 'P'};
|
||||
|
||||
// size of grid
|
||||
private final int[] gridPos = new int[] { 1, 2, 3, 4};
|
||||
|
||||
private GAME_STATE gameState;
|
||||
|
||||
private String playerName;
|
||||
|
||||
// How many pizzas have been successfully delivered
|
||||
private int pizzaDeliveryCount;
|
||||
|
||||
// current house that ordered a pizza
|
||||
private int currentHouseDelivery;
|
||||
|
||||
// Used for keyboard input
|
||||
private final Scanner kbScanner;
|
||||
|
||||
public Pizza() {
|
||||
|
||||
this.gameState = GAME_STATE.STARTING;
|
||||
|
||||
// Initialise kb scanner
|
||||
kbScanner = new Scanner(System.in);
|
||||
}
|
||||
|
||||
/**
|
||||
* Main game loop
|
||||
*/
|
||||
public void play() {
|
||||
|
||||
do {
|
||||
switch (this.gameState) {
|
||||
|
||||
// Show an introduction the first time the game is played.
|
||||
case STARTING:
|
||||
init();
|
||||
intro();
|
||||
this.gameState = GAME_STATE.ENTER_NAME;
|
||||
break;
|
||||
|
||||
// Enter the players name
|
||||
case ENTER_NAME:
|
||||
this.playerName = displayTextAndGetInput("WHAT IS YOUR FIRST NAME? ");
|
||||
System.out.println("HI " + this.playerName + ". IN THIS GAME YOU ARE TO TAKE ORDERS");
|
||||
System.out.println("FOR PIZZAS. THEN YOU ARE TO TELL A DELIVERY BOY");
|
||||
System.out.println("WHERE TO DELIVER THE ORDERED PIZZAS.");
|
||||
System.out.println();
|
||||
this.gameState = GAME_STATE.DRAW_MAP;
|
||||
break;
|
||||
|
||||
// Draw the map
|
||||
case DRAW_MAP:
|
||||
drawMap();
|
||||
this.gameState = GAME_STATE.MORE_DIRECTIONS;
|
||||
break;
|
||||
|
||||
// need more directions (how to play) ?
|
||||
case MORE_DIRECTIONS:
|
||||
extendedIntro();
|
||||
String moreInfo = displayTextAndGetInput("DO YOU NEED MORE DIRECTIONS? ");
|
||||
if(!yesOrNoEntered(moreInfo)) {
|
||||
System.out.println("'YES' OR 'NO' PLEASE, NOW THEN,");
|
||||
} else {
|
||||
// More instructions selected
|
||||
if(yesEntered(moreInfo)) {
|
||||
displayMoreDirections();
|
||||
// Player understand now?
|
||||
if (yesEntered(displayTextAndGetInput("UNDERSTAND? "))) {
|
||||
System.out.println("GOOD. YOU ARE NOW READY TO START TAKING ORDERS.");
|
||||
System.out.println();
|
||||
System.out.println("GOOD LUCK!!");
|
||||
System.out.println();
|
||||
this.gameState = GAME_STATE.START_DELIVER;
|
||||
} else {
|
||||
// Not understood, essentially game over
|
||||
this.gameState = GAME_STATE.TOO_DIFFICULT;
|
||||
}
|
||||
} else {
|
||||
// no more directions were needed, start delivering pizza
|
||||
this.gameState = GAME_STATE.START_DELIVER;
|
||||
}
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
// Too difficult to understand, game over!
|
||||
case TOO_DIFFICULT:
|
||||
System.out.println("THIS JOB IS DEFINITELY TOO DIFFICULT FOR YOU. THANKS ANYWAY");
|
||||
this.gameState = GAME_STATE.GAME_OVER;
|
||||
break;
|
||||
|
||||
// Delivering pizza
|
||||
case START_DELIVER:
|
||||
// select a random house and "order" a pizza for them.
|
||||
this.currentHouseDelivery = (int) (Math.random()
|
||||
* (this.houses.length) + 1) -1; // Deduct 1 for 0-based array
|
||||
|
||||
System.out.println("HELLO " + this.playerName + "'S PIZZA. THIS IS "
|
||||
+ this.houses[this.currentHouseDelivery] + ".");
|
||||
System.out.println(" PLEASE SEND A PIZZA.");
|
||||
this.gameState = GAME_STATE.DELIVER_PIZZA;
|
||||
break;
|
||||
|
||||
// Try and deliver the pizza
|
||||
case DELIVER_PIZZA:
|
||||
|
||||
String question = " DRIVER TO " + this.playerName + ": WHERE DOES "
|
||||
+ this.houses[this.currentHouseDelivery] + " LIVE ? ";
|
||||
String answer = displayTextAndGetInput(question);
|
||||
|
||||
// Convert x,y entered by player to grid position of a house
|
||||
int x = getDelimitedValue(answer, 0);
|
||||
int y = getDelimitedValue(answer, 1);
|
||||
int calculatedPos = (x + (y -1) * 4) -1;
|
||||
|
||||
// Did the player select the right house to deliver?
|
||||
if(calculatedPos == this.currentHouseDelivery) {
|
||||
System.out.println("HELLO " + this.playerName + ". THIS IS " + this.houses[this.currentHouseDelivery]
|
||||
+ ", THANKS FOR THE PIZZA.");
|
||||
this.pizzaDeliveryCount++;
|
||||
|
||||
// Delivered enough pizza?
|
||||
|
||||
if(this.pizzaDeliveryCount > MAX_DELIVERIES) {
|
||||
this.gameState = GAME_STATE.END_GAME;
|
||||
} else {
|
||||
this.gameState = GAME_STATE.START_DELIVER;
|
||||
}
|
||||
} else {
|
||||
System.out.println("THIS IS " + houses[calculatedPos] + ". I DID NOT ORDER A PIZZA.");
|
||||
System.out.println("I LIVE AT " + x + "," + y);
|
||||
// Don't change gameState so this state is executed again
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
// Sign off message for cases where the Chief is not upset
|
||||
case END_GAME:
|
||||
if(yesEntered(displayTextAndGetInput("DO YOU WANT TO DELIVER MORE PIZZAS? "))) {
|
||||
init();
|
||||
this.gameState = GAME_STATE.START_DELIVER;
|
||||
} else {
|
||||
System.out.println();
|
||||
System.out.println("O.K. " + this.playerName + ", SEE YOU LATER!");
|
||||
System.out.println();
|
||||
this.gameState = GAME_STATE.GAME_OVER;
|
||||
}
|
||||
break;
|
||||
|
||||
// GAME_OVER State does not specifically have a case
|
||||
}
|
||||
} while (this.gameState != GAME_STATE.GAME_OVER);
|
||||
}
|
||||
|
||||
private void drawMap() {
|
||||
|
||||
System.out.println("MAP OF THE CITY OF HYATTSVILLE");
|
||||
System.out.println();
|
||||
System.out.println(" -----1-----2-----3-----4-----");
|
||||
int k = 3;
|
||||
for(int i=1; i<5; i++) {
|
||||
System.out.println("-");
|
||||
System.out.println("-");
|
||||
System.out.println("-");
|
||||
System.out.println("-");
|
||||
|
||||
System.out.print(this.gridPos[k]);
|
||||
int pos = 16 - 4 * i;
|
||||
System.out.print(" " + this.houses[pos]);
|
||||
System.out.print(" " + this.houses[pos + 1]);
|
||||
System.out.print(" " + this.houses[pos + 2]);
|
||||
System.out.print(" " + this.houses[pos + 3]);
|
||||
System.out.println(" " + this.gridPos[k]);
|
||||
k = k - 1;
|
||||
}
|
||||
System.out.println("-");
|
||||
System.out.println("-");
|
||||
System.out.println("-");
|
||||
System.out.println("-");
|
||||
System.out.println(" -----1-----2-----3-----4-----");
|
||||
}
|
||||
/**
|
||||
* Basic information about the game
|
||||
*
|
||||
*/
|
||||
private void intro() {
|
||||
System.out.println("PIZZA");
|
||||
System.out.println("CREATIVE COMPUTING MORRISTOWN, NEW JERSEY");
|
||||
System.out.println();
|
||||
System.out.println();
|
||||
System.out.println("PIZZA DELIVERY GAME");
|
||||
System.out.println();
|
||||
}
|
||||
|
||||
private void extendedIntro() {
|
||||
System.out.println("THE OUTPUT IS A MAP OF THE HOMES WHERE");
|
||||
System.out.println("YOU ARE TO SEND PIZZAS.");
|
||||
System.out.println();
|
||||
System.out.println("YOUR JOB IS TO GIVE A TRUCK DRIVER");
|
||||
System.out.println("THE LOCATION OR COORDINATES OF THE");
|
||||
System.out.println("HOME ORDERING THE PIZZA.");
|
||||
System.out.println();
|
||||
}
|
||||
|
||||
private void displayMoreDirections() {
|
||||
System.out.println();
|
||||
System.out.println("SOMEBODY WILL ASK FOR A PIZZA TO BE");
|
||||
System.out.println("DELIVERED. THEN A DELIVERY BOY WILL");
|
||||
System.out.println("ASK YOU FOR THE LOCATION.");
|
||||
System.out.println(" EXAMPLE:");
|
||||
System.out.println("THIS IS J. PLEASE SEND A PIZZA.");
|
||||
System.out.println("DRIVER TO " + this.playerName + ". WHERE DOES J LIVE?");
|
||||
System.out.println("YOUR ANSWER WOULD BE 2,3");
|
||||
System.out.println();
|
||||
}
|
||||
|
||||
private void init() {
|
||||
this.pizzaDeliveryCount = 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Accepts a string delimited by comma's and returns the nth delimited
|
||||
* value (starting at count 0).
|
||||
*
|
||||
* @param text - text with values separated by comma's
|
||||
* @param pos - which position to return a value for
|
||||
* @return the int representation of the value
|
||||
*/
|
||||
private int getDelimitedValue(String text, int pos) {
|
||||
String[] tokens = text.split(",");
|
||||
return Integer.parseInt(tokens[pos]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if a given string is equal to at least one of the values specified in the call
|
||||
* to the stringIsAnyValue method
|
||||
*
|
||||
* @param text string to search
|
||||
* @return true if string is equal to one of the varargs
|
||||
*/
|
||||
private boolean yesEntered(String text) {
|
||||
return stringIsAnyValue(text, "Y", "YES");
|
||||
}
|
||||
|
||||
/**
|
||||
* returns true if Y, YES, N, or NO was the compared value in text
|
||||
* case-insensitive
|
||||
*
|
||||
* @param text search string
|
||||
* @return true if one of the varargs was found in text
|
||||
*/
|
||||
private boolean yesOrNoEntered(String text) {
|
||||
return stringIsAnyValue(text, "Y", "YES", "N", "NO");
|
||||
}
|
||||
/**
|
||||
* Returns true if a given string contains at least one of the varargs (2nd parameter).
|
||||
* Note: Case insensitive comparison.
|
||||
*
|
||||
* @param text string to search
|
||||
* @param values varargs of type string containing values to compare
|
||||
* @return true if one of the varargs arguments was found in text
|
||||
*/
|
||||
private boolean stringIsAnyValue(String text, String... values) {
|
||||
|
||||
// Cycle through the variable number of values and test each
|
||||
for(String val:values) {
|
||||
if(text.equalsIgnoreCase(val)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
// no matches
|
||||
return false;
|
||||
}
|
||||
|
||||
/*
|
||||
* Print a message on the screen, then accept input from Keyboard.
|
||||
*
|
||||
* @param text message to be displayed on screen.
|
||||
* @return what was typed by the player.
|
||||
*/
|
||||
private String displayTextAndGetInput(String text) {
|
||||
System.out.print(text);
|
||||
return kbScanner.next();
|
||||
}
|
||||
|
||||
}
|
||||
8
69 Pizza/java/src/PizzaGame.java
Normal file
8
69 Pizza/java/src/PizzaGame.java
Normal file
@@ -0,0 +1,8 @@
|
||||
public class PizzaGame {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
Pizza pizza = new Pizza();
|
||||
pizza.play();
|
||||
}
|
||||
}
|
||||
84
74 Rock Scissors Paper/python/rockscissors.py
Normal file
84
74 Rock Scissors Paper/python/rockscissors.py
Normal file
@@ -0,0 +1,84 @@
|
||||
#!/usr/bin/env python3
|
||||
# ROCKSCISSORS
|
||||
#
|
||||
# Converted from BASIC to Python by Trevor Hobson
|
||||
|
||||
import random
|
||||
|
||||
|
||||
def play_game():
|
||||
"""Play one round of the game"""
|
||||
|
||||
while True:
|
||||
try:
|
||||
games = int(input("How many games? "))
|
||||
if games >= 11:
|
||||
print("Sorry, but we aren't allowed to play that many.")
|
||||
else:
|
||||
break
|
||||
|
||||
except ValueError:
|
||||
print("Please enter a number.")
|
||||
|
||||
won_computer = 0
|
||||
won_human = 0
|
||||
|
||||
for game in range(games):
|
||||
print("\nGame number", game + 1)
|
||||
guess_computer = random.randint(1, 3)
|
||||
print("3=Rock...2=Scissors...1=Paper")
|
||||
guess_human = 0
|
||||
while guess_human == 0:
|
||||
try:
|
||||
guess_human = int(input("1...2...3...What's your choice "))
|
||||
if guess_human not in [1, 2, 3]:
|
||||
guess_human = 0
|
||||
print("Invalid")
|
||||
|
||||
except ValueError:
|
||||
print("Please enter a number.")
|
||||
print("This is my choice...")
|
||||
if guess_computer == 1:
|
||||
print("...Paper")
|
||||
elif guess_computer == 2:
|
||||
print("...Scissors")
|
||||
elif guess_computer == 3:
|
||||
print("...Rock")
|
||||
if guess_computer == guess_human:
|
||||
print("Tie Game. No winner")
|
||||
elif guess_computer > guess_human:
|
||||
if guess_human != 1 or guess_computer != 3:
|
||||
print("Wow! I win!!!")
|
||||
won_computer = won_computer + 1
|
||||
else:
|
||||
print("You win!!!")
|
||||
won_human = won_human + 1
|
||||
elif guess_computer == 1:
|
||||
if guess_human != 3:
|
||||
print("You win!!!")
|
||||
won_human = won_human + 1
|
||||
else:
|
||||
print("Wow! I win!!!")
|
||||
won_computer = won_computer + 1
|
||||
print("\nHere is the final game score:")
|
||||
print("I have won", won_computer, "game(s).")
|
||||
print("You have won", won_human, "game(s).")
|
||||
print("and", games - (won_computer + won_human), "game(s) ended in a tie.")
|
||||
print("\nThanks for playing!!\n")
|
||||
|
||||
|
||||
def main():
|
||||
print(" " * 21 + "GAME OF ROCK, SCISSORS, PAPER")
|
||||
print(" " * 15 + "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY\n")
|
||||
|
||||
keep_playing = True
|
||||
while keep_playing:
|
||||
|
||||
play_game()
|
||||
|
||||
keep_playing = input(
|
||||
"Play again? (yes or no) ").lower().startswith("y")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
25
78 Sine Wave/csharp/SineWave/SineWave.sln
Normal file
25
78 Sine Wave/csharp/SineWave/SineWave.sln
Normal file
@@ -0,0 +1,25 @@
|
||||
|
||||
Microsoft Visual Studio Solution File, Format Version 12.00
|
||||
# Visual Studio Version 16
|
||||
VisualStudioVersion = 16.0.31005.135
|
||||
MinimumVisualStudioVersion = 10.0.40219.1
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SineWave", "SineWave\SineWave.csproj", "{B316DD7F-5755-4216-AFDC-D83720F8ACA2}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
Release|Any CPU = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
||||
{B316DD7F-5755-4216-AFDC-D83720F8ACA2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{B316DD7F-5755-4216-AFDC-D83720F8ACA2}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{B316DD7F-5755-4216-AFDC-D83720F8ACA2}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{B316DD7F-5755-4216-AFDC-D83720F8ACA2}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
EndGlobalSection
|
||||
GlobalSection(ExtensibilityGlobals) = postSolution
|
||||
SolutionGuid = {32A37343-2955-4124-8765-9143F6C529DC}
|
||||
EndGlobalSection
|
||||
EndGlobal
|
||||
15
78 Sine Wave/csharp/SineWave/SineWave/Program.cs
Normal file
15
78 Sine Wave/csharp/SineWave/SineWave/Program.cs
Normal file
@@ -0,0 +1,15 @@
|
||||
using System;
|
||||
|
||||
Console.WriteLine(Tab(30) + "Sine Wave");
|
||||
Console.WriteLine(Tab(15) + "Creative Computing Morristown, New Jersey\n\n\n\n\n");
|
||||
|
||||
bool isCreative = true;
|
||||
for (double t = 0.0; t <= 40.0; t += 0.25)
|
||||
{
|
||||
int a = (int)(26 + 25 * Math.Sin(t));
|
||||
string word = isCreative ? "Creative" : "Computing";
|
||||
Console.WriteLine($"{Tab(a)}{word}");
|
||||
isCreative = !isCreative;
|
||||
}
|
||||
|
||||
static string Tab(int n) => new string(' ', n);
|
||||
8
78 Sine Wave/csharp/SineWave/SineWave/SineWave.csproj
Normal file
8
78 Sine Wave/csharp/SineWave/SineWave/SineWave.csproj
Normal file
@@ -0,0 +1,8 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net5.0</TargetFramework>
|
||||
</PropertyGroup>
|
||||
|
||||
</Project>
|
||||
35
78 Sine Wave/java/SineWave.java
Normal file
35
78 Sine Wave/java/SineWave.java
Normal file
@@ -0,0 +1,35 @@
|
||||
import java.util.Arrays;
|
||||
|
||||
/**
|
||||
* Sine Wave
|
||||
*
|
||||
* Based on the Sine Wave program here
|
||||
* https://github.com/coding-horror/basic-computer-games/blob/main/78%20Sine%20Wave/sinewave.bas
|
||||
*
|
||||
* Note: The idea was to create a version of this 1970's Basic program in Java, without introducing
|
||||
* new features - no additional text, error checking, etc has been added.
|
||||
*/
|
||||
public class SineWave {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
System.out.println("SINE WAVE");
|
||||
System.out.println("CREATIVE COMPUTING MORRISTOWN, NEW JERSEY");
|
||||
System.out.println();
|
||||
|
||||
int toggle = 0;
|
||||
for(double t = 0; t<40; t += .25) {
|
||||
int a = 26 + (int) (25 * Math.sin(t));
|
||||
char[] repeat = new char[a];
|
||||
Arrays.fill(repeat,' ');
|
||||
System.out.print(new String(repeat));
|
||||
if (toggle == 1) {
|
||||
System.out.println("COMPUTING");
|
||||
toggle = 0;
|
||||
} else {
|
||||
System.out.println("CREATIVE");
|
||||
toggle = 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
242
82 Stars/java/src/Stars.java
Normal file
242
82 Stars/java/src/Stars.java
Normal file
@@ -0,0 +1,242 @@
|
||||
import java.util.Arrays;
|
||||
import java.util.Scanner;
|
||||
|
||||
/**
|
||||
* Game of Stars
|
||||
*
|
||||
* Based on the Basic game of Stars here
|
||||
* https://github.com/coding-horror/basic-computer-games/blob/main/82%20Stars/stars.bas
|
||||
*
|
||||
* Note: The idea was to create a version of this 1970's Basic game in Java, without introducing
|
||||
* new features - no additional text, error checking, etc has been added.
|
||||
*/
|
||||
public class Stars {
|
||||
|
||||
public static final int HIGH_NUMBER_RANGE = 100;
|
||||
public static final int MAX_GUESSES = 7;
|
||||
|
||||
private enum GAME_STATE {
|
||||
STARTING,
|
||||
INSTRUCTIONS,
|
||||
START_GAME,
|
||||
GUESSING,
|
||||
WON,
|
||||
LOST,
|
||||
GAME_OVER
|
||||
}
|
||||
|
||||
// Used for keyboard input
|
||||
private final Scanner kbScanner;
|
||||
|
||||
// Current game state
|
||||
private GAME_STATE gameState;
|
||||
|
||||
// Players guess count;
|
||||
private int playerTotalGuesses;
|
||||
|
||||
// Players current guess
|
||||
private int playerCurrentGuess;
|
||||
|
||||
// Computers random number
|
||||
private int computersNumber;
|
||||
|
||||
public Stars() {
|
||||
|
||||
this.gameState = GAME_STATE.STARTING;
|
||||
|
||||
// Initialise kb scanner
|
||||
kbScanner = new Scanner(System.in);
|
||||
}
|
||||
|
||||
/**
|
||||
* Main game loop
|
||||
*
|
||||
*/
|
||||
public void play() {
|
||||
|
||||
do {
|
||||
switch (gameState) {
|
||||
|
||||
// Show an introduction the first time the game is played.
|
||||
case STARTING:
|
||||
intro();
|
||||
gameState = GAME_STATE.INSTRUCTIONS;
|
||||
break;
|
||||
|
||||
// Ask if instructions are needed and display if yes
|
||||
case INSTRUCTIONS:
|
||||
if(yesEntered(displayTextAndGetInput("DO YOU WANT INSTRUCTIONS? "))) {
|
||||
instructions();
|
||||
}
|
||||
this.gameState = GAME_STATE.START_GAME;
|
||||
break;
|
||||
|
||||
// Generate computers number for player to guess, etc.
|
||||
case START_GAME:
|
||||
init();
|
||||
System.out.println("OK, I AM THINKING OF A NUMBER, START GUESSING.");
|
||||
this.gameState = GAME_STATE.GUESSING;
|
||||
break;
|
||||
|
||||
// Player guesses the number until they get it or run out of guesses
|
||||
case GUESSING:
|
||||
this.playerCurrentGuess = playerGuess();
|
||||
|
||||
// Check if the player guessed the number
|
||||
if(this.playerCurrentGuess == this.computersNumber) {
|
||||
this.gameState = GAME_STATE.WON;
|
||||
} else {
|
||||
// incorrect guess
|
||||
showStars();
|
||||
this.playerTotalGuesses++;
|
||||
// Ran out of guesses?
|
||||
if (this.playerTotalGuesses > MAX_GUESSES) {
|
||||
this.gameState = GAME_STATE.LOST;
|
||||
}
|
||||
}
|
||||
break;
|
||||
|
||||
// Won game.
|
||||
case WON:
|
||||
|
||||
System.out.println(stars(79));
|
||||
System.out.println("YOU GOT IT IN " + this.playerTotalGuesses
|
||||
+ " GUESSES!!! LET'S PLAY AGAIN...");
|
||||
this.gameState = GAME_STATE.START_GAME;
|
||||
break;
|
||||
|
||||
// Lost game by running out of guesses
|
||||
case LOST:
|
||||
System.out.println("SORRY, THAT'S " + MAX_GUESSES
|
||||
+ " GUESSES. THE NUMBER WAS " + this.computersNumber);
|
||||
this.gameState = GAME_STATE.START_GAME;
|
||||
break;
|
||||
}
|
||||
// Endless loop since the original code did not allow the player to exit
|
||||
} while (gameState != GAME_STATE.GAME_OVER);
|
||||
}
|
||||
|
||||
/**
|
||||
* Shows how close a players guess is to the computers number by
|
||||
* showing a series of stars - the more stars the closer to the
|
||||
* number.
|
||||
*
|
||||
*/
|
||||
private void showStars() {
|
||||
int d = Math.abs(this.playerCurrentGuess - this.computersNumber);
|
||||
int starsToShow;
|
||||
if(d >=64) {
|
||||
starsToShow = 1;
|
||||
} else if(d >=32) {
|
||||
starsToShow = 2;
|
||||
} else if (d >= 16) {
|
||||
starsToShow = 3;
|
||||
} else if (d >=8) {
|
||||
starsToShow = 4;
|
||||
} else if( d>= 4) {
|
||||
starsToShow = 5;
|
||||
} else if(d>= 2) {
|
||||
starsToShow = 6;
|
||||
} else {
|
||||
starsToShow = 7;
|
||||
}
|
||||
System.out.println(stars(starsToShow));
|
||||
}
|
||||
|
||||
/**
|
||||
* Show a number of stars (asterisks)
|
||||
* @param number the number of stars needed
|
||||
* @return the string encoded with the number of required stars
|
||||
*/
|
||||
private String stars(int number) {
|
||||
char[] stars = new char[number];
|
||||
Arrays.fill(stars, '*');
|
||||
return new String(stars);
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialise variables before each new game
|
||||
*
|
||||
*/
|
||||
private void init() {
|
||||
this.playerTotalGuesses = 1;
|
||||
this.computersNumber = randomNumber();
|
||||
}
|
||||
|
||||
public void instructions() {
|
||||
System.out.println("I AM THINKING OF A WHOLE NUMBER FROM 1 TO " + HIGH_NUMBER_RANGE);
|
||||
System.out.println("TRY TO GUESS MY NUMBER. AFTER YOU GUESS, I");
|
||||
System.out.println("WILL TYPE ONE OR MORE STARS (*). THE MORE");
|
||||
System.out.println("STARS I TYPE, THE CLOSER YOU ARE TO MY NUMBER.");
|
||||
System.out.println("ONE STAR (*) MEANS FAR AWAY, SEVEN STARS (*******)");
|
||||
System.out.println("MEANS REALLY CLOSE! YOU GET " + MAX_GUESSES + " GUESSES.");
|
||||
}
|
||||
|
||||
public void intro() {
|
||||
System.out.println("STARS");
|
||||
System.out.println("CREATIVE COMPUTING MORRISTOWN, NEW JERSEY");
|
||||
System.out.println();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get players guess from kb
|
||||
*
|
||||
* @return players guess as an int
|
||||
*/
|
||||
private int playerGuess() {
|
||||
return Integer.parseInt((displayTextAndGetInput("YOUR GUESS? ")));
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether player entered Y or YES to a question.
|
||||
*
|
||||
* @param text player string from kb
|
||||
* @return true of Y or YES was entered, otherwise false
|
||||
*/
|
||||
private boolean yesEntered(String text) {
|
||||
return stringIsAnyValue(text, "Y", "YES");
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether a string equals one of a variable number of values
|
||||
* Useful to check for Y or YES for example
|
||||
* Comparison is case insensitive.
|
||||
*
|
||||
* @param text source string
|
||||
* @param values a range of values to compare against the source string
|
||||
* @return true if a comparison was found in one of the variable number of strings passed
|
||||
*/
|
||||
private boolean stringIsAnyValue(String text, String... values) {
|
||||
|
||||
// Cycle through the variable number of values and test each
|
||||
for(String val:values) {
|
||||
if(text.equalsIgnoreCase(val)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
// no matches
|
||||
return false;
|
||||
}
|
||||
|
||||
/*
|
||||
* Print a message on the screen, then accept input from Keyboard.
|
||||
*
|
||||
* @param text message to be displayed on screen.
|
||||
* @return what was typed by the player.
|
||||
*/
|
||||
private String displayTextAndGetInput(String text) {
|
||||
System.out.print(text);
|
||||
return kbScanner.next();
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate random number
|
||||
*
|
||||
* @return random number
|
||||
*/
|
||||
private int randomNumber() {
|
||||
return (int) (Math.random()
|
||||
* (HIGH_NUMBER_RANGE) + 1);
|
||||
}
|
||||
}
|
||||
9
82 Stars/java/src/StarsGame.java
Normal file
9
82 Stars/java/src/StarsGame.java
Normal file
@@ -0,0 +1,9 @@
|
||||
import java.lang.reflect.AnnotatedType;
|
||||
|
||||
public class StarsGame {
|
||||
|
||||
public static void main(String[] args) {
|
||||
Stars stars = new Stars();
|
||||
stars.play();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user