Penney's game: Difference between revisions

Content added Content deleted
No edit summary
Line 1,202: Line 1,202:
function penny_game()
function penny_game()
local player, computer = "", ""
local player, computer = "", ""

function player_choose()
function player_choose()
io.write( "Enter your sequence of three H and/or T: " )
io.write( "Enter your sequence of three H and/or T: " )
local t = io.read():upper()
local t = io.read():upper()
if t:len() > 3 then t = t:sub( 1, 3 ) end
if #t > 3 then t = t:sub( 1, 3 )
elseif #t < 3 then return ""
end

for i = 1, 3 do
for i = 1, 3 do
c = t:sub( i, i )
c = t:sub( i, i )
Line 1,216: Line 1,218:
return t
return t
end
end

function computer_choose()
function computer_choose()
local t = ""
local t = ""
if player:len() > 0 then
if #player > 0 then
if player:sub( 2, 2 ) == "T" then
if player:sub( 2, 2 ) == "T" then
t = "H"
t = "H"
Line 1,237: Line 1,238:
return t
return t
end
end

if math.random( 2 ) == 1 then
if math.random( 2 ) == 1 then
computer = computer_choose()
computer = computer_choose()
Line 1,253: Line 1,253:
io.write( "My sequence is: " .. computer .. "\n" )
io.write( "My sequence is: " .. computer .. "\n" )
end
end

local coin, i = "", 1
local coin, i = "", 1
while( true ) do
while( true ) do
Line 1,263: Line 1,262:
io.write( "H" )
io.write( "H" )
end
end
if #coin > 2 then

if coin:len() > 2 then
local seq = coin:sub( i, i + 2 )
seq = coin:sub( i, i + 2 )
i = i + 1
i = i + 1
if seq == player then
if seq == player then
Line 1,277: Line 1,275:
end
end
end
end

math.randomseed( os.time() )
math.randomseed( os.time() )
local cpu, user = 0, 0
local cpu, user = 0, 0
repeat
while( true ) do
r = penny_game()
r = penny_game()
if r > 0 then
if r > 0 then
Line 1,290: Line 1,287:
io.write( "Play again (Y/N)? " )
io.write( "Play again (Y/N)? " )
r = io.read()
r = io.read()
if( r == "N" or r == "n" ) then return end
until( r == "N" or r == "n" )
end
</lang>
</lang>
{{out}}
{{out}}
Line 1,316: Line 1,312:
>Exit code: 0
>Exit code: 0
</pre>
</pre>

=={{header|Perl}}==
=={{header|Perl}}==
<lang perl>
<lang perl>