2016-07-12 2 views
0

인벤토리가 있고 올바른 화학 물질을 혼합해야하는 JavaScript에서 전보 봇으로 화학 게임을 만들고 있습니다. 인벤토리가 배열에 포함되어 있으며 인벤토리를 붙여 넣기 만하면 수준을 올리는 것을 막기 위해 사용자 입력에 독점적으로 필요한 화학 물질이 포함되어 있는지 확인해야합니다. 정렬. 예를 들어문자열에 배열의 특정 요소가 포함되어 있는지 확인하는 방법

:

users[id].inventory = ["Beaker", "Water", "Baking soda", "Heating plate", "Hydrochloric acid"]; 

if (users[id].level === 1 && 
    msg.text.toLowerCase().indexOf('baking soda') !== -1 && 
    msg.text.toLowerCase().indexOf('hydrochloric acid') !== -1 && 
    msg.text.toLowerCase().indexOf('beaker') === -1 && 
    msg.text.toLowerCase().indexOf('water') === -1 && 
    msg.text.toLowerCase().indexOf('heating plate') === -1) { 

    msg.answer("You mix some baking soda with hydrochloric acid.\nSome fun fizzing happens and you produce useless CO2 gas."); 
} 

당신이 훨씬 더 큰 재고를 얻을 것이다이 매우 큰 경우-문에이 방법을 이끌 것입니다 higer 수준에서. 이것은 나빠 보이고 더 좋은 방법이 있어야합니다. 독점적 인 indexOf() 또는 다른 솔루션과 같은 것이 있습니까? 예를 들어 arr.filter()을 확인했지만이 방법을 구현하는 좋은 방법을 찾을 수 없습니다.

+1

당신이 배열을 반복하는 루프를 사용하여 시도 적이 :

다음은 샘플입니다? – nnnnnn

답변

1

모든 성분을 수동으로 확인하는 것은 좋지 않습니다. 조리법에 대한 요구 사항이 길고 인벤토리가 길면 매우 지루할 것입니다.

두 개의 배열, 즉 요구 사항과 사용 된 항목을 취하는 rightIngredients 함수를 만드는 것이 좋습니다.

레시피의 항목 만 사용해야한다는 점을 감안하면 함수 내부에서 가장 먼저해야 할 일은 두 배열의 길이를 확인하는 것입니다. 그것들이 다른 경우는 false를 돌려 줄 필요가있어, 체크 할 필요는 없습니다.

배열의 길이가 같으면 사용 된 각 항목이 요구 사항에 있는지 확인합니다. 그들 중 하나가 아니라면 우리도 거짓을 돌려줍니다.

requirements = ["baking soda", "hydrochloric acid"]; 

function rightIngredients(req, uses) { 
    if (uses.length != req.length) { 
    console.log(uses.join(', ')+' are not even the right amount of ingredients'); 
    missing = true; 
    } else { 
    var i = 0; 
    var missing = false; 
    while (i<uses.length && !missing) { 
     if (req.indexOf(uses[i].toLowerCase())===-1) missing = true; 
     ++i; 
    } 
    if (missing) console.log(uses.join(', ')+' are not the right ingredients'); 
    else console.log(uses.join(', ')+' are the right ingredients'); 
    } 
    return !missing; 
} 
rightIngredients(requirements, ["Beaker", "Baking Soda", "Hydrochloric Acid"]); 
// Beaker, Baking Soda, Hydrochloric Acid are not even the right amount of ingredients 
rightIngredients(requirements, ["Beaker", "Baking Soda"]); 
// Beaker, Baking Soda are not the right ingredients 
rightIngredients(requirements, ["Baking Soda", "Hydrochloric Acid"]); 
// Baking Soda, Hydrochloric Acid are the right ingredients 
+0

이것은 정말 우아한 솔루션이며 저에게 좋습니다. 이것은 제가 찾고 있던 것입니다. 나는이 기술을 스스로 개발할 수 있기를 희망한다. – bdbdbd

1

당신은 모든 허용 화학 물질의 배열을 만든 다음 모든 요소가이 조건을 만족하는지 확인하기 위해 Array.every를 사용할 수 있습니다. 또한 수준에 따라 다른 조합을 갖게 될 것이므로 수준의지도와 허용되지 않는 화학 물질을 작성하고 기능을 제네릭으로 만들 것을 제안합니다.

// Map object of Level and Chemicals 
var map = [{ 
    level: 1, 
    disallowed_chemicals: ['baking soda', 'hydrochloric acid', 'beaker', 'water', 'heating plate'] 
}]; 

// getter function to get map object for current level. 
// If this returns undefined you can assume, incorrect level is entered 
function getLevelMap(u_level) { 
    return map.find(function(o) { 
    return o.level === u_level; 
    }); 
} 

var m_level = getLevelMap(users[id].level); 
if (m_level && 
    m_level.every(function(ch) { 
    return msg.toLowerCase().indexOf(ch) < 0; 
    })) { 

    msg.answer("You mix some baking soda with hydrochloric acid.\nSome fun fizzing happens and you produce useless CO2 gas."); 
} 
+0

레벨에 여러 단계가 있으므로 각 단계에서 허용되지 않는 화학 물질 대신 필요한 화학 물질을 쓰는 것이 짧기 때문에 Marc Copte의 대답이 가장 좋습니다. +1 노력. – bdbdbd

관련 문제