Historical ReverseGame, Revision 1
In response to Text Based Games, here is a simple text based game (very simple) that shows off a few 4.0 methods, series, shuffle, join, prompt_number. It started off as a response to a post by Paul Bissex, Let's play a game: BASIC vs. Ruby vs. Python vs. PHP.
The game presents a list of numbers, 0-9. You must sort the list in 0-9 order. Initially the list will be shuffled. The trick is you can only reverse the first X number of items. Here's a very simple example:
[0 1 2 3 4 5 6 7 9 8] move (0 to quit)? 10 [8 9 7 6 5 4 3 2 1 0] move (0 to quit)? 2 [9 8 7 6 5 4 3 2 1 0] move (0 to quit)? 10 You've won in only 3 moves!
Here's the game code
include std/sequence.e include std/console.e constant SIZE = 9 sequence board sequence winner = series(0, 1, SIZE - 1) procedure reset_board() board = series(1, 1, SIZE - 1) board = shuffle(board) end procedure function get_board() return "[" & join(board + '0', " ") & "]" end function sequence help_message = ` You will be presented with a sequence of %d digits randomized. You can reverse the first X digits by entering the position number at the play prompt. The goal is to sort the list in the fewest number of moves. ` procedure main() integer turn_number = 1 puts(1, help_message) reset_board() while 1 do integer num = prompt_number(sprintf("%s turn %d, 0 to quit? ", { get_board(), turn_number }), { 0, 10 }) if num = 0 then printf(1, "You've tried %d times before quitting.\n", { turn_number }) abort(0) end if board = reverse(board, 1, num) if equal(board, winner) then printf(1, "You've won in only %d turns!\n", { turn_number }) abort(0) end if turn_number += 1 end while end procedure main()
For the fun of it, here is a code golf version that was entered into the original blog post.
include std/console.e include std/sequence.e object steps=1, gboard={1,2,3,4,5,6,7,8,9}, board=shuffle(gboard) while not equal(gboard, board) do board = reverse(board, 1, prompt_number(join(board+48) & "\nReverse how many? ", {1,9})) steps += 1 end while puts(1, sprintf("Done! That took you %d steps.", steps))
- diff to current revision, view current revision history, backlinks
- Last modified Dec 18, 2010 by jeremy