Visual F# 100 Examples: Example 11

Problem: Make a simple crack the treasure chest console application game.

  1. // Learn more about F# at http://fsharp.net  
  2.   
  3. open System  
  4. //change the title to Crack the Safe  
  5. System.Console.Title<-"Crack the Safe"  
  6. //change the foreground color to green  
  7. Console.ForegroundColor<-ConsoleColor.Green  
  8. //dislay the game title screen  
  9. printfn "\t\t\t Crack the Safe"  
  10. printfn "\t\t\t Press enter to continue..."  
  11. //waits for a keypress from the user  
  12. System.Console.ReadLine()|>ignore  
  13. //Game action sequence  
  14. printfn "\t\t\t You have found a legendary treasure chest"  
  15. printfn "\t\t\t believed to contain the rarest gem on Earth"  
  16. printfn "\t\t\t Press enter to continue... "  
  17. //waits for a keypress from the user  
  18. System.Console.ReadLine()|>ignore  
  19.   
  20. printfn "\t\t\t this chest can be opened only by"  
  21. printfn "\t\t\t entering a mysterious 4-digit key code"  
  22. printfn "\t\t\t Press enter to continue..."  
  23. //waits for a keypress from the user  
  24. System.Console.ReadLine()|>ignore  
  25.   
  26. let random=new Random()  
  27. let intkeycode=Convert.ToInt32(random.Next(1000,9999))  
  28.   
  29. printfn "\t\t\tEnter the keycode:"  
  30. let intusercode= Convert.ToInt32(Console.ReadLine())  
  31. //if usercode is equal to the computer generated code then  
  32. if intusercode=intkeycode then  
  33. //display a congratulatory message  
  34.     printfn "\t\t\Congrats You have opened the treasure chest."  
  35.   
  36. //otherwise   
  37. else  
  38.     printfn "\t\t\tInvalid Code"  
  39.   
  40. printfn "\t\t\tPress enter to continue... "  
  41. System.Console.ReadLine()|>ignore  
  42. printfn "\t\t\tGame Over"  

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.