Jump to content

Penney's game: Difference between revisions

No edit summary
Line 1,202:
function penny_game()
local player, computer = "", ""
 
function player_choose()
io.write( "Enter your sequence of three H and/or T: " )
local t = io.read():upper()
if #t:len() > 3 then t = t:sub( 1, 3 ) end
elseif #t < 3 then return ""
end
 
for i = 1, 3 do
c = t:sub( i, i )
Line 1,216 ⟶ 1,218:
return t
end
 
function computer_choose()
local t = ""
if #player:len() > 0 then
if player:sub( 2, 2 ) == "T" then
t = "H"
Line 1,237 ⟶ 1,238:
return t
end
 
if math.random( 2 ) == 1 then
computer = computer_choose()
Line 1,253:
io.write( "My sequence is: " .. computer .. "\n" )
end
 
local coin, i = "", 1
while( true ) do
Line 1,263 ⟶ 1,262:
io.write( "H" )
end
if #coin > 2 then
 
if local seq = coin:lensub() >i, i + 2 then)
seq = coin:sub( i, i + 2 )
i = i + 1
if seq == player then
Line 1,277 ⟶ 1,275:
end
end
 
math.randomseed( os.time() )
local cpu, user = 0, 0
repeat
while( true ) do
r = penny_game()
if r > 0 then
Line 1,290 ⟶ 1,287:
io.write( "Play again (Y/N)? " )
r = io.read()
ifuntil( r == "N" or r == "n" ) then return end
end
</lang>
{{out}}
Line 1,316 ⟶ 1,312:
>Exit code: 0
</pre>
 
=={{header|Perl}}==
<lang perl>
Cookies help us deliver our services. By using our services, you agree to our use of cookies.