#!/usr/bin/env mars # -------------------------------------------------------------------------- # # Guessing Game in Mars # Copyright (C) 2008 Matt Giuca # -------------------------------------------------------------------------- # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . # -------------------------------------------------------------------------- # # This is intended as a demonstration of the Mars programming language. # -------------------------------------------------------------------------- # # -------------------------------------------------------------------------- # import prelude # Presents a guess and asks the user whether it's higher, lower, or equal. def ask(num :: Int) :: Int: var l :: Array(Int) print_string("My guess: ") print_value(num) print_string(". Higher (h), lower (l) or equal (e)? ") l = get_line() if eq(l, "h"): return 1 else: if eq(l, "l"): return -1 else: if eq(l, "e"): return 0 else: print_string("Please enter h, l or e.\n") return ask(num) # Given a range, makes a guess def guess(min :: Int, max :: Int) :: Int: return add(div(sub(max, min), 2), min) # Plays the game until success def guessing_loop(min :: Int, max :: Int) :: Int: var myguess :: Int var result :: Int if gt(min, max): print_string("You seem a bit confused. Let's start again.\n") min = 0 max = 100 myguess = guess(min, max) result = ask(myguess) switch result: case 0: print_string("I win!\n") return 0 case -1: max = sub(myguess, 1) case 1: min = add(myguess, 1) return guessing_loop(min, max) def main() :: Int: print_string("Think of a number [0,100].\n") return guessing_loop(0, 100)