More efficient choice comparison for Rock Paper Scissors

前端 未结 6 877
你的背包
你的背包 2021-01-07 23:54

This is an ongoing school project that I would like to improve. The point is to make the code as efficient (or short) as possible. I would like to reduce it by finding an al

6条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-08 00:41

    You can define an object that define if your move is weak or strong against another. Example:

    const myChoice = 'Rock'
    const enemyChoice = 'Scissors' 
    
    const weapons = {
       Rock: {weakTo: 'Paper', strongTo: 'Scissors'},
       Paper: {weakTo: 'Scissors', strongTo: 'Rock'},
       Scissors: {weakTo: 'Rock', strongTo: 'Paper'}
    }
    
    if (weapons[myChoice].strongTo === enemyChoice) {
        // I won
        return;
    }
    
    if (weapons[myChoice].weakTo === enemyChoice) {
        // I Lost
        return;
    }
    
    // tie
    

提交回复
热议问题