Rock-paper-scissors: Difference between revisions

→‎{{header|Java}}: Added fixes for expandability, added rules for RPScLSp in comments
m (→‎{{header|Tcl}}: More comments)
(→‎{{header|Java}}: Added fixes for expandability, added rules for RPScLSp in comments)
Line 223:
=={{header|Java}}==
{{works with|Java|1.5+}}
This could probably be made simpler, but some more complexity is necessary so that other items besides rock, paper, and scissors can be added (as school children and nerds like to do [setup for rock-paper-scissors-lizard-spock is in multi-line comments]). The method <code>getAIChoice()</code> borrows from [[#Ada|the Ada example]] in spirit, but is more generic to additional items.
<lang java5>import java.util.EnumMapArrays;
import java.util.Collections;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
Line 230 ⟶ 233:
public class RPS {
public enum Item{
ROCK, PAPER, SCISSORS;, /*LIZARD, SPOCK*/add other throwable items here if you wish;
}
//EnumMap uses a simple array under the hood
public static Map<Item, List<Item>> beats = new EnumMap<Item, List<Item>>(Item.class){{
put(Item.ROCK, Arrays.asList(Item.SCISSORS/*, Item.LIZARD*/));
put(Item.PAPER, Arrays.asList(Item.ROCK/*, Item.SPOCK*/));
put(Item.SCISSORS, Arrays.asList(Item.PAPER/*, Item.LIZARD*/));
/*
//add other rules here for additional types
put(Item.SPOCK, Arrays.asList(Item.ROCK, Item.SCISSORS));
put(Item.LIZARD, Arrays.asList(Item.SPOCK, Item.PAPER));
*/
}};
 
public static Map<Item, List<Item>> losesTo = new EnumMap<Item, List<Item>>(Item.class){{
put(Item.SCISSORS, Arrays.asList(Item.ROCK/*, Item.SPOCK*/));
put(Item.ROCK, Arrays.asList(Item.PAPER/*, Item.SPOCK*/));
put(Item.PAPER, Arrays.asList(Item.SCISSORS/*, Item.LIZARD*/));
/*
//add other rules here for additional types
put(Item.SPOCK, Arrays.asList(Item.PAPER, Item.LIZARD));
put(Item.LIZARD, Arrays.asList(Item.SCISSORS, Item.ROCK));
*/
}};
 
public static Map<Item, Integer> counts = new EnumMap<Item, Integer>(Item.class){{
put(Item.ROCK, 1);
Line 252 ⟶ 261:
put(Item.SCISSORS, 1);
//add other counts here for additional types
/*
put(Item.SPOCK, 1);
put(Item.LIZARD, 1);
*/
}};
 
private static int totalThrows = Item.values().length;
 
public static void main(String[] args){
Scanner in = new Scanner(System.in);
Line 274 ⟶ 287:
if(aiChoice.equals(choice)){
System.out.println("Tie!");
}else if(beats.get(choice).equalscontains(aiChoice)){
System.out.println("You chose...wisely. You win!");
}else{
Line 287 ⟶ 300:
for(Item item:Item.values()){
if(rand < counts.get(item)){
return Collections.shuffle(losesTo.get(item));
return losesTo.get(item).get(0);
}
rand -= counts.get(item);
Anonymous user