简体   繁体   English

基于文字的游戏动作

[英]Text-based game movement

I'm making a text-based game and I would like my hero to be able to move within a 3x3 grid. 我正在制作一个基于文本的游戏,我希望我的英雄能够在3x3网格内移动。 I tried doing this with a two-dimensional array fairly easily. 我尝试用二维数组很容易地做到这一点。 The problem that I encountered was that I wanted to call a method for each grid the hero was in. So if the hero was in grid 0,0 then I would call the atHouse() method, if he went to 0,1 I call the atTree() method. 我遇到的问题是我想为英雄所在的每个网格调用一个方法。因此,如果英雄位于网格0,0中,那么我将调用atHouse()方法,如果他转到了0.1,则调用atTree()方法。 Each of those methods would give a description of that area, items in it, etc... 这些方法中的每一种都将对该区域,其中的项目等进行描述。

So, since I wasn't able to store methods in an array I was thinking of possibly doing another way. 因此,由于无法将方法存储在数组中,因此我在考虑可能采取另一种方法。 I just don't know what way might be the best. 我只是不知道哪种方法最好。 Has anyone setup a world in a quality way that is better than what I described? 有没有人以比我描述的更好的质量方式建立世界?

I would think an array of a base class, call it location with a describe() method would be the best way to do this. 我认为一个基类数组,用describe()方法将其称为location ,将是实现此目的的最佳方法。 Then you can subclass a house class and a tree class. 然后,您可以将house类和tree类分为子类。

Or you could just create instances of location and set a description property. 或者,您可以只创建location实例并设置description属性。

Rather than storing objects in an array you could define a method which would take position as param. 与其将对象存储在数组中,不如定义一个将位置作为参数的方法。 Say position 1 means hero is in 0,0 and position 2 means hero is in 0,1. 说位置1表示英雄在0,0,位置2表示英雄在0,1。 You could define a method as: 您可以将方法定义为:

public void heroMoved(int position){
  switch(position){
    case 1:
           call method associated
           break;
    case 2:
           call method associated
           break;
        .
        .
        so on
}
}

The simplest solution is to create a factory method: 最简单的解决方案是创建一个工厂方法:

I'd suggest a 2d array with names for each position: 我建议一个二维数组,每个位置的名称:

[
    ["House", "Tree", "etc"],
    ["etc", "etc", "etc"],
    ["etc", "etc", "etc"]
]

Then, you'd pass the position into your factory method which would grab the function name for to use in a switch. 然后,将位置传递给工厂方法,该方法将获取要在开关中使用的函数名称。 Obviously, this solution is not the best, as you'll have to explicitly define each method call. 显然,此解决方案不是最佳解决方案,因为您必须显式定义每个方法调用。

public void runMethod(int row, int col)
{
    string mName = myArray[row][col];

    switch(mName)
    {
        case "House":
            atHouse();
        break;
        //etc
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM