Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
216 views
in Technique[技术] by (71.8m points)

java - Scalable solution for Rock-Paper-Scissor

Just went through a variant of the game : Rock-Paper-Scissor-Lizard-Spock

I have written a Java code for traditional R-P-S problem, but when I tried extending my code for the newer version of the game (R-P-S-L-S)..I felt my code is terribly bad. Here is a snippet :

 if (player1.equals("ROCK") && 
         player2.equals("SCISSORS")) {
        winner = 1;
    }
    // Paper covers rock...
    else if (player1.equals("PAPER") &&
         player2.equals("ROCK")) {
        winner = 1;
    }
    // Scissors cut paper...
    else if (player1.equals("SCISSORS") &&
         player2.equals("PAPER")) {
        winner = 1;
    }
    else {
        winner = 2;
    }

I realized the code cant be extended easily for the newer version - as well as for more than 2 players. This is mainly because of multiple if/else or switch/cases. I need some help re-designing my code for achieving the 2 objectives :

  1. Further modification as per R-P-C-L-S problem.

  2. Support for more than 2 players.

I don't need code, just some guidelines should help.

Thanks !!

EDIT : Seems like I was wrong in thinking that this game can be played by more than 2 players. I am sorry for this mistake, please ignore the second requirement.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In, Rock-Paper-Scissor games, it is easy to decide if move a wins against move b using their index at a cycle. So you don't have to manually decide in your code the result of every combination as other answers here suggest.


For the Rock-Paper-Scissor-Spock-Lizard version:

Let's assign a number to each move (0, 1, 2, 3, 4).

Notice that every move beats two moves:

  1. The move previous to it in the cycle (or four cases ahead)
  2. The move two cases ahead in the cycle

So let d = (5 + a - b) % 5. Then:

  1. d = 1 or d = 3 => a wins
  2. d = 2 or d = 4 => b wins
  3. d = 0 => tie

For the Rock-Paper-Scissor version:

let d = (3 + a - b) % 3. Then:

  1. d = 1 => a wins
  2. d = 2 => b wins
  3. d = 0 => tie

Generalization For n >= 3 and n odd:

Let d = (n + a - b) % n. Then:

  1. If d = 0 => tie
  2. If d % 2 = 1 => a wins
  3. If d % 2 = 0 => b wins

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...