7

非常に単純な 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# 構文で記述された手続き型プログラムです。

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

4 に答える 4

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
于 2010-12-21T17:38:41.250 に答える
4

それは素敵な小さなゲームです:-)。関数型プログラミングでは、(他の人が指摘したように) 変更可能な状態の使用を避けたいと思うでしょう。また、ゲームのコアを副作用のない関数として書きたいと思うでしょう (例えば、コンソールからの読み取りと書き込み)。

ゲームの重要な部分は、位置を制御する機能です。型シグネチャを持つ関数を持つようにコードをリファクタリングできます。

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

Noneゲームを終了する必要がある場合、関数は戻ります。それ以外の場合は、シンボルの新しい場所をSome(posX, posY)返しposXます。変更を行うことで、優れた機能コアが得られ、関数のテストも簡単になります (同じ入力に対して常に同じ結果が返されるため)。posY@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
于 2010-12-21T12:55:37.453 に答える
2

ゲームであり、コンソールを使用すると、ここには固有の状態と副作用があります。しかし、重要なことは、これらのミュータブルを排除することです。while ループの代わりに再帰ループを使用すると、再帰呼び出しごとに状態を引数として渡すことができるので、これを行うのに役立ちます。それ以外に、ここで F# の機能を利用する主な方法は、if/then ステートメントとスイッチの代わりにパターン マッチングを使用することですが、これは主に見た目の改善になります。

于 2010-12-21T03:32:22.503 に答える
1

過度に具体的にならないように努めます。別の方向に進みすぎて漠然としすぎている場合は、お知らせください。少し改善します。

ある種の状態を持つ機能的なプログラムを作成する場合、実装する基本的なメカニズムは次のようなものです。

(currentState, input) => newState

次に、その周りに小さなラッパーを記述して、入力のフェッチと出力の描画を処理できます。

于 2010-12-21T03:32:07.493 に答える