I'm no F# expert. I've used F# at work before but only in a single project for lexing and parsing a simple domain specific language (and the bulk of that work was carried out by a colleague). So some of this code may stink, feel free to let me know about it :¬)
I got up this morning and thought: I fancy mucking around with some F#, I know I'll make a little game.
After some Googling I was left a little disappointed when I found no good, simple, tutorials. It's been about a year since I've done any F# so I'm as good as a newbie again and needed some hand-holding. Alas that wasn't going to happen.
So my first mission was to get hold of a simple input and graphics API ... Having used SDL some time ago with C++ I went hunting for a .NET wrapper and handily enough found this: link SDL.Net
Set up:
All you need to do (at least on a Windows box with Visual Studio) is download SDL.NET, run the exe, and add a reference via solution explorer.
Code:
Now, as you can see, this code is not a "game". It simply blits a background to the screen, overlays a sprite and moves him around in response to the left and right arrow keys... VERY not-a-game indeed. But it will hopefully give anyone reading this the simple first steps towards using SDL.NET with F#.
The code also uses mutable state so is not as purely functional as I would have liked.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#light | |
open SdlDotNet.Core; | |
open SdlDotNet.Graphics; | |
open SdlDotNet.Graphics.Sprites; | |
open SdlDotNet.Input; | |
open System.Drawing; | |
open System; | |
type StuperGario = class | |
val mutable location : Point | |
new () = {location = new Point(10,185)} | |
end | |
let screen = Video.SetVideoMode(512, 256) (* Drawing Surface *) | |
let man = new StuperGario() | |
let bg = new Surface(@"..\Imgs\bg.png") (* Background image *) | |
let manSprite = new Sprite(new Surface(@"..\Imgs\gario.png"),man.location) | |
let Update (args : TickEventArgs) = | |
screen.Blit(bg) |> ignore (* Draw Background *) | |
screen.Blit(manSprite,man.location) |> ignore (* Draw man *) | |
screen.Update() (* Render Screen *) | |
if Keyboard.IsKeyPressed(Key.LeftArrow) then man.location.X <- man.location.X + -3 | |
if Keyboard.IsKeyPressed(Key.RightArrow) then man.location.X <- man.location.X + 3 | |
let HandleInputDown(args : KeyboardEventArgs) = | |
match args.Key with | |
| Key.Escape ->Events.QuitApplication() (* Escape -> Quit *) | |
| _ -> ignore|>ignore | |
Video.WindowCaption <- "FSharp Game" (* Set the SDL Window Title *) | |
Events.KeyboardDown.Add(HandleInputDown) | |
Events.Tick.Add(Update) (* Update screen and player position *) | |
Events.Run() |