非常简单的F#中的RogueLike,使其更具“功能性”

时间:2010-12-21 03:22:37

标签: f# functional-programming roguelike

我有一些非常非常简单的RogueLike引擎的现有C#代码。故意天真,因为我试图尽可能简单地做到最低限度。它所做的就是使用箭头键和System.Console:

在硬编码的地图上移动@符号
//define the map
var map = new List<string>{
  "                                        ",
  "                                        ",
  "                                        ",
  "                                        ",
  "    ###############################     ",
  "    #                             #     ",
  "    #         ######              #     ",
  "    #         #    #              #     ",
  "    #### #### #    #              #     ",
  "       # #  # #    #              #     ",
  "       # #  # #    #              #     ",
  "    #### #### ######              #     ",
  "    #              =              #     ",
  "    #              =              #     ",
  "    ###############################     ",
  "                                        ",
  "                                        ",
  "                                        ",
  "                                        ",
  "                                        "
};

//set initial player position on the map
var playerX = 8;
var playerY = 6;

//clear the console
Console.Clear();

//send each row of the map to the Console
map.ForEach( Console.WriteLine );

//create an empty ConsoleKeyInfo for storing the last key pressed
var keyInfo = new ConsoleKeyInfo( );

//keep processing key presses until the player wants to quit
while ( keyInfo.Key != ConsoleKey.Q ) {
  //store the player's current location
  var oldX = playerX;
  var oldY = playerY;

  //change the player's location if they pressed an arrow key
  switch ( keyInfo.Key ) {
    case ConsoleKey.UpArrow:
      playerY--;
      break;
    case ConsoleKey.DownArrow:
      playerY++;
      break;
    case ConsoleKey.LeftArrow:
      playerX--;
      break;
    case ConsoleKey.RightArrow:
      playerX++;
      break;
  }

  //check if the square that the player is trying to move to is empty
  if( map[ playerY ][ playerX ] == ' ' ) {
    //ok it was empty, clear the square they were standing on before
    Console.SetCursorPosition( oldX, oldY );
    Console.Write( ' ' );
    //now draw them at the new square
    Console.SetCursorPosition( playerX, playerY );
    Console.Write( '@' );
  } else {
    //they can't move there, change their location back to the old location
    playerX = oldX;
    playerY = oldY;
  }

  //wait for them to press a key and store it in keyInfo
  keyInfo = Console.ReadKey( true );
}

我正在玩F#,最初我试图用功能概念来编写它,但事实证明我有点过头了,所以我做了一个直接的端口 - 它不是真的一个F#程序(虽然它编译并运行)它是一个用F#语法编写的程序程序:

open System

//define the map
let map = [ "                                        ";
            "                                        ";
            "                                        ";
            "                                        ";
            "    ###############################     ";
            "    #                             #     ";
            "    #         ######              #     ";
            "    #         #    #              #     ";
            "    #### #### #    #              #     ";
            "       # #  # #    #              #     ";
            "       # #  # #    #              #     ";
            "    #### #### ######              #     ";
            "    #              =              #     ";
            "    #              =              #     ";
            "    ###############################     ";
            "                                        ";
            "                                        ";
            "                                        ";
            "                                        ";
            "                                        " ]

//set initial player position on the map
let mutable playerX = 8
let mutable playerY = 6

//clear the console
Console.Clear()

//send each row of the map to the Console
map |> Seq.iter (printfn "%s")

//create an empty ConsoleKeyInfo for storing the last key pressed
let mutable keyInfo = ConsoleKeyInfo()

//keep processing key presses until the player wants to quit
while not ( keyInfo.Key = ConsoleKey.Q ) do
    //store the player's current location
    let mutable oldX = playerX
    let mutable oldY = playerY

    //change the player's location if they pressed an arrow key
    if keyInfo.Key = ConsoleKey.UpArrow then
        playerY <- playerY - 1
    else if keyInfo.Key = ConsoleKey.DownArrow then
        playerY <- playerY + 1
    else if keyInfo.Key = ConsoleKey.LeftArrow then
        playerX <- playerX - 1
    else if keyInfo.Key = ConsoleKey.RightArrow then
        playerX <- playerX + 1

    //check if the square that the player is trying to move to is empty
    if map.Item( playerY ).Chars( playerX ) = ' ' then
        //ok it was empty, clear the square they were standing on
        Console.SetCursorPosition( oldX, oldY )
        Console.Write( ' ' )
        //now draw them at the new square 
        Console.SetCursorPosition( playerX, playerY )
        Console.Write( '@' )
    else
        //they can't move there, change their location back to the old location
        playerX <- oldX
        playerY <- oldY

    //wait for them to press a key and store it in keyInfo
    keyInfo <- Console.ReadKey( true )

所以我的问题是,为了在功能上更加重写,我需要学习什么,你能给我一些提示,一个模糊的概述,那种事情。

我更倾向于向正确的方向推,而不是仅仅看到一些代码,但如果这是向您解释它的最简单的方法那么很好,但在这种情况下,您还可以请解释“为什么”而不是它的“如何”?

4 个答案:

答案 0 :(得分:9)

游戏编程通常会测试您管理复杂性的能力。我发现函数式编程鼓励你将解决问题分解成更小的部分。

您要做的第一件事是通过分离所有不同的问题将您的脚本变成一堆函数。我知道这听起来很愚蠢,但这样做会使代码更具功能性(双关语意)。你主要担心的是状态管理。我使用记录来管理位置状态,使用元组来管理运行状态。随着代码变得更高级,您将需要对象来干净地管理状态。

尝试在此游戏中添加更多功能,并随着功能的增长将功能分开。最终,您将需要对象来管理所有功能。

在游戏编程笔记中,不要将状态更改为其他内容,然后在未通过某些测试时将其更改回来。你想要最小的状态变化。因此,例如下面我计算newPosition,然后只有在此未来位置通过时才更改playerPosition

open System

// use a third party vector class for 2D and 3D positions
// or write your own for pratice
type Pos = {x: int; y: int} 
    with
    static member (+) (a, b) =
        {x = a.x + b.x; y = a.y + b.y}

let drawBoard map =
    //clear the console
    Console.Clear()
    //send each row of the map to the Console
    map |> List.iter (printfn "%s")

let movePlayer (keyInfo : ConsoleKeyInfo) =
    match keyInfo.Key with
    | ConsoleKey.UpArrow -> {x = 0; y = -1}
    | ConsoleKey.DownArrow -> {x = 0; y = 1}
    | ConsoleKey.LeftArrow -> {x = -1; y = 0}
    | ConsoleKey.RightArrow  -> {x = 1; y = 0}
    | _ -> {x = 0; y = 0}

let validPosition (map:string list) position =
    map.Item(position.y).Chars(position.x) = ' '

//clear the square player was standing on
let clearPlayer position =
    Console.SetCursorPosition(position.x, position.y)
    Console.Write( ' ' )

//draw the square player is standing on
let drawPlayer position =
    Console.SetCursorPosition(position.x, position.y)
    Console.Write( '@' )

let takeTurn map playerPosition =
    let keyInfo = Console.ReadKey true
    // check to see if player wants to keep playing
    let keepPlaying = keyInfo.Key <> ConsoleKey.Q
    // get player movement from user input
    let movement = movePlayer keyInfo
    // calculate the players new position
    let newPosition = playerPosition + movement
    // check for valid move
    let validMove = newPosition |> validPosition map
    // update drawing if move was valid
    if validMove then
        clearPlayer playerPosition
        drawPlayer newPosition
    // return state
    if validMove then
        keepPlaying, newPosition
    else
        keepPlaying, playerPosition

// main game loop
let rec gameRun map playerPosition =
    let keepPlaying, newPosition = playerPosition |> takeTurn map 
    if keepPlaying then
        gameRun map newPosition

// setup game
let startGame map playerPosition =
    drawBoard map
    drawPlayer playerPosition
    gameRun map playerPosition


//define the map
let map = [ "                                        ";
            "                                        ";
            "                                        ";
            "                                        ";
            "    ###############################     ";
            "    #                             #     ";
            "    #         ######              #     ";
            "    #         #    #              #     ";
            "    #### #### #    #              #     ";
            "       # #  # #    #              #     ";
            "       # #  # #    #              #     ";
            "    #### #### ######              #     ";
            "    #              =              #     ";
            "    #              =              #     ";
            "    ###############################     ";
            "                                        ";
            "                                        ";
            "                                        ";
            "                                        ";
            "                                        " ]

//initial player position on the map
let playerPosition = {x = 8; y = 6}

startGame map playerPosition

答案 1 :(得分:4)

这是一个不错的小游戏:-)。在函数式编程中,你想要避免使用可变状态(正如其他人所指出的那样)并且你也想要将游戏的核心编写为没有任何副作用的函数(例如从控制台和写入)。

游戏的关键部分是控制位置的功能。您可以重构代码以获得具有类型签名的函数:

val getNextPosition : (int * int) -> ConsoleKey -> option<int * int>

如果游戏应该退出,该函数将返回None。否则返回Some(posX, posY),其中posXposY@符号的新位置。通过执行更改,您可以获得一个很好的功能核心,并且函数getNextPosition也很容易测试(因为它总是为相同的输入返回相同的结果)。

要使用该函数,最好的选择是使用递归编写循环。主函数的结构如下所示:

let rec playing pos =
  match getNextPosition pos (Console.ReadKey()) with
  | None -> () // Quit the game
  | Some(newPos) ->
     // This function redraws the screen (this is a side-effect,
     // but it is localized to a single function)
     redrawScreen pos newPos
     playing newPos

答案 2 :(得分:2)

作为游戏,使用控制台,这里有状态和副作用,这是固有的。但是你要做的关键是消除那些可变的东西。使用递归循环而不是while循环将帮助您实现这一点,从那时起您可以将状态作为参数传递给每个递归调用。除此之外,我可以看到利用F#功能的主要功能是使用模式匹配而不是if / then语句和开关,尽管这主要是美学上的改进。

答案 3 :(得分:1)

我会尽量避免过于具体 - 如果我最后朝另一个方向走得太远而且这太模糊了,请告诉我,我会尝试稍微改进一下。

在制作具有某种状态的功能程序时,您要实现的基本机制如下:

(currentState, input) => newState

然后你可以在它周围编写一个小包装来处理获取输入和绘图输出。