Data update

This commit is contained in:
Ingy döt Net 2026-04-30 12:34:36 -04:00
parent 4bb20c9b71
commit cbaf4c4b64
12390 changed files with 318560 additions and 27248 deletions

View file

@ -1,89 +1,89 @@
bdos: equ 5 ; CP/M syscalls
puts: equ 9
putch: equ 2
getch: equ 1
bdos: equ 5 ; CP/M syscalls
puts: equ 9
putch: equ 2
getch: equ 1
maxtokens: equ 12 ; you can change this for more tokens
maxtokens: equ 12 ; you can change this for more tokens
org 100h
lxi d,nim
call outs
mvi b,maxtokens ; 12 tokens
gameloop: lxi d,tokens ; Show tokens
call outs
mov c,b
showtokens: dcr c
jm tokensdone
mvi a,'|'
call outa
jmp showtokens
tokensdone: lxi d,nl
call outs
lxi d,prompt ; Show prompt
call outs
readinput: call ina ; Read input
sui '1' ; Subtract '1' (lowest acceptable
jc wrong ; input)
cpi 3 ; range of values is [0..2]
jnc wrong
cmp b ; can't take more than there are either
jnc wrong
cma ; negate; -a = ~(a-1)
mov c,a ; keep value
add b ; subtract from tokens
mov b,a
mvi a,4 ; computer take 4-X tokens
add c
mov c,a
lxi d,response ; print how many I take
call outs
mvi a,'0'
add c
call outa
mov a,b ; subtract the ones I take
sub c
jz done ; if I took the last one, I won
mov b,a
lxi d,nl
call outs
call outs
jmp gameloop
done: lxi d,lose ; there's no win condition
jmp outs
;; Invalid input
wrong: lxi d,wronginp
call outs
jmp readinput
;; Read character into A and keep registers
ina: push b
push d
push h
mvi c,getch
call bdos
jmp restore
;; Print A and keep registers
outa: push b
push d
push h
mvi c,putch
mov e,a
call bdos
jmp restore
;; Print string and keep registers
outs: push b
push d
push h
mvi c,puts
call bdos
;; Restore registers
restore: pop h
pop d
pop b
ret
nim: db 'Nim',13,10,13,10,'$'
prompt: db 'How many will you take (1-3)? $'
response: db 13,10,'I take $'
tokens: db 'Tokens: $'
lose: db 13,10,'You lose!$'
nl: db 13,10,'$'
wronginp: db 8,7,32,8,'$' ; beep and erase choice
org 100h
lxi d,nim
call outs
mvi b,maxtokens ; 12 tokens
gameloop: lxi d,tokens ; Show tokens
call outs
mov c,b
showtokens: dcr c
jm tokensdone
mvi a,'|'
call outa
jmp showtokens
tokensdone: lxi d,nl
call outs
lxi d,prompt ; Show prompt
call outs
readinput: call ina ; Read input
sui '1' ; Subtract '1' (lowest acceptable
jc wrong ; input)
cpi 3 ; range of values is [0..2]
jnc wrong
cmp b ; can't take more than there are either
jnc wrong
cma ; negate; -a = ~(a-1)
mov c,a ; keep value
add b ; subtract from tokens
mov b,a
mvi a,4 ; computer take 4-X tokens
add c
mov c,a
lxi d,response ; print how many I take
call outs
mvi a,'0'
add c
call outa
mov a,b ; subtract the ones I take
sub c
jz done ; if I took the last one, I won
mov b,a
lxi d,nl
call outs
call outs
jmp gameloop
done: lxi d,lose ; there's no win condition
jmp outs
;; Invalid input
wrong: lxi d,wronginp
call outs
jmp readinput
;; Read character into A and keep registers
ina: push b
push d
push h
mvi c,getch
call bdos
jmp restore
;; Print A and keep registers
outa: push b
push d
push h
mvi c,putch
mov e,a
call bdos
jmp restore
;; Print string and keep registers
outs: push b
push d
push h
mvi c,puts
call bdos
;; Restore registers
restore: pop h
pop d
pop b
ret
nim: db 'Nim',13,10,13,10,'$'
prompt: db 'How many will you take (1-3)? $'
response: db 13,10,'I take $'
tokens: db 'Tokens: $'
lose: db 13,10,'You lose!$'
nl: db 13,10,'$'
wronginp: db 8,7,32,8,'$' ; beep and erase choice

View file

@ -1,60 +1,60 @@
;; MS-DOS Nim; assembles with nasm.
bits 16
cpu 8086
getch: equ 1
putch: equ 2
puts: equ 9 ; INT 21h calls
maxtokens: equ 12 ; Amount of tokens there are
section .text
org 100h
mov dx,nim ; Print sign-on
call outs
mov ch,maxtokens ; CH = amount of tokens we have
loop: mov dx,tokens ; Tokens: |||...
call outs
mov ah,putch ; Print a | for each token
mov dl,'|'
mov dh,ch
puttoks: int 21h
dec dh
jnz puttoks
mov dx,prompt ; Ask the user how many to take
call outs
ask: mov ah,getch ; Read keypress
int 21h
sub al,'1' ; Make number (minus one)
jc bad ; Carry, it was <1 (bad)
inc al ; Add 1 (because we subtracted '1')
cmp al,3
ja bad ; If it was >3, it is bad
cmp al,ch
ja bad ; If it was > amount left, it is bad
sub ch,al ; Remove your tokens from pile
mov cl,4 ; I take 4-N, which is 3-N-1
sub cl,al
sub ch,cl ; Remove my tokens from pile
mov dx,response ; Tell the user how many I took.
call outs
mov dl,'0'
add dl,cl
mov ah,putch
int 21h
cmp ch,0 ; Are there any tokens left?
jne loop ; If not, prompt again
mov dx,lose ; But otherwise, you've lost
; Fall through into print string routine and then stop.
;; Print string in DX. (This saves a byte each CALL)
outs: mov ah,puts
int 21h
ret
;; Input is bad; beep, erase, ask again
bad: mov dx,wronginp
call outs
jmp ask
section .data
nim: db 'Nim$'
prompt: db 13,10,'How many will you take (1-3)? $'
response: db 13,10,'I take $'
tokens: db 13,10,13,10,'Tokens: $'
lose: db 13,10,'You lose!$'
;; MS-DOS Nim; assembles with nasm.
bits 16
cpu 8086
getch: equ 1
putch: equ 2
puts: equ 9 ; INT 21h calls
maxtokens: equ 12 ; Amount of tokens there are
section .text
org 100h
mov dx,nim ; Print sign-on
call outs
mov ch,maxtokens ; CH = amount of tokens we have
loop: mov dx,tokens ; Tokens: |||...
call outs
mov ah,putch ; Print a | for each token
mov dl,'|'
mov dh,ch
puttoks: int 21h
dec dh
jnz puttoks
mov dx,prompt ; Ask the user how many to take
call outs
ask: mov ah,getch ; Read keypress
int 21h
sub al,'1' ; Make number (minus one)
jc bad ; Carry, it was <1 (bad)
inc al ; Add 1 (because we subtracted '1')
cmp al,3
ja bad ; If it was >3, it is bad
cmp al,ch
ja bad ; If it was > amount left, it is bad
sub ch,al ; Remove your tokens from pile
mov cl,4 ; I take 4-N, which is 3-N-1
sub cl,al
sub ch,cl ; Remove my tokens from pile
mov dx,response ; Tell the user how many I took.
call outs
mov dl,'0'
add dl,cl
mov ah,putch
int 21h
cmp ch,0 ; Are there any tokens left?
jne loop ; If not, prompt again
mov dx,lose ; But otherwise, you've lost
; Fall through into print string routine and then stop.
;; Print string in DX. (This saves a byte each CALL)
outs: mov ah,puts
int 21h
ret
;; Input is bad; beep, erase, ask again
bad: mov dx,wronginp
call outs
jmp ask
section .data
nim: db 'Nim$'
prompt: db 13,10,'How many will you take (1-3)? $'
response: db 13,10,'I take $'
tokens: db 13,10,13,10,'Tokens: $'
lose: db 13,10,'You lose!$'
wronginp: db 8,7,32,8,'$'

View file

@ -0,0 +1,45 @@
with Ada.Text_IO;
procedure Nim is
subtype Token_Range is Positive range 1 .. 3;
package TIO renames Ada.Text_IO;
package Token_IO is new TIO.Integer_IO(Token_Range);
procedure Get_Tokens(remaining : in Natural; how_many : out Token_Range) is
begin
loop
TIO.Put("How many tokens would you like to take? ");
begin
Token_IO.Get(TIO.Standard_Input, how_many);
exit when how_many < remaining;
raise Constraint_Error;
exception
when TIO.Data_Error | Constraint_Error =>
if not TIO.End_Of_Line(TIO.Standard_Input) then
TIO.Skip_Line(TIO.Standard_Input);
end if;
TIO.Put_Line("Invalid input.");
end;
end loop;
end;
tokens : Natural := 12;
how_many : Token_Range;
begin
loop
TIO.Put_Line(tokens'Img & " tokens remain.");
-- no exit condition here: human cannot win.
Get_Tokens(tokens, how_many);
TIO.Put_Line("Human takes" & how_many'Img & " tokens.");
tokens := tokens - how_many;
-- computer's turn: take the remaining N tokens to amount to 4.
how_many := tokens mod 4;
TIO.Put_Line("Computer takes" & how_many'Img & " tokens.");
tokens := tokens - how_many;
Ada.Text_IO.New_Line;
exit when tokens = 0;
end loop;
TIO.Put_Line("Computer won!");
end Nim;

View file

@ -0,0 +1,14 @@
set ntokens to 12
repeat
log "There are " & ntokens & " tokens left."
set taker to display alert "How many tokens to take?" buttons {1, 2, 3}
set ptake to button returned of taker
log "You took " & ptake & " token(s)."
set ctake to 4 - ptake
log "The computer took " & ctake & " token(s)."
set ntokens to ntokens - 4
if ntokens = 0 then
log "No tokens left. Game over!"
exit repeat
end if
end repeat

View file

@ -1,17 +1,17 @@
Play:
tokens := 12
while tokens {
while !(D>0 && D<4)
InputBox, D, Nim Game, % "Tokens Remaining = " tokens
. "`nHow many tokens would you like to take?"
. "`nChoose 1, 2 or 3"
tokens -= D
MsgBox % "Computer Takes " 4-D
tokens -= 4-d, d:=0
while !(D>0 && D<4)
InputBox, D, Nim Game, % "Tokens Remaining = " tokens
. "`nHow many tokens would you like to take?"
. "`nChoose 1, 2 or 3"
tokens -= D
MsgBox % "Computer Takes " 4-D
tokens -= 4-d, d:=0
}
MsgBox, 262212,,Computer Always Wins!`nWould you like to play again?
IfMsgBox, Yes
gosub Play
gosub Play
else
ExitApp
ExitApp
return

View file

@ -2,15 +2,15 @@ monton = 12
llevar = 0
while monton > 0
print "There are "; monton; " tokens remaining. How many would you like to take? ";
input integer llevar
while llevar = 0 or llevar > 3
print "You must take 1, 2, or 3 tokens. How many would you like to take ";
input integer llevar
end while
print "There are "; monton; " tokens remaining. How many would you like to take? ";
input integer llevar
while llevar = 0 or llevar > 3
print "You must take 1, 2, or 3 tokens. How many would you like to take ";
input integer llevar
end while
print "On my turn I will take "; 4 - llevar; " token(s)."
monton = monton - 4
print "On my turn I will take "; 4 - llevar; " token(s)."
monton = monton - 4
end while
print

View file

@ -5,55 +5,55 @@ int computerTurn(int numTokens);
int main(void)
{
printf("Nim Game\n\n");
int Tokens = 12;
while(Tokens > 0)
{
printf("How many tokens would you like to take?: ");
int uin;
scanf("%i", &uin);
int nextTokens = playerTurn(Tokens, uin);
if (nextTokens == Tokens)
{
continue;
}
Tokens = nextTokens;
Tokens = computerTurn(Tokens);
}
printf("Computer wins.");
return 0;
printf("Nim Game\n\n");
int Tokens = 12;
while(Tokens > 0)
{
printf("How many tokens would you like to take?: ");
int uin;
scanf("%i", &uin);
int nextTokens = playerTurn(Tokens, uin);
if (nextTokens == Tokens)
{
continue;
}
Tokens = nextTokens;
Tokens = computerTurn(Tokens);
}
printf("Computer wins.");
return 0;
}
int playerTurn(int numTokens, int take)
{
if (take < 1 || take > 3)
{
printf("\nTake must be between 1 and 3.\n\n");
return numTokens;
}
int remainingTokens = numTokens - take;
printf("\nPlayer takes %i tokens.\n", take);
printf("%i tokens remaining.\n\n", remainingTokens);
return remainingTokens;
if (take < 1 || take > 3)
{
printf("\nTake must be between 1 and 3.\n\n");
return numTokens;
}
int remainingTokens = numTokens - take;
printf("\nPlayer takes %i tokens.\n", take);
printf("%i tokens remaining.\n\n", remainingTokens);
return remainingTokens;
}
int computerTurn(int numTokens)
{
int take = numTokens % 4;
int remainingTokens = numTokens - take;
printf("Computer takes %u tokens.\n", take);
printf("%i tokens remaining.\n\n", remainingTokens);
return remainingTokens;
int take = numTokens % 4;
int remainingTokens = numTokens - take;
printf("Computer takes %u tokens.\n", take);
printf("%i tokens remaining.\n\n", remainingTokens);
return remainingTokens;
}

View file

@ -0,0 +1,25 @@
IDENTIFICATION DIVISION.
PROGRAM-ID. NIM-GAME.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 MONTON PIC 99 VALUE 12.
01 LLEVAR PIC 9 VALUE 0.
01 TEMP PIC 9.
PROCEDURE DIVISION.
PERFORM UNTIL MONTON = 0
DISPLAY "There are " MONTON " tokens remaining. How many"
"would you like to take? "
ACCEPT LLEVAR
PERFORM UNTIL LLEVAR > 0 AND LLEVAR < 4
DISPLAY "You must take 1, 2, or 3 tokens. How many"
"would you like to take "
ACCEPT LLEVAR
END-PERFORM
COMPUTE TEMP = 4 - LLEVAR
DISPLAY "On my turn I will take " TEMP " token(s)."
SUBTRACT 4 FROM MONTON
END-PERFORM
DISPLAY " "
DISPLAY "I got the last token. I win! Better luck next time."
STOP RUN.

View file

@ -1,27 +1,27 @@
(defun pturn (curTokens)
(write-string "How many tokens would you like to take?: ")
(setq ans (read))
(setq tokensRemaining (- curTokens ans))
(format t "You take ~D tokens~%" ans)
(printRemaining tokensRemaining)
tokensRemaining)
(write-string "How many tokens would you like to take?: ")
(setq ans (read))
(setq tokensRemaining (- curTokens ans))
(format t "You take ~D tokens~%" ans)
(printRemaining tokensRemaining)
tokensRemaining)
(defun cturn (curTokens)
(setq take (mod curTokens 4))
(setq tokensRemaining (- curTokens take))
(format t "Computer takes ~D tokens~%" take)
(printRemaining tokensRemaining)
tokensRemaining)
(setq take (mod curTokens 4))
(setq tokensRemaining (- curTokens take))
(format t "Computer takes ~D tokens~%" take)
(printRemaining tokensRemaining)
tokensRemaining)
(defun printRemaining (remaining)
(format t "~D tokens remaining~%~%" remaining))
(format t "~D tokens remaining~%~%" remaining))
(format t "LISP Nim~%~%")
(setq tok 12)
(loop
(setq tok (pturn tok))
(setq tok (cturn tok))
(if (<= tok 0)
(return)))
(setq tok (pturn tok))
(setq tok (cturn tok))
(if (<= tok 0)
(return)))
(write-string "Computer wins!")

View file

@ -2,56 +2,56 @@ let h = 12
label loop
alert "There are ", h ," tokens remaining."
input "How many would you like to take? ", t
alert "There are ", h ," tokens remaining."
input "How many would you like to take? ", t
if t > 3 or t < 1 then
if t > 3 or t < 1 then
alert "You must take between 1 to 3 tokens."
alert "You must take between 1 to 3 tokens."
endif
endif
if h - t < 0 then
if h - t < 0 then
alert "You cannot take that many. There's only ", h ," left."
alert "You cannot take that many. There's only ", h ," left."
endif
endif
if t <= 3 and t >= 1 and h - t >= 0 then
if t <= 3 and t >= 1 and h - t >= 0 then
let h = h - t
let h = h - t
if h = 0 then
if h = 0 then
alert "Congratulations. You got the last token."
end
alert "Congratulations. You got the last token."
end
endif
endif
let t = 4 - t
let t = 4 - t
if h >= 15 then
if h >= 15 then
let t = 3
let t = 3
endif
endif
if h <= 3 then
if h <= 3 then
let t = h
let t = h
endif
endif
alert "I will take ", t ," tokens."
let h = h - t
alert "I will take ", t ," tokens."
let h = h - t
if h = 0 then
if h = 0 then
alert "I got the last token. I win. Better luck next time."
end
alert "I got the last token. I win. Better luck next time."
end
endif
endif
endif
endif
goto loop

View file

@ -4,77 +4,77 @@ gosub intro
do
print "There are " \
print tokens \
print " tokens remaining."
crlf
print "How many would you like to take? " \
print "There are " \
print tokens \
print " tokens remaining."
crlf
print "How many would you like to take? " \
input take
input take
if take > 3 or take < 1 then
if take > 3 or take < 1 then
print "You must take between 1 to 3 tokens."
print "You must take between 1 to 3 tokens."
endif
endif
if tokens - take < 0 then
if tokens - take < 0 then
print "You cannot take that many."
print "You cannot take that many."
endif
endif
if take <= 3 and take >= 1 and tokens - take >= 0 then
if take <= 3 and take >= 1 and tokens - take >= 0 then
let tokens = tokens - take
let tokens = tokens - take
if tokens = 0 then
if tokens = 0 then
bell
print "Congratulations. You got the last token."
pause
end
bell
print "Congratulations. You got the last token."
pause
end
endif
endif
let take = 4 - take
let take = 4 - take
if tokens >= 15 then
if tokens >= 15 then
let take = 3
let take = 3
endif
endif
if tokens <= 3 then
if tokens <= 3 then
let take = tokens
let take = tokens
endif
endif
print "I will take " \
print take \
print " of the tokens."
print "I will take " \
print take \
print " of the tokens."
let tokens = tokens - take
let tokens = tokens - take
if tokens = 0 then
if tokens = 0 then
print "I got the last token. I win. Better luck next time."
pause
end
print "I got the last token. I win. Better luck next time."
pause
end
endif
endif
endif
endif
loop
sub intro
cls
print "NIM game"
crlf
print "Press any key to play..."
cls
cls
print "NIM game"
crlf
print "Press any key to play..."
cls
return

View file

@ -1,51 +1,51 @@
class Nim {
constructor(tokens, printFun) {
this.startTokens = tokens;
this.tokens = tokens;
this.printFun = printFun;
}
constructor(tokens, printFun) {
this.startTokens = tokens;
this.tokens = tokens;
this.printFun = printFun;
}
playerTurn(take) {
take = Math.round(take);
playerTurn(take) {
take = Math.round(take);
if (take < 1 || take > 3) {
this.printFun("take must be between 1 and 3.\n")
return false;
}
this.tokens -= take;
this.printFun("Player takes " + take + " tokens.");
this.printRemaining()
if (take < 1 || take > 3) {
this.printFun("take must be between 1 and 3.\n")
return false;
}
this.tokens -= take;
this.printFun("Player takes " + take + " tokens.");
this.printRemaining()
if (this.tokens === 0) {
this.printFun("Player wins!\n");
}
return true;
}
if (this.tokens === 0) {
this.printFun("Player wins!\n");
}
return true;
}
computerTurn() {
let take = this.tokens % 4;
this.tokens -= take;
this.printFun("Computer takes " + take + " tokens.");
this.printRemaining();
computerTurn() {
let take = this.tokens % 4;
this.tokens -= take;
this.printFun("Computer takes " + take + " tokens.");
this.printRemaining();
if (this.tokens === 0) {
this.printFun("Computer wins.\n");
}
if (this.tokens === 0) {
this.printFun("Computer wins.\n");
}
}
}
printRemaining() {
this.printFun(this.tokens + " tokens remaining.\n");
}
printRemaining() {
this.printFun(this.tokens + " tokens remaining.\n");
}
}
let game = new Nim(12, console.log);
while (true) {
if (game.playerTurn(parseInt(prompt("How many tokens would you like to take?")))){
game.computerTurn();
}
if (game.tokens == 0) {
break;
}
if (game.playerTurn(parseInt(prompt("How many tokens would you like to take?")))){
game.computerTurn();
}
if (game.tokens == 0) {
break;
}
}

View file

@ -12,13 +12,13 @@ def play($tokens):
| .tokens += -4
else .emit = "Please enter a number from 1 to \([3, .tokens]|min) inclusive."
end
end;
end;
.emit,
if .tokens == 0
if .tokens == 0
then "\nComputer wins!", break $out
elif .tokens < 0 then "\nCongratulations!", break $out
else "\(.tokens) tokens remain. How many tokens will you take?"
else "\(.tokens) tokens remain. How many tokens will you take?"
end )) ;
play(12)

View file

@ -0,0 +1,52 @@
import std/os/readline
type player
Bot
Human
fun player/other(p : player): player
match p
Human -> Bot
Bot -> Human
fun player/show(p:player) : string
match p
Bot -> "bot"
Human -> "human"
effect ctl move() : ()
fun get-move(p: player, max-tokens: int, total-tokens: int, last-choice)
match p
Bot ->
val res = min(total-tokens, 4 - last-choice)
println("Bot choosing " ++ res.show)
res
Human ->
var valid := -1
while { valid < 0 }
println("Total tokens: " ++ total-tokens.show)
println("Choose a number of tokens between 1 and " ++ max-tokens.show)
match readline().parse-int
Just(v) ->
if v >= 1 && v <= max-tokens then valid := v
else println("Input number not in range")
Nothing -> println("Input not a number")
valid
pub fun main()
var tokens := 12
var player := Human
var last-choice := 0
with handler
ctl move()
val choice = get-move(player, min(3, tokens), tokens, last-choice)
last-choice := choice
tokens := tokens - choice
if tokens == 0 then
println("Player " ++ player.show ++ " won!")
else
player := player.other
resume(())
while {True}
move()

View file

@ -0,0 +1,29 @@
HAI 1.3
I HAS A NTOKENZ ITZ 12
IM IN YR NIMGAME
VISIBLE "PILE HAS :{NTOKENZ} TOKENZ"
I HAS A PTAEK
IM IN YR INPUT
VISIBLE "HAO MENY U TAEK?"
GIMMEH PTAEK
PTAEK IS NOW A NUMBR
I HAS A UPLIM ITZ BOTH SAEM PTAEK AN BIGGR OF PTAEK AN 1
I HAS A LOWLIM ITZ BOTH SAEM PTAEK AN SMALLR OF PTAEK AN 3
BOTH OF UPLIM AN LOWLIM, O RLY?
YA RLY, GTFO
NO WAI, VISIBLE "UR INPUT IS FAIL"
OIC
IM OUTTA YR INPUT
VISIBLE "U TAEK :{PTAEK} TOKENZ"
I HAS A CTAEK ITZ DIFF OF 4 AN PTAEK
VISIBLE "I TAEK :{CTAEK} TOKENZ"
NTOKENZ R DIFF OF NTOKENZ AN 4
BOTH SAEM NTOKENZ AN 0, O RLY?
YA RLY
VISIBLE "GAEM OVR U FAIL"
GTFO
OIC
IM OUTTA YR NIMGAME
KTHXBYE

View file

@ -4,36 +4,36 @@ print("Nim Game\n")
print("Starting with " .. tokens .. " tokens.\n\n")
function printRemaining()
print(tokens .. " tokens remaining.\n")
print(tokens .. " tokens remaining.\n")
end
function playerTurn(take)
take = math.floor(take)
if (take < 1 or take > 3) then
print ("\nTake must be between 1 and 3.\n")
return false
end
tokens = tokens - take
print ("\nPlayer takes " .. take .. " tokens.")
printRemaining()
return true
take = math.floor(take)
if (take < 1 or take > 3) then
print ("\nTake must be between 1 and 3.\n")
return false
end
tokens = tokens - take
print ("\nPlayer takes " .. take .. " tokens.")
printRemaining()
return true
end
function computerTurn()
take = tokens % 4
tokens = tokens - take
print("Computer takes " .. take .. " tokens.")
printRemaining()
take = tokens % 4
tokens = tokens - take
print("Computer takes " .. take .. " tokens.")
printRemaining()
end
while (tokens > 0) do
io.write("How many tokens would you like to take?: ")
if playerTurn(io.read("*n")) then
computerTurn()
end
io.write("How many tokens would you like to take?: ")
if playerTurn(io.read("*n")) then
computerTurn()
end
end
print ("Computer wins.")

View file

@ -5,36 +5,36 @@ print "Starting with " + tokens + " tokens."
print
printRemaining = function()
print tokens + " tokens remaining."
print
print tokens + " tokens remaining."
print
end function
playerTurn = function(take)
take = floor(val(take))
if take < 1 or take > 3 then
print "Take must be between 1 and 3."
return false
end if
take = floor(val(take))
if take < 1 or take > 3 then
print "Take must be between 1 and 3."
return false
end if
globals.tokens = tokens - take
globals.tokens = tokens - take
print "Player takes " + take + " tokens."
printRemaining
return true
print "Player takes " + take + " tokens."
printRemaining
return true
end function
computerTurn = function()
take = tokens % 4
globals.tokens = tokens - take
take = tokens % 4
globals.tokens = tokens - take
print "Computer takes " + take + " tokens."
printRemaining
print "Computer takes " + take + " tokens."
printRemaining
end function
while tokens > 0
if playerTurn(input("How many tokens would you like to take? ")) then
computerTurn
end if
if playerTurn(input("How many tokens would you like to take? ")) then
computerTurn
end if
end while
print "Computer wins."

View file

@ -5,66 +5,66 @@ program examples\nim
data
int tokens[12]
int take[0]
int tokens[12]
int take[0]
begin
call intro
call intro
label gameloop
label gameloop
echo "There are"
echo [tokens]
echo " tokens remaining."
crlf
echo "How many would you like to take? "
input [take]
echo "There are"
echo [tokens]
echo " tokens remaining."
crlf
echo "How many would you like to take? "
input [take]
if [take] > 3 | [take] < 1 then
if [take] > 3 | [take] < 1 then
echo "You must take between 1 to 3 tokens."
echo "You must take between 1 to 3 tokens."
endif
endif
if [take] <= 3 & [take] >= 1 then
if [take] <= 3 & [take] >= 1 then
[tokens] = [tokens] - [take]
[tokens] = [tokens] - [take]
if [tokens] = 0 then
if [tokens] = 0 then
bell
echo "Congratulations. You got the last token."
pause
kill
bell
echo "Congratulations. You got the last token."
pause
kill
endif
endif
[take] = 4 - [take]
[take] = 4 - [take]
echo "I will take"
echo [take]
echo " tokens.
[tokens] = [tokens] - [take]
echo "I will take"
echo [take]
echo " tokens.
[tokens] = [tokens] - [take]
if [tokens] = 0 then
if [tokens] = 0 then
echo "I got the last token. I win. Better luck next time."
pause
kill
echo "I got the last token. I win. Better luck next time."
pause
kill
endif
endif
endif
endif
goto gameloop
goto gameloop
end
sub intro
cls
echo "NIM game"
crlf
cls
echo "NIM game"
crlf
ret

View file

@ -1,33 +1,33 @@
int tokens = 12;
void get_tokens(int cur_tokens) {
write("How many tokens would you like to take? ");
int take = (int)Stdio.stdin->gets();
write("How many tokens would you like to take? ");
int take = (int)Stdio.stdin->gets();
if (take < 1 || take > 3) {
write("Number must be between 1 and 3.\n");
get_tokens(cur_tokens);
}
else {
tokens = cur_tokens - take;
write("You take " + (string)take + " tokens\n");
write((string)tokens + " tokens remaing\n\n");
}
if (take < 1 || take > 3) {
write("Number must be between 1 and 3.\n");
get_tokens(cur_tokens);
}
else {
tokens = cur_tokens - take;
write("You take " + (string)take + " tokens\n");
write((string)tokens + " tokens remaing\n\n");
}
}
void comp_turn(int cur_tokens) {
int take = cur_tokens % 4;
tokens = cur_tokens - take;
write("Computer take " + (string)take + " tokens\n");
write((string)tokens + " tokens remaing\n\n");
int take = cur_tokens % 4;
tokens = cur_tokens - take;
write("Computer take " + (string)take + " tokens\n");
write((string)tokens + " tokens remaing\n\n");
}
int main() {
write("Pike Nim\n\n");
while(tokens > 0) {
get_tokens(tokens);
comp_turn(tokens);
}
write("Computer wins!\n");
return 0;
write("Pike Nim\n\n");
while(tokens > 0) {
get_tokens(tokens);
comp_turn(tokens);
}
write("Computer wins!\n");
return 0;
}

View file

@ -1,20 +1,20 @@
nim :- next_turn(12), !.
next_turn(N) :-
% Player Turn
format('How many dots would you like to take? '),
read_line_to_codes(user_input, Line),
number_codes(PlayerGuess, Line),
member(PlayerGuess,[1,2,3]),
N1 is N - PlayerGuess,
format('You take ~d dots~n~d dots remaining.~n~n', [PlayerGuess, N1]),
% Player Turn
format('How many dots would you like to take? '),
read_line_to_codes(user_input, Line),
number_codes(PlayerGuess, Line),
member(PlayerGuess,[1,2,3]),
N1 is N - PlayerGuess,
format('You take ~d dots~n~d dots remaining.~n~n', [PlayerGuess, N1]),
% Computer Turn
CompGuess is 4 - PlayerGuess,
N2 is N1 - CompGuess,
format('Computer takes ~d dots~n~d dots remaining.~n~n', [CompGuess, N2]),
(
N2 = 0
-> format('Computer wins!')
; next_turn(N2)
).
% Computer Turn
CompGuess is 4 - PlayerGuess,
N2 is N1 - CompGuess,
format('Computer takes ~d dots~n~d dots remaining.~n~n', [CompGuess, N2]),
(
N2 = 0
-> format('Computer wins!')
; next_turn(N2)
).

View file

@ -1,32 +1,32 @@
print("Py Nim\n")
def getTokens(curTokens):
global tokens
print("How many tokens would you like to take? ", end='')
take = int(input())
if (take < 1 or take > 3):
print("Number must be between 1 and 3.\n")
getTokens(curTokens)
return
tokens = curTokens - take
print(f'You take {take} tokens.')
print(f'{tokens} tokens remaining.\n')
global tokens
print("How many tokens would you like to take? ", end='')
take = int(input())
if (take < 1 or take > 3):
print("Number must be between 1 and 3.\n")
getTokens(curTokens)
return
tokens = curTokens - take
print(f'You take {take} tokens.')
print(f'{tokens} tokens remaining.\n')
def compTurn(curTokens):
global tokens
take = curTokens % 4
tokens = curTokens - take
print (f'Computer takes {take} tokens.')
print (f'{tokens} tokens remaining.\n')
global tokens
take = curTokens % 4
tokens = curTokens - take
print (f'Computer takes {take} tokens.')
print (f'{tokens} tokens remaining.\n')
tokens = 12
while (tokens > 0):
getTokens(tokens)
compTurn(tokens)
getTokens(tokens)
compTurn(tokens)
print("Computer wins!")

View file

@ -5,10 +5,10 @@ DO WHILE monton > 0
PRINT USING "There are ## tokens remaining. How many would you like to take"; monton;
INPUT llevar
DO WHILE llevar = 0 OR llevar > 3
INPUT "You must take 1, 2, or 3 tokens. How many would you like to take"; llevar
INPUT "You must take 1, 2, or 3 tokens. How many would you like to take"; llevar
LOOP
PRINT "On my turn I will take"; 4 - llevar; " token(s)."
PRINT "On my turn I will take"; 4 - llevar; " token(s)."
monton = monton - 4
LOOP

View file

@ -0,0 +1,40 @@
Rebol [
title: "Rosetta code: Nim game"
file: %Nim_game.r3
url: https://rosettacode.org/wiki/Nim_game
]
nim-game: function/with [
"Nim (12-token variant) - the computer always wins with perfect play"
][
tokens: 12
while [
print [newline "Tokens remaining:" as-yellow tokens]
tokens > 0
][
;; Player's turn - validated input ensures n is 1, 2, or 3
n: take-tokens
print ["You took" as-yellow n "tokens."]
tokens: tokens - n
;; Computer's turn - always picks the complement to 4,
;; guaranteeing the pile stays on a multiple of 4 after each round
computer: 4 - n
print ["Computer takes" as-yellow computer "tokens."]
tokens: tokens - computer
]
print as-green "Computer wins!"
][
;; --- Local helper -------------------------------------------------
take-tokens: function [][
forever [
print "Take 1, 2, or 3 tokens (q to quit)?"
n: wait-for-key
if n = #"q" [quit]
n: n - #"0"
either any [n < 1 n > 3][
print as-red "Please enter a number between 1 and 3."
][ return n ]
]
]
]
nim-game

View file

@ -45,52 +45,52 @@ app = new qApp
{
win = new qWidget() {
app.StyleFusionBlack()
setWindowTitle('CalmoSoft Nim Game')
setWinIcon(self,"images/nim.jpg")
setWindowFlags(Qt_SplashScreen | Qt_CustomizeWindowHint)
reSize(620,460)
setWindowTitle('CalmoSoft Nim Game')
setWinIcon(self,"images/nim.jpg")
setWindowFlags(Qt_SplashScreen | Qt_CustomizeWindowHint)
reSize(620,460)
for Col = 1 to limit1
Button1[Col] = new QPushButton(win) {
Button1[Col] = new QPushButton(win) {
y = 230+(Col-1)*height
setgeometry(y+10,70,width,height)
setSizePolicy(1,1)
seticon(new qicon(new qpixmap(C_NIM)))
setIconSize(new qSize(60,60))
}
next
}
next
for Col = 1 to limit2
Button2[Col] = new QPushButton(win) {
Button2[Col] = new QPushButton(win) {
y = 170+(Col-1)*height
setgeometry(y+10,150,width,height)
setSizePolicy(1,1)
seticon(new qicon(new qpixmap(C_NIM)))
setIconSize(new qSize(60,60))
}
next
}
next
for Col = 1 to limit3
Button3[Col] = new QPushButton(win) {
Button3[Col] = new QPushButton(win) {
y = 110+(Col-1)*height
setgeometry(y+10,230,width,height)
setSizePolicy(1,1)
seticon(new qicon(new qpixmap(C_NIM)))
setIconSize(new qSize(60,60))
}
next
}
next
for Col = 1 to limit4
Button4[Col] = new QPushButton(win) {
Button4[Col] = new QPushButton(win) {
y = 50+(Col-1)*height
setgeometry(y+10,310,width,height)
setSizePolicy(1,1)
seticon(new qicon(new qpixmap(C_NIM)))
setIconSize(new qSize(60,60))
}
next
}
next
Row1 = new QPushButton(win) {
Row1 = new QPushButton(win) {
setgeometry(500,70,width,height)
setStyleSheet("color:Black;background-color:Orange")
setSizePolicy(1,1)
@ -98,7 +98,7 @@ app = new qApp
settext("Row1") }
Row2 = new QPushButton(win) {
Row2 = new QPushButton(win) {
setgeometry(500,150,width,height)
setStyleSheet("color:Black;background-color:Orange")
setSizePolicy(1,1)
@ -106,7 +106,7 @@ app = new qApp
settext("Row2") }
Row3 = new QPushButton(win) {
Row3 = new QPushButton(win) {
setgeometry(500,230,width,height)
setStyleSheet("color:Black;background-color:Orange")
setSizePolicy(1,1)
@ -114,33 +114,33 @@ app = new qApp
settext("Row3") }
Row4 = new QPushButton(win) {
Row4 = new QPushButton(win) {
setgeometry(500,310,width,height)
setStyleSheet("color:Black;background-color:Orange")
setSizePolicy(1,1)
setclickevent("deleteRow4()")
settext("Row4") }
labelYourScore = new QLabel(win) { setgeometry(60,20,150,30)
setFont(new qFont("Verdana",C_FONTSIZE,50,0))
labelYourScore = new QLabel(win) { setgeometry(60,20,150,30)
setFont(new qFont("Verdana",C_FONTSIZE,50,0))
settext("Your score: 0") }
labelComputerScore = new QLabel(win) { setgeometry(350,20,150,30)
setFont(new qFont("Verdana",C_FONTSIZE,50,0))
labelComputerScore = new QLabel(win) { setgeometry(350,20,150,30)
setFont(new qFont("Verdana",C_FONTSIZE,50,0))
settext("PC score: 0") }
btnNewGame = new QPushButton(win) { setgeometry(60,400,80,30)
setFont(new qFont("Verdana",C_FONTSIZE,50,0))
btnNewGame = new QPushButton(win) { setgeometry(60,400,80,30)
setFont(new qFont("Verdana",C_FONTSIZE,50,0))
settext("New")
setclickevent("newGame()") }
btnExit = new QPushButton(win) { setgeometry(400,400,80,30)
setFont(new qFont("Verdana",C_FONTSIZE,50,0))
btnExit = new QPushButton(win) { setgeometry(400,400,80,30)
setFont(new qFont("Verdana",C_FONTSIZE,50,0))
settext("Exit")
setclickevent("pQuit()") }
btnPcMove = new QPushButton(win) { setgeometry(200,400,140,30)
setFont(new qFont("Verdana",C_FONTSIZE,50,0))
btnPcMove = new QPushButton(win) { setgeometry(200,400,140,30)
setFont(new qFont("Verdana",C_FONTSIZE,50,0))
settext("PC move")
setclickevent("pcMove()") }
@ -319,53 +319,53 @@ func newGame()
pcMove = 0
for Col = 1 to limit1
Button1[Col] = new QPushButton(win) {
Button1[Col] = new QPushButton(win) {
y = 230+(Col-1)*height
setgeometry(y+10,70,width,height)
setSizePolicy(1,1)
seticon(new qicon(new qpixmap(C_NIM)))
setIconSize(new qSize(60,60))
show()
}
next
}
next
for Col = 1 to limit2
Button2[Col] = new QPushButton(win) {
Button2[Col] = new QPushButton(win) {
y = 170+(Col-1)*height
setgeometry(y+10,150,width,height)
setSizePolicy(1,1)
seticon(new qicon(new qpixmap(C_NIM)))
setIconSize(new qSize(60,60))
show()
}
next
}
next
for Col = 1 to limit3
Button3[Col] = new QPushButton(win) {
Button3[Col] = new QPushButton(win) {
y = 110+(Col-1)*height
setgeometry(y+10,230,width,height)
setSizePolicy(1,1)
seticon(new qicon(new qpixmap(C_NIM)))
setIconSize(new qSize(60,60))
show()
}
next
}
next
for Col = 1 to limit4
Button4[Col] = new QPushButton(win) {
Button4[Col] = new QPushButton(win) {
y = 50+(Col-1)*height
setgeometry(y+10,310,width,height)
setSizePolicy(1,1)
seticon(new qicon(new qpixmap(C_NIM)))
setIconSize(new qSize(60,60))
show()
}
next
}
next
func msgBox(cText)
func msgBox(cText)
mb = new qMessageBox(win) {
setWindowTitle('CalmoSoft Nim Game')
setText(cText)
setWindowTitle('CalmoSoft Nim Game')
setText(cText)
setstandardbuttons(QMessageBox_OK)
result = exec()
}

View file

@ -1,5 +1,5 @@
PROGRAM "nim-game"
VERSION "0.0000"
PROGRAM "nim-game"
VERSION "0.0000"
DECLARE FUNCTION Entry ()
@ -11,10 +11,10 @@ DO WHILE monton > 0
PRINT "There are "; monton; " tokens remaining. How many would you like to take? ";
llevar = UBYTE(INLINE$(""))
DO WHILE (llevar <= 0) OR (llevar > 3)
llevar = UBYTE(INLINE$("You must take 1, 2, or 3 tokens. How many would you like to take"))
llevar = UBYTE(INLINE$("You must take 1, 2, or 3 tokens. How many would you like to take"))
LOOP
PRINT "On my turn I will take"; 4 - llevar; " token(s)."
PRINT "On my turn I will take"; 4 - llevar; " token(s)."
monton = monton - 4
LOOP

View file

@ -5,10 +5,10 @@ while monton > 0
print "There are ", monton, " tokens remaining. How many would you like to take? ";
input "" llevar
while llevar = 0 or llevar > 3
input "You must take 1, 2, or 3 tokens. How many would you like to take? " llevar
input "You must take 1, 2, or 3 tokens. How many would you like to take? " llevar
wend
print "On my turn I will take ", 4 - llevar, " token(s)."
print "On my turn I will take ", 4 - llevar, " token(s)."
monton = monton - 4
wend

View file

@ -1,140 +1,140 @@
;
; Nim game using Z80 assembly language
;
; Runs under CP/M 3.1 on YAZE-AG-2.51.2 Z80 emulator
; Assembled with zsm4 on same emulator/OS, uses macro capabilities of said assembler
; Created with vim under Windows
;
; 2023-04-28 Xorph
;
;
; Nim game using Z80 assembly language
;
; Runs under CP/M 3.1 on YAZE-AG-2.51.2 Z80 emulator
; Assembled with zsm4 on same emulator/OS, uses macro capabilities of said assembler
; Created with vim under Windows
;
; 2023-04-28 Xorph
;
;
; Useful definitions
;
;
; Useful definitions
;
bdos equ 05h ; Call to CP/M BDOS function
readstr equ 0ah ; Read string from console
wrtstr equ 09h ; Write string to console
bdos equ 05h ; Call to CP/M BDOS function
readstr equ 0ah ; Read string from console
wrtstr equ 09h ; Write string to console
cr equ 0dh ; ASCII control characters
lf equ 0ah
cr equ 0dh ; ASCII control characters
lf equ 0ah
buflen equ 01h ; Length of input buffer
maxtok equ 12 ; Starting number of tokens
buflen equ 01h ; Length of input buffer
maxtok equ 12 ; Starting number of tokens
;
; Macro for BDOS calls
;
;
; Macro for BDOS calls
;
readln macro buf ; Read a line from input
push bc
ld c,readstr
ld de,buf
call bdos
pop bc
endm
readln macro buf ; Read a line from input
push bc
ld c,readstr
ld de,buf
call bdos
pop bc
endm
;
; =====================
; Start of main program
; =====================
;
;
; =====================
; Start of main program
; =====================
;
cseg
cseg
ld de,nim ; Print title and initialize
call print
ld c,maxtok ; Register c keeps track of remaining tokens
ld de,nim ; Print title and initialize
call print
ld c,maxtok ; Register c keeps track of remaining tokens
loop:
ld de,tokens ; Print the remaining tokens
call print
ld b,c ; Use b for loop to print remaining tokens
ld de,tokens ; Print the remaining tokens
call print
ld b,c ; Use b for loop to print remaining tokens
printtk:
ld de,token
call print
djnz printtk
ld de,prompt ; Prompt user for input
call print
readln inputbuf
ld de,token
call print
djnz printtk
ld a,(bufcont) ; Now check input for validity and compute response
ld hl,validinp+2 ; Start from end of valid string, so bc gets set to numeric equivalent
push bc ; Save token counter, use bc for cpdr
ld bc,3
cpdr ; Use automatic search function
jr nz,printerr ; If input character not found, print error
ld de,prompt ; Prompt user for input
call print
readln inputbuf
ld hl,mymoves ; Get character for response into a
add hl,bc ; bc contains index into check string as well as response string
pop bc
ld a,(hl)
ld (outbuf),a ; Put it in output buffer
ld a,(bufcont) ; Now check input for validity and compute response
ld hl,validinp+2 ; Start from end of valid string, so bc gets set to numeric equivalent
push bc ; Save token counter, use bc for cpdr
ld bc,3
cpdr ; Use automatic search function
jr nz,printerr ; If input character not found, print error
ld de,response ; Print the computer's move
call print
ld hl,mymoves ; Get character for response into a
add hl,bc ; bc contains index into check string as well as response string
pop bc
ld a,(hl)
ld (outbuf),a ; Put it in output buffer
ld a,c ; Subtract 4 tokens from counter
sub 4
ld c,a
ld de,response ; Print the computer's move
call print
jr nz,loop ; If not finished, repeat
ld de,lose ; Otherwise, player lost
call print
ld a,c ; Subtract 4 tokens from counter
sub 4
ld c,a
ret ; Return to CP/M
jr nz,loop ; If not finished, repeat
ld de,lose ; Otherwise, player lost
call print
printerr: ; Print error message and try again
pop bc
ld de,wronginp
call print
jp loop
ret ; Return to CP/M
print: ; Use subroutine instead of macro for smaller code
push bc
ld c,wrtstr
call bdos
pop bc
ret
printerr: ; Print error message and try again
pop bc
ld de,wronginp
call print
jp loop
;
; ===================
; End of main program
; ===================
;
print: ; Use subroutine instead of macro for smaller code
push bc
ld c,wrtstr
call bdos
pop bc
ret
;
; ================
; Data definitions
; ================
;
;
; ===================
; End of main program
; ===================
;
dseg
;
; ================
; Data definitions
; ================
;
inputbuf: ; Input buffer
defb buflen ; Maximum possible length
defb 00h ; Returned length of actual input
dseg
inputbuf: ; Input buffer
defb buflen ; Maximum possible length
defb 00h ; Returned length of actual input
bufcont:
defs buflen ; Actual input area
defs buflen ; Actual input area
nim:
defb 'Nim$' ; Dialog texts
defb 'Nim$' ; Dialog texts
prompt:
defb cr,lf,'How many will you take (1-3)? $'
defb cr,lf,'How many will you take (1-3)? $'
response:
defb cr,lf,'I take ' ; No $ here! Saves one print command
defb cr,lf,'I take ' ; No $ here! Saves one print command
outbuf:
defb ' $' ; For printing response
defb ' $' ; For printing response
tokens:
defb cr,lf,cr,lf,'Tokens: $'
defb cr,lf,cr,lf,'Tokens: $'
token:
defb '|$'
defb '|$'
lose:
defb cr,lf,'You lose!$'
defb cr,lf,'You lose!$'
wronginp:
defb cr,lf,'Wrong input$'
defb cr,lf,'Wrong input$'
validinp:
defb '123' ; Valid input
defb '123' ; Valid input
mymoves:
defb '321' ; Computer's response
defb '321' ; Computer's response