001 package org.bukkit.command.defaults; 002 003 import com.google.common.collect.ImmutableList; 004 import org.apache.commons.lang.Validate; 005 import org.bukkit.ChatColor; 006 import org.bukkit.command.BlockCommandSender; 007 import org.bukkit.command.Command; 008 import org.bukkit.command.CommandSender; 009 import org.bukkit.util.StringUtil; 010 011 import java.util.ArrayList; 012 import java.util.Arrays; 013 import java.util.List; 014 import org.bukkit.Bukkit; 015 import org.bukkit.World; 016 import org.bukkit.entity.HumanEntity; 017 018 public class GameRuleCommand extends VanillaCommand { 019 private static final List<String> GAMERULE_STATES = ImmutableList.of("true", "false"); 020 021 public GameRuleCommand() { 022 super("gamerule"); 023 this.description = "Sets a server's game rules"; 024 this.usageMessage = "/gamerule <rule name> <value> OR /gamerule <rule name>"; 025 this.setPermission("bukkit.command.gamerule"); 026 } 027 028 @Override 029 public boolean execute(CommandSender sender, String currentAlias, String[] args) { 030 if (!testPermission(sender)) return true; 031 032 if (args.length > 0) { 033 String rule = args[0]; 034 World world = getGameWorld(sender); 035 036 if (world.isGameRule(rule)) { 037 if (args.length > 1) { 038 String value = args[1]; 039 040 world.setGameRuleValue(rule, value); 041 Command.broadcastCommandMessage(sender, "Game rule " + rule + " has been set to: " + value); 042 } else { 043 String value = world.getGameRuleValue(rule); 044 sender.sendMessage(rule + " = " + value); 045 } 046 } else { 047 sender.sendMessage(ChatColor.RED + "No game rule called " + rule + " is available"); 048 } 049 050 return true; 051 } else { 052 sender.sendMessage(ChatColor.RED + "Usage: " + usageMessage); 053 sender.sendMessage("Rules: " + this.createString(getGameWorld(sender).getGameRules(), 0, ", ")); 054 055 return true; 056 } 057 } 058 059 private World getGameWorld(CommandSender sender) { 060 if (sender instanceof HumanEntity) { 061 World world = ((HumanEntity) sender).getWorld(); 062 if (world != null) { 063 return world; 064 } 065 } else if (sender instanceof BlockCommandSender) { 066 return ((BlockCommandSender) sender).getBlock().getWorld(); 067 } 068 069 return Bukkit.getWorlds().get(0); 070 } 071 072 @Override 073 public List<String> tabComplete(CommandSender sender, String alias, String[] args) throws IllegalArgumentException { 074 Validate.notNull(sender, "Sender cannot be null"); 075 Validate.notNull(args, "Arguments cannot be null"); 076 Validate.notNull(alias, "Alias cannot be null"); 077 078 if (args.length == 1) { 079 return StringUtil.copyPartialMatches(args[0], Arrays.asList(getGameWorld(sender).getGameRules()), new ArrayList<String>()); 080 } 081 082 if (args.length == 2) { 083 return StringUtil.copyPartialMatches(args[1], GAMERULE_STATES, new ArrayList<String>(GAMERULE_STATES.size())); 084 } 085 086 return ImmutableList.of(); 087 } 088 }