Flipping bits game: Difference between revisions
→{{header|Haskell}}: Specified imports, applied hlint, hindent
SqrtNegInf (talk | contribs) m (→{{header|Perl 6}}: numeric sorting of rows) |
(→{{header|Haskell}}: Specified imports, applied hlint, hindent) |
||
Line 1,264:
=={{header|Haskell}}==
Maximum game size is 9x9 because the array indices are the characters 1 until 9.
<lang Haskell>import Data.Array (Array, (!), (//), array, bounds)
import Data.List (intersperse)
import Control.Monad (zipWithM_, replicateM, foldM, when)
import System.Random▼
▲import System.Random (randomRIO)
type Board = Array (Char, Char) Int
Line 1,276 ⟶ 1,278:
flp 1 = 0
numRows, numCols :: Board ->
numRows t =
in [a .. b]
numCols t =
in [a .. b]
▲numCols t = let ((_, a), (_, b)) = bounds t in [a .. b]
flipRow, flipCol :: Board -> Char -> Board
flipRow t r =
let e =
zip (repeat r) (numCols t) ]▼
[ (ix, flp
in t // e
flipCol t c =
let e =
zip (numRows t) (repeat c) ]▼
[ (ix, flp
in t // e
printBoard :: Board -> IO ()
printBoard t = do
zipWithM_
▲ p
[ [ t ! (y, x)
| y <- rows ]
-- create a random goal board, and flip rows and columns randomly
-- to get a starting board
setupGame :: Char -> Char -> IO (Board, Board)
setupGame sizey sizex
-- random cell value at (row, col)
= do
let mk rc = fmap (\v -> (rc, v)) $ randomRIO (0, 1)▼
let mk rc = (\v ->
goal <-
array (('a', '1'), (sizey, sizex)) <$>
▲ start <- do
mapM
let change :: Board -> Int -> IO Board▼
mk
[ (r, c)
change t 0 = fmap (flipRow t) $ randomRIO ('a', sizey)▼
| r
, c <- cols ]
change t 1 = fmap (flipCol t) $ randomRIO ('1', sizex)▼
start <-
-- make changes and get a starting board▼
if goal /= start -- check if boards are different▼
numMoves
--
then return (goal, start) -- all ok, return both boards
else setupGame sizey sizex -- try again
main :: IO ()
main = do
▲ where
▲ turns goal current moves = do
▲ putStrLn "\nGoal:"
▲ printBoard goal
printBoard current
▲ putStrLn "\nBoard:"
when (moves > 0)
putStrLn $ "\nYou've made
numRows current
if t == goal
then putStrLn $ "\nYou've won in "
tryAgain =
putStrLn ": Invalid row or
turns goal current moves</lang>
{{Out}}
▲ turns goal current moves
<pre>Select a board size (1 - 9).▼
▲Select a board size (1 - 9).
Press any other key to exit.
3
Line 1,395 ⟶ 1,413:
Flip a row (abc) or a column (123)
c
You've won in 2 moves!</pre>
=={{header|J}}==
|