Saturday, November 27, 2010

Nim

Rem take as many pieces you want from one of the piles . The one who takes the last piece wins
a=7
b=6
c=5
font "arial",20,100
gosub draw
do
Input "Which pile a b or c? ", p$
Input "How many pieces? ", p
If p$ = "a" then a=a-p
If p$ = "b" then b=b-p
If p$ = "c" then c=c-p
Print "Your play"
gosub draw
pause 3
if a+b+c=0 then
print "You win"
end
end if
Print "Computer play"
gosub Computerplay
gosub draw
until a+b+c=0
Print "I Won"
Computerplay:
play=0
n=0
do
n=n+1
ma=0:mb=0:mc=0
letter = int(rand*3)
if a>0 and letter = 0 then
ma = int(rand*a+1)
a= a-ma
end if
if b>0 and letter = 1 then
mb = int(rand*b+1)
b= b-mb
end if
if c>0 and letter = 2 then
mc = int(rand*c+1)
c= c-mc
end if
gosub test
if sum <>0 then
a=a+ma : b=b+mb : c=c+mc
else
if ma+mb+mc>0 then play =1
end if
until play=1 or n=1000

# in this case the computer is loosing
if play = 0 then

letter = int(int(rand*22)/10)

if a=0 and letter = 0 then letter = 1
if b=0 and letter = 1 then letter = 2
if c=0 and letter = 2 then letter = 0
if a=0 and letter = 0 then letter = 1
if b=0 and letter = 1 then letter = 2

if letter = 0 then a= a-int(rand*a*.7+1)
if letter = 1 then b= b-int(rand*b*.7+1)
if letter = 2 then c= c-int(rand*c*.7+1)
end if

return


test:
sum=0
a1=a : b1=b :c1=c
for y=2 to 0 step -1
fa=0 : fb=0 : fc=0
if a>=2^y then
a=a-2^y
fa=1
end if
if b>=2^y then
b=b-2^y
fb=1
end if
if c>=2^y then
c=c-2^y
fc=1
end if
if fa=0 xor fb=0 xor fc=0 then
sum= sum+0
else
sum=sum+1
end if
next y
a=a1 : b=b1 : c=c1
return

draw:
clg
text 33,20," A          B          C"
for n = 1 to 10
if a>= n then circle 50,n*30+30,10
if b>= n then circle 150,n*30+30,10
if c>= n then circle 250,n*30+30,10
next n
print "a "+a
print "b "+b
print "c "+c
return