diff --git a/.classpath b/.classpath deleted file mode 100644 index a6f39b4..0000000 --- a/.classpath +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - - - diff --git a/.externalToolBuilders/Makejar.launch b/.externalToolBuilders/Makejar.launch deleted file mode 100644 index 8e7c645..0000000 --- a/.externalToolBuilders/Makejar.launch +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - - - diff --git a/.gitignore b/.gitignore index 8e397bb..519a052 100644 --- a/.gitignore +++ b/.gitignore @@ -1,9 +1,12 @@ -/nbproject/private/ -/.externalToolBuilders/ -/build/ -/dist/ -/bin -/nbproject/pmd.settings -/.idea/workspace.xml -/.idea/ant.xml -/.idea/workspace.xml \ No newline at end of file +# We use maven! +/build.xml + +# Maven +/target +dependency-reduced-pom.xml + +# IntelliJ +*.iml +*.ipr +*.iws +.idea/ diff --git a/.idea/.name b/.idea/.name deleted file mode 100644 index 06595ce..0000000 --- a/.idea/.name +++ /dev/null @@ -1 +0,0 @@ -Lottery \ No newline at end of file diff --git a/.idea/codeStyleSettings.xml b/.idea/codeStyleSettings.xml deleted file mode 100644 index 9178b38..0000000 --- a/.idea/codeStyleSettings.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - diff --git a/.idea/compiler.xml b/.idea/compiler.xml deleted file mode 100644 index b22c943..0000000 --- a/.idea/compiler.xml +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - diff --git a/.idea/copyright/profiles_settings.xml b/.idea/copyright/profiles_settings.xml deleted file mode 100644 index 3572571..0000000 --- a/.idea/copyright/profiles_settings.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/.idea/encodings.xml b/.idea/encodings.xml deleted file mode 100644 index e206d70..0000000 --- a/.idea/encodings.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - - diff --git a/.idea/libraries/Libs.xml b/.idea/libraries/Libs.xml deleted file mode 100644 index ac8ee69..0000000 --- a/.idea/libraries/Libs.xml +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml deleted file mode 100644 index 708c3fe..0000000 --- a/.idea/misc.xml +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - - http://www.w3.org/1999/xhtml - - - - - - diff --git a/.idea/modules.xml b/.idea/modules.xml deleted file mode 100644 index 0c9a58e..0000000 --- a/.idea/modules.xml +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - - - - diff --git a/.idea/scopes/scope_settings.xml b/.idea/scopes/scope_settings.xml deleted file mode 100644 index 922003b..0000000 --- a/.idea/scopes/scope_settings.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - \ No newline at end of file diff --git a/.idea/uiDesigner.xml b/.idea/uiDesigner.xml deleted file mode 100644 index 3b00020..0000000 --- a/.idea/uiDesigner.xml +++ /dev/null @@ -1,125 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/.idea/vcs.xml b/.idea/vcs.xml deleted file mode 100644 index 275077f..0000000 --- a/.idea/vcs.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/.project b/.project deleted file mode 100644 index b7ebe97..0000000 --- a/.project +++ /dev/null @@ -1,27 +0,0 @@ - - - Lottery - - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.eclipse.ui.externaltools.ExternalToolBuilder - full,incremental, - - - LaunchConfigHandle - <project>/.externalToolBuilders/Makejar.launch - - - - - - org.eclipse.jdt.core.javanature - - diff --git a/Lottery.iml b/Lottery.iml deleted file mode 100644 index bc3668d..0000000 --- a/Lottery.iml +++ /dev/null @@ -1,99 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/NewMakeJar.jardesc b/NewMakeJar.jardesc deleted file mode 100644 index 869adfd..0000000 --- a/NewMakeJar.jardesc +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - - - - - - - - - - - diff --git a/build.xml b/build.xml deleted file mode 100644 index df86c74..0000000 --- a/build.xml +++ /dev/null @@ -1,76 +0,0 @@ - - - - - - - - - - - Builds, tests, and runs the project Lottery. - - - - - diff --git a/lib/BOSEconomy.jar b/lib/BOSEconomy.jar deleted file mode 100644 index 2ce672a..0000000 Binary files a/lib/BOSEconomy.jar and /dev/null differ diff --git a/lib/Essentials.jar b/lib/Essentials.jar deleted file mode 100644 index 77fdef5..0000000 Binary files a/lib/Essentials.jar and /dev/null differ diff --git a/lib/MultiCurrency.jar b/lib/MultiCurrency.jar deleted file mode 100644 index 6a0a02d..0000000 Binary files a/lib/MultiCurrency.jar and /dev/null differ diff --git a/lib/Vault.jar b/lib/Vault.jar deleted file mode 100644 index 96b1625..0000000 Binary files a/lib/Vault.jar and /dev/null differ diff --git a/lib/bukkit.jar b/lib/bukkit.jar deleted file mode 100644 index 7abca41..0000000 Binary files a/lib/bukkit.jar and /dev/null differ diff --git a/lib/iConomy v4.jar b/lib/iConomy v4.jar deleted file mode 100644 index 6cb256b..0000000 Binary files a/lib/iConomy v4.jar and /dev/null differ diff --git a/lib/iConomy v5.jar b/lib/iConomy v5.jar deleted file mode 100644 index 71a5d71..0000000 Binary files a/lib/iConomy v5.jar and /dev/null differ diff --git a/lib/iConomy v6.jar b/lib/iConomy v6.jar deleted file mode 100644 index da3a867..0000000 Binary files a/lib/iConomy v6.jar and /dev/null differ diff --git a/nbproject/build-impl.xml b/nbproject/build-impl.xml deleted file mode 100644 index 5959189..0000000 --- a/nbproject/build-impl.xml +++ /dev/null @@ -1,1042 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Must set src.dir - Must set build.dir - Must set dist.dir - Must set build.classes.dir - Must set dist.javadoc.dir - Must set build.test.classes.dir - Must set build.test.results.dir - Must set build.classes.excludes - Must set dist.jar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Must set javac.includes - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Must set JVM to use for profiling in profiler.info.jvm - Must set profiler agent JVM arguments in profiler.info.jvmargs.agent - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Must select some files in the IDE or set javac.includes - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - To run this application from the command line without Ant, try: - - - - - - - java -cp "${run.classpath.with.dist.jar}" ${main.class} - - - - - - - - - - - - - - - - - - - - - - - - - To run this application from the command line without Ant, try: - - java -jar "${dist.jar.resolved}" - - - - - - - - - - - - - - - - - - - - - - - - - Must select one file in the IDE or set run.class - - - - Must select one file in the IDE or set run.class - - - - - - - - - - - - - - - - - - - - - - - Must select one file in the IDE or set debug.class - - - - - Must select one file in the IDE or set debug.class - - - - - Must set fix.includes - - - - - - - - - - - - - - - - - Must select one file in the IDE or set profile.class - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Must select some files in the IDE or set javac.includes - - - - - - - - - - - - - - - - - - Some tests failed; see details above. - - - - - - - - - Must select some files in the IDE or set test.includes - - - - Some tests failed; see details above. - - - - - Must select one file in the IDE or set test.class - - - - - - - - - - - - - - - - - - - - - - - - - - - Must select one file in the IDE or set applet.url - - - - - - - - - Must select one file in the IDE or set applet.url - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/nbproject/genfiles.properties b/nbproject/genfiles.properties deleted file mode 100644 index fe7eede..0000000 --- a/nbproject/genfiles.properties +++ /dev/null @@ -1,8 +0,0 @@ -build.xml.data.CRC32=f528f0b3 -build.xml.script.CRC32=04b187a3 -build.xml.stylesheet.CRC32=28e38971@1.44.1.45 -# This file is used by a NetBeans-based IDE to track changes in generated files such as build-impl.xml. -# Do not edit this file. You may delete it but then the IDE will never regenerate such files for you. -nbproject/build-impl.xml.data.CRC32=f528f0b3 -nbproject/build-impl.xml.script.CRC32=affd1a68 -nbproject/build-impl.xml.stylesheet.CRC32=fcddb364@1.50.1.46 diff --git a/nbproject/project.properties b/nbproject/project.properties deleted file mode 100644 index 5870188..0000000 --- a/nbproject/project.properties +++ /dev/null @@ -1,90 +0,0 @@ -annotation.processing.enabled=true -annotation.processing.enabled.in.editor=false -annotation.processing.processors.list= -annotation.processing.run.all.processors=true -annotation.processing.source.output=${build.generated.sources.dir}/ap-source-output -application.title=Lottery -application.vendor=Kent Rune Henriksen -auxiliary.org-netbeans-modules-projectimport-eclipse-core.key=src=src;file=lib/BOSEconomy.jar;file=lib/Essentials.jar;file=lib/iConomy v4.jar;file=lib/iConomy v5.jar;file=lib/iConomy v6.jar;file=lib/MultiCurrency.jar;output=bin; -auxiliary.org-netbeans-modules-projectimport-eclipse-core.project=. -auxiliary.org-netbeans-modules-projectimport-eclipse-core.timestamp=1322398032187 -build.classes.dir=${build.dir}/classes -build.classes.excludes=**/*.java,**/*.form -# This directory is removed when the project is cleaned: -build.dir=build -build.generated.dir=${build.dir}/generated -build.generated.sources.dir=${build.dir}/generated-sources -# Only compile against the classpath explicitly listed here: -build.sysclasspath=ignore -build.test.classes.dir=${build.dir}/test/classes -build.test.results.dir=${build.dir}/test/results -# Uncomment to specify the preferred debugger connection transport: -#debug.transport=dt_socket -debug.classpath=\ - ${run.classpath} -debug.test.classpath=\ - ${run.test.classpath} -# This directory is removed when the project is cleaned: -dist.dir=dist -dist.jar=${dist.dir}/Lottery.jar -dist.javadoc.dir=${dist.dir}/javadoc -endorsed.classpath= -excludes= -file.reference.BOSEconomy.jar=lib/BOSEconomy.jar -file.reference.bukkit.jar=lib/bukkit.jar -file.reference.Essentials.jar=lib/Essentials.jar -file.reference.iConomy_v4.jar=lib/iConomy v4.jar -file.reference.iConomy_v5.jar=lib/iConomy v5.jar -file.reference.iConomy_v6.jar=lib/iConomy v6.jar -file.reference.Lottery-src=src -file.reference.MultiCurrency.jar=lib/MultiCurrency.jar -file.reference.Vault.jar=lib/Vault.jar -includes=** -jar.compress=false -javac.classpath=\ - ${file.reference.BOSEconomy.jar}:\ - ${file.reference.Essentials.jar}:\ - ${file.reference.iConomy_v4.jar}:\ - ${file.reference.iConomy_v5.jar}:\ - ${file.reference.iConomy_v6.jar}:\ - ${file.reference.MultiCurrency.jar}:\ - ${file.reference.bukkit.jar}:\ - ${file.reference.Vault.jar} -# Space-separated list of extra javac options -javac.compilerargs= -javac.deprecation=false -javac.processorpath=\ - ${javac.classpath} -javac.source=1.6 -javac.target=1.6 -javac.test.classpath=\ - ${javac.classpath}:\ - ${build.classes.dir} -javac.test.processorpath=\ - ${javac.test.classpath} -javadoc.additionalparam= -javadoc.author=false -javadoc.encoding=${source.encoding} -javadoc.noindex=true -javadoc.nonavbar=true -javadoc.notree=true -javadoc.private=false -javadoc.splitindex=false -javadoc.use=false -javadoc.version=false -javadoc.windowtitle= -meta.inf.dir=${src.dir}/META-INF -mkdist.disabled=true -platform.active=default_platform -run.classpath=\ - ${javac.classpath}:\ - ${build.classes.dir} -# Space-separated list of JVM arguments used when running the project -# (you may also define separate properties like run-sys-prop.name=value instead of -Dname=value -# or test-sys-prop.name=value to set system properties for unit tests): -run.jvmargs= -run.test.classpath=\ - ${javac.test.classpath}:\ - ${build.test.classes.dir} -source.encoding=UTF-8 -src.dir=${file.reference.Lottery-src} diff --git a/nbproject/project.xml b/nbproject/project.xml deleted file mode 100644 index dfecea3..0000000 --- a/nbproject/project.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - org.netbeans.modules.java.j2seproject - - - Lottery - - - - - - - diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..889b2b5 --- /dev/null +++ b/pom.xml @@ -0,0 +1,39 @@ + + + 4.0.0 + + net.erbros + Lottery + 1.1.2 + + + 1.8 + 1.8 + + + + spigot-repo + https://hub.spigotmc.org/nexus/content/repositories/snapshots/ + + + vault-repo + http://nexus.hc.to/content/repositories/pub_releases + + + + + org.spigotmc + spigot-api + 1.11.2-R0.1-SNAPSHOT + provided + + + net.milkbowl.vault + VaultAPI + 1.6 + provided + + + \ No newline at end of file diff --git a/src/main/java/net/erbros/lottery/Etc.java b/src/main/java/net/erbros/lottery/Etc.java new file mode 100644 index 0000000..65d4199 --- /dev/null +++ b/src/main/java/net/erbros/lottery/Etc.java @@ -0,0 +1,145 @@ +package net.erbros.lottery; + +import org.bukkit.Material; + +import java.util.*; + + +public class Etc +{ + public static String formatCost( double cost, LotteryConfig lConfig ) + { + if ( lConfig.useEconomy() ) + { + return lConfig.formatCurrency( ( formatAmount( cost, lConfig.useEconomy() ) ) ); + } + else + { + return String.valueOf( + (int) formatAmount( cost, lConfig.useEconomy() ) ).concat( + " " + formatMaterialName( lConfig.getMaterial() ) ); + } + } + + public static double formatAmount( double amount, final boolean usingiConomy ) + { + + if ( usingiConomy ) + { + return Math.floor( amount * 100 ) / 100; + } + else + { + return Math.floor( amount ); + } + } + + public static String formatMaterialName( final int materialId ) + { + String rawMaterialName = Material.getMaterial( materialId ).toString(); + rawMaterialName = rawMaterialName.toLowerCase( Locale.ENGLISH ); + // Large first letter. + final String firstLetterCapital = rawMaterialName.substring( 0, 1 ).toUpperCase(); + rawMaterialName = firstLetterCapital + rawMaterialName.substring( 1, rawMaterialName.length() ); + return rawMaterialName.replace( "_", " " ); + } + + + public static String timeUntil( final long time, final boolean mini, LotteryConfig lConfig ) + { + long timeLeft = time; + // How many days left? + String stringTimeLeft = ""; + + if ( timeLeft >= 60 * 60 * 24 ) + { + final int days = (int) Math.floor( timeLeft / ( 60 * 60 * 24 ) ); + timeLeft -= 60 * 60 * 24 * days; + if ( mini ) + { + stringTimeLeft += Integer.toString( days ) + "d "; + } + else + { + stringTimeLeft += Integer.toString( days ) + " " + lConfig.getPlural( "day", days ) + ", "; + } + } + if ( timeLeft >= 60 * 60 ) + { + final int hours = (int) Math.floor( timeLeft / ( 60 * 60 ) ); + timeLeft -= 60 * 60 * hours; + if ( mini ) + { + stringTimeLeft += Integer.toString( hours ) + "h "; + } + else + { + stringTimeLeft += Integer.toString( hours ) + " " + lConfig.getPlural( "hour", hours ) + ", "; + } + } + if ( timeLeft >= 60 ) + { + final int minutes = (int) Math.floor( timeLeft / ( 60 ) ); + timeLeft -= 60 * minutes; + if ( mini ) + { + stringTimeLeft += Integer.toString( minutes ) + "m "; + } + else + { + stringTimeLeft += Integer.toString( minutes ) + " " + lConfig.getPlural( "minute", minutes ) + ", "; + } + } + else + { + // Lets remove the last comma, since it will look bad with 2 days, 3 + // hours, and 14 seconds. + if ( !stringTimeLeft.equalsIgnoreCase( "" ) && !mini ) + { + stringTimeLeft = stringTimeLeft.substring( + 0, stringTimeLeft.length() - 1 ); + } + } + final int secs = (int) timeLeft; + if ( mini ) + { + stringTimeLeft += secs + "s"; + } + else + { + if ( !stringTimeLeft.equalsIgnoreCase( "" ) ) + { + stringTimeLeft += "and "; + } + stringTimeLeft += Integer.toString( secs ) + " " + lConfig.getPlural( "second", secs ); + } + + return stringTimeLeft; + } + + public static int parseInt( final String arg ) + { + int newInt = 0; + try + { + newInt = Integer.parseInt( arg ); + } + catch ( NumberFormatException e ) + { + } + return newInt > 0 ? newInt : 0; + } + + public static double parseDouble( final String arg ) + { + double newDouble = 0; + try + { + newDouble = Double.parseDouble( arg ); + } + catch ( NumberFormatException e ) + { + } + return newDouble > 0 ? newDouble : 0; + } +} diff --git a/src/main/java/net/erbros/lottery/Lottery.java b/src/main/java/net/erbros/lottery/Lottery.java new file mode 100644 index 0000000..c81b1ec --- /dev/null +++ b/src/main/java/net/erbros/lottery/Lottery.java @@ -0,0 +1,251 @@ +package net.erbros.lottery; + +import net.milkbowl.vault.economy.Economy; +import org.bukkit.Bukkit; +import org.bukkit.Server; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.plugin.Plugin; +import org.bukkit.plugin.PluginManager; +import org.bukkit.plugin.RegisteredServiceProvider; +import org.bukkit.plugin.java.JavaPlugin; + + +public class Lottery extends JavaPlugin +{ + + public boolean timerStarted = false; + private Server server = null; + private LotteryConfig lConfig; + private LotteryGame lGame; + private static Economy economy; + + @Override + public void onDisable() + { + // Disable all running timers. + Bukkit.getServer().getScheduler().cancelTasks( this ); + + lConfig.debugMsg( "[Lottery]: has been disabled (including timers)." ); + } + + @Override + public void onEnable() + { + + FileConfiguration config; + lConfig = new LotteryConfig( this ); + lGame = new LotteryGame( this ); + // Lets find some configs + config = getConfig(); + config.options().copyDefaults( true ); + saveConfig(); + lConfig.loadConfig(); + + final PluginManager pm = getServer().getPluginManager(); + + server = getServer(); + + if ( lConfig.useWelcomeMessage() ) + { + pm.registerEvents( new PlayerJoinListener( this ), this ); + } + + getCommand( "lottery" ).setExecutor( new MainCommandExecutor( this ) ); + + // Is the date we are going to draw the lottery set? If not, we should + // do it. + if ( getNextexec() == 0 ) + { + // Set first time to be config hours later? Millisecs, * 1000. + setNextexec( System.currentTimeMillis() + extendTime() ); + } + setupEconomy(); + + // Start the timer for the first time. + startTimerSchedule( false ); + } + + private boolean setupEconomy() + { + if ( getServer().getPluginManager().getPlugin( "Vault" ) == null ) + { + return false; + } + RegisteredServiceProvider rsp = getServer().getServicesManager().getRegistration( Economy.class ); + if ( rsp == null ) + { + return false; + } + economy = rsp.getProvider(); + return economy != null; + } + + public boolean hasEconomy() + { + return economy != null; + } + + public Economy getEconomy() + { + return economy; + } + + public Server getBukkitServer() + { + return server; + } + + public LotteryConfig getLotteryConfig() + { + return lConfig; + } + + public LotteryGame getLotteryGame() + { + return lGame; + } + + protected long getNextexec() + { + return lConfig.getNextexec(); + } + + protected void setNextexec( final long aNextexec ) + { + lConfig.setNextexec( aNextexec ); + } + + public boolean isLotteryDue() + { + return getNextexec() > 0 && System.currentTimeMillis() + 1000 >= getNextexec(); + } + + public void startTimerSchedule( final boolean drawAtOnce ) + { + long extendtime; + // Cancel any existing timers. + if ( timerStarted ) + { + // Let's try and stop any running threads. + try + { + Bukkit.getServer().getScheduler().cancelTasks( (Plugin) this ); + } + catch ( ClassCastException exception ) + { + } + + extendtime = extendTime(); + } + else + { + // Get time until lottery drawing. + extendtime = getNextexec() - System.currentTimeMillis(); + } + // What if the admin changed the config to a shorter time? lets check, + // and if + // that is the case, lets use the new time. + if ( System.currentTimeMillis() + extendTime() < getNextexec() ) + { + setNextexec( System.currentTimeMillis() + extendTime() ); + } + + // If the time is passed (perhaps the server was offline?), draw lottery + // at once. + if ( extendtime <= 0 ) + { + extendtime = 1000; + lConfig.debugMsg( "Seems we need to make a draw at once!" ); + } + + // Is the drawAtOnce boolean set to true? In that case, do drawing in a + // few secs. + if ( drawAtOnce ) + { + extendtime = 100; + setNextexec( System.currentTimeMillis() + 100 ); + lConfig.debugMsg( "DRAW NOW" ); + } + + // Delay in server ticks. 20 ticks = 1 second. + extendtime = extendtime / 1000 * 20; + runDrawTimer( extendtime ); + + // Timer is now started, let it know. + timerStarted = true; + } + + public void lotteryDraw() + { + lConfig.debugMsg( "Doing a lottery draw" ); + + if ( getNextexec() > 0 && System.currentTimeMillis() + 1000 >= getNextexec() ) + { + // Get the winner, if any. And remove file so we are ready for + // new round. + lConfig.debugMsg( "Getting winner." ); + if ( !lGame.getWinner() ) + { + lConfig.debugMsg( "Failed getting winner" ); + } + setNextexec( System.currentTimeMillis() + extendTime() ); + } + // Call a new timer. + startTimerSchedule( false ); + } + + public void extendLotteryDraw() + { + // Cancel timer. + try + { + Bukkit.getServer().getScheduler().cancelTasks( (Plugin) this ); + } + catch ( ClassCastException exception ) + { + } + + long extendtime; + + // How much time left? Below 0? + if ( getNextexec() < System.currentTimeMillis() ) + { + extendtime = 3000; + } + else + { + extendtime = getNextexec() - System.currentTimeMillis(); + } + // Delay in server ticks. 20 ticks = 1 second. + extendtime = extendtime / 1000 * 20; + runDrawTimer( extendtime ); + } + + private void runDrawTimer( final long extendtime ) + { + // Is this very long until? On servers with lag and long between + // restarts there might be a very long time between when server + // should have drawn winner and when it will draw. Perhaps help the + // server a bit by only scheduling for half the length at a time? + // But only if its more than 5 seconds left. + if ( extendtime < 5 * 20 ) + { + server.getScheduler().runTaskLaterAsynchronously( this, new LotteryDraw( this, true ), extendtime ); + lConfig.debugMsg( "LotteryDraw() " + extendtime + 100 ); + } + else + { + final long newtime = extendtime / 10; + server.getScheduler().runTaskLaterAsynchronously( this, new LotteryDraw( this, false ), newtime ); + lConfig.debugMsg( "extendLotteryDraw() " + newtime ); + } + } + + public long extendTime() + { + final double exacttime = lConfig.getHours() * 60 * 60 * 1000; + final long extendTime = (long) exacttime; + lConfig.debugMsg( "extendTime: " + extendTime ); + return extendTime; + } +} \ No newline at end of file diff --git a/src/main/java/net/erbros/lottery/LotteryConfig.java b/src/main/java/net/erbros/lottery/LotteryConfig.java new file mode 100644 index 0000000..81933c3 --- /dev/null +++ b/src/main/java/net/erbros/lottery/LotteryConfig.java @@ -0,0 +1,400 @@ +package net.erbros.lottery; + +import org.bukkit.configuration.file.FileConfiguration; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.logging.Level; + + +public class LotteryConfig +{ + + final private Lottery plugin; + private FileConfiguration config; + private double cost; + private double hours; + private long nextexec; + private boolean useiConomy; + private int material; + private double extraInPot; + private boolean broadcastBuying; + private int broadcastBuyingTime; + private boolean welcomeMessage; + private double netPayout; + private boolean clearExtraInPot; + private int maxTicketsEachUser; + private int ticketsAvailable; + private String lastwinner; + private double lastwinneramount; + private boolean buyingExtendDeadline; + private int buyingExtendRemaining; + private double buyingExtendBase; + private double buyingExtendMultiplier; + private String taxTarget; + + private HashMap> messages; + + + public LotteryConfig( final Lottery plugin ) + { + this.plugin = plugin; + this.config = plugin.getConfig(); + } + + + public void loadConfig() + { + plugin.reloadConfig(); + config = plugin.getConfig(); + + debugMsg( "Loading Lottery configuration" ); + + hours = config.getDouble( "config.hours", 24 ); + + useiConomy = config.getBoolean( "config.useiConomy", true ); + material = config.getInt( "config.material", 266 ); + broadcastBuying = config.getBoolean( "config.broadcastBuying", true ); + broadcastBuyingTime = config.getInt( "config.broadcastBuyingTime", 120 ); + welcomeMessage = config.getBoolean( "config.welcomeMessage", true ); + extraInPot = config.getDouble( "config.extraInPot", 0 ); + clearExtraInPot = config.getBoolean( "config.clearExtraInPot", true ); + netPayout = config.getDouble( "config.netPayout", 100 ); + maxTicketsEachUser = config.getInt( "config.maxTicketsEachUser", 1 ); + ticketsAvailable = config.getInt( "config.numberOfTicketsAvailable", 0 ); + nextexec = config.getLong( "config.nextexec" ); + cost = Etc.formatAmount( config.getDouble( "config.cost", 5 ), useiConomy ); + lastwinner = config.getString( "config.lastwinner", "" ); + lastwinneramount = config.getDouble( "config.lastwinneramount", 0 ); + buyingExtendDeadline = config.getBoolean( "config.buyingExtend.enabled", true ); + buyingExtendRemaining = config.getInt( "config.buyingExtend.secondsRemaining", 30 ); + buyingExtendBase = config.getDouble( "config.buyingExtend.extendBase", 15 ); + buyingExtendMultiplier = config.getDouble( "config.buyingExtend.extendMultiplier", 1.5 ); + taxTarget = config.getString( "config.taxTarget", "" ); + + // Load messages? + loadCustomMessages(); + // Then lets save this stuff :) + plugin.saveConfig(); + } + + public void set( final String path, final Object value ) + { + config.set( path, value ); + plugin.saveConfig(); + } + + public void loadCustomMessages() + { + messages = new HashMap>(); + messages.put( "prefix", formatCustomMessage( "message.prefix", "&6[LOTTERY]&r" ) ); + + messages.put( "Welcome", formatCustomMessage( "message.Welcome", "%prefix% &fDraw in: &c%drawLong%" ) ); + messages.put( "ErrorPlugin", formatCustomMessage( "message.ErrorPlugin", "%prefix% Sorry, we haven\'t found a money plugin yet.." ) ); + messages.put( "ErrorAccess", formatCustomMessage( "message.ErrorAccess", "%prefix% You don\'t have access to that command." ) ); + messages.put( "ErrorCommand", formatCustomMessage( "message.ErrorCommand", "%prefix% Hey, I don\'t recognize that command!" ) ); + messages.put( "ErrorConsole", formatCustomMessage( "message.ErrorConsole", "%prefix% You\'re the console, I can\'t sell you tickets." ) ); + messages.put( "ErrorConsole2", formatCustomMessage( "message.ErrorConsole2", "%prefix% You\'re the console, you don\'t have an inventory." ) ); + messages.put( "ErrorConsole3", formatCustomMessage( "message.ErrorConsole3", "%prefix% You\'re the console, you can\'t change that." ) ); + messages.put( "ErrorNoAvailable", formatCustomMessage( "message.ErrorNoAvailable", "%prefix% There are no more tickets available" ) ); + messages.put( "ErrorAtMax", formatCustomMessage( "message.ErrorAtMax", "%prefix% You already have the maximum of %0% %1% already." ) ); + messages.put( "ErrorNotAfford", formatCustomMessage( "message.ErrorNotAfford", "%prefix% You can\'t afford a ticket" ) ); + messages.put( "ErrorNumber", formatCustomMessage( "message.ErrorNumber", "%prefix% Provide a number greater than zero (decimals accepted)" ) ); + messages.put( "ErrorClaim", formatCustomMessage( "message.ErrorClaim", "%prefix% You did not have anything unclaimed." ) ); + + messages.put( "TicketCommand", formatCustomMessage( "message.TicketCommand", "%prefix% Buy a ticket for &c%cost% &rwith &c/lottery buy" ) ); + messages.put( "PotAmount", formatCustomMessage( "message.PotAmount", "%prefix% There is currently &a%pot% &rin the pot." ) ); + messages.put( "YourTickets", formatCustomMessage( "message.YourTickets", "%prefix% You have &c%0% &r%1%" ) ); + messages.put( "TicketRemaining", formatCustomMessage( "message.TimeRemaining", "%prefix% There is &c%0% &r%1% left." ) ); + messages.put( "CommandHelp", formatCustomMessage( "message.CommandHelp", "%prefix% &c/lottery help&r for other commands" ) ); + messages.put( "LastWinner", formatCustomMessage( "message.LastWinner", "%prefix% Last winner: %0% %1%" ) ); + messages.put( "CheckClaim", formatCustomMessage( "message.CheckClaim", "%prefix% Check if you have won with &c/lottery claim" ) ); + messages.put( "BoughtTicket", formatCustomMessage( "message.BoughtTicket", "%prefix% You got &c%0% &r%1% for &c%2%" ) ); + messages.put( "BoughtTickets", formatCustomMessage( "message.BoughtTickets", "%prefix% You now have &c%0% &r%1%" ) ); + messages.put( "BoughtAnnounceDraw", formatCustomMessage( "message.BoughtAnnounceDraw", "%prefix% &r%0% &rjust bought %1% %2%! Draw in %3%" ) ); + messages.put( "BoughtAnnounce", formatCustomMessage( "message.BoughtAnnounce", "%prefix% &r%0% &rjust bought %1% %2%!" ) ); + messages.put( "DrawIn", formatCustomMessage( "message.DrawIn", "%prefix% Draw in: &c%0%" ) ); + messages.put( "DrawNow", formatCustomMessage( "message.DrawNow", "%prefix% Lottery will be drawn at once." ) ); + messages.put( "DrawSoon", formatCustomMessage( "message.DrawSoon", "Soon" ) ); + messages.put( "DrawSoonLong", formatCustomMessage( "message.DrawSoonLong", "Draw will occur soon!" ) ); + messages.put( "PlayerClaim", formatCustomMessage( "message.PlayerClaim", "%prefix You just claimed %0%" ) ); + messages.put( "MessagesEnabled", formatCustomMessage( "message.MessagesEnabled", "%prefix% You will now receive Lottery broadcast messages." ) ); + messages.put( "MessagesDisabled", formatCustomMessage( "message.MessagesDisabled", "%prefix% You will no longer receive Lottery broadcast messages." ) ); + + messages.put( "NoWinnerTickets", formatCustomMessage( "message.NoWinnerTickets", "%prefix% No tickets sold this round. That\'s a shame." ) ); + messages.put( "WinnerCongrat", formatCustomMessage( "message.WinnerCongrat", "%prefix% Congratulations go to %0% &rfor winning &c%1%&r with &c%2%&r %3%." ) ); + messages.put( "WinnerCongratClaim", formatCustomMessage( "message.WinnerCongratClaim", "%prefix% Use &c/lottery claim &rto claim the winnings." ) ); + messages.put( "WinnerSummary", formatCustomMessage( "message.WinnerSummary", "%prefix% There was a total of %0% %1% buying %2% %3%" ) ); + + messages.put( "AddToPot", formatCustomMessage( "message.AddToPot", "%prefix% Added &a%0% &rto pot. Extra total is &a%1%" ) ); + messages.put( "ConfigCost", formatCustomMessage( "message.ConfigCost", "%prefix% Cost changed to &c%0%" ) ); + messages.put( "ConfigHours", formatCustomMessage( "message.ConfigHours", "%prefix% Hours changed to &c%0%" ) ); + messages.put( "ConfigMax", formatCustomMessage( "message.ConfigMax", "%prefix% Max amount of tickets changed to &c%0%" ) ); + messages.put( "ConfigReload", formatCustomMessage( "message.ConfigReload", "%prefix% Config reloaded" ) ); + + messages.put( + "Help", formatCustomMessage( + "message.Help", + "%prefix% Help commands%newline%%prefix% &c/lottery&r : Basic lottery info.%newline%%prefix% &c/lottery buy &r : Buy ticket(s)." + + "%newline%%prefix% &c/lottery claim&r : Claim outstanding wins.%newline%%prefix% &c/lottery winners&r : Check last winners." ) ); + messages.put( + "HelpAdmin", formatCustomMessage( + "message.HelpAdmin", + "%prefix% &1/lottery draw&r : Draw lottery.%newline%%prefix% &1/lottery addtopot&r : Add number to pot.%newline%%prefix% &1/lottery " + + "config&r : Edit the config." ) ); + messages.put( "HelpPot", formatCustomMessage( "message.HelpPot", "%prefix% /lottery addtopot " ) ); + messages.put( + "HelpConfig", formatCustomMessage( + "message.HelpConfig", + "%prefix% Edit config commands%newline%%prefix% &c/lottery config cost %newline%%prefix% &c/lottery config hours %newline%%prefix% " + + "&c/lottery config maxTicketsEachUser %newline%%prefix% &c/lottery config reload" ) ); + messages.put( "ticket", formatCustomMessage( "message.Ticket", "ticket" ) ); + messages.put( "tickets", formatCustomMessage( "message.Tickets", "tickets" ) ); + messages.put( "player", formatCustomMessage( "message.player", "player" ) ); + messages.put( "players", formatCustomMessage( "message.players", "players" ) ); + messages.put( "day", formatCustomMessage( "message.day", "day" ) ); + messages.put( "days", formatCustomMessage( "message.days", "days" ) ); + messages.put( "hour", formatCustomMessage( "message.hour", "hour" ) ); + messages.put( "hours", formatCustomMessage( "message.hours", "hours" ) ); + messages.put( "minute", formatCustomMessage( "message.minute", "minute" ) ); + messages.put( "minutes", formatCustomMessage( "message.minutes", "minutes" ) ); + messages.put( "second", formatCustomMessage( "message.second", "second" ) ); + messages.put( "seconds", formatCustomMessage( "message.seconds", "seconds" ) ); + } + + public String getPlural( String word, int amount ) + { + String tlkey = ""; + + if ( word.equalsIgnoreCase( "ticket" ) ) + { + tlkey = amount == 1 ? "ticket" : "tickets"; + } + if ( word.equalsIgnoreCase( "player" ) ) + { + tlkey = amount == 1 ? "player" : "players"; + } + if ( word.equalsIgnoreCase( "day" ) ) + { + tlkey = amount == 1 ? "day" : "days"; + } + if ( word.equalsIgnoreCase( "hour" ) ) + { + tlkey = amount == 1 ? "hour" : "hours"; + } + if ( word.equalsIgnoreCase( "minute" ) ) + { + tlkey = amount == 1 ? "minute" : "minutes"; + } + if ( word.equalsIgnoreCase( "second" ) ) + { + tlkey = amount == 1 ? "second" : "seconds"; + } + + String pluralTl = ""; + try + { + for ( String message : getMessage( tlkey ) ) + { + pluralTl = message; + } + return pluralTl; + } + catch ( Exception e ) + { + e.printStackTrace(); + } + return pluralTl; + } + + public List getMessage( final String topic ) throws Exception + { + if ( !messages.containsKey( topic ) ) + { + throw new Exception( "Invalid Translation key" ); + } + return Collections.unmodifiableList( messages.get( topic ) ); + } + + public List formatCustomMessage( final String node, final String def ) + { + final List fList = new ArrayList(); + // Lets find a msg. + final String msg = config.getString( node, def ); + config.set( node, msg ); + + // Lets put this in a arrayList in case we want more than one line. + Collections.addAll( fList, msg.split( "%newline%" ) ); + return fList; + } + + // Enable some debugging? + public void debugMsg( final String msg ) + { + if ( config.getBoolean( "config.debug" ) && msg != null ) + { + plugin.getLogger().log( Level.INFO, msg ); + } + } + + public double getCost() + { + return cost; + } + + public void setCost( final double cost ) + { + this.cost = cost; + set( "config.cost", cost ); + } + + public double getHours() + { + return hours; + } + + public void setHours( final double hours ) + { + this.hours = hours; + set( "config.hours", hours ); + } + + public long getNextexec() + { + return nextexec; + } + + public void setNextexec( final long nextexec ) + { + this.nextexec = nextexec; + set( "config.nextexec", nextexec ); + } + + public boolean useEconomy() + { + return useiConomy; + } + + public int getMaterial() + { + return material; + } + + public double getExtraInPot() + { + return extraInPot; + } + + public void setExtraInPot( final double extraInPot ) + { + this.extraInPot = extraInPot; + set( "config.extraInPot", extraInPot ); + } + + public void addExtraInPot( final double extra ) + { + extraInPot += extra; + setExtraInPot( extraInPot ); + } + + public boolean useBroadcastBuying() + { + return broadcastBuying; + } + + public int getBroadcastBuyingTime() + { + return broadcastBuyingTime; + } + + public boolean useWelcomeMessage() + { + return welcomeMessage; + } + + public double getNetPayout() + { + return netPayout; + } + + public void setNetPayout( final double netPayout ) + { + this.netPayout = netPayout; + set( "config.netPayout", netPayout ); + } + + public boolean clearExtraInPot() + { + return clearExtraInPot; + } + + public int getMaxTicketsEachUser() + { + return maxTicketsEachUser; + } + + public void setMaxTicketsEachUser( final int maxTicketsEachUser ) + { + this.maxTicketsEachUser = maxTicketsEachUser; + set( "config.maxTicketsEachUser", maxTicketsEachUser ); + } + + public int getTicketsAvailable() + { + return ticketsAvailable; + } + + public String getLastwinner() + { + return lastwinner; + } + + public void setLastwinner( final String lastwinner ) + { + this.lastwinner = lastwinner; + set( "config.lastwinner", lastwinner ); + } + + public double getLastwinneramount() + { + return lastwinneramount; + } + + public void setLastwinneramount( final double lastwinneramount ) + { + this.lastwinneramount = lastwinneramount; + set( "config.lastwinneramount", lastwinneramount ); + } + + public boolean isBuyingExtendDeadline() + { + return buyingExtendDeadline; + } + + public int getBuyingExtendRemaining() + { + return buyingExtendRemaining; + } + + public double getBuyingExtendBase() + { + return buyingExtendBase; + } + + public double getBuyingExtendMultiplier() + { + return buyingExtendMultiplier; + } + + public String getTaxTarget() + { + return taxTarget; + } + + public String formatCurrency( double amount ) + { + return plugin.getEconomy().format( amount ); + } +} diff --git a/src/main/java/net/erbros/lottery/LotteryDraw.java b/src/main/java/net/erbros/lottery/LotteryDraw.java new file mode 100644 index 0000000..30242e8 --- /dev/null +++ b/src/main/java/net/erbros/lottery/LotteryDraw.java @@ -0,0 +1,38 @@ +package net.erbros.lottery; + +import java.util.TimerTask; + + +class LotteryDraw extends TimerTask +{ + + final private Lottery plugin; + final private boolean draw; + + public LotteryDraw( final Lottery plugin, final boolean draw ) + { + this.plugin = plugin; + this.draw = draw; + } + + public void run() + { + + if ( draw && plugin.isLotteryDue() ) + { + plugin.getServer().getScheduler().scheduleSyncDelayedTask( + plugin, new Runnable() + { + @Override + public void run() + { + plugin.lotteryDraw(); + } + } ); + } + else + { + plugin.extendLotteryDraw(); + } + } +} \ No newline at end of file diff --git a/src/main/java/net/erbros/lottery/LotteryEntry.java b/src/main/java/net/erbros/lottery/LotteryEntry.java new file mode 100644 index 0000000..5e908d7 --- /dev/null +++ b/src/main/java/net/erbros/lottery/LotteryEntry.java @@ -0,0 +1,47 @@ +package net.erbros.lottery; + +import java.util.UUID; + +/* + * Copyright 2015 Luuk Jacobs + + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +public class LotteryEntry +{ + private final UUID uuid; + private final String name; + private int tickets; + + public LotteryEntry( UUID uuid, String name, int tickets ) + { + this.uuid = uuid; + this.name = name; + this.tickets = tickets; + } + + public UUID getUUID() + { + return uuid; + } + + public String getName() + { + return name; + } + + public int getTickets() + { + return tickets; + } +} diff --git a/src/main/java/net/erbros/lottery/LotteryGame.java b/src/main/java/net/erbros/lottery/LotteryGame.java new file mode 100644 index 0000000..97971dc --- /dev/null +++ b/src/main/java/net/erbros/lottery/LotteryGame.java @@ -0,0 +1,522 @@ +package net.erbros.lottery; + +import net.erbros.lottery.events.LotteryBuyTicketEvent; +import net.erbros.lottery.events.LotteryDrawEvent; +import org.bukkit.Bukkit; +import org.bukkit.OfflinePlayer; +import org.bukkit.command.CommandSender; +import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import java.io.*; +import java.util.ArrayList; +import java.util.UUID; +import java.util.logging.Level; +import java.util.regex.Matcher; + + +public class LotteryGame +{ + + final private Lottery plugin; + final private LotteryConfig lConfig; + final private File playersfile; + + public LotteryGame( final Lottery plugin ) + { + playersfile = new File( plugin.getDataFolder(), "lotteryPlayers.yml" ); + this.plugin = plugin; + lConfig = plugin.getLotteryConfig(); + } + + public boolean addPlayer( final Player player, final int maxAmountOfTickets, final int numberOfTickets ) + { + LotteryBuyTicketEvent buyEvent = new LotteryBuyTicketEvent( player, numberOfTickets ); + plugin.getServer().getPluginManager().callEvent( buyEvent ); + if ( buyEvent.isCancelled() ) + { + return false; + } + // Do the ticket cost money or item? + if ( lConfig.useEconomy() && plugin.hasEconomy() ) + { + // Do the player have money? + // First checking if the player got an account, if not let's create + // it. + OfflinePlayer p = Bukkit.getOfflinePlayer( player.getUniqueId() ); + if ( !plugin.getEconomy().hasAccount( p ) ) + { + plugin.getEconomy().createPlayerAccount( p ); + } + final double balance = plugin.getEconomy().getBalance( p ); + + // And lets withdraw some money + if ( balance > lConfig.getCost() * numberOfTickets ) + { + // Removing coins from players account. + plugin.getEconomy().withdrawPlayer( p, lConfig.getCost() * numberOfTickets ); + } + else + { + return false; + } + lConfig.debugMsg( "taking " + ( lConfig.getCost() * numberOfTickets ) + "from account" ); + } + else + { + // Do the user have the item + if ( player.getInventory().contains( lConfig.getMaterial(), (int) lConfig.getCost() * numberOfTickets ) ) + { + // Remove items. + player.getInventory().removeItem( + new ItemStack( lConfig.getMaterial(), (int) lConfig.getCost() * numberOfTickets ) ); + } + else + { + return false; + } + } + // If the user paid, continue. Else we would already have sent return + // false + YamlConfiguration config = loadPlayersFile(); + int tickets = config.getInt( "players." + player.getUniqueId() + ".tickets", 0 ); + tickets += numberOfTickets; + config.set( "players." + player.getUniqueId() + ".tickets", tickets ); + config.set( "players." + player.getUniqueId() + ".name", player.getName() ); + savePlayersFile( config ); + return true; + } + + public RandomCollection getBoughtTickets() + { + final RandomCollection players = new RandomCollection<>(); + + YamlConfiguration config = loadPlayersFile(); + if ( !config.isConfigurationSection( "players" ) ) + { + return new RandomCollection<>(); + } + ConfigurationSection section = config.getConfigurationSection( "players" ); + for ( String key : section.getKeys( false ) ) + { + UUID uuid = UUID.fromString( key ); + int tickets = section.getInt( key + ".tickets", 0 ); + String name = section.getString( key + ".name", "" ); + players.add( tickets, new LotteryEntry( uuid, name, tickets ) ); + } + return players; + } + + private YamlConfiguration loadPlayersFile() + { + if ( !playersfile.exists() ) + { + try + { + playersfile.createNewFile(); + } + catch ( IOException e ) + { + e.printStackTrace(); + } + } + return YamlConfiguration.loadConfiguration( playersfile ); + } + + private void savePlayersFile( YamlConfiguration config ) + { + try + { + config.save( playersfile ); + } + catch ( IOException e ) + { + e.printStackTrace(); + } + } + + public double winningAmount() + { + double amount; + final RandomCollection players = getBoughtTickets(); + int ticketsize = 0; + for ( LotteryEntry entry : players.values() ) + { + ticketsize += entry.getTickets(); + } + amount = ticketsize * Etc.formatAmount( lConfig.getCost(), lConfig.useEconomy() ); + lConfig.debugMsg( "playerno: " + players.size() + " amount: " + amount ); + // Set the net payout as configured in the config. + if ( lConfig.getNetPayout() > 0 ) + { + amount = amount * lConfig.getNetPayout() / 100; + } + // Add extra money added by admins and mods? + amount += lConfig.getExtraInPot(); + // Any money in jackpot? + + // format it once again. + amount = Etc.formatAmount( amount, lConfig.useEconomy() ); + + return amount; + } + + public double taxAmount() + { + double amount = 0; + + // we only have tax is the net payout is between 0 and 100. + if ( lConfig.getNetPayout() >= 100 || lConfig.getNetPayout() <= 0 || !lConfig.useEconomy() ) + { + return amount; + } + + final RandomCollection players = getBoughtTickets(); + amount = players.size() * Etc.formatAmount( lConfig.getCost(), lConfig.useEconomy() ); + + // calculate the tax. + amount = amount * ( 1 - ( lConfig.getNetPayout() / 100 ) ); + + // format it once again. + amount = Etc.formatAmount( amount, lConfig.useEconomy() ); + + return amount; + } + + public int ticketsSold() + { + int sold; + final RandomCollection players = getBoughtTickets(); + sold = players.size(); + return sold; + } + + public void removeFromClaimList( final Player player ) + { + // Do the player have something to claim? + final ArrayList otherPlayersClaims = new ArrayList(); + final ArrayList claimArray = new ArrayList(); + try + { + final BufferedReader in = new BufferedReader( + new FileReader( plugin.getDataFolder() + File.separator + "lotteryClaim.txt" ) ); + String str; + while ( ( str = in.readLine() ) != null ) + { + final String[] split = str.split( ":" ); + if ( split[0].equals( player.getUniqueId().toString() ) ) + { + // Adding this to player claim. + claimArray.add( str ); + } + else + { + otherPlayersClaims.add( str ); + } + } + in.close(); + } + catch ( IOException e ) + { + } + + // Did the user have any claims? + if ( claimArray.isEmpty() ) + { + sendMessage( player, "ErrorClaim" ); + } + // Do a bit payout. + for ( String aClaimArray : claimArray ) + { + final String[] split = aClaimArray.split( ":" ); + final int claimAmount = Integer.parseInt( split[1] ); + final int claimMaterial = Integer.parseInt( split[2] ); + player.getInventory().addItem( new ItemStack( claimMaterial, claimAmount ) ); + sendMessage( player, "PlayerClaim", Etc.formatMaterialName( claimMaterial ) ); + } + + // Add the other players claims to the file again. + try + { + final BufferedWriter out = new BufferedWriter( + new FileWriter( plugin.getDataFolder() + File.separator + "lotteryClaim.txt" ) ); + for ( String otherPlayersClaim : otherPlayersClaims ) + { + out.write( otherPlayersClaim ); + out.newLine(); + } + + out.close(); + } + catch ( IOException e ) + { + } + } + + public void addToClaimList( final UUID player, final int winningAmount, final int winningMaterial ) + { + // Then first add new winner, and after that the old winners. + try + { + final BufferedWriter out = new BufferedWriter( + new FileWriter( plugin.getDataFolder() + File.separator + "lotteryClaim.txt", true ) ); + out.write( player + ":" + winningAmount + ":" + winningMaterial ); + out.newLine(); + out.close(); + } + catch ( IOException e ) + { + } + } + + public void addToWinnerList( final String playerName, final Double winningAmount, final int winningMaterial ) + { + // This list should be 10 players long. + final ArrayList winnerArray = new ArrayList(); + try + { + final BufferedReader in = new BufferedReader( + new FileReader( plugin.getDataFolder() + File.separator + "lotteryWinners.txt" ) ); + String str; + while ( ( str = in.readLine() ) != null ) + { + winnerArray.add( str ); + } + in.close(); + } + catch ( IOException e ) + { + } + // Then first add new winner, and after that the old winners. + try + { + final BufferedWriter out = new BufferedWriter( + new FileWriter( plugin.getDataFolder() + File.separator + "lotteryWinners.txt" ) ); + out.write( playerName + ":" + winningAmount + ":" + winningMaterial ); + out.newLine(); + // How long is the array? We just want the top 9. Removing index 9 + // since its starting at 0. + if ( !winnerArray.isEmpty() ) + { + if ( winnerArray.size() > 9 ) + { + winnerArray.remove( 9 ); + } + // Go trough list and output lines. + for ( String aWinnerArray : winnerArray ) + { + out.write( aWinnerArray ); + out.newLine(); + } + } + out.close(); + } + catch ( IOException e ) + { + } + } + + public long timeUntil() + { + final long nextDraw = lConfig.getNextexec(); + return ( ( nextDraw - System.currentTimeMillis() ) / 1000 ); + } + + public String timeUntil( final boolean mini ) + { + final long timeLeft = timeUntil(); + // If negative number, just tell them its DRAW TIME! + if ( timeLeft < 0 ) + { + // Lets make it draw at once.. ;) + plugin.startTimerSchedule( true ); + // And return some string to let the user know we are doing our best ;) + if ( mini ) + { + return "Soon"; + } + return "Draw will occur soon!"; + } + + return Etc.timeUntil( timeLeft, mini, lConfig ); + } + + public boolean getWinner() + { + final RandomCollection players = getBoughtTickets(); + if ( players.isEmpty() ) + { + broadcastMessage( "NoWinnerTickets" ); + return false; + } + else + { + LotteryEntry winner = players.next(); + double amount = winningAmount(); + int ticketsBought = winner.getTickets(); + if ( lConfig.useEconomy() ) + { + OfflinePlayer p = Bukkit.getOfflinePlayer( winner.getUUID() ); + if ( !plugin.getEconomy().hasAccount( p ) ) + { + plugin.getEconomy().createPlayerAccount( p ); + } + + // Just make sure the account exists, or make it with default + // value. + // Add money to account. + plugin.getEconomy().depositPlayer( p, amount ); + // Announce the winner: + broadcastMessage( "WinnerCongrat", winner.getName(), Etc.formatCost( amount, lConfig ), ticketsBought, lConfig.getPlural( "ticket", ticketsBought ) ); + addToWinnerList( winner.getName(), amount, 0 ); + + double taxAmount = taxAmount(); + if ( taxAmount() > 0 && lConfig.getTaxTarget().length() > 0 ) + { + OfflinePlayer target = Bukkit.getOfflinePlayer( lConfig.getTaxTarget() ); + if ( target == null ) + { + plugin.getLogger().warning( "Invalid economy account specified '" + lConfig.getTaxTarget() + "', tax lost. Fix your 'taxTarget' in config file." ); + } + if ( !plugin.getEconomy().hasAccount( target ) ) + { + plugin.getEconomy().createPlayerAccount( target ); + } + plugin.getEconomy().depositPlayer( target, taxAmount ); + } + } + else + { + // let's throw it to an int. + final int matAmount = (int) Etc.formatAmount( amount, lConfig.useEconomy() ); + amount = (double) matAmount; + + broadcastMessage( "WinnerCongrat", winner.getName(), Etc.formatCost( amount, lConfig ), ticketsBought, lConfig.getPlural( "ticket", ticketsBought ) ); + broadcastMessage( "WinnerCongratClaim" ); + addToWinnerList( winner.getName(), amount, lConfig.getMaterial() ); + + addToClaimList( winner.getUUID(), matAmount, lConfig.getMaterial() ); + } + int ticketsize = 0; + for ( LotteryEntry entry : players.values() ) + { + ticketsize += entry.getTickets(); + } + broadcastMessage( + "WinnerSummary", players.size(), lConfig.getPlural( + "player", players.size() ), ticketsize, lConfig.getPlural( "ticket", ticketsize ) ); + + // Add last winner to config. + lConfig.setLastwinner( winner.getName() ); + lConfig.setLastwinneramount( amount ); + + clearAfterGettingWinner(); + + int material = lConfig.useEconomy() ? -1 : lConfig.getMaterial(); + LotteryDrawEvent drawEvent = new LotteryDrawEvent( winner.getUUID(), winner.getName(), ticketsBought, amount, material ); + Bukkit.getServer().getPluginManager().callEvent( drawEvent ); + } + return true; + } + + public void clearAfterGettingWinner() + { + + // extra money in pot added by admins and mods? + // Should this be removed? + if ( lConfig.clearExtraInPot() ) + { + lConfig.setExtraInPot( 0 ); + } + // Clear file. + YamlConfiguration config = loadPlayersFile(); + config.set( "players", null ); + savePlayersFile( config ); + } + + + public void broadcastMessage( final String topic, final Object... args ) + { + try + { + for ( String message : lConfig.getMessage( topic ) ) + { + String outMessage = formatCustomMessageLive( message, args ); + for ( Player player : plugin.getServer().getOnlinePlayers() ) + { + if ( player.hasMetadata( "LotteryOptOut" ) && player.getMetadata( "LotteryOptOut" ).get( 0 ).asBoolean() ) + { + continue; + } + outMessage = outMessage.replaceAll( "%player%", player.getDisplayName() ); + player.sendMessage( outMessage ); + } + } + } + catch ( Exception e ) + { + plugin.getLogger().log( Level.WARNING, "Invalid Translation Key: " + topic, e ); + } + } + + public void sendMessage( final CommandSender player, final String topic, final Object... args ) + { + try + { + for ( String message : lConfig.getMessage( topic ) ) + { + String outMessage = formatCustomMessageLive( message, args ); + if ( player instanceof Player ) + { + outMessage = outMessage.replaceAll( "%player%", Matcher.quoteReplacement( ( (Player) player ).getDisplayName() ) ); + } + player.sendMessage( outMessage ); + } + } + catch ( Exception e ) + { + plugin.getLogger().log( Level.WARNING, "Invalid Translation Key: " + topic, e ); + } + } + + public String formatCustomMessageLive( final String message, final Object... args ) throws Exception + { + //Lets give timeLeft back if user provie %draw% + String outMessage = message.replaceAll( "%draw%", Matcher.quoteReplacement( timeUntil( true ) ) ); + + //Lets give timeLeft with full words back if user provie %drawLong% + outMessage = outMessage.replaceAll( "%drawLong%", Matcher.quoteReplacement( timeUntil( false ) ) ); + + // %cost% = cost + outMessage = outMessage.replaceAll( "%cost%", Matcher.quoteReplacement( Etc.formatCost( lConfig.getCost(), lConfig ) ) ); + + // %pot% + outMessage = outMessage.replaceAll( "%pot%", Matcher.quoteReplacement( Etc.formatCost( winningAmount(), lConfig ) ) ); + + // %prefix% + outMessage = outMessage.replaceAll( "%prefix%", Matcher.quoteReplacement( lConfig.getMessage( "prefix" ).get( 0 ) ) ); + + for ( int i = 0; i < args.length; i++ ) + { + outMessage = outMessage.replaceAll( "%" + i + "%", Matcher.quoteReplacement( args[i].toString() ) ); + } + + // Lets get some colors on this, shall we? + outMessage = outMessage.replaceAll( "(&([a-fk-or0-9]))", "\u00A7$2" ); + return outMessage; + } + + public int getTickets( Player player ) + { + for ( LotteryEntry entry : getBoughtTickets().values() ) + { + if ( entry.getUUID().equals( player.getUniqueId() ) ) + { + return entry.getTickets(); + } + } + return 0; + } +} diff --git a/src/main/java/net/erbros/lottery/MainCommandExecutor.java b/src/main/java/net/erbros/lottery/MainCommandExecutor.java new file mode 100644 index 0000000..0224848 --- /dev/null +++ b/src/main/java/net/erbros/lottery/MainCommandExecutor.java @@ -0,0 +1,406 @@ +package net.erbros.lottery; + +import org.bukkit.command.Command; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.metadata.FixedMetadataValue; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.util.ArrayList; + + +public class MainCommandExecutor implements CommandExecutor +{ + + final private Lottery plugin; + final private LotteryConfig lConfig; + final private LotteryGame lGame; + + public MainCommandExecutor( final Lottery plugin ) + { + this.plugin = plugin; + lConfig = plugin.getLotteryConfig(); + lGame = plugin.getLotteryGame(); + } + + @Override + public boolean onCommand( final CommandSender sender, final Command command, final String label, final String[] args ) + { + + // Lets check if we have found a plugin for money. + if ( lConfig.useEconomy() && !plugin.hasEconomy() ) + { + lConfig.debugMsg( "No money plugin found yet." ); + lGame.sendMessage( sender, "ErrorPlugin" ); + return true; + } + + // Can the player access the plugin? + if ( !sender.hasPermission( "lottery.buy" ) ) + { + lGame.sendMessage( sender, "ErrorAccess" ); + } + + // If its just /lottery, and no args. + if ( args.length == 0 ) + { + commandNull( sender, args ); + } + else if ( args[0].equalsIgnoreCase( "buy" ) ) + { + commandBuy( sender, args ); + } + else if ( args[0].equalsIgnoreCase( "claim" ) ) + { + commandClaim( sender, args ); + } + else if ( args[0].equalsIgnoreCase( "winners" ) ) + { + commandWinners( sender, args ); + } + else if ( args[0].equalsIgnoreCase( "messages" ) ) + { + commandMessages( sender, args ); + } + else if ( args[0].equalsIgnoreCase( "help" ) ) + { + commandHelp( sender, args ); + } + else if ( args[0].equalsIgnoreCase( "draw" ) ) + { + if ( sender.hasPermission( "lottery.admin.draw" ) ) + { + commandDraw( sender, args ); + } + else + { + lGame.sendMessage( sender, "ErrorAccess" ); + } + } + else if ( args[0].equalsIgnoreCase( "addtopot" ) ) + { + if ( sender.hasPermission( "lottery.admin.addtopot" ) ) + { + commandAddToPot( sender, args ); + } + else + { + lGame.sendMessage( sender, "ErrorAccess" ); + } + } + else if ( args[0].equalsIgnoreCase( "config" ) ) + { + if ( sender.hasPermission( "lottery.admin.editconfig" ) ) + { + commandConfig( sender, args ); + } + else + { + lGame.sendMessage( sender, "ErrorAccess" ); + } + } + else + { + lGame.sendMessage( sender, "ErrorCommand" ); + } + + return true; + } + + public void commandNull( final CommandSender sender, final String[] args ) + { + // Is this a console? If so, just tell that lottery is running and time until next draw. + if ( !( sender instanceof Player ) ) + { + sender.sendMessage( "Hi Console - The Lottery plugin is running" ); + lGame.sendMessage( sender, "DrawIn", lGame.timeUntil( false ) ); + return; + } + final Player player = (Player) sender; + + // Check if we got any money/items in the pot. + final double amount = lGame.winningAmount(); + lConfig.debugMsg( "pot current total: " + amount ); + // Send some messages: + lGame.sendMessage( sender, "DrawIn", lGame.timeUntil( false ) ); + lGame.sendMessage( sender, "TicketCommand" ); + lGame.sendMessage( sender, "PotAmount" ); + if ( lConfig.getMaxTicketsEachUser() > 1 ) + { + lGame.sendMessage( + player, "YourTickets", lGame.getTickets( player ), lConfig.getPlural( "ticket", lGame.getTickets( player ) ) ); + } + // Number of tickets available? + if ( lConfig.getTicketsAvailable() > 0 ) + { + lGame.sendMessage( + sender, "TicketRemaining", ( lConfig.getTicketsAvailable() - lGame.ticketsSold() ), lConfig.getPlural( + "ticket", lConfig.getTicketsAvailable() - lGame.ticketsSold() ) ); + } + lGame.sendMessage( sender, "CommandHelp" ); + + // Does lastwinner exist and != null? Show. + // Show different things if we are using iConomy over + // material. + if ( lConfig.getLastwinner() != null ) + { + lGame.sendMessage( sender, "LastWinner", lConfig.getLastwinner(), Etc.formatCost( lConfig.getLastwinneramount(), lConfig ) ); + } + + // if not iConomy, make players check for claims. + if ( !lConfig.useEconomy() ) + { + lGame.sendMessage( sender, "CheckClaim" ); + } + } + + public void commandMessages( final CommandSender sender, final String[] args ) + { + if ( !( sender instanceof Player ) ) + { + lGame.sendMessage( sender, "ErrorConsole3" ); + return; + } + Player player = (Player) sender; + + if ( player.hasMetadata( "LotteryOptOut" ) && player.getMetadata( "LotteryOptOut" ).get( 0 ).asBoolean() ) + { + player.setMetadata( "LotteryOptOut", new FixedMetadataValue( plugin, false ) ); + lGame.sendMessage( sender, "MessagesEnabled" ); + } + else + { + player.setMetadata( "LotteryOptOut", new FixedMetadataValue( plugin, true ) ); + lGame.sendMessage( sender, "MessagesDisabled" ); + } + } + + public void commandHelp( final CommandSender sender, final String[] args ) + { + lGame.sendMessage( sender, "Help" ); + // Are we dealing with admins? + if ( sender.hasPermission( "lottery.admin.draw" ) || sender.hasPermission( "lottery.admin.addtopot" ) || sender.hasPermission( "lottery.admin.editconfig" ) ) + { + lGame.sendMessage( sender, "HelpAdmin" ); + } + } + + public void commandBuy( final CommandSender sender, final String[] args ) + { + // Is this a console? If so, just tell that lottery is running and time until next draw. + if ( !( sender instanceof Player ) ) + { + lGame.sendMessage( sender, "ErrorConsole" ); + return; + } + final Player player = (Player) sender; + + int buyTickets = 1; + if ( args.length > 1 ) + { + // How many tickets do the player want to buy? + buyTickets = Etc.parseInt( args[1] ); + + if ( buyTickets < 1 ) + { + buyTickets = 1; + } + } + + final int allowedTickets = lConfig.getMaxTicketsEachUser() - lGame.getTickets( player ); + + if ( buyTickets > allowedTickets && allowedTickets > 0 ) + { + buyTickets = allowedTickets; + } + + // Have the admin entered a max number of tickets in the lottery? + if ( lConfig.getTicketsAvailable() > 0 ) + { + // If so, can this user buy the selected amount? + if ( lGame.ticketsSold() + buyTickets > lConfig.getTicketsAvailable() ) + { + if ( lGame.ticketsSold() >= lConfig.getTicketsAvailable() ) + { + lGame.sendMessage( sender, "ErrorNoAvailable" ); + return; + } + else + { + buyTickets = lConfig.getTicketsAvailable() - lGame.ticketsSold(); + } + } + } + + if ( lConfig.getMaxTicketsEachUser() > 0 && lGame.getTickets( + player ) + buyTickets > lConfig.getMaxTicketsEachUser() ) + { + lGame.sendMessage( sender, "ErrorAtMax", lConfig.getMaxTicketsEachUser(), lConfig.getPlural( "ticket", lConfig.getMaxTicketsEachUser() ) ); + return; + } + + if ( lGame.addPlayer( player, lConfig.getMaxTicketsEachUser(), buyTickets ) ) + { + // You got your ticket. + lGame.sendMessage( + sender, "BoughtTicket", buyTickets, lConfig.getPlural( "ticket", buyTickets ), Etc.formatCost( lConfig.getCost() * buyTickets, lConfig ) ); + + // Can a user buy more than one ticket? How many + // tickets have he bought now? + if ( lConfig.getMaxTicketsEachUser() > 1 ) + { + lGame.sendMessage( + sender, "BoughtTickets", lGame.getTickets( player ), lConfig.getPlural( "ticket", lGame.getTickets( player ) ) ); + } + if ( lConfig.isBuyingExtendDeadline() && lGame.timeUntil() < lConfig.getBuyingExtendRemaining() ) + { + final long timeBonus = (long) ( lConfig.getBuyingExtendBase() + ( lConfig.getBuyingExtendMultiplier() * Math.sqrt( + buyTickets ) ) ); + lConfig.setNextexec( lConfig.getNextexec() + ( timeBonus * 1000 ) ); + } + if ( lConfig.useBroadcastBuying() ) + { + if ( lGame.timeUntil() < lConfig.getBroadcastBuyingTime() ) + { + lGame.broadcastMessage( + "BoughtAnnounceDraw", player.getDisplayName(), buyTickets, lConfig.getPlural( "ticket", buyTickets ), lGame.timeUntil( true ) ); + } + else + { + lGame.broadcastMessage( + "BoughtAnnounce", player.getDisplayName(), buyTickets, lConfig.getPlural( "ticket", buyTickets ) ); + } + } + } + else + { + // Something went wrong. + lGame.sendMessage( sender, "ErrorNotAfford" ); + } + } + + public void commandClaim( final CommandSender sender, final String[] args ) + { + // Is this a console? If so, just tell that lottery is running and time until next draw. + if ( !( sender instanceof Player ) ) + { + lGame.sendMessage( sender, "ErrorConsole2" ); + return; + } + + lGame.removeFromClaimList( (Player) sender ); + } + + public void commandDraw( final CommandSender sender, final String[] args ) + { + // Start a timer that ends in 3 secs. + lGame.sendMessage( sender, "DrawNow" ); + plugin.startTimerSchedule( true ); + } + + public void commandWinners( final CommandSender sender, final String[] args ) + { + // Get the winners. + final ArrayList winnerArray = new ArrayList(); + try + { + final BufferedReader in = new BufferedReader( + new FileReader( plugin.getDataFolder() + File.separator + "lotteryWinners.txt" ) ); + String str; + while ( ( str = in.readLine() ) != null ) + { + winnerArray.add( str ); + } + in.close(); + } + catch ( IOException e ) + { + } + String[] split; + String winListPrice; + for ( int i = 0; i < winnerArray.size(); i++ ) + { + split = winnerArray.get( i ).split( ":" ); + if ( split[2].equalsIgnoreCase( "0" ) ) + { + winListPrice = plugin.getEconomy().format( Double.parseDouble( split[1] ) ); + } + else + { + winListPrice = split[1] + " " + Etc.formatMaterialName( + Integer.parseInt( split[2] ) ); + } + sender.sendMessage( ( i + 1 ) + ". " + split[0] + " " + winListPrice ); + } + } + + public void commandAddToPot( final CommandSender sender, final String[] args ) + { + if ( args.length < 2 ) + { + lGame.sendMessage( sender, "HelpPot" ); + return; + } + + final double addToPot = Etc.parseDouble( args[1] ); + + if ( addToPot == 0 ) + { + lGame.sendMessage( sender, "ErrorNumber" ); + return; + } + lConfig.addExtraInPot( addToPot ); + lGame.sendMessage( sender, "AddToPot", addToPot, lConfig.getExtraInPot() ); + } + + public void commandConfig( final CommandSender sender, final String[] args ) + { + if ( args.length == 1 ) + { + lGame.sendMessage( sender, "HelpConfig" ); + return; + } + else if ( args.length > 2 ) + { + if ( args[1].equalsIgnoreCase( "cost" ) ) + { + final double newCoin = Etc.parseDouble( args[2] ); + if ( newCoin <= 0 ) + { + lGame.sendMessage( sender, "ErrorNumber" ); + } + else + { + lGame.sendMessage( sender, "ConfigCost", newCoin ); + lConfig.setCost( newCoin ); + } + } + else if ( args[1].equalsIgnoreCase( "hours" ) ) + { + final double newHours = Etc.parseDouble( args[2] ); + if ( newHours <= 0 ) + { + lGame.sendMessage( sender, "ErrorNumber" ); + } + else + { + lGame.sendMessage( sender, "ConfigHours", newHours ); + lConfig.setHours( newHours ); + } + } + else if ( args[1].equalsIgnoreCase( "maxTicketsEachUser" ) || args[1].equalsIgnoreCase( "max" ) ) + { + final int newMaxTicketsEachUser = Etc.parseInt( args[2] ); + lGame.sendMessage( sender, "ConfigMax", newMaxTicketsEachUser ); + lConfig.setMaxTicketsEachUser( newMaxTicketsEachUser ); + } + } + // Lets just reload the config. + lConfig.loadConfig(); + lGame.sendMessage( sender, "ConfigReload" ); + } +} diff --git a/src/main/java/net/erbros/lottery/PlayerJoinListener.java b/src/main/java/net/erbros/lottery/PlayerJoinListener.java new file mode 100644 index 0000000..23ba48d --- /dev/null +++ b/src/main/java/net/erbros/lottery/PlayerJoinListener.java @@ -0,0 +1,33 @@ +package net.erbros.lottery; + +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerJoinEvent; + +public class PlayerJoinListener implements Listener +{ + + final private Lottery plugin; + final private LotteryConfig lConfig; + final private LotteryGame lGame; + + public PlayerJoinListener( final Lottery plugin ) + { + this.plugin = plugin; + lGame = plugin.getLotteryGame(); + lConfig = plugin.getLotteryConfig(); + } + + @EventHandler( priority = EventPriority.MONITOR ) + public void onPlayerJoin( final PlayerJoinEvent event ) + { + Player player = event.getPlayer(); + if (player.hasPermission("lottery.notify")) + { + // Send the player some info about time until lottery draw? + lGame.sendMessage( event.getPlayer(), "Welcome" ); + } + } +} diff --git a/src/main/java/net/erbros/lottery/RandomCollection.java b/src/main/java/net/erbros/lottery/RandomCollection.java new file mode 100644 index 0000000..2a04b3c --- /dev/null +++ b/src/main/java/net/erbros/lottery/RandomCollection.java @@ -0,0 +1,57 @@ +package net.erbros.lottery; + +import java.util.*; + +public class RandomCollection +{ + private final NavigableMap map = new TreeMap<>(); + private final Random random; + private double total = 0; + + public RandomCollection() + { + this( new Random() ); + } + + public RandomCollection( Random random ) + { + this.random = random; + } + + public void add( double weight, E result ) + { + if ( weight <= 0 ) + { + return; + } + total += weight; + map.put( total, result ); + } + + public E next() + { + double value = random.nextDouble() * total; + return map.ceilingEntry( value ).getValue(); + } + + public int size() + { + return map.size(); + } + + public boolean isEmpty() + { + return map.isEmpty(); + } + + + public List values() + { + return new ArrayList<>( map.values() ); + } + + public String toString() + { + return map.toString(); + } +} \ No newline at end of file diff --git a/src/main/java/net/erbros/lottery/events/LotteryBuyTicketEvent.java b/src/main/java/net/erbros/lottery/events/LotteryBuyTicketEvent.java new file mode 100644 index 0000000..4e4e03a --- /dev/null +++ b/src/main/java/net/erbros/lottery/events/LotteryBuyTicketEvent.java @@ -0,0 +1,54 @@ +package net.erbros.lottery.events; + +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; + +public class LotteryBuyTicketEvent extends Event implements Cancellable +{ + + private Player player; + private int amount; + private boolean canceled = false; + private static final HandlerList handlers = new HandlerList(); + + public LotteryBuyTicketEvent( Player player, int amount ) + { + this.player = player; + this.amount = amount; + } + + @Override + public HandlerList getHandlers() + { + return handlers; + } + + public static HandlerList getHandlerList() + { + return handlers; + } + + @Override + public boolean isCancelled() + { + return canceled; + } + + @Override + public void setCancelled( boolean b ) + { + canceled = true; + } + + public int getAmount() + { + return amount; + } + + public Player getPlayer() + { + return player; + } +} diff --git a/src/main/java/net/erbros/lottery/events/LotteryDrawEvent.java b/src/main/java/net/erbros/lottery/events/LotteryDrawEvent.java new file mode 100644 index 0000000..053c67f --- /dev/null +++ b/src/main/java/net/erbros/lottery/events/LotteryDrawEvent.java @@ -0,0 +1,62 @@ +package net.erbros.lottery.events; + +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; + +import java.util.UUID; + +public class LotteryDrawEvent extends Event +{ + + private UUID winner; + private int ticketsBought; + private double winnings; + private int material; + private static final HandlerList handlers = new HandlerList(); + private String winnerName; + + public LotteryDrawEvent( UUID winner, String winnerName, int ticketsBought, double winnings, int material ) + { + this.winner = winner; + this.winnerName = winnerName; + this.ticketsBought = ticketsBought; + this.winnings = winnings; + this.material = material; + } + + @Override + public HandlerList getHandlers() + { + return handlers; + } + + public static HandlerList getHandlerList() + { + return handlers; + } + + public UUID getWinner() + { + return winner; + } + + public String getWinnerName() + { + return winnerName; + } + + public int getTicketsBought() + { + return ticketsBought; + } + + public double getWinnings() + { + return winnings; + } + + public int getMaterial() + { + return material; + } +} diff --git a/src/config.yml b/src/main/resources/config.yml similarity index 95% rename from src/config.yml rename to src/main/resources/config.yml index c477754..ca54f81 100644 --- a/src/config.yml +++ b/src/main/resources/config.yml @@ -1,5 +1,5 @@ config: - # Set this option to true if your using ANY supported economy system + # Set this option to true if you're using ANY supported economy system useiConomy: false # Cost per ticket cost: 5 @@ -23,9 +23,7 @@ config: taxTarget: "" # How many tickets can each player buy? maxTicketsEachUser: 1 - # Use this option to enable fixed ticket mode. Setting this will cause rollovers. - numberOfTicketsAvailable: 0 - + buyingExtend: # Should the next draw timer be extended if someone buys a ticket close to the draw? enabled: true @@ -39,7 +37,6 @@ config: nextexec: 0 extraInPot: 0 - jackpot: 0 debug: false message: prefix: '&6[LOTTERY]&r' diff --git a/src/plugin.yml b/src/main/resources/plugin.yml similarity index 83% rename from src/plugin.yml rename to src/main/resources/plugin.yml index 6fc7a44..70732d3 100644 --- a/src/plugin.yml +++ b/src/main/resources/plugin.yml @@ -1,33 +1,38 @@ -name: Lottery -main: net.erbros.lottery.Lottery -version: 0.9.4 -authors: - - Erbros - - KHobbits -website: www.erbros.net -commands: - lottery: - description: Provides access to Permissions commands and information. - permission: lottery.buy - usage: / [winners|claim|help|messages|buy [amount]] - aliases: [lot,lotto] -permissions: - lottery.*: - description: Full access to Lottery plugin. - children: - lottery.buy: true - lottery.admin.draw: true - lottery.admin.addtopot: true - lottery.admin.editconfig: true - lottery.buy: - description: Basic lottery rights. Can buy, check lottery info and claim winnings. - default: true - lottery.admin.draw: - description: Access to /lottery draw command. - default: op - lottery.admin.addtopot: - description: Access to /lottery addtopot command. - default: op - lottery.admin.editconfig: - description: Access to ingame config editing and reloading. - default: op +name: Lottery +main: net.erbros.lottery.Lottery +version: 1.1.2 +authors: + - Erbros + - KHobbits + - Kukelekuuk00 +softDepend: [Vault] +commands: + lottery: + description: Provides access to Permissions commands and information. + permission: lottery.buy + usage: / [winners|claim|help|messages|buy [amount]] + aliases: [lot,lotto] +permissions: + lottery.*: + description: Full access to Lottery plugin. + children: + lottery.buy: true + lottery.notify: true + lottery.admin.draw: true + lottery.admin.addtopot: true + lottery.admin.editconfig: true + lottery.buy: + description: Basic lottery rights. Can buy, check lottery info and claim winnings. + default: true + lottery.notify: + description: Notifies a joined player about the next draw. + default: true + lottery.admin.draw: + description: Access to /lottery draw command. + default: op + lottery.admin.addtopot: + description: Access to /lottery addtopot command. + default: op + lottery.admin.editconfig: + description: Access to ingame config editing and reloading. + default: op diff --git a/src/net/erbros/lottery/Etc.java b/src/net/erbros/lottery/Etc.java deleted file mode 100644 index d8a2204..0000000 --- a/src/net/erbros/lottery/Etc.java +++ /dev/null @@ -1,168 +0,0 @@ -package net.erbros.lottery; - -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import org.bukkit.Material; - - -public class Etc -{ - public static String formatCost(double cost, LotteryConfig lConfig) - { - if (lConfig.useiConomy()) - { - return lConfig.formatCurrency((formatAmount(cost, lConfig.useiConomy()))); - } - else - { - return String.valueOf( - (int)formatAmount(cost, lConfig.useiConomy())).concat( - " " + formatMaterialName(lConfig.getMaterial())); - } - } - - public static double formatAmount(double amount, final boolean usingiConomy) - { - - if (usingiConomy) - { - return Math.floor(amount * 100) / 100; - } - else - { - return Math.floor(amount); - } - } - - public static String formatMaterialName(final int materialId) - { - String rawMaterialName = Material.getMaterial(materialId).toString(); - rawMaterialName = rawMaterialName.toLowerCase(Locale.ENGLISH); - // Large first letter. - final String firstLetterCapital = rawMaterialName.substring(0, 1).toUpperCase(); - rawMaterialName = firstLetterCapital + rawMaterialName.substring(1, rawMaterialName.length()); - return rawMaterialName.replace("_", " "); - } - - - - public static String timeUntil(final long time, final boolean mini, LotteryConfig lConfig) - { - long timeLeft = time; - // How many days left? - String stringTimeLeft = ""; - - if (timeLeft >= 60 * 60 * 24) - { - final int days = (int)Math.floor(timeLeft / (60 * 60 * 24)); - timeLeft -= 60 * 60 * 24 * days; - if (mini) - { - stringTimeLeft += Integer.toString(days) + "d "; - } - else - { - stringTimeLeft += Integer.toString(days) + " " + lConfig.getPlural("day", days) + ", "; - } - } - if (timeLeft >= 60 * 60) - { - final int hours = (int)Math.floor(timeLeft / (60 * 60)); - timeLeft -= 60 * 60 * hours; - if (mini) - { - stringTimeLeft += Integer.toString(hours) + "h "; - } - else - { - stringTimeLeft += Integer.toString(hours) + " " + lConfig.getPlural("hour", hours) + ", "; - } - } - if (timeLeft >= 60) - { - final int minutes = (int)Math.floor(timeLeft / (60)); - timeLeft -= 60 * minutes; - if (mini) - { - stringTimeLeft += Integer.toString(minutes) + "m "; - - } - else - { - stringTimeLeft += Integer.toString(minutes) + " " + lConfig.getPlural("minute", minutes) + ", "; - } - } - else - { - // Lets remove the last comma, since it will look bad with 2 days, 3 - // hours, and 14 seconds. - if (!stringTimeLeft.equalsIgnoreCase("") && !mini) - { - stringTimeLeft = stringTimeLeft.substring( - 0, stringTimeLeft.length() - 1); - } - } - final int secs = (int)timeLeft; - if (mini) - { - stringTimeLeft += secs + "s"; - } - else - { - if (!stringTimeLeft.equalsIgnoreCase("")) - { - stringTimeLeft += "and "; - } - stringTimeLeft += Integer.toString(secs) + " " + lConfig.getPlural("second", secs); - } - - return stringTimeLeft; - } - - public static Map realPlayersFromList(final List ticketList) - { - final Map playerList = new HashMap(); - int value; - for (String check : ticketList) - { - if (playerList.containsKey(check)) - { - value = Integer.parseInt(playerList.get(check).toString()) + 1; - } - else - { - value = 1; - } - playerList.put(check, value); - } - return playerList; - } - - public static int parseInt(final String arg) - { - int newInt = 0; - try - { - newInt = Integer.parseInt(arg); - } - catch (NumberFormatException e) - { - } - return newInt > 0 ? newInt : 0; - } - - public static double parseDouble(final String arg) - { - double newDouble = 0; - try - { - newDouble = Double.parseDouble(arg); - } - catch (NumberFormatException e) - { - } - return newDouble > 0 ? newDouble : 0; - } -} diff --git a/src/net/erbros/lottery/Lottery.java b/src/net/erbros/lottery/Lottery.java deleted file mode 100644 index 0e5b7b3..0000000 --- a/src/net/erbros/lottery/Lottery.java +++ /dev/null @@ -1,244 +0,0 @@ -package net.erbros.lottery; - -import org.bukkit.Bukkit; -import org.bukkit.Server; -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.plugin.Plugin; -import org.bukkit.plugin.PluginManager; -import org.bukkit.plugin.java.JavaPlugin; -import net.erbros.lottery.register.payment.Method; -import net.erbros.lottery.register.payment.Methods; - - -public class Lottery extends JavaPlugin -{ - - private Method method = null; - public Methods methods = null; - public boolean timerStarted = false; - private Server server = null; - private LotteryConfig lConfig; - private LotteryGame lGame; - - @Override - public void onDisable() - { - // Disable all running timers. - Bukkit.getServer().getScheduler().cancelTasks(this); - - lConfig.debugMsg("[Lottery]: has been disabled (including timers)."); - } - - @Override - public void onEnable() - { - - FileConfiguration config; - lConfig = new LotteryConfig(this); - lGame = new LotteryGame(this); - // Lets find some configs - config = getConfig(); - config.options().copyDefaults(true); - saveConfig(); - lConfig.loadConfig(); - - final PluginManager pm = getServer().getPluginManager(); - - server = getServer(); - - pm.registerEvents(new PluginListener(this), this); - if (lConfig.useWelcomeMessage()) - { - pm.registerEvents(new PlayerJoinListener(this), this); - } - - getCommand("lottery").setExecutor(new MainCommandExecutor(this)); - - // Is the date we are going to draw the lottery set? If not, we should - // do it. - if (getNextexec() == 0) - { - // Set first time to be config hours later? Millisecs, * 1000. - setNextexec(System.currentTimeMillis() + extendTime()); - } - - // Start the timer for the first time. - startTimerSchedule(false); - - } - - public Server getBukkitServer() - { - return server; - } - - public LotteryConfig getLotteryConfig() - { - return lConfig; - } - - public LotteryGame getLotteryGame() - { - return lGame; - } - - protected long getNextexec() - { - return lConfig.getNextexec(); - } - - protected void setNextexec(final long aNextexec) - { - lConfig.setNextexec(aNextexec); - } - - public boolean isLotteryDue() - { - return getNextexec() > 0 && System.currentTimeMillis() + 1000 >= getNextexec(); - } - - public void startTimerSchedule(final boolean drawAtOnce) - { - long extendtime; - // Cancel any existing timers. - if (timerStarted) - { - // Let's try and stop any running threads. - try - { - Bukkit.getServer().getScheduler().cancelTasks((Plugin)this); - } - catch (ClassCastException exception) - { - } - - extendtime = extendTime(); - } - else - { - // Get time until lottery drawing. - extendtime = getNextexec() - System.currentTimeMillis(); - } - // What if the admin changed the config to a shorter time? lets check, - // and if - // that is the case, lets use the new time. - if (System.currentTimeMillis() + extendTime() < getNextexec()) - { - setNextexec(System.currentTimeMillis() + extendTime()); - } - - // If the time is passed (perhaps the server was offline?), draw lottery - // at once. - if (extendtime <= 0) - { - extendtime = 1000; - lConfig.debugMsg("Seems we need to make a draw at once!"); - } - - // Is the drawAtOnce boolean set to true? In that case, do drawing in a - // few secs. - if (drawAtOnce) - { - extendtime = 100; - setNextexec(System.currentTimeMillis() + 100); - lConfig.debugMsg("DRAW NOW"); - } - - // Delay in server ticks. 20 ticks = 1 second. - extendtime = extendtime / 1000 * 20; - runDrawTimer(extendtime); - - // Timer is now started, let it know. - timerStarted = true; - } - - public void lotteryDraw() - { - lConfig.debugMsg("Doing a lottery draw"); - - if (getNextexec() > 0 && System.currentTimeMillis() + 1000 >= getNextexec()) - { - // Get the winner, if any. And remove file so we are ready for - // new round. - lConfig.debugMsg("Getting winner."); - if (!lGame.getWinner()) - { - lConfig.debugMsg("Failed getting winner"); - } - setNextexec(System.currentTimeMillis() + extendTime()); - } - // Call a new timer. - startTimerSchedule(false); - } - - public void extendLotteryDraw() - { - // Cancel timer. - try - { - Bukkit.getServer().getScheduler().cancelTasks((Plugin)this); - } - catch (ClassCastException exception) - { - } - - long extendtime; - - // How much time left? Below 0? - if (getNextexec() < System.currentTimeMillis()) - { - extendtime = 3000; - } - else - { - extendtime = getNextexec() - System.currentTimeMillis(); - } - // Delay in server ticks. 20 ticks = 1 second. - extendtime = extendtime / 1000 * 20; - runDrawTimer(extendtime); - } - - private void runDrawTimer(final long extendtime) - { - // Is this very long until? On servers with lag and long between - // restarts there might be a very long time between when server - // should have drawn winner and when it will draw. Perhaps help the - // server a bit by only scheduling for half the length at a time? - // But only if its more than 5 seconds left. - if (extendtime < 5 * 20) - { - server.getScheduler().runTaskLaterAsynchronously(this, new LotteryDraw(this, true), extendtime); - lConfig.debugMsg("LotteryDraw() " + extendtime + 100); - } - else - { - final long newtime = extendtime / 10; - server.getScheduler().runTaskLaterAsynchronously(this, new LotteryDraw(this, false), newtime); - lConfig.debugMsg("extendLotteryDraw() " + newtime); - } - } - - public long extendTime() - { - final double exacttime = lConfig.getHours() * 60 * 60 * 1000; - final long extendTime = (long)exacttime; - lConfig.debugMsg("extendTime: " + extendTime); - return extendTime; - } - - public Method getMethod() - { - if (method == null) { - Methods.setMethod(this.getServer().getPluginManager()); - } - if (method == null) { - this.getLogger().severe("Could not find valid economy plugin."); - } - return method; - } - - public void setMethod(Method method) - { - this.method = method; - } -} \ No newline at end of file diff --git a/src/net/erbros/lottery/LotteryConfig.java b/src/net/erbros/lottery/LotteryConfig.java deleted file mode 100644 index eb136cd..0000000 --- a/src/net/erbros/lottery/LotteryConfig.java +++ /dev/null @@ -1,410 +0,0 @@ -package net.erbros.lottery; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.logging.Level; -import org.bukkit.configuration.file.FileConfiguration; - - -public class LotteryConfig -{ - - final private Lottery plugin; - private FileConfiguration config; - private double cost; - private double hours; - private long nextexec; - private boolean useiConomy; - private int material; - private double extraInPot; - private boolean broadcastBuying; - private int broadcastBuyingTime; - private boolean welcomeMessage; - private double netPayout; - private boolean clearExtraInPot; - private int maxTicketsEachUser; - private int ticketsAvailable; - private double jackpot; - private String lastwinner; - private double lastwinneramount; - private boolean buyingExtendDeadline; - private int buyingExtendRemaining; - private double buyingExtendBase; - private double buyingExtendMultiplier; - private String taxTarget; - - private HashMap> messages; - - - public LotteryConfig(final Lottery plugin) - { - this.plugin = plugin; - this.config = plugin.getConfig(); - } - - - - public void loadConfig() - { - plugin.reloadConfig(); - config = plugin.getConfig(); - - debugMsg("Loading Lottery configuration"); - - hours = config.getDouble("config.hours", 24); - - useiConomy = config.getBoolean("config.useiConomy", true); - material = config.getInt("config.material", 266); - broadcastBuying = config.getBoolean("config.broadcastBuying", true); - broadcastBuyingTime = config.getInt("config.broadcastBuyingTime", 120); - welcomeMessage = config.getBoolean("config.welcomeMessage", true); - extraInPot = config.getDouble("config.extraInPot", 0); - clearExtraInPot = config.getBoolean("config.clearExtraInPot", true); - netPayout = config.getDouble("config.netPayout", 100); - maxTicketsEachUser = config.getInt("config.maxTicketsEachUser", 1); - ticketsAvailable = config.getInt("config.numberOfTicketsAvailable", 0); - jackpot = config.getDouble("config.jackpot", 0); - nextexec = config.getLong("config.nextexec"); - cost = Etc.formatAmount(config.getDouble("config.cost", 5), useiConomy); - lastwinner = config.getString("config.lastwinner", ""); - lastwinneramount = config.getDouble("config.lastwinneramount", 0); - buyingExtendDeadline = config.getBoolean("config.buyingExtend.enabled", true); - buyingExtendRemaining = config.getInt("config.buyingExtend.secondsRemaining", 30); - buyingExtendBase = config.getDouble("config.buyingExtend.extendBase", 15); - buyingExtendMultiplier = config.getDouble("config.buyingExtend.extendMultiplier", 1.5); - taxTarget = config.getString("config.taxTarget", ""); - - // Load messages? - loadCustomMessages(); - // Then lets save this stuff :) - plugin.saveConfig(); - } - - public void set(final String path, final Object value) - { - config.set(path, value); - plugin.saveConfig(); - } - - public void loadCustomMessages() - { - messages = new HashMap>(); - messages.put("prefix", formatCustomMessage("message.prefix", "&6[LOTTERY]&r")); - - messages.put("Welcome", formatCustomMessage("message.Welcome", "%prefix% &fDraw in: &c%drawLong%")); - messages.put("ErrorPlugin", formatCustomMessage("message.ErrorPlugin", "%prefix% Sorry, we haven\'t found a money plugin yet..")); - messages.put("ErrorAccess", formatCustomMessage("message.ErrorAccess", "%prefix% You don\'t have access to that command.")); - messages.put("ErrorCommand", formatCustomMessage("message.ErrorCommand", "%prefix% Hey, I don\'t recognize that command!")); - messages.put("ErrorConsole", formatCustomMessage("message.ErrorConsole", "%prefix% You\'re the console, I can\'t sell you tickets.")); - messages.put("ErrorConsole2", formatCustomMessage("message.ErrorConsole2", "%prefix% You\'re the console, you don\'t have an inventory.")); - messages.put("ErrorConsole3", formatCustomMessage("message.ErrorConsole3", "%prefix% You\'re the console, you can\'t change that.")); - messages.put("ErrorNoAvailable", formatCustomMessage("message.ErrorNoAvailable", "%prefix% There are no more tickets available")); - messages.put("ErrorAtMax", formatCustomMessage("message.ErrorAtMax", "%prefix% You already have the maximum of %0% %1% already.")); - messages.put("ErrorNotAfford", formatCustomMessage("message.ErrorNotAfford", "%prefix% You can\'t afford a ticket")); - messages.put("ErrorNumber", formatCustomMessage("message.ErrorNumber", "%prefix% Provide a number greater than zero (decimals accepted)")); - messages.put("ErrorClaim", formatCustomMessage("message.ErrorClaim", "%prefix% You did not have anything unclaimed.")); - - messages.put("TicketCommand", formatCustomMessage("message.TicketCommand", "%prefix% Buy a ticket for &c%cost% &rwith &c/lottery buy")); - messages.put("PotAmount", formatCustomMessage("message.PotAmount", "%prefix% There is currently &a%pot% &rin the pot.")); - messages.put("YourTickets", formatCustomMessage("message.YourTickets", "%prefix% You have &c%0% &r%1%")); - messages.put("TicketRemaining", formatCustomMessage("message.TimeRemaining", "%prefix% There is &c%0% &r%1% left.")); - messages.put("CommandHelp", formatCustomMessage("message.CommandHelp", "%prefix% &c/lottery help&r for other commands")); - messages.put("LastWinner", formatCustomMessage("message.LastWinner", "%prefix% Last winner: %0% %1%")); - messages.put("CheckClaim", formatCustomMessage("message.CheckClaim", "%prefix% Check if you have won with &c/lottery claim")); - messages.put("BoughtTicket", formatCustomMessage("message.BoughtTicket", "%prefix% You got &c%0% &r%1% for &c%2%")); - messages.put("BoughtTickets", formatCustomMessage("message.BoughtTickets", "%prefix% You now have &c%0% &r%1%")); - messages.put("BoughtAnnounceDraw", formatCustomMessage("message.BoughtAnnounceDraw", "%prefix% &r%0% &rjust bought %1% %2%! Draw in %3%")); - messages.put("BoughtAnnounce", formatCustomMessage("message.BoughtAnnounce", "%prefix% &r%0% &rjust bought %1% %2%!")); - messages.put("DrawIn", formatCustomMessage("message.DrawIn", "%prefix% Draw in: &c%0%")); - messages.put("DrawNow", formatCustomMessage("message.DrawNow", "%prefix% Lottery will be drawn at once.")); - messages.put("DrawSoon", formatCustomMessage("message.DrawSoon", "Soon")); - messages.put("DrawSoonLong", formatCustomMessage("message.DrawSoonLong", "Draw will occur soon!")); - messages.put("PlayerClaim", formatCustomMessage("message.PlayerClaim", "%prefix You just claimed %0%")); - messages.put("MessagesEnabled", formatCustomMessage("message.MessagesEnabled", "%prefix% You will now receive Lottery broadcast messages.")); - messages.put("MessagesDisabled", formatCustomMessage("message.MessagesDisabled", "%prefix% You will no longer receive Lottery broadcast messages.")); - - messages.put("NoWinnerTickets", formatCustomMessage("message.NoWinnerTickets", "%prefix% No tickets sold this round. That\'s a shame.")); - messages.put( - "NoWinnerRollover", formatCustomMessage("message.NoWinnerRollover", "%prefix% No winner, we have a rollover! &a%0% &rwent to jackpot!")); - messages.put("WinnerCongrat", formatCustomMessage("message.WinnerCongrat", "%prefix% Congratulations go to %0% &rfor winning &c%1%&r with &c%2%&r %3%.")); - messages.put("WinnerCongratClaim", formatCustomMessage("message.WinnerCongratClaim", "%prefix% Use &c/lottery claim &rto claim the winnings.")); - messages.put("WinnerSummary", formatCustomMessage("message.WinnerSummary", "%prefix% There was a total of %0% %1% buying %2% %3%")); - - messages.put("AddToPot", formatCustomMessage("message.AddToPot", "%prefix% Added &a%0% &rto pot. Extra total is &a%1%")); - messages.put("ConfigCost", formatCustomMessage("message.ConfigCost", "%prefix% Cost changed to &c%0%")); - messages.put("ConfigHours", formatCustomMessage("message.ConfigHours", "%prefix% Hours changed to &c%0%")); - messages.put("ConfigMax", formatCustomMessage("message.ConfigMax", "%prefix% Max amount of tickets changed to &c%0%")); - messages.put("ConfigReload", formatCustomMessage("message.ConfigReload", "%prefix% Config reloaded")); - - messages.put( - "Help", formatCustomMessage( - "message.Help", - "%prefix% Help commands%newline%%prefix% &c/lottery&r : Basic lottery info.%newline%%prefix% &c/lottery buy &r : Buy ticket(s)." + - "%newline%%prefix% &c/lottery claim&r : Claim outstanding wins.%newline%%prefix% &c/lottery winners&r : Check last winners.")); - messages.put( - "HelpAdmin", formatCustomMessage( - "message.HelpAdmin", - "%prefix% &1/lottery draw&r : Draw lottery.%newline%%prefix% &1/lottery addtopot&r : Add number to pot.%newline%%prefix% &1/lottery " + - "config&r : Edit the config.")); - messages.put("HelpPot", formatCustomMessage("message.HelpPot", "%prefix% /lottery addtopot ")); - messages.put( - "HelpConfig", formatCustomMessage( - "message.HelpConfig", - "%prefix% Edit config commands%newline%%prefix% &c/lottery config cost %newline%%prefix% &c/lottery config hours %newline%%prefix% " + - "&c/lottery config maxTicketsEachUser %newline%%prefix% &c/lottery config reload")); - messages.put("ticket", formatCustomMessage("message.Ticket", "ticket")); - messages.put("tickets", formatCustomMessage("message.Tickets", "tickets")); - messages.put("player", formatCustomMessage("message.player", "player")); - messages.put("players", formatCustomMessage("message.players", "players")); - messages.put("day", formatCustomMessage("message.day", "day")); - messages.put("days", formatCustomMessage("message.days", "days")); - messages.put("hour", formatCustomMessage("message.hour", "hour")); - messages.put("hours", formatCustomMessage("message.hours", "hours")); - messages.put("minute", formatCustomMessage("message.minute", "minute")); - messages.put("minutes", formatCustomMessage("message.minutes", "minutes")); - messages.put("second", formatCustomMessage("message.second", "second")); - messages.put("seconds", formatCustomMessage("message.seconds", "seconds")); - } - - public String getPlural(String word, int amount){ - String tlkey = ""; - - if (word.equalsIgnoreCase("ticket")) - { - tlkey = amount == 1 ? "ticket" : "tickets"; - } - if (word.equalsIgnoreCase("player")) - { - tlkey = amount == 1 ? "player" : "players"; - } - if (word.equalsIgnoreCase("day")) - { - tlkey = amount == 1 ? "day" : "days"; - } - if (word.equalsIgnoreCase("hour")) - { - tlkey = amount == 1 ? "hour" : "hours"; - } - if (word.equalsIgnoreCase("minute")) - { - tlkey = amount == 1 ? "minute" : "minutes"; - } - if (word.equalsIgnoreCase("second")) - { - tlkey = amount == 1 ? "second" : "seconds"; - } - - String pluralTl = ""; - try { - for (String message : getMessage(tlkey)){ - pluralTl = message; - } - return pluralTl; - } catch (Exception e) { - e.printStackTrace(); - } - return pluralTl; - } - - public List getMessage(final String topic) throws Exception - { - if (!messages.containsKey(topic)) - { - throw new Exception("Invalid Translation key"); - } - return Collections.unmodifiableList(messages.get(topic)); - } - - public List formatCustomMessage(final String node, final String def) - { - final List fList = new ArrayList(); - // Lets find a msg. - final String msg = config.getString(node, def); - config.set(node, msg); - - // Lets put this in a arrayList in case we want more than one line. - Collections.addAll(fList, msg.split("%newline%")); - return fList; - } - - // Enable some debugging? - public void debugMsg(final String msg) - { - if (config.getBoolean("config.debug") && msg != null) - { - plugin.getLogger().log(Level.INFO, msg); - } - } - - public double getCost() - { - return cost; - } - - public void setCost(final double cost) - { - this.cost = cost; - set("config.cost", cost); - } - - public double getHours() - { - return hours; - } - - public void setHours(final double hours) - { - this.hours = hours; - set("config.hours", hours); - } - - public long getNextexec() - { - return nextexec; - } - - public void setNextexec(final long nextexec) - { - this.nextexec = nextexec; - set("config.nextexec", nextexec); - } - - public boolean useiConomy() - { - return useiConomy; - } - - public int getMaterial() - { - return material; - } - - public double getExtraInPot() - { - return extraInPot; - } - - public void setExtraInPot(final double extraInPot) - { - this.extraInPot = extraInPot; - set("config.extraInPot", extraInPot); - } - - public void addExtraInPot(final double extra) - { - extraInPot += extra; - setExtraInPot(extraInPot); - } - - public boolean useBroadcastBuying() - { - return broadcastBuying; - } - - public int getBroadcastBuyingTime() - { - return broadcastBuyingTime; - } - - public boolean useWelcomeMessage() - { - return welcomeMessage; - } - - public double getNetPayout() - { - return netPayout; - } - - public void setNetPayout(final double netPayout) - { - this.netPayout = netPayout; - set("config.netPayout", netPayout); - } - - public boolean clearExtraInPot() - { - return clearExtraInPot; - } - - public int getMaxTicketsEachUser() - { - return maxTicketsEachUser; - } - - public void setMaxTicketsEachUser(final int maxTicketsEachUser) - { - this.maxTicketsEachUser = maxTicketsEachUser; - set("config.maxTicketsEachUser", maxTicketsEachUser); - } - - public int getTicketsAvailable() - { - return ticketsAvailable; - } - - public double getJackpot() - { - return jackpot; - } - - public void setJackpot(final double jackpot) - { - this.jackpot = jackpot; - set("config.jackpot", jackpot); - } - - public String getLastwinner() - { - return lastwinner; - } - - public void setLastwinner(final String lastwinner) - { - this.lastwinner = lastwinner; - set("config.lastwinner", lastwinner); - } - - public double getLastwinneramount() - { - return lastwinneramount; - } - - public void setLastwinneramount(final double lastwinneramount) - { - this.lastwinneramount = lastwinneramount; - set("config.lastwinneramount", lastwinneramount); - } - - public boolean isBuyingExtendDeadline() - { - return buyingExtendDeadline; - } - - public int getBuyingExtendRemaining() - { - return buyingExtendRemaining; - } - - public double getBuyingExtendBase() - { - return buyingExtendBase; - } - - public double getBuyingExtendMultiplier() - { - return buyingExtendMultiplier; - } - - public String getTaxTarget() - { - return taxTarget; - } - - public String formatCurrency(double amount) - { - return plugin.getMethod().format(amount); - } -} diff --git a/src/net/erbros/lottery/LotteryDraw.java b/src/net/erbros/lottery/LotteryDraw.java deleted file mode 100644 index edf98a2..0000000 --- a/src/net/erbros/lottery/LotteryDraw.java +++ /dev/null @@ -1,39 +0,0 @@ -package net.erbros.lottery; - -import java.util.TimerTask; - - -class LotteryDraw extends TimerTask -{ - - final private Lottery plugin; - final private boolean draw; - - public LotteryDraw(final Lottery plugin, final boolean draw) - { - this.plugin = plugin; - this.draw = draw; - } - - public void run() - { - - if (draw && plugin.isLotteryDue()) - { - plugin.getServer().getScheduler().scheduleSyncDelayedTask( - plugin, new Runnable() - { - @Override - public void run() - { - plugin.lotteryDraw(); - } - }); - - } - else - { - plugin.extendLotteryDraw(); - } - } -} \ No newline at end of file diff --git a/src/net/erbros/lottery/LotteryGame.java b/src/net/erbros/lottery/LotteryGame.java deleted file mode 100644 index f803825..0000000 --- a/src/net/erbros/lottery/LotteryGame.java +++ /dev/null @@ -1,540 +0,0 @@ -package net.erbros.lottery; - -import java.io.*; -import java.security.SecureRandom; -import java.util.ArrayList; -import java.util.logging.Level; -import java.util.regex.Matcher; -import org.bukkit.Bukkit; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; -import net.erbros.lottery.register.payment.Method; - - -public class LotteryGame -{ - - final private Lottery plugin; - final private LotteryConfig lConfig; - - public LotteryGame(final Lottery plugin) - { - this.plugin = plugin; - lConfig = plugin.getLotteryConfig(); - } - - public boolean addPlayer(final Player player, final int maxAmountOfTickets, final int numberOfTickets) - { - - // Do the ticket cost money or item? - if (lConfig.useiConomy()) - { - // Do the player have money? - // First checking if the player got an account, if not let's create - // it. - plugin.getMethod().hasAccount(player.getName()); - final Method.MethodAccount account = plugin.getMethod().getAccount(player.getName()); - - // And lets withdraw some money - if (account != null && account.hasEnough(lConfig.getCost() * numberOfTickets)) - { - // Removing coins from players account. - account.subtract(lConfig.getCost() * numberOfTickets); - } - else - { - return false; - } - lConfig.debugMsg("taking " + (lConfig.getCost() * numberOfTickets) + "from account"); - } - else - { - // Do the user have the item - if (player.getInventory().contains(lConfig.getMaterial(), (int)lConfig.getCost() * numberOfTickets)) - { - // Remove items. - player.getInventory().removeItem( - new ItemStack(lConfig.getMaterial(), (int)lConfig.getCost() * numberOfTickets)); - } - else - { - return false; - } - - - } - // If the user paid, continue. Else we would already have sent return - // false - try - { - final BufferedWriter out = new BufferedWriter( - new FileWriter(plugin.getDataFolder() + File.separator + "lotteryPlayers.txt", true)); - for (Integer i = 0; i < numberOfTickets; i++) - { - out.write(player.getName()); - out.newLine(); - } - out.close(); - - } - catch (IOException e) - { - } - - return true; - } - - public Integer playerInList(final Player player) - { - return playerInList(player.getName()); - } - - public Integer playerInList(final String player) - { - int numberOfTickets = 0; - try - { - final BufferedReader in = new BufferedReader( - new FileReader(plugin.getDataFolder() + File.separator + "lotteryPlayers.txt")); - - String str; - while ((str = in.readLine()) != null) - { - - if (str.equalsIgnoreCase(player)) - { - numberOfTickets++; - } - } - in.close(); - } - catch (IOException e) - { - } - - return numberOfTickets; - } - - public ArrayList playersInFile(final String file) - { - final ArrayList players = new ArrayList(); - try - { - final BufferedReader in = new BufferedReader( - new FileReader(plugin.getDataFolder() + File.separator + file)); - String str; - while ((str = in.readLine()) != null) - { - // add players to array. - players.add(str); - } - in.close(); - } - catch (IOException e) - { - } - return players; - } - - public double winningAmount() - { - double amount; - final ArrayList players = playersInFile("lotteryPlayers.txt"); - amount = players.size() * Etc.formatAmount(lConfig.getCost(), lConfig.useiConomy()); - lConfig.debugMsg("playerno: " + players.size() + " amount: " + amount); - // Set the net payout as configured in the config. - if (lConfig.getNetPayout() > 0) - { - amount = amount * lConfig.getNetPayout() / 100; - } - // Add extra money added by admins and mods? - amount += lConfig.getExtraInPot(); - // Any money in jackpot? - - lConfig.debugMsg("using config store: " + lConfig.getJackpot()); - amount += lConfig.getJackpot(); - - // format it once again. - amount = Etc.formatAmount(amount, lConfig.useiConomy()); - - return amount; - } - - public double taxAmount() - { - double amount = 0; - - // we only have tax is the net payout is between 0 and 100. - if (lConfig.getNetPayout() >= 100 || lConfig.getNetPayout() <= 0 || !lConfig.useiConomy()) - { - return amount; - } - - final ArrayList players = playersInFile("lotteryPlayers.txt"); - amount = players.size() * Etc.formatAmount(lConfig.getCost(), lConfig.useiConomy()); - - // calculate the tax. - amount = amount * (1 - (lConfig.getNetPayout() / 100)); - - // format it once again. - amount = Etc.formatAmount(amount, lConfig.useiConomy()); - - return amount; - } - - public int ticketsSold() - { - int sold; - final ArrayList players = playersInFile("lotteryPlayers.txt"); - sold = players.size(); - return sold; - } - - public void removeFromClaimList(final Player player) - { - // Do the player have something to claim? - final ArrayList otherPlayersClaims = new ArrayList(); - final ArrayList claimArray = new ArrayList(); - try - { - final BufferedReader in = new BufferedReader( - new FileReader(plugin.getDataFolder() + File.separator + "lotteryClaim.txt")); - String str; - while ((str = in.readLine()) != null) - { - final String[] split = str.split(":"); - if (split[0].equals(player.getName())) - { - // Adding this to player claim. - claimArray.add(str); - } - else - { - otherPlayersClaims.add(str); - } - } - in.close(); - } - catch (IOException e) - { - } - - // Did the user have any claims? - if (claimArray.isEmpty()) - { - sendMessage(player, "ErrorClaim"); - } - // Do a bit payout. - for (String aClaimArray : claimArray) - { - final String[] split = aClaimArray.split(":"); - final int claimAmount = Integer.parseInt(split[1]); - final int claimMaterial = Integer.parseInt(split[2]); - player.getInventory().addItem(new ItemStack(claimMaterial, claimAmount)); - sendMessage(player, "PlayerClaim", Etc.formatMaterialName(claimMaterial)); - } - - // Add the other players claims to the file again. - try - { - final BufferedWriter out = new BufferedWriter( - new FileWriter(plugin.getDataFolder() + File.separator + "lotteryClaim.txt")); - for (String otherPlayersClaim : otherPlayersClaims) - { - out.write(otherPlayersClaim); - out.newLine(); - } - - out.close(); - - } - catch (IOException e) - { - } - } - - public void addToClaimList(final String playerName, final int winningAmount, final int winningMaterial) - { - // Then first add new winner, and after that the old winners. - try - { - final BufferedWriter out = new BufferedWriter( - new FileWriter(plugin.getDataFolder() + File.separator + "lotteryClaim.txt", true)); - out.write(playerName + ":" + winningAmount + ":" + winningMaterial); - out.newLine(); - out.close(); - } - catch (IOException e) - { - } - } - - public void addToWinnerList(final String playerName, final Double winningAmount, final int winningMaterial) - { - // This list should be 10 players long. - final ArrayList winnerArray = new ArrayList(); - try - { - final BufferedReader in = new BufferedReader( - new FileReader(plugin.getDataFolder() + File.separator + "lotteryWinners.txt")); - String str; - while ((str = in.readLine()) != null) - { - winnerArray.add(str); - } - in.close(); - } - catch (IOException e) - { - } - // Then first add new winner, and after that the old winners. - try - { - final BufferedWriter out = new BufferedWriter( - new FileWriter(plugin.getDataFolder() + File.separator + "lotteryWinners.txt")); - out.write(playerName + ":" + winningAmount + ":" + winningMaterial); - out.newLine(); - // How long is the array? We just want the top 9. Removing index 9 - // since its starting at 0. - if (!winnerArray.isEmpty()) - { - if (winnerArray.size() > 9) - { - winnerArray.remove(9); - } - // Go trough list and output lines. - for (String aWinnerArray : winnerArray) - { - out.write(aWinnerArray); - out.newLine(); - } - } - out.close(); - - } - catch (IOException e) - { - } - } - - public long timeUntil() - { - final long nextDraw = lConfig.getNextexec(); - return ((nextDraw - System.currentTimeMillis()) / 1000); - } - - public String timeUntil(final boolean mini) - { - final long timeLeft = timeUntil(); - // If negative number, just tell them its DRAW TIME! - if (timeLeft < 0) - { - // Lets make it draw at once.. ;) - plugin.startTimerSchedule(true); - // And return some string to let the user know we are doing our best ;) - if (mini) - { - return "Soon"; - } - return "Draw will occur soon!"; - - } - - return Etc.timeUntil(timeLeft, mini, lConfig); - } - - public boolean getWinner() - { - final ArrayList players = playersInFile("lotteryPlayers.txt"); - - if (players.isEmpty()) - { - broadcastMessage("NoWinnerTickets"); - return false; - } - else - { - // Find rand. Do minus 1 since its a zero based array. - int rand; - - // is max number of tickets 0? If not, include empty tickets not sold. - if (lConfig.getTicketsAvailable() > 0 && ticketsSold() < lConfig.getTicketsAvailable()) - { - rand = new SecureRandom().nextInt(lConfig.getTicketsAvailable()); - // If it wasn't a player winning, then do some stuff. If it was a player, just continue below. - if (rand > players.size() - 1) - { - // No winner this time, pot goes on to jackpot! - final double jackpot = winningAmount(); - - lConfig.setJackpot(jackpot); - - addToWinnerList("Jackpot", jackpot, lConfig.useiConomy() ? 0 : lConfig.getMaterial()); - lConfig.setLastwinner("Jackpot"); - lConfig.setLastwinneramount(jackpot); - broadcastMessage("NoWinnerRollover", Etc.formatCost(jackpot, lConfig)); - clearAfterGettingWinner(); - return true; - } - } - else - { - // Else just continue - rand = new SecureRandom().nextInt(players.size()); - } - - - - lConfig.debugMsg("Rand: " + Integer.toString(rand)); - double amount = winningAmount(); - int ticketsBought = playerInList(players.get(rand)); - if (lConfig.useiConomy()) - { - plugin.getMethod().hasAccount(players.get(rand)); - final Method.MethodAccount account = plugin.getMethod().getAccount(players.get(rand)); - - // Just make sure the account exists, or make it with default - // value. - // Add money to account. - account.add(amount); - // Announce the winner: - broadcastMessage("WinnerCongrat", players.get(rand), Etc.formatCost(amount, lConfig), ticketsBought, lConfig.getPlural("ticket", ticketsBought)); - addToWinnerList(players.get(rand), amount, 0); - - double taxAmount = taxAmount(); - if (taxAmount() > 0 && lConfig.getTaxTarget().length() > 0) - { - String target = lConfig.getTaxTarget(); - plugin.getMethod().hasAccount(target); - final Method.MethodAccount targetaccount = plugin.getMethod().getAccount(target); - if (targetaccount != null) { - targetaccount.add(taxAmount); - } - else { - plugin.getLogger().warning("Invalid economy account specified '"+target+"', tax lost. Fix your 'taxTarget' in config file."); - } - } - - } - else - { - // let's throw it to an int. - final int matAmount = (int)Etc.formatAmount(amount, lConfig.useiConomy()); - amount = (double)matAmount; - broadcastMessage("WinnerCongrat", players.get(rand), Etc.formatCost(amount, lConfig), ticketsBought, lConfig.getPlural("ticket", ticketsBought)); - broadcastMessage("WinnerCongratClaim"); - addToWinnerList(players.get(rand), amount, lConfig.getMaterial()); - - addToClaimList(players.get(rand), matAmount, lConfig.getMaterial()); - } - broadcastMessage( - "WinnerSummary", Etc.realPlayersFromList(players).size(), lConfig.getPlural( - "player", Etc.realPlayersFromList(players).size()), players.size(), lConfig.getPlural("ticket", players.size())); - - // Add last winner to config. - lConfig.setLastwinner(players.get(rand)); - lConfig.setLastwinneramount(amount); - - lConfig.setJackpot(0); - - - clearAfterGettingWinner(); - } - return true; - } - - public void clearAfterGettingWinner() - { - - // extra money in pot added by admins and mods? - // Should this be removed? - if (lConfig.clearExtraInPot()) - { - lConfig.setExtraInPot(0); - } - // Clear file. - try - { - final BufferedWriter out = new BufferedWriter( - new FileWriter(plugin.getDataFolder() + File.separator + "lotteryPlayers.txt", false)); - out.write(""); - out.close(); - - } - catch (IOException e) - { - } - } - - public void broadcastMessage(final String topic, final Object... args) - { - try - { - for (String message : lConfig.getMessage(topic)) - { - String outMessage = formatCustomMessageLive(message, args); - for (Player player : plugin.getServer().getOnlinePlayers()) - { - if (player.hasMetadata("LotteryOptOut") && player.getMetadata("LotteryOptOut").get(0).asBoolean()) { - continue; - } - outMessage = outMessage.replaceAll("%player%", player.getDisplayName()); - player.sendMessage(outMessage); - } - } - } - catch (Exception e) - { - plugin.getLogger().log(Level.WARNING, "Invalid Translation Key: " + topic, e); - } - } - - public void sendMessage(final CommandSender player, final String topic, final Object... args) - { - try - { - for (String message : lConfig.getMessage(topic)) - { - String outMessage = formatCustomMessageLive(message, args); - if (player instanceof Player) { - outMessage = outMessage.replaceAll("%player%", Matcher.quoteReplacement(((Player)player).getDisplayName())); - } - player.sendMessage(outMessage); - } - } - catch (Exception e) - { - plugin.getLogger().log(Level.WARNING, "Invalid Translation Key: " + topic, e); - } - } - - public String formatCustomMessageLive(final String message, final Object... args) throws Exception - { - //Lets give timeLeft back if user provie %draw% - String outMessage = message.replaceAll("%draw%", Matcher.quoteReplacement(timeUntil(true))); - - //Lets give timeLeft with full words back if user provie %drawLong% - outMessage = outMessage.replaceAll("%drawLong%", Matcher.quoteReplacement(timeUntil(false))); - - // %cost% = cost - outMessage = outMessage.replaceAll("%cost%", Matcher.quoteReplacement(Etc.formatCost(lConfig.getCost(), lConfig))); - - // %pot% - outMessage = outMessage.replaceAll("%pot%", Matcher.quoteReplacement(Etc.formatCost(winningAmount(), lConfig))); - - // %prefix% - outMessage = outMessage.replaceAll("%prefix%", Matcher.quoteReplacement(lConfig.getMessage("prefix").get(0))); - - for (int i = 0; i < args.length; i++) - { - outMessage = outMessage.replaceAll("%" + i + "%", Matcher.quoteReplacement(args[i].toString())); - } - - // Lets get some colors on this, shall we? - outMessage = outMessage.replaceAll("(&([a-fk-or0-9]))", "\u00A7$2"); - return outMessage; - } - - -} diff --git a/src/net/erbros/lottery/MainCommandExecutor.java b/src/net/erbros/lottery/MainCommandExecutor.java deleted file mode 100644 index abc6720..0000000 --- a/src/net/erbros/lottery/MainCommandExecutor.java +++ /dev/null @@ -1,406 +0,0 @@ -package net.erbros.lottery; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileReader; -import java.io.IOException; -import java.util.ArrayList; -import org.bukkit.command.Command; -import org.bukkit.command.CommandExecutor; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; -import org.bukkit.metadata.FixedMetadataValue; -import net.erbros.lottery.register.payment.Methods; - - -public class MainCommandExecutor implements CommandExecutor -{ - - final private Lottery plugin; - final private LotteryConfig lConfig; - final private LotteryGame lGame; - - public MainCommandExecutor(final Lottery plugin) - { - this.plugin = plugin; - lConfig = plugin.getLotteryConfig(); - lGame = plugin.getLotteryGame(); - } - - @Override - public boolean onCommand(final CommandSender sender, final Command command, final String label, final String[] args) - { - - // Lets check if we have found a plugin for money. - if (lConfig.useiConomy() && !Methods.hasMethod()) - { - lConfig.debugMsg("No money plugin found yet."); - lGame.sendMessage(sender, "ErrorPlugin"); - return true; - } - - // Can the player access the plugin? - if (!sender.hasPermission("lottery.buy")) - { - lGame.sendMessage(sender, "ErrorAccess"); - } - - // If its just /lottery, and no args. - if (args.length == 0) - { - commandNull(sender, args); - } - else if (args[0].equalsIgnoreCase("buy")) - { - commandBuy(sender, args); - } - else if (args[0].equalsIgnoreCase("claim")) - { - commandClaim(sender, args); - } - else if (args[0].equalsIgnoreCase("winners")) - { - commandWinners(sender, args); - } - else if (args[0].equalsIgnoreCase("messages")) - { - commandMessages(sender, args); - } - else if (args[0].equalsIgnoreCase("help")) - { - commandHelp(sender, args); - } - else if (args[0].equalsIgnoreCase("draw")) - { - if (sender.hasPermission("lottery.admin.draw")) - { - commandDraw(sender, args); - } - else - { - lGame.sendMessage(sender, "ErrorAccess"); - } - } - else if (args[0].equalsIgnoreCase("addtopot")) - { - if (sender.hasPermission("lottery.admin.addtopot")) - { - commandAddToPot(sender, args); - } - else - { - lGame.sendMessage(sender, "ErrorAccess"); - } - } - else if (args[0].equalsIgnoreCase("config")) - { - if (sender.hasPermission("lottery.admin.editconfig")) - { - commandConfig(sender, args); - } - else - { - lGame.sendMessage(sender, "ErrorAccess"); - } - } - else - { - lGame.sendMessage(sender, "ErrorCommand"); - } - - return true; - } - - public void commandNull(final CommandSender sender, final String[] args) - { - // Is this a console? If so, just tell that lottery is running and time until next draw. - if (!(sender instanceof Player)) - { - sender.sendMessage("Hi Console - The Lottery plugin is running"); - lGame.sendMessage(sender, "DrawIn", lGame.timeUntil(false)); - return; - } - final Player player = (Player)sender; - - // Check if we got any money/items in the pot. - final double amount = lGame.winningAmount(); - lConfig.debugMsg("pot current total: " + amount); - // Send some messages: - lGame.sendMessage(sender, "DrawIn", lGame.timeUntil(false)); - lGame.sendMessage(sender, "TicketCommand"); - lGame.sendMessage(sender, "PotAmount"); - if (lConfig.getMaxTicketsEachUser() > 1) - { - lGame.sendMessage( - player, "YourTickets", lGame.playerInList(player), lConfig.getPlural("ticket", lGame.playerInList(player))); - } - // Number of tickets available? - if (lConfig.getTicketsAvailable() > 0) - { - lGame.sendMessage( - sender, "TicketRemaining", (lConfig.getTicketsAvailable() - lGame.ticketsSold()), lConfig.getPlural( - "ticket", lConfig.getTicketsAvailable() - lGame.ticketsSold())); - } - lGame.sendMessage(sender, "CommandHelp"); - - // Does lastwinner exist and != null? Show. - // Show different things if we are using iConomy over - // material. - if (lConfig.getLastwinner() != null) - { - lGame.sendMessage(sender, "LastWinner", lConfig.getLastwinner(), Etc.formatCost(lConfig.getLastwinneramount(), lConfig)); - } - - // if not iConomy, make players check for claims. - if (!lConfig.useiConomy()) - { - lGame.sendMessage(sender, "CheckClaim"); - } - } - - public void commandMessages(final CommandSender sender, final String[] args) - { - if (!(sender instanceof Player)) { - lGame.sendMessage(sender, "ErrorConsole3"); - return; - } - Player player = (Player)sender; - - if (player.hasMetadata("LotteryOptOut") && player.getMetadata("LotteryOptOut").get(0).asBoolean()) { - player.setMetadata("LotteryOptOut", new FixedMetadataValue(plugin, false)); - lGame.sendMessage(sender, "MessagesEnabled"); - } - else { - player.setMetadata("LotteryOptOut", new FixedMetadataValue(plugin, true)); - lGame.sendMessage(sender, "MessagesDisabled"); - } - } - - public void commandHelp(final CommandSender sender, final String[] args) - { - lGame.sendMessage(sender, "Help"); - // Are we dealing with admins? - if (sender.hasPermission("lottery.admin.draw") || sender.hasPermission("lottery.admin.addtopot") || sender.hasPermission("lottery.admin.editconfig")) - { - lGame.sendMessage(sender, "HelpAdmin"); - } - } - - public void commandBuy(final CommandSender sender, final String[] args) - { - // Is this a console? If so, just tell that lottery is running and time until next draw. - if (!(sender instanceof Player)) - { - lGame.sendMessage(sender, "ErrorConsole"); - return; - } - final Player player = (Player)sender; - - int buyTickets = 1; - if (args.length > 1) - { - // How many tickets do the player want to buy? - buyTickets = Etc.parseInt(args[1]); - - if (buyTickets < 1) - { - buyTickets = 1; - } - } - - final int allowedTickets = lConfig.getMaxTicketsEachUser() - lGame.playerInList(player); - - if (buyTickets > allowedTickets && allowedTickets > 0) - { - buyTickets = allowedTickets; - } - - // Have the admin entered a max number of tickets in the lottery? - if (lConfig.getTicketsAvailable() > 0) - { - // If so, can this user buy the selected amount? - if (lGame.ticketsSold() + buyTickets > lConfig.getTicketsAvailable()) - { - if (lGame.ticketsSold() >= lConfig.getTicketsAvailable()) - { - lGame.sendMessage(sender, "ErrorNoAvailable"); - return; - } - else - { - buyTickets = lConfig.getTicketsAvailable() - lGame.ticketsSold(); - } - } - } - - if (lConfig.getMaxTicketsEachUser() > 0 && lGame.playerInList( - player) + buyTickets > lConfig.getMaxTicketsEachUser()) - { - lGame.sendMessage(sender, "ErrorAtMax", lConfig.getMaxTicketsEachUser(), lConfig.getPlural("ticket", lConfig.getMaxTicketsEachUser())); - return; - } - - if (lGame.addPlayer(player, lConfig.getMaxTicketsEachUser(), buyTickets)) - { - // You got your ticket. - lGame.sendMessage( - sender, "BoughtTicket", buyTickets, lConfig.getPlural("ticket", buyTickets), Etc.formatCost(lConfig.getCost() * buyTickets, lConfig)); - - // Can a user buy more than one ticket? How many - // tickets have he bought now? - if (lConfig.getMaxTicketsEachUser() > 1) - { - lGame.sendMessage( - sender, "BoughtTickets", lGame.playerInList(player), lConfig.getPlural("ticket", lGame.playerInList(player))); - } - if (lConfig.isBuyingExtendDeadline() && lGame.timeUntil() < lConfig.getBuyingExtendRemaining()) - { - final long timeBonus = (long)(lConfig.getBuyingExtendBase() + (lConfig.getBuyingExtendMultiplier() * Math.sqrt( - buyTickets))); - lConfig.setNextexec(lConfig.getNextexec() + (timeBonus * 1000)); - } - if (lConfig.useBroadcastBuying()) - { - if (lGame.timeUntil() < lConfig.getBroadcastBuyingTime()) - { - lGame.broadcastMessage( - "BoughtAnnounceDraw", player.getDisplayName(), buyTickets, lConfig.getPlural("ticket", buyTickets), lGame.timeUntil(true)); - } - else - { - lGame.broadcastMessage( - "BoughtAnnounce", player.getDisplayName(), buyTickets, lConfig.getPlural("ticket", buyTickets)); - } - } - - } - else - { - // Something went wrong. - lGame.sendMessage(sender,"ErrorNotAfford"); - } - - } - - public void commandClaim(final CommandSender sender, final String[] args) - { - // Is this a console? If so, just tell that lottery is running and time until next draw. - if (!(sender instanceof Player)) - { - lGame.sendMessage(sender,"ErrorConsole2"); - return; - } - - lGame.removeFromClaimList((Player)sender); - } - - public void commandDraw(final CommandSender sender, final String[] args) - { - // Start a timer that ends in 3 secs. - lGame.sendMessage(sender,"DrawNow"); - plugin.startTimerSchedule(true); - } - - public void commandWinners(final CommandSender sender, final String[] args) - { - // Get the winners. - final ArrayList winnerArray = new ArrayList(); - try - { - final BufferedReader in = new BufferedReader( - new FileReader(plugin.getDataFolder() + File.separator + "lotteryWinners.txt")); - String str; - while ((str = in.readLine()) != null) - { - winnerArray.add(str); - } - in.close(); - } - catch (IOException e) - { - } - String[] split; - String winListPrice; - for (int i = 0; i < winnerArray.size(); i++) - { - split = winnerArray.get(i).split(":"); - if (split[2].equalsIgnoreCase("0")) - { - winListPrice = plugin.getMethod().format(Double.parseDouble(split[1])); - } - else - { - winListPrice = split[1] + " " + Etc.formatMaterialName( - Integer.parseInt(split[2])); - } - sender.sendMessage((i + 1) + ". " + split[0] + " " + winListPrice); - } - } - - public void commandAddToPot(final CommandSender sender, final String[] args) - { - if (args.length < 2) - { - lGame.sendMessage(sender,"HelpPot"); - return; - } - - final double addToPot = Etc.parseDouble(args[1]); - - if (addToPot == 0) - { - lGame.sendMessage(sender,"ErrorNumber"); - return; - } - lConfig.addExtraInPot(addToPot); - lGame.sendMessage(sender,"AddToPot", addToPot, lConfig.getExtraInPot()); - } - - public void commandConfig(final CommandSender sender, final String[] args) - { - if (args.length == 1) - { - lGame.sendMessage(sender,"HelpConfig"); - return; - } - else if (args.length > 2) - { - if (args[1].equalsIgnoreCase("cost")) - { - final double newCoin = Etc.parseDouble(args[2]); - if (newCoin <= 0) - { - lGame.sendMessage(sender,"ErrorNumber"); - } - else - { - lGame.sendMessage(sender,"ConfigCost", newCoin); - lConfig.setCost(newCoin); - } - } - else if (args[1].equalsIgnoreCase("hours")) - { - final double newHours = Etc.parseDouble(args[2]); - if (newHours <= 0) - { - lGame.sendMessage(sender,"ErrorNumber"); - } - else - { - lGame.sendMessage(sender,"ConfigHours", newHours); - lConfig.setHours(newHours); - } - - } - else if (args[1].equalsIgnoreCase("maxTicketsEachUser") || args[1].equalsIgnoreCase("max")) - { - final int newMaxTicketsEachUser = Etc.parseInt(args[2]); - lGame.sendMessage(sender,"ConfigMax", newMaxTicketsEachUser); - lConfig.setMaxTicketsEachUser(newMaxTicketsEachUser); - } - } - // Lets just reload the config. - lConfig.loadConfig(); - lGame.sendMessage(sender,"ConfigReload"); - } -} diff --git a/src/net/erbros/lottery/PlayerJoinListener.java b/src/net/erbros/lottery/PlayerJoinListener.java deleted file mode 100644 index e35b096..0000000 --- a/src/net/erbros/lottery/PlayerJoinListener.java +++ /dev/null @@ -1,29 +0,0 @@ -package net.erbros.lottery; - -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; -import org.bukkit.event.player.PlayerJoinEvent; - - -public class PlayerJoinListener implements Listener -{ - - final private Lottery plugin; - final private LotteryConfig lConfig; - final private LotteryGame lGame; - - public PlayerJoinListener(final Lottery plugin) - { - this.plugin = plugin; - lGame = plugin.getLotteryGame(); - lConfig = plugin.getLotteryConfig(); - } - - @EventHandler(priority = EventPriority.MONITOR) - public void onPlayerJoin(final PlayerJoinEvent event) - { - // Send the player some info about time until lottery draw? - lGame.sendMessage(event.getPlayer(),"Welcome"); - } -} diff --git a/src/net/erbros/lottery/PluginListener.java b/src/net/erbros/lottery/PluginListener.java deleted file mode 100644 index fec2997..0000000 --- a/src/net/erbros/lottery/PluginListener.java +++ /dev/null @@ -1,52 +0,0 @@ -package net.erbros.lottery; - -import org.bukkit.Bukkit; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; -import org.bukkit.event.server.PluginDisableEvent; -import org.bukkit.event.server.PluginEnableEvent; -import net.erbros.lottery.register.payment.Methods; - - -public class PluginListener implements Listener -{ - - final private Lottery plugin; - final private Methods Methods; - - public PluginListener(final Lottery plugin) - { - this.plugin = plugin; - this.Methods = new Methods(); - } - - @EventHandler(priority = EventPriority.MONITOR) - public void onPluginDisable(final PluginDisableEvent event) - { - if (this.Methods != null && Methods.hasMethod()) - { - final boolean check = Methods.checkDisabled(event.getPlugin()); - - if (check) - { - this.plugin.setMethod(null); - System.out.println("[Lottery] Payment method was disabled. No longer accepting payments."); - } - } - } - - @EventHandler(priority = EventPriority.MONITOR) - public void onPluginEnable(final PluginEnableEvent event) - { - if (!Methods.hasMethod()) - { - if (Methods.setMethod(Bukkit.getPluginManager())) - { - this.plugin.setMethod(Methods.getMethod()); - System.out.println( - "[Lottery] Payment method found (" + this.plugin.getMethod().getName() + " version: " + this.plugin.getMethod().getVersion() + ")"); - } - } - } -} \ No newline at end of file diff --git a/src/net/erbros/lottery/register/payment/Method.java b/src/net/erbros/lottery/register/payment/Method.java deleted file mode 100644 index fcfff03..0000000 --- a/src/net/erbros/lottery/register/payment/Method.java +++ /dev/null @@ -1,202 +0,0 @@ -package net.erbros.lottery.register.payment; - -import org.bukkit.plugin.Plugin; - - -/** - * Interface to be implemented by a payment method. - * - * @author Nijikokun (@nijikokun) @copyright Copyright - * (C) 2011 @license AOL license - */ -public interface Method -{ - - /** - * Encodes the Plugin into an Object disguised as the Plugin. If you want - * the original Plugin Class you must cast it to the correct Plugin, to do - * so you have to verify the name and or version then cast. - *

- *

-	 *  if(method.getName().equalsIgnoreCase("iConomy"))
-	 *   iConomy plugin = ((iConomy)method.getPlugin());
- * - * @return Object - * @see #getName() - * @see #getVersion() - */ - public Object getPlugin(); - - /** - * Returns the actual name of this method. - * - * @return String Plugin name. - */ - public String getName(); - - /** - * Returns the actual version of this method. - * - * @return String Plugin version. - */ - public String getVersion(); - - /** - * Returns the amount of decimal places that get stored NOTE: it will return - * -1 if there is no rounding - * - * @return int for each decimal place - */ - public int fractionalDigits(); - - /** - * Formats amounts into this payment methods style of currency display. - * - * @param amount Double - * @return String - Formatted Currency Display. - */ - public String format(double amount); - - /** - * Allows the verification of bank API existence in this payment method. - * - * @return boolean - */ - public boolean hasBanks(); - - /** - * Determines the existence of a bank via name. - * - * @param bank Bank name - * @return boolean - * @see #hasBanks - */ - public boolean hasBank(String bank); - - /** - * Determines the existence of an account via name. - * - * @param name Account name - * @return boolean - */ - public boolean hasAccount(String name); - - /** - * Check to see if an account - * name is tied to a - * bank. - * - * @param bank Bank name - * @param name Account name - * @return boolean - */ - public boolean hasBankAccount(String bank, String name); - - /** - * Returns a - * MethodAccount class for an account - * name. - * - * @param name Account name - * @return MethodAccount or - * Null - */ - public MethodAccount getAccount(String name); - - /** - * Returns a - * MethodBankAccount class for an account - * name. - * - * @param bank Bank name - * @param name Account name - * @return MethodBankAccount or - * Null - */ - public MethodBankAccount getBankAccount(String bank, String name); - - /** - * Checks to verify the compatibility between this Method and a plugin. - * Internal usage only, for the most part. - * - * @param plugin Plugin - * @return boolean - */ - public boolean isCompatible(Plugin plugin); - - /** - * Set Plugin data. - * - * @param plugin Plugin - */ - public void setPlugin(Plugin plugin); - - /** - * Contains Calculator and Balance functions for Accounts. - */ - public interface MethodAccount - { - - public double balance(); - - public boolean set(double amount); - - public boolean add(double amount); - - public boolean subtract(double amount); - - public boolean multiply(double amount); - - public boolean divide(double amount); - - public boolean hasEnough(double amount); - - public boolean hasOver(double amount); - - public boolean hasUnder(double amount); - - public boolean isNegative(); - - public boolean remove(); - - @Override - public String toString(); - } - - - /** - * Contains Calculator and Balance functions for Bank Accounts. - */ - public interface MethodBankAccount - { - - public double balance(); - - public String getBankName(); - - public int getBankId(); - - public boolean set(double amount); - - public boolean add(double amount); - - public boolean subtract(double amount); - - public boolean multiply(double amount); - - public boolean divide(double amount); - - public boolean hasEnough(double amount); - - public boolean hasOver(double amount); - - public boolean hasUnder(double amount); - - public boolean isNegative(); - - public boolean remove(); - - @Override - public String toString(); - } -} diff --git a/src/net/erbros/lottery/register/payment/Methods.java b/src/net/erbros/lottery/register/payment/Methods.java deleted file mode 100644 index 69c02fc..0000000 --- a/src/net/erbros/lottery/register/payment/Methods.java +++ /dev/null @@ -1,296 +0,0 @@ -package net.erbros.lottery.register.payment; - -import java.util.HashSet; -import java.util.Set; -import org.bukkit.plugin.Plugin; -import org.bukkit.plugin.PluginManager; - - -/** - * The - * Methods initializes Methods that utilize the Method interface - * based on a "first come, first served" basis. - *

- * Allowing you to check whether a payment method exists or not. - *

- * Methods also allows you to set a preferred method of payment before it - * captures payment plugins in the initialization process. - *

- * in - * bukkit.yml:

- *  economy:
- *      preferred: "iConomy"
- * 
- * - * @author: Nijikokun (@nijikokun) @copyright: - * Copyright (C) 2011 @license: AOL license - */ -public class Methods -{ - - private static String version = null; - private static boolean self = false; - private static Method Method = null; - private static String preferred = ""; - private static Set Methods = new HashSet(); - private static Set Dependencies = new HashSet(); - private static Set Attachables = new HashSet(); - - static - { - _init(); - } - - /** - * Implement all methods along with their respective name & class. - */ - private static void _init() - { - addMethod("iConomy", new net.erbros.lottery.register.payment.methods.iCo6()); - addMethod("iConomy", new net.erbros.lottery.register.payment.methods.iCo5()); - addMethod("iConomy", new net.erbros.lottery.register.payment.methods.iCo4()); - addMethod("BOSEconomy", new net.erbros.lottery.register.payment.methods.BOSE6()); - addMethod("BOSEconomy", new net.erbros.lottery.register.payment.methods.BOSE7()); - addMethod("Essentials", new net.erbros.lottery.register.payment.methods.EE17()); - addMethod("Currency", new net.erbros.lottery.register.payment.methods.MCUR()); - Dependencies.add("MultiCurrency"); - addMethod("Vault", new net.erbros.lottery.register.payment.methods.VaultEco()); - } - - /** - * Used by the plugin to setup version - * - * @param v version - */ - public static void setVersion(String v) - { - version = v; - } - - /** - * Use to reset methods during disable - */ - public static void reset() - { - version = null; - self = false; - Method = null; - preferred = ""; - Attachables.clear(); - } - - /** - * Use to get version of Register plugin - * - * @return version - */ - public static String getVersion() - { - return version; - } - - /** - * Returns an array of payment method names that have been loaded through - * the - * _init method. - * - * @return Set - Array of payment methods that are loaded. - * @see #setMethod(org.bukkit.plugin.Plugin) - */ - public static Set getDependencies() - { - return Dependencies; - } - - /** - * Interprets Plugin class data to verify whether it is compatible with an - * existing payment method to use for payments and other various economic - * activity. - * - * @param plugin Plugin data from bukkit, Internal Class file. - * @return Method or Null - */ - public static Method createMethod(Plugin plugin) - { - for (Method method : Methods) - { - if (method.isCompatible(plugin)) - { - method.setPlugin(plugin); - return method; - } - } - - return null; - } - - private static void addMethod(String name, Method method) - { - Dependencies.add(name); - Methods.add(method); - } - - /** - * Verifies if Register has set a payment method for usage yet. - * - * @return boolean - * @see #setMethod(org.bukkit.plugin.Plugin) - * @see #checkDisabled(org.bukkit.plugin.Plugin) - */ - public static boolean hasMethod() - { - return (Method != null); - } - - /** - * Checks Plugin Class against a multitude of checks to verify it's - * usability as a payment method. - * - * @param PluginManager the plugin manager for the server - * @return boolean True on success, False on failure. - */ - public static boolean setMethod(PluginManager manager) - { - if (hasMethod()) - { - return true; - } - - if (self) - { - self = false; - return false; - } - - int count = 0; - boolean match = false; - Plugin plugin = null; - - for (String name : getDependencies()) - { - if (hasMethod()) - { - break; - } - - plugin = manager.getPlugin(name); - if (plugin == null) - { - continue; - } - - Method current = createMethod(plugin); - if (current == null) - { - continue; - } - - if (preferred.isEmpty()) - { - Method = current; - } - else - { - Attachables.add(current); - } - } - - if (!preferred.isEmpty()) - { - do - { - if (hasMethod()) - { - match = true; - } - else - { - for (Method attached : Attachables) - { - if (attached == null) - { - continue; - } - - if (hasMethod()) - { - match = true; - break; - } - - if (preferred.isEmpty()) - { - Method = attached; - } - - if (count == 0) - { - if (preferred.equalsIgnoreCase(attached.getName())) - { - Method = attached; - } - } - else - { - Method = attached; - } - } - - count++; - } - } - while (!match); - } - - return hasMethod(); - } - - /** - * Sets the preferred economy - * - * @return boolean - */ - public static boolean setPreferred(String check) - { - if (getDependencies().contains(check)) - { - preferred = check; - return true; - } - - return false; - } - - /** - * Grab the existing and initialized (hopefully) Method Class. - * - * @return Method or - * Null - */ - public static Method getMethod() - { - return Method; - } - - /** - * Verify is a plugin is disabled, only does this if we there is an existing - * payment method initialized in Register. - * - * @param method Plugin data from bukkit, Internal Class file. - * @return boolean - */ - public static boolean checkDisabled(Plugin method) - { - if (!hasMethod()) - { - return true; - } - - if (Method.isCompatible(method)) - { - Method = null; - } - - return (Method == null); - } -} diff --git a/src/net/erbros/lottery/register/payment/methods/BOSE6.java b/src/net/erbros/lottery/register/payment/methods/BOSE6.java deleted file mode 100644 index 30b05ed..0000000 --- a/src/net/erbros/lottery/register/payment/methods/BOSE6.java +++ /dev/null @@ -1,264 +0,0 @@ -package net.erbros.lottery.register.payment.methods; - -import org.bukkit.plugin.Plugin; -import cosine.boseconomy.BOSEconomy; -import net.erbros.lottery.register.payment.Method; - - -/** - * BOSEconomy 6 Implementation of Method - * - * @author Nijikokun (@nijikokun) - * @copyright (c) 2011 - * @license AOL license - */ -@SuppressWarnings("deprecation") -public class BOSE6 implements Method -{ - private BOSEconomy BOSEconomy; - - public BOSEconomy getPlugin() - { - return this.BOSEconomy; - } - - public String getName() - { - return "BOSEconomy"; - } - - public String getVersion() - { - return "0.6.2"; - } - - public int fractionalDigits() - { - return 0; - } - - public String format(double amount) - { - String currency = this.BOSEconomy.getMoneyNamePlural(); - - if (amount == 1) - { - currency = this.BOSEconomy.getMoneyName(); - } - - return amount + " " + currency; - } - - public boolean hasBanks() - { - return true; - } - - public boolean hasBank(String bank) - { - return this.BOSEconomy.bankExists(bank); - } - - public boolean hasAccount(String name) - { - return this.BOSEconomy.playerRegistered(name, false); - } - - public boolean hasBankAccount(String bank, String name) - { - return this.BOSEconomy.isBankOwner(bank, name) || this.BOSEconomy.isBankMember(bank, name); - } - - public MethodAccount getAccount(String name) - { - if (!hasAccount(name)) - { - return null; - } - - return new BOSEAccount(name, this.BOSEconomy); - } - - public MethodBankAccount getBankAccount(String bank, String name) - { - if (!hasBankAccount(bank, name)) - { - return null; - } - - return new BOSEBankAccount(bank, BOSEconomy); - } - - public boolean isCompatible(Plugin plugin) - { - return plugin.getDescription().getName().equalsIgnoreCase( - "boseconomy") && plugin instanceof BOSEconomy && plugin.getDescription().getVersion().equals("0.6.2"); - } - - public void setPlugin(Plugin plugin) - { - BOSEconomy = (BOSEconomy)plugin; - } - - public class BOSEAccount implements MethodAccount - { - private final String name; - private final BOSEconomy BOSEconomy; - - public BOSEAccount(String name, BOSEconomy bOSEconomy) - { - this.name = name; - this.BOSEconomy = bOSEconomy; - } - - public double balance() - { - return (double)this.BOSEconomy.getPlayerMoney(this.name); - } - - public boolean set(double amount) - { - int IntAmount = (int)Math.ceil(amount); - return this.BOSEconomy.setPlayerMoney(this.name, IntAmount, false); - } - - public boolean add(double amount) - { - int IntAmount = (int)Math.ceil(amount); - return this.BOSEconomy.addPlayerMoney(this.name, IntAmount, false); - } - - public boolean subtract(double amount) - { - int IntAmount = (int)Math.ceil(amount); - int balance = (int)this.balance(); - return this.BOSEconomy.setPlayerMoney(this.name, (balance - IntAmount), false); - } - - public boolean multiply(double amount) - { - int IntAmount = (int)Math.ceil(amount); - int balance = (int)this.balance(); - return this.BOSEconomy.setPlayerMoney(this.name, (balance * IntAmount), false); - } - - public boolean divide(double amount) - { - int IntAmount = (int)Math.ceil(amount); - int balance = (int)this.balance(); - return this.BOSEconomy.setPlayerMoney(this.name, (balance / IntAmount), false); - } - - public boolean hasEnough(double amount) - { - return (this.balance() >= amount); - } - - public boolean hasOver(double amount) - { - return (this.balance() > amount); - } - - public boolean hasUnder(double amount) - { - return (this.balance() < amount); - } - - public boolean isNegative() - { - return (this.balance() < 0); - } - - public boolean remove() - { - return false; - } - } - - - public class BOSEBankAccount implements MethodBankAccount - { - private final String bank; - private final BOSEconomy BOSEconomy; - - public BOSEBankAccount(String bank, BOSEconomy bOSEconomy) - { - this.bank = bank; - this.BOSEconomy = bOSEconomy; - } - - public String getBankName() - { - return this.bank; - } - - public int getBankId() - { - return -1; - } - - public double balance() - { - return (double)this.BOSEconomy.getBankMoney(bank); - } - - public boolean set(double amount) - { - int IntAmount = (int)Math.ceil(amount); - return this.BOSEconomy.setBankMoney(bank, IntAmount, true); - } - - public boolean add(double amount) - { - int IntAmount = (int)Math.ceil(amount); - int balance = (int)this.balance(); - return this.BOSEconomy.setBankMoney(bank, (balance + IntAmount), false); - } - - public boolean subtract(double amount) - { - int IntAmount = (int)Math.ceil(amount); - int balance = (int)this.balance(); - return this.BOSEconomy.setBankMoney(bank, (balance - IntAmount), false); - } - - public boolean multiply(double amount) - { - int IntAmount = (int)Math.ceil(amount); - int balance = (int)this.balance(); - return this.BOSEconomy.setBankMoney(bank, (balance * IntAmount), false); - } - - public boolean divide(double amount) - { - int IntAmount = (int)Math.ceil(amount); - int balance = (int)this.balance(); - return this.BOSEconomy.setBankMoney(bank, (balance / IntAmount), false); - } - - public boolean hasEnough(double amount) - { - return (this.balance() >= amount); - } - - public boolean hasOver(double amount) - { - return (this.balance() > amount); - } - - public boolean hasUnder(double amount) - { - return (this.balance() < amount); - } - - public boolean isNegative() - { - return (this.balance() < 0); - } - - public boolean remove() - { - return this.BOSEconomy.removeBank(bank); - } - } -} \ No newline at end of file diff --git a/src/net/erbros/lottery/register/payment/methods/BOSE7.java b/src/net/erbros/lottery/register/payment/methods/BOSE7.java deleted file mode 100644 index 9a323ed..0000000 --- a/src/net/erbros/lottery/register/payment/methods/BOSE7.java +++ /dev/null @@ -1,254 +0,0 @@ -package net.erbros.lottery.register.payment.methods; - -import org.bukkit.plugin.Plugin; -import cosine.boseconomy.BOSEconomy; -import net.erbros.lottery.register.payment.Method; - - -/** - * BOSEconomy 7 Implementation of Method - * - * @author Acrobot - * @author Nijikokun (@nijikokun) - * @copyright (c) 2011 - * @license AOL license - */ -public class BOSE7 implements Method -{ - private BOSEconomy BOSEconomy; - - public BOSEconomy getPlugin() - { - return this.BOSEconomy; - } - - public String getName() - { - return "BOSEconomy"; - } - - public String getVersion() - { - return "0.7.0"; - } - - public int fractionalDigits() - { - return this.BOSEconomy.getFractionalDigits(); - } - - public String format(double amount) - { - String currency = this.BOSEconomy.getMoneyNamePlural(); - - if (amount == 1) - { - currency = this.BOSEconomy.getMoneyName(); - } - - return amount + " " + currency; - } - - public boolean hasBanks() - { - return true; - } - - public boolean hasBank(String bank) - { - return this.BOSEconomy.bankExists(bank); - } - - public boolean hasAccount(String name) - { - return this.BOSEconomy.playerRegistered(name, false); - } - - public boolean hasBankAccount(String bank, String name) - { - return this.BOSEconomy.isBankOwner(bank, name) || this.BOSEconomy.isBankMember(bank, name); - } - - public MethodAccount getAccount(String name) - { - if (!hasAccount(name)) - { - return null; - } - - return new BOSEAccount(name, this.BOSEconomy); - } - - public MethodBankAccount getBankAccount(String bank, String name) - { - if (!hasBankAccount(bank, name)) - { - return null; - } - - return new BOSEBankAccount(bank, BOSEconomy); - } - - public boolean isCompatible(Plugin plugin) - { - return plugin.getDescription().getName().equalsIgnoreCase( - "boseconomy") && plugin instanceof BOSEconomy && !plugin.getDescription().getVersion().equals("0.6.2"); - } - - public void setPlugin(Plugin plugin) - { - BOSEconomy = (BOSEconomy)plugin; - } - - public class BOSEAccount implements MethodAccount - { - private String name; - private BOSEconomy BOSEconomy; - - public BOSEAccount(String name, BOSEconomy bOSEconomy) - { - this.name = name; - this.BOSEconomy = bOSEconomy; - } - - public double balance() - { - return this.BOSEconomy.getPlayerMoneyDouble(this.name); - } - - public boolean set(double amount) - { - return this.BOSEconomy.setPlayerMoney(this.name, amount, false); - } - - public boolean add(double amount) - { - return this.BOSEconomy.addPlayerMoney(this.name, amount, false); - } - - public boolean subtract(double amount) - { - double balance = this.balance(); - return this.BOSEconomy.setPlayerMoney(this.name, (balance - amount), false); - } - - public boolean multiply(double amount) - { - double balance = this.balance(); - return this.BOSEconomy.setPlayerMoney(this.name, (balance * amount), false); - } - - public boolean divide(double amount) - { - double balance = this.balance(); - return this.BOSEconomy.setPlayerMoney(this.name, (balance / amount), false); - } - - public boolean hasEnough(double amount) - { - return (this.balance() >= amount); - } - - public boolean hasOver(double amount) - { - return (this.balance() > amount); - } - - public boolean hasUnder(double amount) - { - return (this.balance() < amount); - } - - public boolean isNegative() - { - return (this.balance() < 0); - } - - public boolean remove() - { - return false; - } - } - - - public class BOSEBankAccount implements MethodBankAccount - { - private String bank; - private BOSEconomy BOSEconomy; - - public BOSEBankAccount(String bank, BOSEconomy bOSEconomy) - { - this.bank = bank; - this.BOSEconomy = bOSEconomy; - } - - public String getBankName() - { - return this.bank; - } - - public int getBankId() - { - return -1; - } - - public double balance() - { - return this.BOSEconomy.getBankMoneyDouble(bank); - } - - public boolean set(double amount) - { - return this.BOSEconomy.setBankMoney(bank, amount, true); - } - - public boolean add(double amount) - { - double balance = this.balance(); - return this.BOSEconomy.setBankMoney(bank, (balance + amount), false); - } - - public boolean subtract(double amount) - { - double balance = this.balance(); - return this.BOSEconomy.setBankMoney(bank, (balance - amount), false); - } - - public boolean multiply(double amount) - { - double balance = this.balance(); - return this.BOSEconomy.setBankMoney(bank, (balance * amount), false); - } - - public boolean divide(double amount) - { - double balance = this.balance(); - return this.BOSEconomy.setBankMoney(bank, (balance / amount), false); - } - - public boolean hasEnough(double amount) - { - return (this.balance() >= amount); - } - - public boolean hasOver(double amount) - { - return (this.balance() > amount); - } - - public boolean hasUnder(double amount) - { - return (this.balance() < amount); - } - - public boolean isNegative() - { - return (this.balance() < 0); - } - - public boolean remove() - { - return this.BOSEconomy.removeBank(bank); - } - } -} \ No newline at end of file diff --git a/src/net/erbros/lottery/register/payment/methods/EE17.java b/src/net/erbros/lottery/register/payment/methods/EE17.java deleted file mode 100644 index 39bc0df..0000000 --- a/src/net/erbros/lottery/register/payment/methods/EE17.java +++ /dev/null @@ -1,290 +0,0 @@ -package net.erbros.lottery.register.payment.methods; - -import org.bukkit.plugin.Plugin; -import com.earth2me.essentials.Essentials; -import com.earth2me.essentials.api.Economy; -import com.earth2me.essentials.api.NoLoanPermittedException; -import com.earth2me.essentials.api.UserDoesNotExistException; -import net.erbros.lottery.register.payment.Method; - - -/** - * Essentials 17 Implementation of Method - * - * @author Nijikokun (@nijikokun) - * @author Snowleo - * @author Acrobot - * @author KHobbits - * @copyright (c) 2011 - * @license AOL license - */ -public class EE17 implements Method -{ - private Essentials Essentials; - - public Essentials getPlugin() - { - return this.Essentials; - } - - public String getName() - { - return "Essentials"; - } - - public String getVersion() - { - return "2.2"; - } - - public int fractionalDigits() - { - return -1; - } - - public String format(double amount) - { - return Economy.format(amount); - } - - public boolean hasBanks() - { - return false; - } - - public boolean hasBank(String bank) - { - return false; - } - - public boolean hasAccount(String name) - { - return Economy.playerExists(name); - } - - public boolean hasBankAccount(String bank, String name) - { - return false; - } - - public MethodAccount getAccount(String name) - { - if (!hasAccount(name)) - { - return null; - } - - return new EEcoAccount(name); - } - - public MethodBankAccount getBankAccount(String bank, String name) - { - return null; - } - - public boolean isCompatible(Plugin plugin) - { - try - { - Class.forName("com.earth2me.essentials.api.Economy"); - } - catch (Exception e) - { - return false; - } - - return plugin.getDescription().getName().equalsIgnoreCase("essentials") && plugin instanceof Essentials; - } - - public void setPlugin(Plugin plugin) - { - Essentials = (Essentials)plugin; - } - - public class EEcoAccount implements MethodAccount - { - private String name; - - public EEcoAccount(String name) - { - this.name = name; - } - - public double balance() - { - Double balance = 0.0; - - try - { - balance = Economy.getMoney(this.name); - } - catch (UserDoesNotExistException ex) - { - System.out.println("[REGISTER] Failed to grab balance in Essentials Economy: " + ex.getMessage()); - } - - return balance; - } - - public boolean set(double amount) - { - try - { - Economy.setMoney(name, amount); - } - catch (UserDoesNotExistException ex) - { - System.out.println("[REGISTER] User does not exist in Essentials Economy: " + ex.getMessage()); - return false; - } - catch (NoLoanPermittedException ex) - { - System.out.println("[REGISTER] No loan permitted in Essentials Economy: " + ex.getMessage()); - return false; - } - - return true; - } - - public boolean add(double amount) - { - try - { - Economy.add(name, amount); - } - catch (UserDoesNotExistException ex) - { - System.out.println("[REGISTER] User does not exist in Essentials Economy: " + ex.getMessage()); - return false; - } - catch (NoLoanPermittedException ex) - { - System.out.println("[REGISTER] No loan permitted in Essentials Economy: " + ex.getMessage()); - return false; - } - - return true; - } - - public boolean subtract(double amount) - { - try - { - Economy.subtract(name, amount); - } - catch (UserDoesNotExistException ex) - { - System.out.println("[REGISTER] User does not exist in Essentials Economy: " + ex.getMessage()); - return false; - } - catch (NoLoanPermittedException ex) - { - System.out.println("[REGISTER] No loan permitted in Essentials Economy: " + ex.getMessage()); - return false; - } - - return true; - } - - public boolean multiply(double amount) - { - try - { - Economy.multiply(name, amount); - } - catch (UserDoesNotExistException ex) - { - System.out.println("[REGISTER] User does not exist in Essentials Economy: " + ex.getMessage()); - return false; - } - catch (NoLoanPermittedException ex) - { - System.out.println("[REGISTER] No loan permitted in Essentials Economy: " + ex.getMessage()); - return false; - } - - return true; - } - - public boolean divide(double amount) - { - try - { - Economy.divide(name, amount); - } - catch (UserDoesNotExistException ex) - { - System.out.println("[REGISTER] User does not exist in Essentials Economy: " + ex.getMessage()); - return false; - } - catch (NoLoanPermittedException ex) - { - System.out.println("[REGISTER] No loan permitted in Essentials Economy: " + ex.getMessage()); - return false; - } - - return true; - } - - public boolean hasEnough(double amount) - { - try - { - return Economy.hasEnough(name, amount); - } - catch (UserDoesNotExistException ex) - { - System.out.println("[REGISTER] User does not exist in Essentials Economy: " + ex.getMessage()); - } - - return false; - } - - public boolean hasOver(double amount) - { - try - { - return Economy.hasMore(name, amount); - } - catch (UserDoesNotExistException ex) - { - System.out.println("[REGISTER] User does not exist in Essentials Economy: " + ex.getMessage()); - } - - return false; - } - - public boolean hasUnder(double amount) - { - try - { - return Economy.hasLess(name, amount); - } - catch (UserDoesNotExistException ex) - { - System.out.println("[REGISTER] User does not exist in Essentials Economy: " + ex.getMessage()); - } - - return false; - } - - public boolean isNegative() - { - try - { - return Economy.isNegative(name); - } - catch (UserDoesNotExistException ex) - { - System.out.println("[REGISTER] User does not exist in Essentials Economy: " + ex.getMessage()); - } - - return false; - } - - public boolean remove() - { - return false; - } - } -} \ No newline at end of file diff --git a/src/net/erbros/lottery/register/payment/methods/MCUR.java b/src/net/erbros/lottery/register/payment/methods/MCUR.java deleted file mode 100644 index bbe3ab6..0000000 --- a/src/net/erbros/lottery/register/payment/methods/MCUR.java +++ /dev/null @@ -1,152 +0,0 @@ -package net.erbros.lottery.register.payment.methods; - -import org.bukkit.plugin.Plugin; -import me.ashtheking.currency.Currency; -import me.ashtheking.currency.CurrencyList; -import net.erbros.lottery.register.payment.Method; - - -/** - * MultiCurrency Method implementation. - * - * @author Acrobot - * @copyright (c) 2011 - * @license AOL license - */ -public class MCUR implements Method -{ - private Currency currencyList; - - public Object getPlugin() - { - return this.currencyList; - } - - public String getName() - { - return "MultiCurrency"; - } - - public String getVersion() - { - return "0.09"; - } - - public int fractionalDigits() - { - return -1; - } - - public String format(double amount) - { - return amount + " Currency"; - } - - public boolean hasBanks() - { - return false; - } - - public boolean hasBank(String bank) - { - return false; - } - - public boolean hasAccount(String name) - { - return true; - } - - public boolean hasBankAccount(String bank, String name) - { - return false; - } - - public MethodAccount getAccount(String name) - { - return new MCurrencyAccount(name); - } - - public MethodBankAccount getBankAccount(String bank, String name) - { - return null; - } - - public boolean isCompatible(Plugin plugin) - { - return (plugin.getDescription().getName().equalsIgnoreCase( - "Currency") || plugin.getDescription().getName().equalsIgnoreCase( - "MultiCurrency")) && plugin instanceof Currency; - } - - public void setPlugin(Plugin plugin) - { - currencyList = (Currency)plugin; - } - - public class MCurrencyAccount implements MethodAccount - { - private String name; - - public MCurrencyAccount(String name) - { - this.name = name; - } - - public double balance() - { - return CurrencyList.getValue((String)CurrencyList.maxCurrency(name)[0], name); - } - - public boolean set(double amount) - { - CurrencyList.setValue((String)CurrencyList.maxCurrency(name)[0], name, amount); - return true; - } - - public boolean add(double amount) - { - return CurrencyList.add(name, amount); - } - - public boolean subtract(double amount) - { - return CurrencyList.subtract(name, amount); - } - - public boolean multiply(double amount) - { - return CurrencyList.multiply(name, amount); - } - - public boolean divide(double amount) - { - return CurrencyList.divide(name, amount); - } - - public boolean hasEnough(double amount) - { - return CurrencyList.hasEnough(name, amount); - } - - public boolean hasOver(double amount) - { - return CurrencyList.hasOver(name, amount); - } - - public boolean hasUnder(double amount) - { - return CurrencyList.hasUnder(name, amount); - } - - public boolean isNegative() - { - return CurrencyList.isNegative(name); - } - - public boolean remove() - { - return CurrencyList.remove(name); - } - } -} diff --git a/src/net/erbros/lottery/register/payment/methods/VaultEco.java b/src/net/erbros/lottery/register/payment/methods/VaultEco.java deleted file mode 100644 index e8157b4..0000000 --- a/src/net/erbros/lottery/register/payment/methods/VaultEco.java +++ /dev/null @@ -1,294 +0,0 @@ -package net.erbros.lottery.register.payment.methods; - -import org.bukkit.plugin.Plugin; -import org.bukkit.plugin.RegisteredServiceProvider; -import net.erbros.lottery.register.payment.Method; -import net.milkbowl.vault.Vault; -import net.milkbowl.vault.economy.Economy; - - -public class VaultEco implements Method -{ - - private Vault vault; - private Economy economy; - - public Vault getPlugin() - { - return this.vault; - } - - public String getName() - { - - return this.vault.getDescription().getName().concat(" - Economy: ").concat( - economy == null ? "NoEco" : economy.getName()); - } - - public String getVersion() - { - return this.vault.getDescription().getVersion(); - } - - public int fractionalDigits() - { - return 0; - } - - public String format(double amount) - { - return this.economy.format(amount); - } - - public boolean hasBanks() - { - return this.economy.hasBankSupport(); - } - - public boolean hasBank(String bank) - { - return this.economy.getBanks().contains(bank); - } - - public boolean hasAccount(String name) - { - return this.economy.hasAccount(name); - } - - public boolean hasBankAccount(String bank, String name) - { - return this.economy.isBankOwner(bank, name).transactionSuccess() || this.economy.isBankMember( - bank, name).transactionSuccess(); - } - - public boolean createAccount(String name) - { - return this.economy.createBank(name, "").transactionSuccess(); - } - - public boolean createAccount(String name, Double balance) - { - if (!this.economy.createBank(name, "").transactionSuccess()) - { - return false; - } - return this.economy.bankDeposit(name, balance).transactionSuccess(); - } - - public MethodAccount getAccount(String name) - { - if (!hasAccount(name)) - { - return null; - } - - return new VaultAccount(name, this.economy); - } - - public MethodBankAccount getBankAccount(String bank, String name) - { - if (!hasBankAccount(bank, name)) - { - return null; - } - - return new VaultBankAccount(bank, economy); - } - - public boolean isCompatible(Plugin plugin) - { - try - { - RegisteredServiceProvider ecoPlugin = plugin.getServer().getServicesManager().getRegistration( - net.milkbowl.vault.economy.Economy.class); - return plugin instanceof Vault && ecoPlugin != null && !ecoPlugin.getProvider().getName().equals( - "Essentials Economy"); - } - catch (LinkageError e) - { - return false; - } - catch (Exception e) - { - return false; - } - } - - public void setPlugin(Plugin plugin) - { - this.vault = (Vault)plugin; - RegisteredServiceProvider economyProvider = this.vault.getServer().getServicesManager().getRegistration( - net.milkbowl.vault.economy.Economy.class); - if (economyProvider != null) - { - this.economy = economyProvider.getProvider(); - } - } - - public class VaultAccount implements MethodAccount - { - - private final String name; - private final Economy economy; - - public VaultAccount(String name, Economy economy) - { - this.name = name; - this.economy = economy; - } - - public double balance() - { - return this.economy.getBalance(this.name); - } - - public boolean set(double amount) - { - if (!this.economy.withdrawPlayer(this.name, this.balance()).transactionSuccess()) - { - return false; - } - if (amount == 0) - { - return true; - } - return this.economy.depositPlayer(this.name, amount).transactionSuccess(); - } - - public boolean add(double amount) - { - return this.economy.depositPlayer(this.name, amount).transactionSuccess(); - } - - public boolean subtract(double amount) - { - return this.economy.withdrawPlayer(this.name, amount).transactionSuccess(); - } - - public boolean multiply(double amount) - { - double balance = this.balance(); - return this.set(balance * amount); - } - - public boolean divide(double amount) - { - double balance = this.balance(); - return this.set(balance / amount); - } - - public boolean hasEnough(double amount) - { - return (this.balance() >= amount); - } - - public boolean hasOver(double amount) - { - return (this.balance() > amount); - } - - public boolean hasUnder(double amount) - { - return (this.balance() < amount); - } - - public boolean isNegative() - { - return (this.balance() < 0); - } - - public boolean remove() - { - return this.set(0.0); - } - } - - - public class VaultBankAccount implements MethodBankAccount - { - - private final String bank; - private final Economy economy; - - public VaultBankAccount(String bank, Economy economy) - { - this.bank = bank; - this.economy = economy; - } - - public String getBankName() - { - return this.bank; - } - - public int getBankId() - { - return -1; - } - - public double balance() - { - return this.economy.bankBalance(this.bank).balance; - } - - public boolean set(double amount) - { - if (!this.economy.bankWithdraw(this.bank, this.balance()).transactionSuccess()) - { - return false; - } - if (amount == 0) - { - return true; - } - return this.economy.bankDeposit(this.bank, amount).transactionSuccess(); - } - - public boolean add(double amount) - { - return this.economy.bankDeposit(this.bank, amount).transactionSuccess(); - } - - public boolean subtract(double amount) - { - return this.economy.bankWithdraw(this.bank, amount).transactionSuccess(); - } - - public boolean multiply(double amount) - { - double balance = this.balance(); - return this.set(balance * amount); - } - - public boolean divide(double amount) - { - double balance = this.balance(); - return this.set(balance / amount); - } - - public boolean hasEnough(double amount) - { - return (this.balance() >= amount); - } - - public boolean hasOver(double amount) - { - return (this.balance() > amount); - } - - public boolean hasUnder(double amount) - { - return (this.balance() < amount); - } - - public boolean isNegative() - { - return (this.balance() < 0); - } - - public boolean remove() - { - return this.set(0.0); - } - } -} \ No newline at end of file diff --git a/src/net/erbros/lottery/register/payment/methods/iCo4.java b/src/net/erbros/lottery/register/payment/methods/iCo4.java deleted file mode 100644 index f9d133d..0000000 --- a/src/net/erbros/lottery/register/payment/methods/iCo4.java +++ /dev/null @@ -1,185 +0,0 @@ -package net.erbros.lottery.register.payment.methods; - -import org.bukkit.plugin.Plugin; -import com.nijiko.coelho.iConomy.iConomy; -import com.nijiko.coelho.iConomy.system.Account; -import net.erbros.lottery.register.payment.Method; - - -/** - * iConomy 4 Implementation of Method - * - * @author Nijikokun (@nijikokun) - * @copyright (c) 2011 - * @license AOL license - */ -public class iCo4 implements Method -{ - private iConomy iConomy; - - public iConomy getPlugin() - { - return this.iConomy; - } - - public String getName() - { - return "iConomy"; - } - - public String getVersion() - { - return "4"; - } - - public int fractionalDigits() - { - return 2; - } - - public String format(double amount) - { - return com.nijiko.coelho.iConomy.iConomy.getBank().format(amount); - } - - public boolean hasBanks() - { - return false; - } - - public boolean hasBank(String bank) - { - return false; - } - - public boolean hasAccount(String name) - { - return com.nijiko.coelho.iConomy.iConomy.getBank().hasAccount(name); - } - - public boolean hasBankAccount(String bank, String name) - { - return false; - } - - public MethodAccount getAccount(String name) - { - return new iCoAccount(com.nijiko.coelho.iConomy.iConomy.getBank().getAccount(name)); - } - - public MethodBankAccount getBankAccount(String bank, String name) - { - return null; - } - - public boolean isCompatible(Plugin plugin) - { - return plugin.getDescription().getName().equalsIgnoreCase("iconomy") && plugin.getClass().getName().equals( - "com.nijiko.coelho.iConomy.iConomy") && plugin instanceof iConomy; - } - - public void setPlugin(Plugin plugin) - { - iConomy = (iConomy)plugin; - } - - public class iCoAccount implements MethodAccount - { - private Account account; - - public iCoAccount(Account account) - { - this.account = account; - } - - public Account getiCoAccount() - { - return account; - } - - public double balance() - { - return this.account.getBalance(); - } - - public boolean set(double amount) - { - if (this.account == null) - { - return false; - } - this.account.setBalance(amount); - return true; - } - - public boolean add(double amount) - { - if (this.account == null) - { - return false; - } - this.account.add(amount); - return true; - } - - public boolean subtract(double amount) - { - if (this.account == null) - { - return false; - } - this.account.subtract(amount); - return true; - } - - public boolean multiply(double amount) - { - if (this.account == null) - { - return false; - } - this.account.multiply(amount); - return true; - } - - public boolean divide(double amount) - { - if (this.account == null) - { - return false; - } - this.account.divide(amount); - return true; - } - - public boolean hasEnough(double amount) - { - return this.account.hasEnough(amount); - } - - public boolean hasOver(double amount) - { - return this.account.hasOver(amount); - } - - public boolean hasUnder(double amount) - { - return (this.balance() < amount); - } - - public boolean isNegative() - { - return this.account.isNegative(); - } - - public boolean remove() - { - if (this.account == null) - { - return false; - } - this.account.remove(); - return true; - } - } -} diff --git a/src/net/erbros/lottery/register/payment/methods/iCo5.java b/src/net/erbros/lottery/register/payment/methods/iCo5.java deleted file mode 100644 index b5a7406..0000000 --- a/src/net/erbros/lottery/register/payment/methods/iCo5.java +++ /dev/null @@ -1,303 +0,0 @@ -package net.erbros.lottery.register.payment.methods; - -import org.bukkit.plugin.Plugin; -import com.iConomy.iConomy; -import com.iConomy.system.Account; -import com.iConomy.system.BankAccount; -import com.iConomy.system.Holdings; -import com.iConomy.util.Constants; -import net.erbros.lottery.register.payment.Method; - - -/** - * iConomy 5 Implementation of Method - * - * @author Nijikokun (@nijikokun) - * @copyright (c) 2011 - * @license AOL license - */ -public class iCo5 implements Method -{ - private iConomy iConomy; - - public iConomy getPlugin() - { - return this.iConomy; - } - - public String getName() - { - return "iConomy"; - } - - public String getVersion() - { - return "5"; - } - - public int fractionalDigits() - { - return 2; - } - - public String format(double amount) - { - return com.iConomy.iConomy.format(amount); - } - - public boolean hasBanks() - { - return Constants.Banking; - } - - public boolean hasBank(String bank) - { - return (hasBanks()) && com.iConomy.iConomy.Banks.exists(bank); - } - - public boolean hasAccount(String name) - { - return com.iConomy.iConomy.hasAccount(name); - } - - public boolean hasBankAccount(String bank, String name) - { - return (hasBank(bank)) && com.iConomy.iConomy.getBank(bank).hasAccount(name); - } - - public MethodAccount getAccount(String name) - { - return new iCoAccount(com.iConomy.iConomy.getAccount(name)); - } - - public MethodBankAccount getBankAccount(String bank, String name) - { - return new iCoBankAccount(com.iConomy.iConomy.getBank(bank).getAccount(name)); - } - - public boolean isCompatible(Plugin plugin) - { - return plugin.getDescription().getName().equalsIgnoreCase("iconomy") && plugin.getClass().getName().equals( - "com.iConomy.iConomy") && plugin instanceof iConomy; - } - - public void setPlugin(Plugin plugin) - { - iConomy = (iConomy)plugin; - } - - public class iCoAccount implements MethodAccount - { - private Account account; - private Holdings holdings; - - public iCoAccount(Account account) - { - this.account = account; - this.holdings = account.getHoldings(); - } - - public Account getiCoAccount() - { - return account; - } - - public double balance() - { - return this.holdings.balance(); - } - - public boolean set(double amount) - { - if (this.holdings == null) - { - return false; - } - this.holdings.set(amount); - return true; - } - - public boolean add(double amount) - { - if (this.holdings == null) - { - return false; - } - this.holdings.add(amount); - return true; - } - - public boolean subtract(double amount) - { - if (this.holdings == null) - { - return false; - } - this.holdings.subtract(amount); - return true; - } - - public boolean multiply(double amount) - { - if (this.holdings == null) - { - return false; - } - this.holdings.multiply(amount); - return true; - } - - public boolean divide(double amount) - { - if (this.holdings == null) - { - return false; - } - this.holdings.divide(amount); - return true; - } - - public boolean hasEnough(double amount) - { - return this.holdings.hasEnough(amount); - } - - public boolean hasOver(double amount) - { - return this.holdings.hasOver(amount); - } - - public boolean hasUnder(double amount) - { - return this.holdings.hasUnder(amount); - } - - public boolean isNegative() - { - return this.holdings.isNegative(); - } - - public boolean remove() - { - if (this.account == null) - { - return false; - } - this.account.remove(); - return true; - } - } - - - public class iCoBankAccount implements MethodBankAccount - { - private BankAccount account; - private Holdings holdings; - - public iCoBankAccount(BankAccount account) - { - this.account = account; - this.holdings = account.getHoldings(); - } - - public BankAccount getiCoBankAccount() - { - return account; - } - - public String getBankName() - { - return this.account.getBankName(); - } - - public int getBankId() - { - return this.account.getBankId(); - } - - public double balance() - { - return this.holdings.balance(); - } - - public boolean set(double amount) - { - if (this.holdings == null) - { - return false; - } - this.holdings.set(amount); - return true; - } - - public boolean add(double amount) - { - if (this.holdings == null) - { - return false; - } - this.holdings.add(amount); - return true; - } - - public boolean subtract(double amount) - { - if (this.holdings == null) - { - return false; - } - this.holdings.subtract(amount); - return true; - } - - public boolean multiply(double amount) - { - if (this.holdings == null) - { - return false; - } - this.holdings.multiply(amount); - return true; - } - - public boolean divide(double amount) - { - if (this.holdings == null) - { - return false; - } - this.holdings.divide(amount); - return true; - } - - public boolean hasEnough(double amount) - { - return this.holdings.hasEnough(amount); - } - - public boolean hasOver(double amount) - { - return this.holdings.hasOver(amount); - } - - public boolean hasUnder(double amount) - { - return this.holdings.hasUnder(amount); - } - - public boolean isNegative() - { - return this.holdings.isNegative(); - } - - public boolean remove() - { - if (this.account == null) - { - return false; - } - this.account.remove(); - return true; - } - } -} \ No newline at end of file diff --git a/src/net/erbros/lottery/register/payment/methods/iCo6.java b/src/net/erbros/lottery/register/payment/methods/iCo6.java deleted file mode 100644 index c99deed..0000000 --- a/src/net/erbros/lottery/register/payment/methods/iCo6.java +++ /dev/null @@ -1,189 +0,0 @@ -package net.erbros.lottery.register.payment.methods; - -import org.bukkit.plugin.Plugin; -import com.iCo6.iConomy; -import com.iCo6.system.Account; -import com.iCo6.system.Accounts; -import com.iCo6.system.Holdings; -import net.erbros.lottery.register.payment.Method; - - -/** - * iConomy 6 Implementation of Method - * - * @author Nijikokun (@nijikokun) - * @copyright (c) 2011 - * @license AOL license - */ -public class iCo6 implements Method -{ - private iConomy iConomy; - - public iConomy getPlugin() - { - return this.iConomy; - } - - public String getName() - { - return "iConomy"; - } - - public String getVersion() - { - return "6"; - } - - public int fractionalDigits() - { - return 2; - } - - public String format(double amount) - { - return com.iCo6.iConomy.format(amount); - } - - public boolean hasBanks() - { - return false; - } - - public boolean hasBank(String bank) - { - return false; - } - - public boolean hasAccount(String name) - { - return (new Accounts()).exists(name); - } - - public boolean hasBankAccount(String bank, String name) - { - return false; - } - - public MethodAccount getAccount(String name) - { - return new iCoAccount((new Accounts()).get(name)); - } - - public MethodBankAccount getBankAccount(String bank, String name) - { - return null; - } - - public boolean isCompatible(Plugin plugin) - { - return plugin.getDescription().getName().equalsIgnoreCase("iconomy") && plugin.getClass().getName().equals( - "com.iCo6.iConomy") && plugin instanceof iConomy; - } - - public void setPlugin(Plugin plugin) - { - iConomy = (iConomy)plugin; - } - - public class iCoAccount implements MethodAccount - { - private Account account; - private Holdings holdings; - - public iCoAccount(Account account) - { - this.account = account; - this.holdings = account.getHoldings(); - } - - public Account getiCoAccount() - { - return account; - } - - public double balance() - { - return this.holdings.getBalance(); - } - - public boolean set(double amount) - { - if (this.holdings == null) - { - return false; - } - this.holdings.setBalance(amount); - return true; - } - - public boolean add(double amount) - { - if (this.holdings == null) - { - return false; - } - this.holdings.add(amount); - return true; - } - - public boolean subtract(double amount) - { - if (this.holdings == null) - { - return false; - } - this.holdings.subtract(amount); - return true; - } - - public boolean multiply(double amount) - { - if (this.holdings == null) - { - return false; - } - this.holdings.multiply(amount); - return true; - } - - public boolean divide(double amount) - { - if (this.holdings == null) - { - return false; - } - this.holdings.divide(amount); - return true; - } - - public boolean hasEnough(double amount) - { - return this.holdings.hasEnough(amount); - } - - public boolean hasOver(double amount) - { - return this.holdings.hasOver(amount); - } - - public boolean hasUnder(double amount) - { - return this.holdings.hasUnder(amount); - } - - public boolean isNegative() - { - return this.holdings.isNegative(); - } - - public boolean remove() - { - if (this.account == null) - { - return false; - } - this.account.remove(); - return true; - } - } -}