返回介绍

Reading a level

发布于 2025-02-27 23:45:51 字数 2557 浏览 0 评论 0 收藏 0

The following constructor builds a level object. Its argument should be the array of strings that define the level.

function Level(plan) {
  this.width = plan[0].length;
  this.height = plan.length;
  this.grid = [];
  this.actors = [];

  for (var y = 0; y < this.height; y++) {
    var line = plan[y], gridLine = [];
    for (var x = 0; x < this.width; x++) {
      var ch = line[x], fieldType = null;
      var Actor = actorChars[ch];
      if (Actor)
        this.actors.push(new Actor(new Vector(x, y), ch));
      else if (ch == "x")
        fieldType = "wall";
      else if (ch == "!")
        fieldType = "lava";
      gridLine.push(fieldType);
    }
    this.grid.push(gridLine);
  }

  this.player = this.actors.filter(function(actor) {
    return actor.type == "player";
  })[0];
  this.status = this.finishDelay = null;
}

For brevity, the code does not check for malformed input. It assumes that you’ve given it a proper level plan, complete with a player start position and other essentials.

A level stores its width and height, along with two arrays—one for the grid and one for the actors, which are the dynamic elements. The grid is represented as an array of arrays, where each of the inner arrays represents a horizontal line and each square contains either null, for empty squares, or a string indicating the type of the square— "wall" or "lava" .

The actors array holds objects that track the current position and state of the dynamic elements in the level. Each of these is expected to have a pos property that gives its position (the coordinates of its top-left corner), a size property that gives its size, and a type property that holds a string identifying the element ( "lava" , "coin" , or "player" ).

After building the grid, we use the filter method to find the player actor object, which we store in a property of the level. The status property tracks whether the player has won or lost. When this happens, finishDelay is used to keep the level active for a short period of time so that a simple animation can be shown. (Immediately resetting or advancing the level would look cheap.) This method can be used to find out whether a level is finished:

Level.prototype.isFinished = function() {
  return this.status != null && this.finishDelay < 0;
};

This is a book about getting computers to do what you want them to do. Computers are about as common as screwdrivers today, but they contain a lot more hidden complexity and thus are harder to operate and understand. To many, they remain alien, slightly threatening things.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文