diff --git a/.gitignore b/.gitignore index e11e9ab3..c99880a0 100644 --- a/.gitignore +++ b/.gitignore @@ -1,11 +1,10 @@ -.settings -bin -.classpath -.project -*.bak -*.rar -*.zip -*.class -target/ -javadocs/ -*.iml \ No newline at end of file +bin +*.bak +*.rar +*.zip +*.class +target/ +javadocs/ +*.iml +**/.$* +**/.$* \ No newline at end of file diff --git a/.project b/.project new file mode 100644 index 00000000..05b4ed7c --- /dev/null +++ b/.project @@ -0,0 +1,17 @@ + + + MinigamesLib-parent + + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.m2e.core.maven2Nature + + diff --git a/.settings/org.eclipse.core.resources.prefs b/.settings/org.eclipse.core.resources.prefs new file mode 100644 index 00000000..99f26c02 --- /dev/null +++ b/.settings/org.eclipse.core.resources.prefs @@ -0,0 +1,2 @@ +eclipse.preferences.version=1 +encoding/=UTF-8 diff --git a/.settings/org.eclipse.m2e.core.prefs b/.settings/org.eclipse.m2e.core.prefs new file mode 100644 index 00000000..f897a7f1 --- /dev/null +++ b/.settings/org.eclipse.m2e.core.prefs @@ -0,0 +1,4 @@ +activeProfiles= +eclipse.preferences.version=1 +resolveWorkspaceProjects=true +version=1 diff --git a/1_7_R3/pom.xml b/1_7_R3/pom.xml deleted file mode 100644 index b15df559..00000000 --- a/1_7_R3/pom.xml +++ /dev/null @@ -1,45 +0,0 @@ - - 4.0.0 - com.comze_instancelabs - MinigamesLib-1_7_R3 - v1_7_R3 - jar - MinigamesLib-NMS-1_7_R3 - v1_7_R3 NMS for MinigamesAPI - - - com.comze_instancelabs - MinigamesLib-parent - parent - - - - - org.bukkit - craftbukkit - 1.7.9-R0.1-SNAPSHOT - jar - - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 2.3.2 - - 1.6 - 1.6 - - - - - \ No newline at end of file diff --git a/API/.classpath b/API/.classpath new file mode 100644 index 00000000..9107fba7 --- /dev/null +++ b/API/.classpath @@ -0,0 +1,31 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/API/.project b/API/.project new file mode 100644 index 00000000..8d550315 --- /dev/null +++ b/API/.project @@ -0,0 +1,29 @@ + + + MinigamesLib + + + + + + org.eclipse.wst.common.project.facet.core.builder + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.jdt.core.javanature + org.eclipse.m2e.core.maven2Nature + org.eclipse.wst.common.project.facet.core.nature + + diff --git a/API/.settings/org.eclipse.core.resources.prefs b/API/.settings/org.eclipse.core.resources.prefs new file mode 100644 index 00000000..ed7df2b3 --- /dev/null +++ b/API/.settings/org.eclipse.core.resources.prefs @@ -0,0 +1,6 @@ +eclipse.preferences.version=1 +encoding//src/main/java=UTF-8 +encoding//src/main/resources=UTF-8 +encoding//src/test/java=UTF-8 +encoding/=UTF-8 +encoding/src=UTF-8 diff --git a/API/.settings/org.eclipse.jdt.core.prefs b/API/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 00000000..597b1ac6 --- /dev/null +++ b/API/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,433 @@ +eclipse.preferences.version=1 +org.eclipse.jdt.core.codeComplete.argumentPrefixes= +org.eclipse.jdt.core.codeComplete.argumentSuffixes= +org.eclipse.jdt.core.codeComplete.fieldPrefixes= +org.eclipse.jdt.core.codeComplete.fieldSuffixes= +org.eclipse.jdt.core.codeComplete.localPrefixes= +org.eclipse.jdt.core.codeComplete.localSuffixes= +org.eclipse.jdt.core.codeComplete.staticFieldPrefixes= +org.eclipse.jdt.core.codeComplete.staticFieldSuffixes= +org.eclipse.jdt.core.codeComplete.staticFinalFieldPrefixes= +org.eclipse.jdt.core.codeComplete.staticFinalFieldSuffixes= +org.eclipse.jdt.core.compiler.annotation.inheritNullAnnotations=disabled +org.eclipse.jdt.core.compiler.annotation.missingNonNullByDefaultAnnotation=ignore +org.eclipse.jdt.core.compiler.annotation.nonnull=org.eclipse.jdt.annotation.NonNull +org.eclipse.jdt.core.compiler.annotation.nonnull.secondary= +org.eclipse.jdt.core.compiler.annotation.nonnullbydefault=org.eclipse.jdt.annotation.NonNullByDefault +org.eclipse.jdt.core.compiler.annotation.nonnullbydefault.secondary= +org.eclipse.jdt.core.compiler.annotation.nullable=org.eclipse.jdt.annotation.Nullable +org.eclipse.jdt.core.compiler.annotation.nullable.secondary= +org.eclipse.jdt.core.compiler.annotation.nullanalysis=disabled +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.methodParameters=do not generate +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 +org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve +org.eclipse.jdt.core.compiler.compliance=1.8 +org.eclipse.jdt.core.compiler.debug.lineNumber=generate +org.eclipse.jdt.core.compiler.debug.localVariable=generate +org.eclipse.jdt.core.compiler.debug.sourceFile=generate +org.eclipse.jdt.core.compiler.doc.comment.support=enabled +org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.autoboxing=ignore +org.eclipse.jdt.core.compiler.problem.comparingIdentical=warning +org.eclipse.jdt.core.compiler.problem.deadCode=warning +org.eclipse.jdt.core.compiler.problem.deprecation=warning +org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled +org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=disabled +org.eclipse.jdt.core.compiler.problem.discouragedReference=warning +org.eclipse.jdt.core.compiler.problem.emptyStatement=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.problem.explicitlyClosedAutoCloseable=warning +org.eclipse.jdt.core.compiler.problem.fallthroughCase=warning +org.eclipse.jdt.core.compiler.problem.fatalOptionalError=disabled +org.eclipse.jdt.core.compiler.problem.fieldHiding=warning +org.eclipse.jdt.core.compiler.problem.finalParameterBound=warning +org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=warning +org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning +org.eclipse.jdt.core.compiler.problem.hiddenCatchBlock=warning +org.eclipse.jdt.core.compiler.problem.includeNullInfoFromAsserts=enabled +org.eclipse.jdt.core.compiler.problem.incompatibleNonInheritedInterfaceMethod=warning +org.eclipse.jdt.core.compiler.problem.incompleteEnumSwitch=warning +org.eclipse.jdt.core.compiler.problem.indirectStaticAccess=warning +org.eclipse.jdt.core.compiler.problem.invalidJavadoc=warning +org.eclipse.jdt.core.compiler.problem.invalidJavadocTags=enabled +org.eclipse.jdt.core.compiler.problem.invalidJavadocTagsDeprecatedRef=enabled +org.eclipse.jdt.core.compiler.problem.invalidJavadocTagsNotVisibleRef=enabled +org.eclipse.jdt.core.compiler.problem.invalidJavadocTagsVisibility=private +org.eclipse.jdt.core.compiler.problem.localVariableHiding=warning +org.eclipse.jdt.core.compiler.problem.methodWithConstructorName=warning +org.eclipse.jdt.core.compiler.problem.missingDefaultCase=warning +org.eclipse.jdt.core.compiler.problem.missingDeprecatedAnnotation=warning +org.eclipse.jdt.core.compiler.problem.missingEnumCaseDespiteDefault=enabled +org.eclipse.jdt.core.compiler.problem.missingHashCodeMethod=error +org.eclipse.jdt.core.compiler.problem.missingJavadocComments=warning +org.eclipse.jdt.core.compiler.problem.missingJavadocCommentsOverriding=disabled +org.eclipse.jdt.core.compiler.problem.missingJavadocCommentsVisibility=private +org.eclipse.jdt.core.compiler.problem.missingJavadocTagDescription=return_tag +org.eclipse.jdt.core.compiler.problem.missingJavadocTags=warning +org.eclipse.jdt.core.compiler.problem.missingJavadocTagsMethodTypeParameters=disabled +org.eclipse.jdt.core.compiler.problem.missingJavadocTagsOverriding=disabled +org.eclipse.jdt.core.compiler.problem.missingJavadocTagsVisibility=private +org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotation=warning +org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotationForInterfaceMethodImplementation=enabled +org.eclipse.jdt.core.compiler.problem.missingSerialVersion=warning +org.eclipse.jdt.core.compiler.problem.missingSynchronizedOnInheritedMethod=warning +org.eclipse.jdt.core.compiler.problem.noEffectAssignment=warning +org.eclipse.jdt.core.compiler.problem.noImplicitStringConversion=warning +org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral=warning +org.eclipse.jdt.core.compiler.problem.nonnullParameterAnnotationDropped=warning +org.eclipse.jdt.core.compiler.problem.nonnullTypeVariableFromLegacyInvocation=warning +org.eclipse.jdt.core.compiler.problem.nullAnnotationInferenceConflict=error +org.eclipse.jdt.core.compiler.problem.nullReference=warning +org.eclipse.jdt.core.compiler.problem.nullSpecViolation=error +org.eclipse.jdt.core.compiler.problem.nullUncheckedConversion=warning +org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod=warning +org.eclipse.jdt.core.compiler.problem.parameterAssignment=error +org.eclipse.jdt.core.compiler.problem.pessimisticNullAnalysisForFreeTypeVariables=warning +org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment=warning +org.eclipse.jdt.core.compiler.problem.potentialNullReference=warning +org.eclipse.jdt.core.compiler.problem.potentiallyUnclosedCloseable=warning +org.eclipse.jdt.core.compiler.problem.rawTypeReference=warning +org.eclipse.jdt.core.compiler.problem.redundantNullAnnotation=warning +org.eclipse.jdt.core.compiler.problem.redundantNullCheck=warning +org.eclipse.jdt.core.compiler.problem.redundantSpecificationOfTypeArguments=warning +org.eclipse.jdt.core.compiler.problem.redundantSuperinterface=warning +org.eclipse.jdt.core.compiler.problem.reportMethodCanBePotentiallyStatic=ignore +org.eclipse.jdt.core.compiler.problem.reportMethodCanBeStatic=ignore +org.eclipse.jdt.core.compiler.problem.specialParameterHidingField=disabled +org.eclipse.jdt.core.compiler.problem.staticAccessReceiver=warning +org.eclipse.jdt.core.compiler.problem.suppressOptionalErrors=disabled +org.eclipse.jdt.core.compiler.problem.suppressWarnings=enabled +org.eclipse.jdt.core.compiler.problem.syntacticNullAnalysisForFields=disabled +org.eclipse.jdt.core.compiler.problem.syntheticAccessEmulation=warning +org.eclipse.jdt.core.compiler.problem.typeParameterHiding=warning +org.eclipse.jdt.core.compiler.problem.unavoidableGenericTypeProblems=enabled +org.eclipse.jdt.core.compiler.problem.uncheckedTypeOperation=warning +org.eclipse.jdt.core.compiler.problem.unclosedCloseable=warning +org.eclipse.jdt.core.compiler.problem.undocumentedEmptyBlock=error +org.eclipse.jdt.core.compiler.problem.unhandledWarningToken=warning +org.eclipse.jdt.core.compiler.problem.unnecessaryElse=warning +org.eclipse.jdt.core.compiler.problem.unnecessaryTypeCheck=warning +org.eclipse.jdt.core.compiler.problem.unqualifiedFieldAccess=warning +org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownException=warning +org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionExemptExceptionAndThrowable=enabled +org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionIncludeDocCommentReference=enabled +org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionWhenOverriding=disabled +org.eclipse.jdt.core.compiler.problem.unusedExceptionParameter=warning +org.eclipse.jdt.core.compiler.problem.unusedImport=warning +org.eclipse.jdt.core.compiler.problem.unusedLabel=warning +org.eclipse.jdt.core.compiler.problem.unusedLocal=warning +org.eclipse.jdt.core.compiler.problem.unusedObjectAllocation=warning +org.eclipse.jdt.core.compiler.problem.unusedParameter=warning +org.eclipse.jdt.core.compiler.problem.unusedParameterIncludeDocCommentReference=enabled +org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=disabled +org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=disabled +org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=warning +org.eclipse.jdt.core.compiler.problem.unusedTypeParameter=warning +org.eclipse.jdt.core.compiler.problem.unusedWarningToken=warning +org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning +org.eclipse.jdt.core.compiler.source=1.8 +org.eclipse.jdt.core.formatter.align_fields_grouping_blank_lines=2147483647 +org.eclipse.jdt.core.formatter.align_type_members_on_columns=true +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression=16 +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_annotation=0 +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_enum_constant=16 +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_explicit_constructor_call=16 +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_method_invocation=16 +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_qualified_allocation_expression=16 +org.eclipse.jdt.core.formatter.alignment_for_assignment=0 +org.eclipse.jdt.core.formatter.alignment_for_binary_expression=16 +org.eclipse.jdt.core.formatter.alignment_for_compact_if=16 +org.eclipse.jdt.core.formatter.alignment_for_conditional_expression=80 +org.eclipse.jdt.core.formatter.alignment_for_enum_constants=0 +org.eclipse.jdt.core.formatter.alignment_for_expressions_in_array_initializer=16 +org.eclipse.jdt.core.formatter.alignment_for_expressions_in_for_loop_header=0 +org.eclipse.jdt.core.formatter.alignment_for_method_declaration=0 +org.eclipse.jdt.core.formatter.alignment_for_multiple_fields=16 +org.eclipse.jdt.core.formatter.alignment_for_parameterized_type_references=0 +org.eclipse.jdt.core.formatter.alignment_for_parameters_in_constructor_declaration=16 +org.eclipse.jdt.core.formatter.alignment_for_parameters_in_method_declaration=16 +org.eclipse.jdt.core.formatter.alignment_for_resources_in_try=80 +org.eclipse.jdt.core.formatter.alignment_for_selector_in_method_invocation=16 +org.eclipse.jdt.core.formatter.alignment_for_superclass_in_type_declaration=16 +org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_enum_declaration=16 +org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_type_declaration=16 +org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_constructor_declaration=16 +org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_method_declaration=16 +org.eclipse.jdt.core.formatter.alignment_for_type_arguments=0 +org.eclipse.jdt.core.formatter.alignment_for_type_parameters=0 +org.eclipse.jdt.core.formatter.alignment_for_union_type_in_multicatch=16 +org.eclipse.jdt.core.formatter.blank_lines_after_imports=1 +org.eclipse.jdt.core.formatter.blank_lines_after_package=1 +org.eclipse.jdt.core.formatter.blank_lines_before_field=0 +org.eclipse.jdt.core.formatter.blank_lines_before_first_class_body_declaration=0 +org.eclipse.jdt.core.formatter.blank_lines_before_imports=1 +org.eclipse.jdt.core.formatter.blank_lines_before_member_type=1 +org.eclipse.jdt.core.formatter.blank_lines_before_method=1 +org.eclipse.jdt.core.formatter.blank_lines_before_new_chunk=1 +org.eclipse.jdt.core.formatter.blank_lines_before_package=0 +org.eclipse.jdt.core.formatter.blank_lines_between_import_groups=1 +org.eclipse.jdt.core.formatter.blank_lines_between_type_declarations=1 +org.eclipse.jdt.core.formatter.brace_position_for_annotation_type_declaration=next_line +org.eclipse.jdt.core.formatter.brace_position_for_anonymous_type_declaration=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_array_initializer=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_block=next_line +org.eclipse.jdt.core.formatter.brace_position_for_block_in_case=next_line +org.eclipse.jdt.core.formatter.brace_position_for_constructor_declaration=next_line +org.eclipse.jdt.core.formatter.brace_position_for_enum_constant=next_line +org.eclipse.jdt.core.formatter.brace_position_for_enum_declaration=next_line +org.eclipse.jdt.core.formatter.brace_position_for_lambda_body=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_method_declaration=next_line +org.eclipse.jdt.core.formatter.brace_position_for_switch=next_line +org.eclipse.jdt.core.formatter.brace_position_for_type_declaration=next_line +org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_block_comment=false +org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_javadoc_comment=false +org.eclipse.jdt.core.formatter.comment.format_block_comments=true +org.eclipse.jdt.core.formatter.comment.format_header=false +org.eclipse.jdt.core.formatter.comment.format_html=true +org.eclipse.jdt.core.formatter.comment.format_javadoc_comments=true +org.eclipse.jdt.core.formatter.comment.format_line_comments=true +org.eclipse.jdt.core.formatter.comment.format_source_code=true +org.eclipse.jdt.core.formatter.comment.indent_parameter_description=true +org.eclipse.jdt.core.formatter.comment.indent_root_tags=true +org.eclipse.jdt.core.formatter.comment.insert_new_line_before_root_tags=insert +org.eclipse.jdt.core.formatter.comment.insert_new_line_for_parameter=insert +org.eclipse.jdt.core.formatter.comment.line_length=200 +org.eclipse.jdt.core.formatter.comment.new_lines_at_block_boundaries=true +org.eclipse.jdt.core.formatter.comment.new_lines_at_javadoc_boundaries=true +org.eclipse.jdt.core.formatter.comment.preserve_white_space_between_code_and_line_comments=false +org.eclipse.jdt.core.formatter.compact_else_if=true +org.eclipse.jdt.core.formatter.continuation_indentation=2 +org.eclipse.jdt.core.formatter.continuation_indentation_for_array_initializer=2 +org.eclipse.jdt.core.formatter.disabling_tag=@formatter\:off +org.eclipse.jdt.core.formatter.enabling_tag=@formatter\:on +org.eclipse.jdt.core.formatter.format_guardian_clause_on_one_line=false +org.eclipse.jdt.core.formatter.format_line_comment_starting_on_first_column=true +org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_annotation_declaration_header=true +org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_constant_header=true +org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_declaration_header=true +org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_type_header=true +org.eclipse.jdt.core.formatter.indent_breaks_compare_to_cases=true +org.eclipse.jdt.core.formatter.indent_empty_lines=true +org.eclipse.jdt.core.formatter.indent_statements_compare_to_block=true +org.eclipse.jdt.core.formatter.indent_statements_compare_to_body=true +org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_cases=true +org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_switch=true +org.eclipse.jdt.core.formatter.indentation.size=4 +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_enum_constant=insert +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_field=insert +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_local_variable=insert +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_method=insert +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_package=insert +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_parameter=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_type=insert +org.eclipse.jdt.core.formatter.insert_new_line_after_label=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_after_opening_brace_in_array_initializer=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_after_type_annotation=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_at_end_of_file_if_missing=insert +org.eclipse.jdt.core.formatter.insert_new_line_before_catch_in_try_statement=insert +org.eclipse.jdt.core.formatter.insert_new_line_before_closing_brace_in_array_initializer=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_before_else_in_if_statement=insert +org.eclipse.jdt.core.formatter.insert_new_line_before_finally_in_try_statement=insert +org.eclipse.jdt.core.formatter.insert_new_line_before_while_in_do_statement=insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_annotation_declaration=insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_anonymous_type_declaration=insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_block=insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_constant=insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_declaration=insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_method_body=insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_type_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_after_and_in_type_parameter=insert +org.eclipse.jdt.core.formatter.insert_space_after_assignment_operator=insert +org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation_type_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_binary_operator=insert +org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_parameters=insert +org.eclipse.jdt.core.formatter.insert_space_after_closing_brace_in_block=insert +org.eclipse.jdt.core.formatter.insert_space_after_closing_paren_in_cast=insert +org.eclipse.jdt.core.formatter.insert_space_after_colon_in_assert=insert +org.eclipse.jdt.core.formatter.insert_space_after_colon_in_case=insert +org.eclipse.jdt.core.formatter.insert_space_after_colon_in_conditional=insert +org.eclipse.jdt.core.formatter.insert_space_after_colon_in_for=insert +org.eclipse.jdt.core.formatter.insert_space_after_colon_in_labeled_statement=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_allocation_expression=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_annotation=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_array_initializer=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_parameters=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_throws=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_constant_arguments=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_declarations=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_explicitconstructorcall_arguments=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_increments=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_inits=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_parameters=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_throws=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_invocation_arguments=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_field_declarations=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_local_declarations=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_parameterized_type_reference=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_superinterfaces=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_arguments=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_parameters=insert +org.eclipse.jdt.core.formatter.insert_space_after_ellipsis=insert +org.eclipse.jdt.core.formatter.insert_space_after_lambda_arrow=insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_parameterized_type_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_brace_in_array_initializer=insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_allocation_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_annotation=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_cast=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_catch=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_constructor_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_enum_constant=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_for=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_if=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_invocation=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_parenthesized_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_switch=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_synchronized=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_try=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_while=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_postfix_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_prefix_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_question_in_conditional=insert +org.eclipse.jdt.core.formatter.insert_space_after_question_in_wildcard=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_for=insert +org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_try_resources=insert +org.eclipse.jdt.core.formatter.insert_space_after_unary_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_and_in_type_parameter=insert +org.eclipse.jdt.core.formatter.insert_space_before_assignment_operator=insert +org.eclipse.jdt.core.formatter.insert_space_before_at_in_annotation_type_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_binary_operator=insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_parameterized_type_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_brace_in_array_initializer=insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_allocation_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_annotation=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_cast=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_catch=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_constructor_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_enum_constant=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_for=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_if=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_invocation=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_parenthesized_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_switch=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_synchronized=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_try=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_while=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_assert=insert +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_case=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_conditional=insert +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_default=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_for=insert +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_labeled_statement=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_allocation_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_annotation=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_array_initializer=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_throws=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_constant_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_declarations=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_explicitconstructorcall_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_increments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_inits=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_throws=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_invocation_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_field_declarations=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_local_declarations=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_parameterized_type_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_superinterfaces=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_ellipsis=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_lambda_arrow=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_parameterized_type_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_annotation_type_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_anonymous_type_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_array_initializer=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_block=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_constructor_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_constant=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_method_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_switch=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_type_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_allocation_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_type_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation_type_member_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_catch=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_constructor_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_enum_constant=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_for=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_if=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_invocation=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_parenthesized_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_switch=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_synchronized=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_try=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_while=insert +org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_return=insert +org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_throw=insert +org.eclipse.jdt.core.formatter.insert_space_before_postfix_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_prefix_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_question_in_conditional=insert +org.eclipse.jdt.core.formatter.insert_space_before_question_in_wildcard=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_semicolon=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_semicolon_in_for=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_semicolon_in_try_resources=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_unary_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_brackets_in_array_type_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_braces_in_array_initializer=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_brackets_in_array_allocation_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_annotation_type_member_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_constructor_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_enum_constant=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_invocation=do not insert +org.eclipse.jdt.core.formatter.join_lines_in_comments=true +org.eclipse.jdt.core.formatter.join_wrapped_lines=true +org.eclipse.jdt.core.formatter.keep_else_statement_on_same_line=false +org.eclipse.jdt.core.formatter.keep_empty_array_initializer_on_one_line=false +org.eclipse.jdt.core.formatter.keep_imple_if_on_one_line=false +org.eclipse.jdt.core.formatter.keep_then_statement_on_same_line=false +org.eclipse.jdt.core.formatter.lineSplit=200 +org.eclipse.jdt.core.formatter.never_indent_block_comments_on_first_column=false +org.eclipse.jdt.core.formatter.never_indent_line_comments_on_first_column=false +org.eclipse.jdt.core.formatter.number_of_blank_lines_at_beginning_of_method_body=0 +org.eclipse.jdt.core.formatter.number_of_empty_lines_to_preserve=1 +org.eclipse.jdt.core.formatter.parentheses_positions_in_annotation=common_lines +org.eclipse.jdt.core.formatter.parentheses_positions_in_catch_clause=common_lines +org.eclipse.jdt.core.formatter.parentheses_positions_in_enum_constant_declaration=common_lines +org.eclipse.jdt.core.formatter.parentheses_positions_in_for_statment=common_lines +org.eclipse.jdt.core.formatter.parentheses_positions_in_if_while_statement=common_lines +org.eclipse.jdt.core.formatter.parentheses_positions_in_lambda_declaration=common_lines +org.eclipse.jdt.core.formatter.parentheses_positions_in_method_delcaration=common_lines +org.eclipse.jdt.core.formatter.parentheses_positions_in_method_invocation=common_lines +org.eclipse.jdt.core.formatter.parentheses_positions_in_switch_statement=common_lines +org.eclipse.jdt.core.formatter.parentheses_positions_in_try_clause=common_lines +org.eclipse.jdt.core.formatter.put_empty_statement_on_new_line=true +org.eclipse.jdt.core.formatter.tabulation.char=space +org.eclipse.jdt.core.formatter.tabulation.size=4 +org.eclipse.jdt.core.formatter.use_on_off_tags=true +org.eclipse.jdt.core.formatter.use_tabs_only_for_leading_indentations=false +org.eclipse.jdt.core.formatter.wrap_before_assignment_operator=false +org.eclipse.jdt.core.formatter.wrap_before_binary_operator=true +org.eclipse.jdt.core.formatter.wrap_before_conditional_operator=true +org.eclipse.jdt.core.formatter.wrap_before_or_operator_multicatch=true +org.eclipse.jdt.core.formatter.wrap_outer_expressions_when_nested=true +org.eclipse.jdt.core.javaFormatter=org.eclipse.jdt.core.defaultJavaFormatter diff --git a/API/.settings/org.eclipse.jdt.ui.prefs b/API/.settings/org.eclipse.jdt.ui.prefs new file mode 100644 index 00000000..51307816 --- /dev/null +++ b/API/.settings/org.eclipse.jdt.ui.prefs @@ -0,0 +1,67 @@ +cleanup.add_default_serial_version_id=false +cleanup.add_generated_serial_version_id=true +cleanup.add_missing_annotations=true +cleanup.add_missing_deprecated_annotations=true +cleanup.add_missing_methods=false +cleanup.add_missing_nls_tags=false +cleanup.add_missing_override_annotations=true +cleanup.add_missing_override_annotations_interface_methods=true +cleanup.add_serial_version_id=true +cleanup.always_use_blocks=true +cleanup.always_use_parentheses_in_expressions=false +cleanup.always_use_this_for_non_static_field_access=true +cleanup.always_use_this_for_non_static_method_access=true +cleanup.convert_functional_interfaces=true +cleanup.convert_to_enhanced_for_loop=true +cleanup.correct_indentation=true +cleanup.format_source_code=true +cleanup.format_source_code_changes_only=false +cleanup.insert_inferred_type_arguments=false +cleanup.make_local_variable_final=true +cleanup.make_parameters_final=true +cleanup.make_private_fields_final=true +cleanup.make_type_abstract_if_missing_method=false +cleanup.make_variable_declarations_final=true +cleanup.never_use_blocks=false +cleanup.never_use_parentheses_in_expressions=true +cleanup.organize_imports=true +cleanup.qualify_static_field_accesses_with_declaring_class=true +cleanup.qualify_static_member_accesses_through_instances_with_declaring_class=true +cleanup.qualify_static_member_accesses_through_subtypes_with_declaring_class=true +cleanup.qualify_static_member_accesses_with_declaring_class=true +cleanup.qualify_static_method_accesses_with_declaring_class=true +cleanup.remove_private_constructors=true +cleanup.remove_redundant_type_arguments=true +cleanup.remove_trailing_whitespaces=true +cleanup.remove_trailing_whitespaces_all=true +cleanup.remove_trailing_whitespaces_ignore_empty=false +cleanup.remove_unnecessary_casts=true +cleanup.remove_unnecessary_nls_tags=true +cleanup.remove_unused_imports=true +cleanup.remove_unused_local_variables=false +cleanup.remove_unused_private_fields=true +cleanup.remove_unused_private_members=false +cleanup.remove_unused_private_methods=true +cleanup.remove_unused_private_types=true +cleanup.sort_members=false +cleanup.sort_members_all=false +cleanup.use_anonymous_class_creation=false +cleanup.use_blocks=true +cleanup.use_blocks_only_for_return_and_throw=false +cleanup.use_lambda=true +cleanup.use_parentheses_in_expressions=false +cleanup.use_this_for_non_static_field_access=true +cleanup.use_this_for_non_static_field_access_only_if_necessary=false +cleanup.use_this_for_non_static_method_access=true +cleanup.use_this_for_non_static_method_access_only_if_necessary=false +cleanup_profile=_Minigames +cleanup_settings_version=2 +eclipse.preferences.version=1 +formatter_profile=_Minigames +formatter_settings_version=12 +org.eclipse.jdt.ui.exception.name=e +org.eclipse.jdt.ui.gettersetter.use.is=true +org.eclipse.jdt.ui.javadoc=true +org.eclipse.jdt.ui.keywordthis=true +org.eclipse.jdt.ui.overrideannotation=true +org.eclipse.jdt.ui.text.custom_code_templates= diff --git a/API/.settings/org.eclipse.m2e.core.prefs b/API/.settings/org.eclipse.m2e.core.prefs new file mode 100644 index 00000000..f897a7f1 --- /dev/null +++ b/API/.settings/org.eclipse.m2e.core.prefs @@ -0,0 +1,4 @@ +activeProfiles= +eclipse.preferences.version=1 +resolveWorkspaceProjects=true +version=1 diff --git a/API/.settings/org.eclipse.wst.common.project.facet.core.xml b/API/.settings/org.eclipse.wst.common.project.facet.core.xml new file mode 100644 index 00000000..7cbf563e --- /dev/null +++ b/API/.settings/org.eclipse.wst.common.project.facet.core.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/API/maxMcVersion.txt b/API/maxMcVersion.txt new file mode 100644 index 00000000..35d51f33 --- /dev/null +++ b/API/maxMcVersion.txt @@ -0,0 +1 @@ +1.12 \ No newline at end of file diff --git a/API/minMcVersion.txt b/API/minMcVersion.txt new file mode 100644 index 00000000..46843749 --- /dev/null +++ b/API/minMcVersion.txt @@ -0,0 +1 @@ +1.8 \ No newline at end of file diff --git a/API/pom.xml b/API/pom.xml index c7539cc1..6d4dcda6 100644 --- a/API/pom.xml +++ b/API/pom.xml @@ -1,145 +1,143 @@ - - 4.0.0 - com.comze_instancelabs - MinigamesLib - 1.13.1 - jar - MinigamesLib-API - Rich Minigames API - - - com.comze_instancelabs - MinigamesLib-parent - parent - - - - - private-crackshot-repo - http://www.instancedev.com/bukkitdev/MinigamesAPI/dependencies/Crackshot/maven/ - - - vault-repo - http://nexus.theyeticave.net/content/repositories/pub_releases - - - - - - org.bukkit - bukkit - - 1.7.2-R0.3 - jar - - - net.milkbowl.vault - Vault - 1.3.01 - provided - - - com.shampaggon.crackshot - Crackshot - 0.97.13 - provided - - - - - - instancedev - - - - - - maven-eclipse-plugin - 2.9 - - - org.eclipse.m2e.core.maven2Nature - - - org.eclipse.jdt.core.javabuilder - org.eclipse.m2e.core.maven2Builder - - - - - org.apache.maven.plugins - maven-compiler-plugin - 2.3.2 - - 1.6 - 1.6 - - - - 2.1.2 - org.apache.maven.plugins - maven-source-plugin - - - attach-sources - - jar - - - - - - org.apache.maven.plugins - maven-shade-plugin - 1.4 - - - package - - shade - - - - - com.comze_instancelabs:* - - - - - - - - org.apache.maven.plugins - maven-dependency-plugin - 2.8 - - - copy - package - - copy - - - - - com.comze_instancelabs - MinigamesLib - ${version} - jar - false - C:/Users/Rnetwork/Desktop/mc_new/mc servers/minecraft 1.5.2 bukkit RAW/plugins/ - MinigamesLib-${version}.jar - - - ${project.build.directory}/wars - true - true - - - - - - - + + 4.0.0 + com.github.MCE-Plugins + MinigamesLib + 1.14.18-SNAPSHOT + jar + MinigamesLib-API + Rich Minigames API + + + com.github.MCE-Plugins + MinigamesLib-parent + 1.14.18-SNAPSHOT + + + + + org.spigotmc + spigot + + + net.milkbowl.vault + Vault + + + com.shampaggon.crackshot + Crackshot + + + + junit + junit + + + org.powermock + powermock-module-junit4 + + + org.powermock + powermock-api-mockito + + + com.github.MCE-Plugins + MinigamesLib-Spigot-Test + + + + + + + src/main/resources + true + + + src/main/java + + **/*.properties + + + + + + 3.0.0 + org.apache.maven.plugins + maven-source-plugin + + + attach-sources + + jar + + + + + + 2.10.3 + org.apache.maven.plugins + maven-javadoc-plugin + + + attach-javadoc + + jar + + + + + + org.apache.maven.plugins + maven-shade-plugin + 1.4 + + + package + + shade + + + + + com.comze_instancelabs:* + + + + + + + + + org.jacoco + jacoco-maven-plugin + 0.7.6.201602180812 + + + default-prepare-agent + prepare-agent + + surefireArgLine + + + + default-report + test + report + + ${project.build.directory}/coverage-report + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + ${surefireArgLine} + + + + + \ No newline at end of file diff --git a/API/src/main/java/com/comze_instancelabs/minigamesapi/Arena.java b/API/src/main/java/com/comze_instancelabs/minigamesapi/Arena.java index a1abc23e..608dfe6e 100644 --- a/API/src/main/java/com/comze_instancelabs/minigamesapi/Arena.java +++ b/API/src/main/java/com/comze_instancelabs/minigamesapi/Arena.java @@ -1,8 +1,25 @@ +/* + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ package com.comze_instancelabs.minigamesapi; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; +import java.util.List; +import java.util.UUID; +import java.util.logging.Level; import org.bukkit.Bukkit; import org.bukkit.ChatColor; @@ -17,8 +34,6 @@ import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; -import org.bukkit.scheduler.BukkitTask; -import org.bukkit.util.Vector; import com.comze_instancelabs.minigamesapi.arcade.ArcadeInstance; import com.comze_instancelabs.minigamesapi.events.ArenaStartEvent; @@ -32,1418 +47,2547 @@ import com.comze_instancelabs.minigamesapi.util.Util; import com.comze_instancelabs.minigamesapi.util.Validator; -public class Arena { - - // Plugin the arena belongs to - JavaPlugin plugin; - PluginInstance pli; - private ArcadeInstance ai; - private boolean isArcadeMain = false; - private boolean isSuccessfullyInitialized = false; - - private ArrayList spawns = new ArrayList(); - HashMap pspawnloc = new HashMap(); - public HashMap lastdamager = new HashMap(); - public HashMap temp_kill_count = new HashMap(); - public HashMap temp_death_count = new HashMap(); - - private Location mainlobby; - private Location waitinglobby; - private Location specspawn; - private Location signloc; - - private int max_players; - private int min_players; - private boolean viparena; - private String permission_node; - - private ArrayList players = new ArrayList(); - private ArrayList temp_players = new ArrayList(); - - private ArenaType type = ArenaType.DEFAULT; - private ArenaState currentstate = ArenaState.JOIN; - String name = "mainarena"; - String displayname = "mainarena"; - - private Arena currentarena; - boolean started = false; - boolean startedIngameCountdown = false; - private boolean showArenascoreboard = true; - private boolean alwaysPvP = false; - - SmartReset sr = null; - - Cuboid boundaries; - Cuboid lobby_boundaries; - Cuboid spec_boundaries; - - boolean temp_countdown = true; - boolean skip_join_lobby = false; - - int currentspawn = 0; - - int global_coin_multiplier = 1; - - BukkitTask maximum_game_time; - - ArrayList global_drops = new ArrayList(); - - /** - * Creates a normal singlespawn arena - * - * @param plugin - * JavaPlugin the arena belongs to - * @param name - * name of the arena - */ - public Arena(JavaPlugin plugin, String name) { - currentarena = this; - this.plugin = plugin; - this.name = name; - sr = new SmartReset(this); - this.pli = MinigamesAPI.getAPI().getPluginInstance(plugin); - } - - /** - * Creates an arena of given arenatype - * - * @param name - * name of the arena - * @param type - * arena type - */ - public Arena(JavaPlugin plugin, String name, ArenaType type) { - this(plugin, name); - this.type = type; - } - - // This is for loading existing arenas - public void init(Location signloc, ArrayList spawns, Location mainlobby, Location waitinglobby, int max_players, int min_players, boolean viparena) { - this.signloc = signloc; - this.spawns = spawns; - this.mainlobby = mainlobby; - this.waitinglobby = waitinglobby; - this.viparena = viparena; - this.min_players = min_players; - this.max_players = max_players; - this.showArenascoreboard = pli.arenaSetup.getShowScoreboard(plugin, this.getInternalName()); - isSuccessfullyInitialized = true; - if (Util.isComponentForArenaValid(plugin, this.getInternalName(), "bounds.low") && Util.isComponentForArenaValid(plugin, this.getInternalName(), "bounds.high")) { - try { - Location low_boundary = Util.getComponentForArena(plugin, this.getInternalName(), "bounds.low"); - Location high_boundary = Util.getComponentForArena(plugin, this.getInternalName(), "bounds.high"); - if (low_boundary != null && high_boundary != null) { - this.boundaries = new Cuboid(low_boundary, high_boundary); - } else { - plugin.getServer().getConsoleSender().sendMessage(ChatColor.RED + "The boundaries of an arena appear to be invalid (missing world?), please fix! Arena: " + this.getInternalName()); - } - } catch (Exception e) { - plugin.getServer().getConsoleSender().sendMessage(ChatColor.RED + "Failed to save arenas as you forgot to set boundaries or they could not be found. This will lead to errors later, please fix your setup. " + e.getMessage()); - isSuccessfullyInitialized = false; - } - } - if (Util.isComponentForArenaValid(plugin, this.getInternalName(), "lobbybounds.bounds.low") && Util.isComponentForArenaValid(plugin, this.getInternalName(), "lobbybounds.bounds.high")) { - try { - this.lobby_boundaries = new Cuboid(Util.getComponentForArena(plugin, this.getInternalName(), "lobbybounds.bounds.low"), Util.getComponentForArena(plugin, this.getInternalName(), "lobbybounds.bounds.high")); - } catch (Exception e) { - isSuccessfullyInitialized = false; - } - } - if (Util.isComponentForArenaValid(plugin, this.getInternalName(), "specbounds.bounds.low") && Util.isComponentForArenaValid(plugin, this.getInternalName(), "specbounds.bounds.high")) { - try { - this.spec_boundaries = new Cuboid(Util.getComponentForArena(plugin, this.getInternalName(), "specbounds.bounds.low"), Util.getComponentForArena(plugin, this.getInternalName(), "specbounds.bounds.high")); - } catch (Exception e) { - isSuccessfullyInitialized = false; - } - } - - if (Util.isComponentForArenaValid(plugin, this.getInternalName(), "specspawn")) { - this.specspawn = Util.getComponentForArena(plugin, this.getInternalName(), "specspawn"); - } - - String path = "arenas." + name + ".displayname"; - if (pli.getArenasConfig().getConfig().isSet(path)) { - this.displayname = ChatColor.translateAlternateColorCodes('&', pli.getArenasConfig().getConfig().getString("arenas." + name + ".displayname")); - } else { - pli.getArenasConfig().getConfig().set(path, name); - pli.getArenasConfig().saveConfig(); - this.displayname = name; - } - - } - - // This is for loading existing arenas - @Deprecated - public Arena initArena(Location signloc, ArrayList spawn, Location mainlobby, Location waitinglobby, int max_players, int min_players, boolean viparena) { - this.init(signloc, spawn, mainlobby, waitinglobby, max_players, min_players, viparena); - return this; - } - - public Arena getArena() { - return this; - } - - public SmartReset getSmartReset() { - return this.sr; - } - - public boolean getShowScoreboard() { - return this.showArenascoreboard; - } - - public boolean getAlwaysPvP() { - return this.alwaysPvP; - } - - public void setAlwaysPvP(boolean t) { - this.alwaysPvP = t; - } - - public Location getSignLocation() { - return this.signloc; - } - - public void setSignLocation(Location l) { - this.signloc = l; - } - - public ArrayList getSpawns() { - return this.spawns; - } - - public Cuboid getBoundaries() { - return this.boundaries; - } - - public Cuboid getLobbyBoundaries() { - return this.lobby_boundaries; - } - - public Cuboid getSpecBoundaries() { - return this.spec_boundaries; - } - - public String getInternalName() { - return name; - } - - public String getDisplayName() { - return displayname; - } - - /** - * Please use getInternalName() for the internal name and getDisplayName() for the optional displayname - * - * @return Internal name of arena (same as getInternalName()) - */ - @Deprecated - public String getName() { - return name; - } - - public int getMaxPlayers() { - return this.max_players; - } - - public int getMinPlayers() { - return this.min_players; - } - - public void setMinPlayers(int i) { - this.min_players = i; - } - - public void setMaxPlayers(int i) { - this.max_players = i; - } - - public boolean isVIPArena() { - return this.viparena; - } - - public void setVIPArena(boolean t) { - this.viparena = t; - } - - public ArrayList getAllPlayers() { - return this.players; - } - - public boolean containsPlayer(String playername) { - return players.contains(playername); - } - - /** - * Please do not use this function to add players - * - * @param playername - * @return - */ - @Deprecated - public boolean addPlayer(String playername) { - return players.add(playername); - } - - /** - * Please do not use this function to remove players - * - * @param playername - * @return - */ - @Deprecated - public boolean removePlayer(String playername) { - return players.remove(playername); - } - - public ArenaState getArenaState() { - return this.currentstate; - } - - public void setArenaState(ArenaState s) { - this.currentstate = s; - } - - public ArenaType getArenaType() { - return this.type; - } - - /** - * Joins the waiting lobby of an arena - * - * @param playername - * the playername - */ - public void joinPlayerLobby(String playername) { - if (this.getArenaState() != ArenaState.JOIN && this.getArenaState() != ArenaState.STARTING) { - // arena ingame or restarting - return; - } - if (!pli.arenaSetup.getArenaEnabled(plugin, this.getInternalName())) { - Util.sendMessage(plugin, Bukkit.getPlayer(playername), pli.getMessagesConfig().arena_disabled); - return; - } - if (pli.containsGlobalPlayer(playername)) { - Util.sendMessage(plugin, Bukkit.getPlayer(playername), pli.getMessagesConfig().already_in_arena); - return; - } - if (ai == null && this.isVIPArena()) { - if (Validator.isPlayerOnline(playername)) { - if (!Bukkit.getPlayer(playername).hasPermission("arenas." + this.getInternalName()) && !Bukkit.getPlayer(playername).hasPermission("arenas.*")) { - Util.sendMessage(plugin, Bukkit.getPlayer(playername), pli.getMessagesConfig().no_perm_to_join_arena.replaceAll("", this.getInternalName())); - return; - } - } - } - if (ai == null && this.getAllPlayers().size() > this.max_players - 1) { - // arena full - - // if player vip -> kick someone and continue - System.out.println(playername + " is vip: " + Bukkit.getPlayer(playername).hasPermission("arenas.*")); - if (!Bukkit.getPlayer(playername).hasPermission("arenas." + this.getInternalName()) && !Bukkit.getPlayer(playername).hasPermission("arenas.*")) { - return; - } else { - // player has vip - boolean noone_found = true; - ArrayList temp = new ArrayList(this.getAllPlayers()); - for (String p_ : temp) { - if (Validator.isPlayerOnline(p_)) { - if (!Bukkit.getPlayer(p_).hasPermission("arenas." + this.getInternalName()) && !Bukkit.getPlayer(p_).hasPermission("arenas.*")) { - this.leavePlayer(p_, false, true); - Bukkit.getPlayer(p_).sendMessage(pli.getMessagesConfig().you_got_kicked_because_vip_joined); - noone_found = false; - break; - } - } - } - if (noone_found) { - // apparently everyone is vip, can't join - return; - } - } - } - - if (MinigamesAPI.getAPI().global_party.containsKey(playername)) { - Party party = MinigamesAPI.getAPI().global_party.get(playername); - int playersize = party.getPlayers().size() + 1; - if (this.getAllPlayers().size() + playersize > this.max_players) { - Bukkit.getPlayer(playername).sendMessage(MinigamesAPI.getAPI().partymessages.party_too_big_to_join); - return; - } else { - for (String p_ : party.getPlayers()) { - if (Validator.isPlayerOnline(p_)) { - boolean cont = true; - for (PluginInstance pli_ : MinigamesAPI.getAPI().pinstances.values()) { - // if (!pli_.getPlugin().getName().equalsIgnoreCase("MGArcade") && pli_.global_players.containsKey(p_)) { - if (pli_.containsGlobalPlayer(p_)) { - cont = false; - } - } - if (cont) { - this.joinPlayerLobby(p_); - } - } - } - } - } - - if (this.getAllPlayers().size() == this.max_players - 1) { - if (currentlobbycount > 16 && this.getArenaState() == ArenaState.STARTING) { - currentlobbycount = 16; - } - } - pli.global_players.put(playername, this); - this.players.add(playername); - - if (Validator.isPlayerValid(plugin, playername, this)) { - final Player p = Bukkit.getPlayer(playername); - final ArenaPlayer ap = ArenaPlayer.getPlayerInstance(playername); - Bukkit.getServer().getPluginManager().callEvent(new PlayerJoinLobbyEvent(p, plugin, this)); - Util.sendMessage(plugin, p, pli.getMessagesConfig().you_joined_arena.replaceAll("", this.getDisplayName())); - Util.sendMessage(plugin, p, pli.getMessagesConfig().minigame_description); - if (pli.getArenasConfig().getConfig().isSet("arenas." + this.getInternalName() + ".author")) { - Util.sendMessage(plugin, p, pli.getMessagesConfig().author_of_the_map.replaceAll("", this.getDisplayName()).replaceAll("", pli.getArenasConfig().getConfig().getString("arenas." + this.getInternalName() + ".author"))); - } - if (pli.getArenasConfig().getConfig().isSet("arenas." + this.getInternalName() + ".description")) { - Util.sendMessage(plugin, p, pli.getMessagesConfig().description_of_the_map.replaceAll("", this.getDisplayName()).replaceAll("", pli.getArenasConfig().getConfig().getString("arenas." + this.getInternalName() + ".description"))); - } - - Bukkit.getScheduler().runTaskLater(this.getPlugin(), new Runnable() { - public void run() { - try { - if (p != null) { - pli.getHologramsHandler().sendAllHolograms(p); - } - } catch (Exception e) { - System.out.println("Failed playing hologram: " + e.getMessage()); - if (MinigamesAPI.getAPI().debug) { - e.printStackTrace(); - } - } - } - }, 10L); - - for (String p_ : this.getAllPlayers()) { - if (Validator.isPlayerOnline(p_) && !p_.equalsIgnoreCase(p.getName())) { - Player p__ = Bukkit.getPlayer(p_); - int count = this.getAllPlayers().size(); - int maxcount = this.getMaxPlayers(); - Util.sendMessage(plugin, p__, pli.getMessagesConfig().broadcast_player_joined.replaceAll("", p.getName()).replace("", Integer.toString(count)).replace("", Integer.toString(maxcount))); - } - } - Util.updateSign(plugin, this); - - if (ai == null && !this.isArcadeMain()) { - this.skip_join_lobby = plugin.getConfig().getBoolean("config.countdowns.skip_lobby"); - } - - final Arena a = this; - ap.setInventories(p.getInventory().getContents(), p.getInventory().getArmorContents()); - if (this.getArenaType() == ArenaType.JUMPNRUN) { - Util.teleportPlayerFixed(p, this.spawns.get(currentspawn)); - if (currentspawn < this.spawns.size() - 1) { - currentspawn++; - } - Util.clearInv(p); - ap.setOriginalGamemode(p.getGameMode()); - ap.setOriginalXplvl(p.getLevel()); - p.setGameMode(GameMode.SURVIVAL); - p.setHealth(20D); - return; - } else { - if (startedIngameCountdown) { - pli.scoreboardLobbyManager.removeScoreboard(this.getInternalName(), p); - Util.teleportAllPlayers(currentarena.getArena().getAllPlayers(), currentarena.getArena().spawns); - p.setFoodLevel(5); - p.addPotionEffect(new PotionEffect(PotionEffectType.JUMP, 9999999, -7)); // -5 - Bukkit.getScheduler().runTaskLater(MinigamesAPI.getAPI(), new Runnable() { - public void run() { - p.setWalkSpeed(0.0F); - } - }, 1L); - Bukkit.getScheduler().runTaskLater(MinigamesAPI.getAPI(), new Runnable() { - public void run() { - Util.clearInv(p); - } - }, 10L); - ap.setOriginalXplvl(p.getLevel()); - Bukkit.getScheduler().runTaskLater(MinigamesAPI.getAPI(), new Runnable() { - public void run() { - if (a.getArenaState() != ArenaState.INGAME) { - Util.giveLobbyItems(plugin, p); - } - ap.setOriginalGamemode(p.getGameMode()); - p.setGameMode(GameMode.SURVIVAL); - } - }, 15L); - pli.scoreboardManager.updateScoreboard(plugin, this); - return; - } else { - pli.scoreboardLobbyManager.updateScoreboard(plugin, this); - if (!skip_join_lobby) { - Util.teleportPlayerFixed(p, this.waitinglobby); - Bukkit.getScheduler().runTaskLater(MinigamesAPI.getAPI(), new Runnable() { - public void run() { - p.setHealth(20D); - } - }, 2L); - } else { - Util.teleportAllPlayers(currentarena.getArena().getAllPlayers(), currentarena.getArena().spawns); - } - } - } - Bukkit.getScheduler().runTaskLater(MinigamesAPI.getAPI(), new Runnable() { - public void run() { - Util.clearInv(p); - } - }, 10L); - ap.setOriginalXplvl(p.getLevel()); - Bukkit.getScheduler().runTaskLater(MinigamesAPI.getAPI(), new Runnable() { - public void run() { - if (a.getArenaState() != ArenaState.INGAME) { - Util.giveLobbyItems(plugin, p); - } - ap.setOriginalGamemode(p.getGameMode()); - p.setGameMode(GameMode.SURVIVAL); - p.setHealth(20D); - } - }, 15L); - if (!skip_join_lobby) { - if (ai == null && this.getAllPlayers().size() > this.min_players - 1) { - this.startLobby(temp_countdown); - } else if (ai != null) { - this.startLobby(temp_countdown); - } - } else { - if (ai == null && !this.isArcadeMain() && this.getAllPlayers().size() > this.min_players - 1) { - this.startLobby(false); - } - } - } - } - - /** - * Primarily used for ArcadeInstance to join a waiting lobby without countdown - * - * @param playername - * @param countdown - */ - public void joinPlayerLobby(String playername, boolean countdown) { - temp_countdown = countdown; - joinPlayerLobby(playername); - } - - /** - * Joins the waiting lobby of an arena - * - * @param playername - * the playername - * @param ai - * the ArcadeInstance - */ - public void joinPlayerLobby(String playername, ArcadeInstance ai, boolean countdown, boolean skip_lobby) { - this.skip_join_lobby = skip_lobby; - this.ai = ai; - joinPlayerLobby(playername, countdown); // join playerlobby without lobby countdown - } - - /** - * Leaves the current arena, won't do anything if not present in any arena - * - * @param playername - * @param fullLeave - * Determines if player left only minigame or the server - */ - @Deprecated - public void leavePlayer(final String playername, boolean fullLeave) { - this.leavePlayerRaw(playername, fullLeave); - } - - public void leavePlayer(final String playername, boolean fullLeave, boolean endofGame) { - if (!endofGame) { - ArenaPlayer ap = ArenaPlayer.getPlayerInstance(playername); - ap.setNoReward(true); - } - - this.leavePlayer(playername, fullLeave); - - if (!endofGame) { - if (this.getAllPlayers().size() < 2) { - if (this.getArenaState() != ArenaState.JOIN) { - if (this.getArenaState() == ArenaState.STARTING && !startedIngameCountdown) { - // cancel starting - this.setArenaState(ArenaState.JOIN); - Util.updateSign(plugin, this); - try { - Bukkit.getScheduler().cancelTask(currenttaskid); - } catch (Exception e) { - ; - } - for (String p_ : this.getAllPlayers()) { - if (Validator.isPlayerOnline(p_)) { - Util.sendMessage(plugin, Bukkit.getPlayer(p_), pli.getMessagesConfig().cancelled_starting); - } - } - return; - } - this.stop(); - } - } - } - } - - public void leavePlayerRaw(final String playername, final boolean fullLeave) { - if (!this.containsPlayer(playername)) { - return; - } - final Player p = Bukkit.getPlayer(playername); - final ArenaPlayer ap = ArenaPlayer.getPlayerInstance(playername); - if (p == null) { - return; - } - if (p.isDead()) { - System.out.println(p.getName() + " unexpectedly appeared dead! Sending respawn packet."); - Effects.playRespawn(p, plugin); - Bukkit.getScheduler().runTaskLater(plugin, new Runnable() { - public void run() { - leavePlayerRaw(playername, fullLeave); - } - }, 10L); - return; - } - this.players.remove(playername); - if (pli.containsGlobalPlayer(playername)) { - pli.global_players.remove(playername); - } - if (fullLeave) { - plugin.getConfig().set("temp.left_players." + playername + ".name", playername); - plugin.getConfig().set("temp.left_players." + playername + ".plugin", plugin.getName()); - if (plugin.getConfig().getBoolean("config.reset_inventory_when_players_leave_server")) { - for (ItemStack i : ap.getInventory()) { - if (i != null) { - plugin.getConfig().set("temp.left_players." + playername + ".items." + Integer.toString((int) Math.round(Math.random() * 10000)) + i.getType().toString(), i); - } - } - } - plugin.saveConfig(); - - try { - if (pli.global_lost.containsKey(playername)) { - pli.getSpectatorManager().showSpectator(p); - pli.global_lost.remove(playername); - } else { - pli.getSpectatorManager().showSpectators(p); - } - if (pli.global_arcade_spectator.containsKey(playername)) { - pli.global_arcade_spectator.remove(playername); - } - if (p != null) { - p.removePotionEffect(PotionEffectType.JUMP); - Util.teleportPlayerFixed(p, this.mainlobby); - p.setFireTicks(0); - p.setFlying(false); - if (!p.isOp()) { - p.setAllowFlight(false); - } - p.setGameMode(ap.getOriginalGamemode()); - p.setLevel(ap.getOriginalXplvl()); - p.getInventory().setContents(ap.getInventory()); - p.getInventory().setArmorContents(ap.getArmorInventory()); - p.updateInventory(); - - p.setWalkSpeed(0.2F); - p.setFoodLevel(20); - p.setHealth(20D); - p.removePotionEffect(PotionEffectType.JUMP); - pli.getSpectatorManager().setSpectate(p, false); - pli.getStatsInstance().updateSQLKillsDeathsAfter(p, this); - } - if (pli.getClassesHandler().lasticonm.containsKey(p.getName())) { - IconMenu iconm = pli.getClassesHandler().lasticonm.get(p.getName()); - iconm.destroy(); - pli.getClassesHandler().lasticonm.remove(p.getName()); - } - } catch (Exception e) { - System.out.println("Failed to log out player out of arena. " + e.getMessage()); - } - return; - } - Util.clearInv(p); - p.setWalkSpeed(0.2F); - p.setFoodLevel(20); - p.setHealth(20D); - p.setFireTicks(0); - p.removePotionEffect(PotionEffectType.JUMP); - pli.getSpectatorManager().setSpectate(p, false); - - Bukkit.getServer().getPluginManager().callEvent(new PlayerLeaveArenaEvent(p, plugin, this)); - - for (PotionEffect effect : p.getActivePotionEffects()) { - if (effect != null) { - p.removePotionEffect(effect.getType()); - } - } - - for (Entity e : p.getNearbyEntities(50D, 50D, 50D)) { - if (e.getType() == EntityType.DROPPED_ITEM || e.getType() == EntityType.SLIME || e.getType() == EntityType.ZOMBIE || e.getType() == EntityType.SKELETON || e.getType() == EntityType.SPIDER || e.getType() == EntityType.CREEPER) { - e.remove(); - } - } - - // pli.global_players.remove(playername); - if (pli.global_arcade_spectator.containsKey(playername)) { - pli.global_arcade_spectator.remove(playername); - } - - if (pli.getPClasses().containsKey(playername)) { - pli.getPClasses().remove(playername); - } - - Util.updateSign(plugin, this); - - Bukkit.getScheduler().runTaskLater(this.getPlugin(), new Runnable() { - public void run() { - try { - if (p != null) { - pli.getHologramsHandler().sendAllHolograms(p); - } - } catch (Exception e) { - System.out.println("Failed playing hologram: " + e.getMessage()); - if (MinigamesAPI.getAPI().debug) { - e.printStackTrace(); - } - } - } - }, 10L); - - if (pli.getClassesHandler().lasticonm.containsKey(p.getName())) { - IconMenu iconm = pli.getClassesHandler().lasticonm.get(p.getName()); - iconm.destroy(); - pli.getClassesHandler().lasticonm.remove(p.getName()); - } - - final String arenaname = this.getInternalName(); - final Arena a = this; - final boolean started_ = started; - Bukkit.getScheduler().runTaskLater(plugin, new Runnable() { - public void run() { - if (p != null) { - if (ai == null || a.isArcadeMain()) { - if (a.mainlobby != null) { - Util.teleportPlayerFixed(p, a.mainlobby); - } else if (a.waitinglobby != null) { - Util.teleportPlayerFixed(p, a.waitinglobby); - } - } - p.setFireTicks(0); - p.setFlying(false); - if (!p.isOp()) { - p.setAllowFlight(false); - } - p.setGameMode(ap.getOriginalGamemode()); - p.setLevel(ap.getOriginalXplvl()); - p.getInventory().setContents(ap.getInventory()); - p.getInventory().setArmorContents(ap.getArmorInventory()); - p.updateInventory(); - p.updateInventory(); - - if (started_) { - pli.getStatsInstance().updateSQLKillsDeathsAfter(p, a); - if (!ap.isNoReward()) { - pli.getRewardsInstance().giveWinReward(playername, a, temp_players, global_coin_multiplier); - } else { - ap.setNoReward(false); - } - } - - if (plugin.getConfig().getBoolean("config.send_stats_on_stop")) { - Util.sendStatsMessage(pli, p); - } - - if (pli.global_lost.containsKey(playername)) { - pli.getSpectatorManager().showSpectator(p); - pli.global_lost.remove(playername); - } else { - pli.getSpectatorManager().showSpectators(p); - } - - try { - pli.scoreboardManager.removeScoreboard(arenaname, p); - } catch (Exception e) { - // - } - } - } - }, 5L); - - if (plugin.getConfig().getBoolean("config.bungee.teleport_all_to_server_on_stop.tp")) { - final String server = plugin.getConfig().getString("config.bungee.teleport_all_to_server_on_stop.server"); - Bukkit.getScheduler().runTaskLater(plugin, new Runnable() { - public void run() { - BungeeUtil.connectToServer(MinigamesAPI.getAPI(), p.getName(), server); - } - }, 30L); - return; - } - } - - /** - * Spectate the game generally (not specifically after death) - * - * @param playername - * name of the player - */ - public void spectateGame(String playername) { - final Player p = Bukkit.getPlayer(playername); - if (p == null) { - return; - } - Util.clearInv(p); - p.setAllowFlight(true); - p.setFlying(true); - pli.getSpectatorManager().hideSpectator(p, this.getAllPlayers()); - pli.scoreboardManager.updateScoreboard(plugin, this); - if (!pli.last_man_standing) { - if (this.getPlayerAlive() < 1) { - final Arena a = this; - Bukkit.getScheduler().runTaskLater(plugin, new Runnable() { - public void run() { - a.stop(); - } - }, 20L); - } else { - spectateRaw(p); - } - } else { - if (this.getPlayerAlive() < 2) { - final Arena a = this; - Bukkit.getScheduler().runTaskLater(plugin, new Runnable() { - public void run() { - a.stop(); - } - }, 20L); - } else { - spectateRaw(p); - } - } - Bukkit.getScheduler().runTaskLater(plugin, new Runnable() { - public void run() { - Util.clearInv(p); - Util.giveSpectatorItems(plugin, p); - } - }, 3L); - } - - /** - * Spectate the game after death - * - * @param playername - * name of the player - */ - public void spectate(String playername) { - if (Validator.isPlayerValid(plugin, playername, this)) { - this.onEliminated(playername); - final Player p = Bukkit.getPlayer(playername); - if (p == null) { - return; - } - - pli.global_lost.put(playername, this); - - pli.getSpectatorManager().setSpectate(p, true); - if (!plugin.getConfig().getBoolean("config.spectator.spectator_after_fall_or_death")) { - this.leavePlayer(playername, false, false); - pli.scoreboardManager.updateScoreboard(plugin, this); - return; - } - spectateGame(playername); - } - } - - public void spectateRaw(final Player p) { - if (pli.dead_in_fake_bed_effects) { - Effects.playFakeBed(this, p); - } - - if (pli.spectator_mode_1_8) { - Effects.sendGameModeChange(p, 3); - } - - final Location temp = this.spawns.get(0); - try { - Bukkit.getScheduler().runTaskLater(plugin, new Runnable() { - public void run() { - if (specspawn != null) { - Util.teleportPlayerFixed(p, specspawn); - } else { - Util.teleportPlayerFixed(p, temp.clone().add(0D, 30D, 0D)); - } - } - }, 2L); - } catch (Exception e) { - if (specspawn != null) { - Util.teleportPlayerFixed(p, specspawn); - } else { - Util.teleportPlayerFixed(p, temp.clone().add(0D, 30D, 0D)); - } - } - } - - public void spectateArcade(String playername) { - Player p = Bukkit.getPlayer(playername); - pli.global_players.put(playername, currentarena); - pli.global_arcade_spectator.put(playername, currentarena); - Util.teleportPlayerFixed(p, currentarena.getSpawns().get(0).clone().add(0D, 30D, 0D)); - p.setAllowFlight(true); - p.setFlying(true); - pli.getSpectatorManager().setSpectate(p, true); - } - - int currentlobbycount = 10; - int currentingamecount = 10; - int currenttaskid = 0; - - public void setTaskId(int id) { - this.currenttaskid = id; - } - - public int getTaskId() { - return this.currenttaskid; - } - - /** - * Starts the lobby countdown and the arena afterwards - * - * You can insta-start an arena by using Arena.start(); - */ - public void startLobby() { - startLobby(true); - } - - public void startLobby(final boolean countdown) { - if (currentstate != ArenaState.JOIN) { - return; - } - this.setArenaState(ArenaState.STARTING); - Util.updateSign(plugin, this); - currentlobbycount = pli.lobby_countdown; - final Arena a = this; - - // skip countdown - if (!countdown) { - Bukkit.getScheduler().runTaskLater(plugin, new Runnable() { - public void run() { - currentarena.getArena().start(true); - } - }, 10L); - } - - Sound lobbycountdown_sound_ = null; - try { - lobbycountdown_sound_ = Sound.valueOf(plugin.getConfig().getString("config.sounds.lobby_countdown")); - } catch (Exception e) { - ; - } - final Sound lobbycountdown_sound = lobbycountdown_sound_; - - currenttaskid = Bukkit.getScheduler().runTaskTimer(MinigamesAPI.getAPI(), new Runnable() { - public void run() { - currentlobbycount--; - if (currentlobbycount == 60 || currentlobbycount == 30 || currentlobbycount == 15 || currentlobbycount == 10 || currentlobbycount < 6) { - for (String p_ : a.getAllPlayers()) { - if (Validator.isPlayerOnline(p_)) { - Player p = Bukkit.getPlayer(p_); - if (countdown) { - Util.sendMessage(plugin, p, pli.getMessagesConfig().teleporting_to_arena_in.replaceAll("", Integer.toString(currentlobbycount))); - if (lobbycountdown_sound != null) { - p.playSound(p.getLocation(), lobbycountdown_sound, 1F, 0F); - } - } - } - } - } - for (String p_ : a.getAllPlayers()) { - if (Validator.isPlayerOnline(p_)) { - Player p = Bukkit.getPlayer(p_); - p.setExp(1F * ((1F * currentlobbycount) / (1F * pli.lobby_countdown))); - if (pli.use_xp_bar_level) { - p.setLevel(currentlobbycount); - } - } - } - if (currentlobbycount < 1) { - Bukkit.getScheduler().runTaskLater(plugin, new Runnable() { - public void run() { - currentarena.getArena().start(true); - } - }, 10L); - try { - Bukkit.getScheduler().cancelTask(currenttaskid); - } catch (Exception e) { - } - } - } - }, 5L, 20).getTaskId(); - } - - /** - * Instantly starts the arena, teleports players and udpates the arena - */ - public void start(boolean tp) { - try { - Bukkit.getScheduler().cancelTask(currenttaskid); - } catch (Exception e) { - } - currentingamecount = pli.ingame_countdown; - if (tp) { - pspawnloc = Util.teleportAllPlayers(currentarena.getArena().getAllPlayers(), currentarena.getArena().spawns); - } - boolean clearinv = plugin.getConfig().getBoolean("config.countdowns.clearinv_while_ingamecountdown"); - for (String p_ : currentarena.getArena().getAllPlayers()) { - Player p = Bukkit.getPlayer(p_); - p.setWalkSpeed(0.0F); - p.setFoodLevel(5); - p.addPotionEffect(new PotionEffect(PotionEffectType.JUMP, 9999999, -7)); // -5 - pli.scoreboardLobbyManager.removeScoreboard(this.getInternalName(), p); - if (clearinv) { - Util.clearInv(p); - } - } - final Arena a = this; - Bukkit.getScheduler().runTaskLater(plugin, new Runnable() { - public void run() { - pli.scoreboardManager.updateScoreboard(plugin, a); - } - }, 20L); - startedIngameCountdown = true; - if (!plugin.getConfig().getBoolean("config.countdowns.ingame_countdown_enabled")) { - startRaw(a); - return; - } - - Sound ingamecountdown_sound_ = null; - try { - ingamecountdown_sound_ = Sound.valueOf(plugin.getConfig().getString("config.sounds.ingame_countdown")); - } catch (Exception e) { - ; - } - final Sound ingamecountdown_sound = ingamecountdown_sound_; - - currenttaskid = Bukkit.getScheduler().runTaskTimer(MinigamesAPI.getAPI(), new Runnable() { - public void run() { - currentingamecount--; - if (currentingamecount == 60 || currentingamecount == 30 || currentingamecount == 15 || currentingamecount == 10 || currentingamecount < 6) { - for (String p_ : a.getAllPlayers()) { - if (Validator.isPlayerOnline(p_)) { - Player p = Bukkit.getPlayer(p_); - Util.sendMessage(plugin, p, pli.getMessagesConfig().starting_in.replaceAll("", Integer.toString(currentingamecount))); - if (ingamecountdown_sound != null) { - p.playSound(p.getLocation(), ingamecountdown_sound, 1F, 0F); - } - } - } - } - for (String p_ : a.getAllPlayers()) { - if (Validator.isPlayerOnline(p_)) { - Player p = Bukkit.getPlayer(p_); - p.setExp(1F * ((1F * currentingamecount) / (1F * pli.ingame_countdown))); - if (pli.use_xp_bar_level) { - p.setLevel(currentingamecount); - } - } - } - if (currentingamecount < 1) { - startRaw(a); - } - } - }, 5L, 20).getTaskId(); - - for (final String p_ : this.getAllPlayers()) { - if (pli.getShopHandler().hasItemBought(p_, "coin_boost2")) { - global_coin_multiplier = 2; - break; - } - if (pli.getShopHandler().hasItemBought(p_, "coin_boost3")) { - global_coin_multiplier = 3; - break; - } - } - } - - public void startRaw(final Arena a) { - currentarena.getArena().setArenaState(ArenaState.INGAME); - startedIngameCountdown = false; - Util.updateSign(plugin, a); - Bukkit.getServer().getPluginManager().callEvent(new ArenaStartEvent(plugin, this)); - boolean send_game_started_msg = plugin.getConfig().getBoolean("config.send_game_started_msg"); - for (String p_ : a.getAllPlayers()) { - try { - if (!pli.global_lost.containsKey(p_)) { - Player p = Bukkit.getPlayer(p_); - if (plugin.getConfig().getBoolean("config.auto_add_default_kit")) { - if (!pli.getClassesHandler().hasClass(p_)) { - pli.getClassesHandler().setClass("default", p_, false); - } - pli.getClassesHandler().getClass(p_); - } else { - Util.clearInv(Bukkit.getPlayer(p_)); - pli.getClassesHandler().getClass(p_); - } - if (plugin.getConfig().getBoolean("config.shop_enabled")) { - pli.getShopHandler().giveShopItems(p); - } - p.setFlying(false); - p.setAllowFlight(false); - } - } catch (Exception e) { - if (MinigamesAPI.debug) { - e.printStackTrace(); - } - System.out.println("Failed to set class: " + e.getMessage() + " at [1] " + e.getStackTrace()[1].getLineNumber() + " [0] " + e.getStackTrace()[0].getLineNumber()); - } - Player p = Bukkit.getPlayer(p_); - p.setWalkSpeed(0.2F); - p.setFoodLevel(20); - p.removePotionEffect(PotionEffectType.JUMP); - if (send_game_started_msg) { - p.sendMessage(pli.getMessagesConfig().game_started); - } - } - if (plugin.getConfig().getBoolean("config.bungee.whitelist_while_game_running")) { - Bukkit.setWhitelist(true); - } - started = true; - Bukkit.getServer().getPluginManager().callEvent(new ArenaStartedEvent(plugin, this)); - started(); - try { - Bukkit.getScheduler().cancelTask(currenttaskid); - } catch (Exception e) { - } - - // Maximum game time: - maximum_game_time = Bukkit.getScheduler().runTaskLater(plugin, new Runnable() { - public void run() { - for (String p_ : a.getAllPlayers()) { - if (Validator.isPlayerValid(plugin, p_, a)) { - Bukkit.getPlayer(p_).sendMessage(pli.getMessagesConfig().stop_cause_maximum_game_time); - } - } - Bukkit.getScheduler().runTaskLater(plugin, new Runnable() { - public void run() { - a.stop(); - } - }, 5 * 20L); - } - }, 20L * 60L * (long) plugin.getConfig().getDouble("config.defaults.default_max_game_time_in_minutes") - 5 * 20L); - } - - /** - * Gets executed after an arena started (after ingame countdown) - */ - public void started() { - System.out.println(this.getInternalName() + " started."); - } - - boolean temp_delay_stopped = false; - - /** - * Stops the arena and teleports all players to the mainlobby - */ - public void stop() { - Bukkit.getServer().getPluginManager().callEvent(new ArenaStopEvent(plugin, this)); - final Arena a = this; - if (maximum_game_time != null) { - maximum_game_time.cancel(); - } - temp_players = new ArrayList(players); - if (!temp_delay_stopped) { - if (plugin.getConfig().getBoolean("config.delay.enabled")) { - Bukkit.getScheduler().runTaskLater(plugin, new Runnable() { - public void run() { - temp_delay_stopped = true; - a.stop(); - } - }, plugin.getConfig().getInt("config.delay.amount_seconds") * 20L); - this.setArenaState(ArenaState.RESTARTING); - Util.updateSign(plugin, this); - if (plugin.getConfig().getBoolean("config.spawn_fireworks_for_winners")) { - if (this.getAllPlayers().size() > 0) { - Util.spawnFirework(Bukkit.getPlayer(this.getAllPlayers().get(0))); - } - } - return; - } - } - temp_delay_stopped = false; - - try { - Bukkit.getScheduler().cancelTask(currenttaskid); - } catch (Exception e) { - - } - - this.setArenaState(ArenaState.RESTARTING); - - final ArrayList temp = new ArrayList(this.getAllPlayers()); - for (final String p_ : temp) { - try { - Bukkit.getScheduler().runTaskLater(plugin, new Runnable() { - public void run() { - if (Validator.isPlayerOnline(p_)) { - for (Entity e : Bukkit.getPlayer(p_).getNearbyEntities(50, 50, 50)) { - if (e.getType() == EntityType.DROPPED_ITEM || e.getType() == EntityType.SLIME || e.getType() == EntityType.ZOMBIE || e.getType() == EntityType.SKELETON || e.getType() == EntityType.SPIDER || e.getType() == EntityType.CREEPER) { - e.remove(); - } - } - } - } - }, 10L); - } catch (Exception e) { - System.out.println("Failed clearing entities."); - } - leavePlayer(p_, false, true); - } - - try { - for (ItemStack item : global_drops) { - if (item != null) { - item.setType(Material.AIR); - } - } - } catch (Exception e) { - System.out.println("Failed clearing items: " + e.getMessage()); - } - - if (a.getArenaType() == ArenaType.REGENERATION) { - reset(); - } else { - a.setArenaState(ArenaState.JOIN); - Util.updateSign(plugin, a); - } - - Bukkit.getScheduler().runTaskLater(plugin, new Runnable() { - public void run() { - players.clear(); - for (IconMenu im : pli.getClassesHandler().lasticonm.values()) { - im.destroy(); - } - } - }, 10L); - - started = false; - startedIngameCountdown = false; - - temp_countdown = true; - skip_join_lobby = false; - currentspawn = 0; - - try { - pli.scoreboardManager.clearScoreboard(this.getInternalName()); - pli.scoreboardLobbyManager.clearScoreboard(this.getInternalName()); - } catch (Exception e) { - // - } - - /* - * try { pli.getStatsInstance().updateSkulls(); } catch (Exception e) { - * - * } - */ - - if (plugin.getConfig().getBoolean("config.bungee.whitelist_while_game_running")) { - Bukkit.setWhitelist(false); - } - - if (plugin.getConfig().getBoolean("config.execute_cmds_on_stop")) { - String[] cmds = plugin.getConfig().getString("config.cmds").split(";"); - if (cmds.length > 0) { - for (String cmd : cmds) { - Bukkit.dispatchCommand(Bukkit.getConsoleSender(), cmd); - } - } - } - - if (plugin.getConfig().getBoolean("config.bungee.teleport_all_to_server_on_stop.tp")) { - final String server = plugin.getConfig().getString("config.bungee.teleport_all_to_server_on_stop.server"); - Bukkit.getScheduler().runTaskLater(plugin, new Runnable() { - public void run() { - for (Player p : Bukkit.getOnlinePlayers()) { - BungeeUtil.connectToServer(MinigamesAPI.getAPI(), p.getName(), server); - } - } - }, 30L); - return; - } - - if (plugin.getConfig().getBoolean("config.execute_cmds_on_stop")) { - String[] cmds = plugin.getConfig().getString("config.cmds_after").split(";"); - if (cmds.length > 0) { - for (String cmd : cmds) { - Bukkit.dispatchCommand(Bukkit.getConsoleSender(), cmd); - } - } - } - - if (ai != null) { - Bukkit.getScheduler().runTaskLater(plugin, new Runnable() { - public void run() { - if (ai != null) { - ai.nextMinigame(); - ai = null; - } - } - }, 10L); - } else { - // Map rotation only works without Arcade - // check if there is only one player or none left - if (temp.size() < 2) { - return; - } - if (plugin.getConfig().getBoolean("config.map_rotation")) { - Bukkit.getScheduler().runTaskLater(plugin, new Runnable() { - public void run() { - a.nextArenaOnMapRotation(temp); - } - }, 35L); - } - } - - } - - /** - * Rebuilds an arena from file (only for arenas of REGENERATION type) - */ - public void reset() { - if (pli.old_reset) { - ArenaLogger.debug("Resetting using old method."); - try { - Util.loadArenaFromFileSYNC(plugin, this); - } catch (Exception e) { - ArenaLogger.debug("Error resetting map using old method. " + e.getMessage()); - } - } else { - sr.reset(); - } - } - - /*** - * Use this when someone got killed/pushed down/eliminated in some way by a player - * - * @param playername - * The player that got eliminated - */ - public void onEliminated(String playername) { - if (lastdamager.containsKey(playername)) { - Player killer = Bukkit.getPlayer(lastdamager.get(playername)); - if (killer != null) { - pli.getStatsInstance().addDeath(playername); - this.temp_kill_count.put(killer.getName(), this.temp_kill_count.containsKey(killer.getName()) ? this.temp_kill_count.get(killer.getName()) + 1 : 1); - this.temp_death_count.put(playername, this.temp_death_count.containsKey(playername) ? this.temp_death_count.get(playername) + 1 : 1); - pli.getRewardsInstance().giveKillReward(killer.getName()); - Util.sendMessage(plugin, killer, MinigamesAPI.getAPI().getPluginInstance(plugin).getMessagesConfig().you_got_a_kill.replaceAll("", playername)); - for (String p_ : this.getAllPlayers()) { - if (!p_.equalsIgnoreCase(killer.getName())) { - if (Validator.isPlayerOnline(p_)) { - Bukkit.getPlayer(p_).sendMessage(MinigamesAPI.getAPI().getPluginInstance(plugin).getMessagesConfig().player_was_killed_by.replaceAll("", playername).replaceAll("", killer.getName())); - } - } - } - } - lastdamager.remove(playername); - } else { - pli.getStatsInstance().addDeath(playername); - } - } - - /** - * Will shuffle all arenas and join the next available arena - * - * @param players - */ - public void nextArenaOnMapRotation(ArrayList players) { - ArrayList arenas = pli.getArenas(); - Collections.shuffle(arenas); - for (Arena a : arenas) { - if (a.getArenaState() == ArenaState.JOIN && a != this) { - System.out.println(plugin.getName() + ": Next arena on map rotation: " + a.getInternalName()); - for (String p_ : players) { - if (!a.containsPlayer(p_)) { - a.joinPlayerLobby(p_, false); - } - } - } - } - } - - public String getPlayerCount() { - int alive = 0; - for (String p_ : getAllPlayers()) { - if (pli.global_lost.containsKey(p_)) { - continue; - } else { - alive++; - } - } - return Integer.toString(alive) + "/" + Integer.toString(getAllPlayers().size()); - } - - public int getPlayerAlive() { - int alive = 0; - for (String p_ : getAllPlayers()) { - if (pli.global_lost.containsKey(p_)) { - continue; - } else { - alive++; - } - } - return alive; - } - - public Location getWaitingLobbyTemp() { - return this.waitinglobby; - } - - public Location getMainLobbyTemp() { - return this.mainlobby; - } - - public ArcadeInstance getArcadeInstance() { - return ai; - } - - public boolean isArcadeMain() { - return isArcadeMain; - } - - public void setArcadeMain(boolean t) { - isArcadeMain = t; - } - - public HashMap getPSpawnLocs() { - return pspawnloc; - } - - public JavaPlugin getPlugin() { - return plugin; - } - - public PluginInstance getPluginInstance() { - return pli; - } - - public int getCurrentIngameCountdownTime() { - return this.currentingamecount; - } - - public int getCurrentLobbyCountdownTime() { - return this.currentlobbycount; - } - - public boolean getIngameCountdownStarted() { - return this.startedIngameCountdown; - } - - public boolean isSuccessfullyInit() { - return isSuccessfullyInitialized; - } - +/** + * This is the base class for arenas. + * + *

+ * An arena is a place the players fight against and where all the action takes place. + *

+ * + *

+ * Minigames will have to override this class. + *

+ * + *

+ * NOTICE: There are some race conditions on high load. For example joining VIPs while state switches etc. Spigot itself may invoke the tasks serial meaning one after another but there can be external + * events from network at the moment (MinigamesAPI-Bungee). + *

+ * + * @author instancelabs + */ +public class Arena +{ + + /** + * Plugin the arena belongs to. + */ + private final JavaPlugin plugin; + + /** + * Minigames lib representation of the minigame plugin. + */ + private final PluginInstance pli; + + /** + * The reference to the arcade instance if this arena is part of arcade mode; {@code null} for classic arena. + * + *

+ * TODO: Review if we really need a back reference to the arcade instance. + *

+ */ + private ArcadeInstance ai; + + /** + * {@code true} if this is the main (= first arena) for arcade. + */ + private boolean isArcadeMain = false; + + /** + * {@code true} {@link #init(Location, ArrayList, Location, Location, int, int, boolean)} was called. + */ + private boolean isSuccessfullyInitialized = false; + + /** + * List of configured spawn locations. + */ + private final ArrayList spawns = new ArrayList<>(); + + /** + * The player spawn locations. + */ + private HashMap pspawnloc = new HashMap<>(); + + /** + * Match statistics: The last damager of players; helps fetching the player that kills another one. + */ + private final HashMap lastdamager = new HashMap<>(); + + /** + * Match statistics: Kill count of players. + */ + HashMap temp_kill_count = new HashMap<>(); + + /** + * Match statistics: Death count of players. + */ + HashMap temp_death_count = new HashMap<>(); + + /** + * Location of the main lobby. + */ + private Location mainlobby; + + /** + * Location of the waiting lobby. + */ + private Location waitinglobby; + + /** + * Spawn location for spectators. + */ + private Location specspawn; + + /** + * The join sign location. + */ + private Location signloc; + + /** + * The spectator join sign location. + */ + private Location specsignloc; + + /** + * Max amount of players for the game. + */ + private int max_players; + + /** + * The minimum amount of players for starting the game. + */ + private int min_players; + + /** + * {@code true} if this is a vip arena. + * + *

+ * Players can only join vip arenas if they have permission "arenas.$arenaname$". + *

+ */ + private boolean viparena; + + /** + * The players joined the arena and playing. + */ + private final ArrayList players = new ArrayList<>(); + + private ArrayList temp_players = new ArrayList<>(); + + /** + * The arena type. + */ + private ArenaType type = ArenaType.DEFAULT; + + /** + * The current arena state. + */ + private ArenaState currentstate = ArenaState.JOIN; + + /** + * Internal/ technical name of the arena. + */ + private String name = "mainarena"; + + /** + * The human readable arena name (public name). + */ + private String displayname = "mainarena"; + + private boolean started = false; + private boolean startedIngameCountdown = false; + + /** + * {@code true} if the arenaa score board will be shown. + */ + private boolean showArenascoreboard = true; + + /** + * {@code true} if the pvp is allowed in every game state. + */ + private boolean alwaysPvP = false; + + private SmartReset sr = null; + + /** + * The arena boundaries. + */ + private Cuboid boundaries; + + /** + * The lobby boundaries. + */ + private Cuboid lobby_boundaries; + + /** + * The spectator boundaries. + */ + private Cuboid spec_boundaries; + + private boolean temp_countdown = true; + boolean skip_join_lobby = false; + + private int currentspawn = 0; + + int global_coin_multiplier = 1; + + // private BukkitTask maximum_game_time; + + ArrayList global_drops = new ArrayList<>(); + + private int currentlobbycount = 10; + private int currentingamecount = 10; + + /** + * the current task id. + * + * @deprecated remove in 1.5.0; current no one ever sets this, review the trials to cancel tasks to find out what is going on here; possibly a bug. + */ + @Deprecated + private int currenttaskid = 0; + + boolean temp_delay_stopped = false; + + /** the arenam logger. */ + protected ArenaLogger logger; + + protected MatchTimer timer; + + /** + * Creates a normal singlespawn arena + * + * @param plugin + * JavaPlugin the arena belongs to + * @param name + * name of the arena + */ + public Arena(final JavaPlugin plugin, final String name) + { + this.plugin = plugin; + this.name = name; + this.sr = new SmartReset(this); + this.pli = MinigamesAPI.getAPI().getPluginInstance(plugin); + this.logger = new ArenaLogger(this.plugin.getLogger(), this.name); + + // Maximum game time: + this.timer = new MatchTimer((int) this.plugin.getConfig().getDouble(ArenaConfigStrings.CONFIG_DEFAULT_MAX_GAME_TIME_IN_MINUTES) * 60, () -> { + for (final String p_ : Arena.this.getAllPlayers()) + { + if (Validator.isPlayerValid(Arena.this.plugin, p_, Arena.this)) + { + Bukkit.getPlayer(p_).sendMessage(Arena.this.pli.getMessagesConfig().stop_cause_maximum_game_time_now); + } + } + Bukkit.getScheduler().runTaskLater(Arena.this.plugin, () -> this.stopArena(), 1); + }, (sec) -> { + for (final String p_ : Arena.this.getAllPlayers()) + { + if (Validator.isPlayerValid(Arena.this.plugin, p_, Arena.this)) + { + Bukkit.getPlayer(p_).sendMessage(Arena.this.pli.getMessagesConfig().stop_cause_maximum_game_time_sec.replace("", String.valueOf(sec))); + } + } + }); + } + + /** + * Creates an arena of given arenatype + * + * @param plugin + * JavaPlugin the arena belongs to + * @param name + * name of the arena + * @param type + * arena type + */ + public Arena(final JavaPlugin plugin, final String name, final ArenaType type) + { + this(plugin, name); + this.type = type; + } + + /** + * This is for loading existing arenas + * + * @param signloc + * (optional) Location of join sign; {@link Util#getSignLocationFromArena} + * @param spawns + * (optional) The spawn points; {@link Util#getAllSpawns} + * @param mainlobby + * The main lobby location; {@link Util#getMainLobby} + * @param waitinglobby + * The waiting lobby location; F.e. {@code Util#getComponentForArena} with argument "lobby". + * @param max_players + * The max players count; {@link ArenaSetup#getPlayerCount} + * @param min_players + * The min players count; {@link ArenaSetup#getPlayerCount} + * @param viparena + * {@code true} for vip arena; players will need a permission in vip arenas. + */ + @SuppressWarnings("hiding") + public void init(final Location signloc, final ArrayList spawns, final Location mainlobby, final Location waitinglobby, final int max_players, final int min_players, + final boolean viparena) + { + // TODO Disallow duplicate init; reloading should create a new arena instance. + this.signloc = signloc; + this.specsignloc = Util.getSpecSignLocationFromArena(this.plugin, this.getInternalName()); + this.spawns.clear(); + if (spawns != null) + { + this.spawns.addAll(spawns); + } + this.mainlobby = mainlobby; + this.waitinglobby = waitinglobby; + this.viparena = viparena; + this.min_players = min_players; + this.max_players = max_players; + this.showArenascoreboard = this.pli.arenaSetup.getShowScoreboard(this.plugin, this.getInternalName()); + this.isSuccessfullyInitialized = true; + if (Util.isComponentForArenaValid(this.plugin, this.getInternalName(), ArenaConfigStrings.BOUNDS_LOW) + && Util.isComponentForArenaValid(this.plugin, this.getInternalName(), ArenaConfigStrings.BOUNDS_HIGH)) + { + try + { + final Location low_boundary = Util.getComponentForArena(this.plugin, this.getInternalName(), ArenaConfigStrings.BOUNDS_LOW); + final Location high_boundary = Util.getComponentForArena(this.plugin, this.getInternalName(), ArenaConfigStrings.BOUNDS_HIGH); + if (low_boundary != null && high_boundary != null) + { + this.boundaries = new Cuboid(low_boundary, high_boundary); + } + else + { + this.plugin.getServer().getConsoleSender().sendMessage(String.format(Messages.getString("Arena.BoundariesInvalid", MinigamesAPI.LOCALE), this.getInternalName())); //$NON-NLS-1$ + this.isSuccessfullyInitialized = false; + } + } + catch (final Exception e) + { + this.logger.log(Level.WARNING, "Problems checking arena boundaries", e); //$NON-NLS-1$ + this.plugin.getServer().getConsoleSender().sendMessage(String.format(Messages.getString("Arena.SaveFailedBoundaries", MinigamesAPI.LOCALE), e.getMessage())); //$NON-NLS-1$ + this.isSuccessfullyInitialized = false; + } + } + if (Util.isComponentForArenaValid(this.plugin, this.getInternalName(), ArenaConfigStrings.LOBBY_BOUNDS_LOW) + && Util.isComponentForArenaValid(this.plugin, this.getInternalName(), ArenaConfigStrings.LOBBY_BOUNDS_HIGH)) + { + try + { + this.lobby_boundaries = new Cuboid(Util.getComponentForArena(this.plugin, this.getInternalName(), ArenaConfigStrings.LOBBY_BOUNDS_LOW), + Util.getComponentForArena(this.plugin, this.getInternalName(), ArenaConfigStrings.LOBBY_BOUNDS_HIGH)); + } + catch (final Exception e) + { + this.logger.log(Level.WARNING, "Problems checking lobby boundaries", e); //$NON-NLS-1$ + this.isSuccessfullyInitialized = false; + } + } + if (Util.isComponentForArenaValid(this.plugin, this.getInternalName(), ArenaConfigStrings.SPEC_BOUNDS_LOW) + && Util.isComponentForArenaValid(this.plugin, this.getInternalName(), ArenaConfigStrings.SPEC_BOUNDS_HIGH)) + { + try + { + this.spec_boundaries = new Cuboid(Util.getComponentForArena(this.plugin, this.getInternalName(), ArenaConfigStrings.SPEC_BOUNDS_LOW), + Util.getComponentForArena(this.plugin, this.getInternalName(), ArenaConfigStrings.SPEC_BOUNDS_HIGH)); + } + catch (final Exception e) + { + this.logger.log(Level.WARNING, "Problems checking spectator boundaries", e); //$NON-NLS-1$ + this.isSuccessfullyInitialized = false; + } + } + + if (Util.isComponentForArenaValid(this.plugin, this.getInternalName(), ArenaConfigStrings.SPEC_SPAWN)) + { + this.specspawn = Util.getComponentForArena(this.plugin, this.getInternalName(), ArenaConfigStrings.SPEC_SPAWN); + } + + final String path = ArenaConfigStrings.ARENAS_PREFIX + this.name + ArenaConfigStrings.DISPLAYNAME_SUFFIX; + if (this.pli.getArenasConfig().getConfig().isSet(path)) + { + this.displayname = ChatColor.translateAlternateColorCodes('&', + this.pli.getArenasConfig().getConfig().getString(ArenaConfigStrings.ARENAS_PREFIX + this.name + ArenaConfigStrings.DISPLAYNAME_SUFFIX)); + } + else + { + this.pli.getArenasConfig().getConfig().set(path, this.name); + this.pli.getArenasConfig().saveConfig(); + this.displayname = this.name; + } + + } + + /** + * This is for loading existing arenas + * + * @param signloc + * @param spawn + * @param mainlobby + * @param waitinglobby + * @param max_players + * @param min_players + * @param viparena + * @return this object + * @deprecated use {@link #init(Location, ArrayList, Location, Location, int, int, boolean)} instead; will be removed in 1.15.X + */ + @SuppressWarnings("hiding") + @Deprecated + public Arena initArena(final Location signloc, final ArrayList spawn, final Location mainlobby, final Location waitinglobby, final int max_players, final int min_players, + final boolean viparena) + { + this.init(signloc, spawn, mainlobby, waitinglobby, max_players, min_players, viparena); + return this; + } + + /** + * Returns this object + * + * @return this object + * @deprecated will be removed in 1.15.X + */ + @Deprecated + public Arena getArena() + { + return this; + } + + /** + * Returns the smart reset object for resetting blocks that changed during game play. + * + * @return smart reset helper. + */ + public SmartReset getSmartReset() + { + return this.sr; + } + + /** + * Returns the show scoreboard flag, read from arena setup. + * + *

+ * If set to false the score boards are not shown/ updated. + *

+ * + * @return {@code true} to show the score oards. + */ + public boolean getShowScoreboard() + { + return this.showArenascoreboard; + } + + /** + * Returns the always pvp flag that controls the pvp behaviour. + * + *

+ * TODO describe what the flag actually does in ArenaListener + *

+ * + * @return {@code true} for allowing pvp in any game state. + */ + public boolean getAlwaysPvP() + { + return this.alwaysPvP; + } + + /** + * Sets the always pvp flag; see {@link #getAlwaysPvP()} for details. + * + * @param t + * new value + */ + public void setAlwaysPvP(final boolean t) + { + this.alwaysPvP = t; + } + + /** + * Returns the join sign location. + * + * @return join sign location; {@code null} if there is no join sign. + */ + public Location getSignLocation() + { + return this.signloc; + } + + /** + * Sets the join sign location. + * + * @param l + * new location. + */ + public void setSignLocation(final Location l) + { + this.signloc = l; + } + + /** + * Returns the spectator join sign location. + * + * @return spectator join sign location; {@code null} if there is no spectator join sign. + */ + public Location getSpecSignLocation() + { + return this.specsignloc; + } + + /** + * Sets the join sign location. + * + * @param l + * new location. + */ + public void setSpecSignLocation(final Location l) + { + this.specsignloc = l; + } + + /** + * Returns the spawns of this arena. + * + * @return spawns. + * + * @deprecated The method signature will change in 1.15.0; will return the List interface instead of ArrayList and will return an immutable list so that spawns cannot be changed from outside. + */ + @Deprecated + public ArrayList getSpawns() + { + return this.spawns; + } + + /** + * Returns the arena boundaries. + * + * @return arena boundaries; may return {@code null} for invalid arena setups. + */ + public Cuboid getBoundaries() + { + return this.boundaries; + } + + /** + * Returns the lobby boundaries. + * + * @return lobby boundaries; may return {@code null} if no arena lobby exists. + */ + public Cuboid getLobbyBoundaries() + { + return this.lobby_boundaries; + } + + /** + * Returns the spectator boundaries. + * + * @return spec boundaries; may return {@code null} if spectating is not configured. + */ + public Cuboid getSpecBoundaries() + { + return this.spec_boundaries; + } + + /** + * Returns the technical/ internal arena name. + * + * @return technical arena name. + */ + public String getInternalName() + { + return this.name; + } + + /** + * Returns the human readable arena name. + * + * @return arena name used by signs and messages. + */ + public String getDisplayName() + { + return this.displayname; + } + + /** + * Please use getInternalName() for the internal name and getDisplayName() for the optional displayname + * + * @return Internal name of arena (same as getInternalName()) + * @deprecated replaced by {@link #getInternalName()} or {@link #getDisplayName()} + */ + @Deprecated + public String getName() + { + return this.name; + } + + /** + * Returns the maximum players playing a match. + * + * @return maximum players. + */ + public int getMaxPlayers() + { + return this.max_players; + } + + /** + * Returns the minimum players. + * + * @return minimum players. + */ + public int getMinPlayers() + { + return this.min_players; + } + + /** + * Sets the minimum players. + * + *

+ * Changes are only respected in a new match, cannot influence an already running match. + *

+ * + * @param i + * new minimum players. + */ + public void setMinPlayers(final int i) + { + this.min_players = i; + } + + /** + * Sets the maximum players. + * + *

+ * Changes are only respected in a new match, cannot influence an already running match. + *

+ * + * @param i + * new maximum players. + */ + public void setMaxPlayers(final int i) + { + this.max_players = i; + } + + /** + * Checks if this is a vip arena. + * + * @return {@code true} if the players need a permission to play within this arena. + */ + public boolean isVIPArena() + { + return this.viparena; + } + + /** + * Sets the vip arena flag. + * + *

+ * Changes are only respected in a new match/joins, cannot influence players already being in the waiting lobby. + *

+ * + * @param t + * {@code true} to make this a vip arena. + */ + public void setVIPArena(final boolean t) + { + this.viparena = t; + } + + /** + * Returns the players that joined the arena. + * + * @return active players within this arena. + * + * @deprecated The method signature will change in 1.15.0; will return the List interface instead of ArrayList and will return an immutable list so that spawns cannot be changed from outside. + */ + @Deprecated + public ArrayList getAllPlayers() + { + return this.players; + } + + /** + * Checks if a player already joined the arena. + * + * @param playername + * Name of the player to be searched. + * @return {@code true} if the player already joined the arena. + */ + public boolean containsPlayer(final String playername) + { + // potential performance lack for huge arenas or massive invocation count; hash set can be better. + // at the moment we decided to keep up the ordering the players joined the arena. + return this.players.contains(playername); + } + + /** + * Please do not use this function to add players + * + * @param playername + * name of the player + * @return true on success + * + * @deprecated will be removed in 1.15.0; replaces by {@link #spectateGame(String)} or {@link #joinPlayerLobby(String)} + */ + @Deprecated + public boolean addPlayer(final String playername) + { + return this.players.add(playername); + } + + /** + * Please do not use this function to remove players + * + * @param playername + * name of the player + * @return true on success + * + * @deprecated will be removed in 1.15.0; replaces by {@link #leavePlayer(String, boolean, boolean)} + */ + @Deprecated + public boolean removePlayer(final String playername) + { + return this.players.remove(playername); + } + + /** + * Returns the current state of arena. + * + * @return current arena state. + */ + public ArenaState getArenaState() + { + return this.currentstate; + } + + /** + * Sets the current arena state. + * + * @param s + * new arena state. + */ + void setArenaState(final ArenaState s) + { + this.currentstate = s; + } + + /** + * Returns the arena type. + * + * @return type of this arena. + */ + public ArenaType getArenaType() + { + return this.type; + } + + /** + * Joins the waiting lobby of an arena + * + * @param playername + * the playername + * @deprecated will be removed in 1.5.0; string names replaced by UUID + */ + @Deprecated + public void joinPlayerLobby(final String playername) + { + this.joinPlayerLobby(MinigamesAPI.playerToUUID(playername)); + } + + /** + * Joins the waiting lobby of an arena + * + * @param playerUuid + * the players uuid + */ + public void joinPlayerLobby(final UUID playerUuid) + { + if (this.getArenaState() != ArenaState.JOIN && this.getArenaState() != ArenaState.STARTING) + { + // arena ingame or restarting + return; + } + final Player player = MinigamesAPI.uuidToPlayer(playerUuid); + if (player == null) + return; + + final String playername = player.getName(); + if (!this.pli.arenaSetup.getArenaEnabled(this.plugin, this.getInternalName())) + { + Util.sendMessage(this.plugin, player, this.pli.getMessagesConfig().arena_disabled); + return; + } + if (this.pli.containsGlobalPlayer(playername)) + { + Util.sendMessage(this.plugin, player, this.pli.getMessagesConfig().already_in_arena); + return; + } + if (this.ai == null && this.isVIPArena()) + { + if (Validator.isPlayerOnline(playername)) + { + if (!player.hasPermission(MinigamesAPI.getAPI().getPermissionGamePrefix(this.plugin.getName()) + ArenaPermissionStrings.PREFIX + this.getInternalName() + ArenaPermissionStrings.VIP)) + { + Util.sendMessage(this.plugin, player, this.pli.getMessagesConfig().no_perm_to_join_arena.replaceAll(ArenaMessageStrings.ARENA, this.getInternalName())); + return; + } + } + } + if (this.ai == null && this.getAllPlayers().size() > this.max_players - 1) + { + // arena full + + // if player vip -> kick someone and continue + this.logger.fine(playername + " is vip: " //$NON-NLS-1$ + + player.hasPermission(MinigamesAPI.getAPI().getPermissionGamePrefix(this.plugin.getName()) + ArenaPermissionStrings.PREFIX + this.getInternalName() + ArenaPermissionStrings.VIP)); + if (!player.hasPermission(MinigamesAPI.getAPI().getPermissionGamePrefix(this.plugin.getName()) + ArenaPermissionStrings.PREFIX + this.getInternalName() + ArenaPermissionStrings.VIP)) + { + // no VIP. + return; + } + + // player has vip + boolean noone_found = true; + final ArrayList temp = new ArrayList<>(this.getAllPlayers()); + for (final String p_ : temp) + { + if (Validator.isPlayerOnline(p_)) + { + final Player player_ = Bukkit.getPlayer(p_); + if (!player_ + .hasPermission(MinigamesAPI.getAPI().getPermissionGamePrefix(this.plugin.getName()) + ArenaPermissionStrings.PREFIX + this.getInternalName() + ArenaPermissionStrings.VIP)) + { + this.leavePlayer(p_, false, true); + player_.sendMessage(this.pli.getMessagesConfig().you_got_kicked_because_vip_joined); + noone_found = false; + break; + } + } + } + if (noone_found) + { + // apparently everyone is vip, can't join + return; + } + } + + if (MinigamesAPI.getAPI().hasParty(player.getUniqueId())) + { + final Party party = MinigamesAPI.getAPI().getParty(player.getUniqueId()); + final int playersize = party.getPlayers().size() + 1; + if (this.getAllPlayers().size() + playersize > this.max_players) + { + player.sendMessage(MinigamesAPI.getAPI().partymessages.party_too_big_to_join); + return; + } + + for (final UUID p_ : party.getPlayers()) + { + if (Validator.isPlayerOnline(p_)) + { + boolean cont = true; + MinigamesAPI.getAPI(); + for (final PluginInstance pli_ : MinigamesAPI.pinstances.values()) + { + // if (!pli_.getPlugin().getName().equalsIgnoreCase("MGArcade") && pli_.global_players.containsKey(p_)) { + if (pli_.containsGlobalPlayer(Bukkit.getPlayer(p_).getName())) + { + cont = false; + } + } + if (cont) + { + this.joinPlayerLobby(p_); + } + } + } + } + + if (this.getAllPlayers().size() == this.max_players - 1) + { + if (this.currentlobbycount > 16 && this.getArenaState() == ArenaState.STARTING) + { + this.currentlobbycount = 16; + } + } + this.pli.global_players.put(playername, this); + this.players.add(playername); + + if (Validator.isPlayerValid(this.plugin, playername, this)) + { + final Player p = player; + final ArenaPlayer ap = ArenaPlayer.getPlayerInstance(playername); + Bukkit.getServer().getPluginManager().callEvent(new PlayerJoinLobbyEvent(p, this.plugin, this)); + Util.sendMessage(this.plugin, p, this.pli.getMessagesConfig().you_joined_arena.replaceAll(ArenaMessageStrings.ARENA, this.getDisplayName())); + Util.sendMessage(this.plugin, p, this.pli.getMessagesConfig().minigame_description); + if (this.pli.getArenasConfig().getConfig().isSet(ArenaConfigStrings.ARENAS_PREFIX + this.getInternalName() + ArenaConfigStrings.AUTHOR_SUFFIX)) + { + Util.sendMessage(this.plugin, p, this.pli.getMessagesConfig().author_of_the_map.replaceAll(ArenaMessageStrings.ARENA, this.getDisplayName()).replaceAll(ArenaMessageStrings.AUTHOR, + this.pli.getArenasConfig().getConfig().getString(ArenaConfigStrings.ARENAS_PREFIX + this.getInternalName() + ArenaConfigStrings.AUTHOR_SUFFIX))); + } + if (this.pli.getArenasConfig().getConfig().isSet(ArenaConfigStrings.ARENAS_PREFIX + this.getInternalName() + ArenaConfigStrings.DESCRIPTION_SUFFIX)) + { + Util.sendMessage(this.plugin, p, + this.pli.getMessagesConfig().description_of_the_map.replaceAll(ArenaMessageStrings.ARENA, this.getDisplayName()).replaceAll(ArenaMessageStrings.DESCRIPTION, + this.pli.getArenasConfig().getConfig().getString(ArenaConfigStrings.ARENAS_PREFIX + this.getInternalName() + ArenaConfigStrings.DESCRIPTION_SUFFIX))); + } + + Bukkit.getScheduler().runTaskLater(this.getPlugin(), () -> { + try + { + Arena.this.pli.getHologramsHandler().sendAllHolograms(p); + } + catch (final Exception e) + { + this.logger.log(Level.WARNING, "Failed playing hologram: ", e); //$NON-NLS-1$ + } + }, 15L); + + for (final String p_ : this.getAllPlayers()) + { + if (Validator.isPlayerOnline(p_) && !p_.equalsIgnoreCase(p.getName())) + { + final Player p__ = Bukkit.getPlayer(p_); + final int count = this.getAllPlayers().size(); + final int maxcount = this.getMaxPlayers(); + Util.sendMessage(this.plugin, p__, this.pli.getMessagesConfig().broadcast_player_joined.replaceAll(ArenaMessageStrings.PLAYER, p.getName()) + .replace(ArenaMessageStrings.COUNT, Integer.toString(count)).replace(ArenaMessageStrings.MAXCOUNT, Integer.toString(maxcount))); + } + } + Util.updateSign(this.plugin, this); + + if (this.ai == null && !this.isArcadeMain()) + { + this.skip_join_lobby = this.plugin.getConfig().getBoolean(ArenaConfigStrings.CONFIG_SKIP_LOBBY); + } + + final Arena a = this; + ap.setInventories(p.getInventory().getContents(), p.getInventory().getArmorContents()); + if (this.getArenaType() == ArenaType.JUMPNRUN) + { + // jump & run + Util.teleportPlayerFixed(p, this.spawns.get(this.currentspawn)); + if (this.currentspawn < this.spawns.size() - 1) + { + this.currentspawn++; + } + Util.clearInv(p); + ap.setOriginalGamemode(p.getGameMode()); + ap.setOriginalXplvl(p.getLevel()); + p.setGameMode(GameMode.SURVIVAL); + p.addPotionEffect(new PotionEffect(PotionEffectType.HEAL, 20 * 2, 50)); + return; + } + + // no jump & run + if (this.startedIngameCountdown) + { + // already in count down + this.pli.scoreboardLobbyManager.removeScoreboard(this.getInternalName(), p); + Util.teleportAllPlayers(this.getAllPlayers(), this.spawns); + p.setFoodLevel(5); + p.addPotionEffect(new PotionEffect(PotionEffectType.JUMP, 9999999, -7)); // -5 + Bukkit.getScheduler().runTaskLater(MinigamesAPI.getAPI(), () -> p.setWalkSpeed(0.0F), 1L); + Bukkit.getScheduler().runTaskLater(MinigamesAPI.getAPI(), () -> Util.clearInv(p), 15L); + ap.setOriginalXplvl(p.getLevel()); + Bukkit.getScheduler().runTaskLater(MinigamesAPI.getAPI(), () -> { + if (a.getArenaState() != ArenaState.INGAME) + { + Util.giveLobbyItems(Arena.this.plugin, p); + } + ap.setOriginalGamemode(p.getGameMode()); + p.setGameMode(GameMode.SURVIVAL); + }, 20L); + this.pli.scoreboardManager.updateScoreboard(this.plugin, this); + return; + } + + // no count down + this.pli.scoreboardLobbyManager.updateScoreboard(this.plugin, this); + if (!this.skip_join_lobby) + { + Util.teleportPlayerFixed(p, this.waitinglobby); + Bukkit.getScheduler().runTaskLater(MinigamesAPI.getAPI(), () -> p.addPotionEffect(new PotionEffect(PotionEffectType.HEAL, 20 * 2, 50)), 3L); + } + else + { + Util.teleportAllPlayers(this.getAllPlayers(), this.spawns); + } + + Bukkit.getScheduler().runTaskLater(MinigamesAPI.getAPI(), () -> Util.clearInv(p), 10L); + ap.setOriginalXplvl(p.getLevel()); + Bukkit.getScheduler().runTaskLater(MinigamesAPI.getAPI(), () -> { + if (a.getArenaState() != ArenaState.INGAME) + { + Util.giveLobbyItems(Arena.this.plugin, p); + } + ap.setOriginalGamemode(p.getGameMode()); + p.setGameMode(GameMode.SURVIVAL); + p.addPotionEffect(new PotionEffect(PotionEffectType.HEAL, 20 * 2, 50)); + }, 15L); + if (!this.skip_join_lobby) + { + if (this.ai == null && this.getAllPlayers().size() > this.min_players - 1) + { + this.startLobby(this.temp_countdown); + } + else if (this.ai != null) + { + this.startLobby(this.temp_countdown); + } + } + else + { + if (this.ai == null && !this.isArcadeMain() && this.getAllPlayers().size() > this.min_players - 1) + { + this.startLobby(false); + } + } + } + } + + /** + * Primarily used for ArcadeInstance to join a waiting lobby without countdown + * + * @param playername + * name of the player + * @param countdown + * count down in seconds. + */ + public void joinPlayerLobby(final String playername, final boolean countdown) + { + this.temp_countdown = countdown; + this.joinPlayerLobby(playername); + } + + /** + * Joins the waiting lobby of an arena using given arcade instance + * + * @param playername + * the player name + * @param arcade + * the ArcadeInstance + * @param countdown + * count down in seconds. + * @param skip_lobby + * {@code true} to directly get to the spawn by skipping the lobby. + */ + public void joinPlayerLobby(final String playername, final ArcadeInstance arcade, final boolean countdown, final boolean skip_lobby) + { + this.skip_join_lobby = skip_lobby; + this.ai = arcade; + this.joinPlayerLobby(playername, countdown); // join playerlobby without lobby countdown + } + + /** + * Leaves the current arena, won't do anything if not present in any arena + * + * @param playername + * @param fullLeave + * Determines if player left only minigame or the server + * @deprecated replaced by {@code leavePlayer(playername, fullLeave, false)}; removed in 1.15.0 + */ + @Deprecated + public void leavePlayer(final String playername, final boolean fullLeave) + { + this.leavePlayerRaw(playername, fullLeave); + } + + /** + * Leaves the current arena, won't do anything if not present in any arena + * + * @param playername + * name of the player that left the arena + * @param fullLeave + * Determines if player left only minigame ({@code false}) or the server ({@code true}) + * @param endofGame + * {@code true} if the game leave was caused by the end of the game. + */ + public void leavePlayer(final String playername, final boolean fullLeave, final boolean endofGame) + { + if (!endofGame) + { + final ArenaPlayer ap = ArenaPlayer.getPlayerInstance(playername); + ap.setNoReward(true); + } + + // replace with leavePlayerRaw as soon as the method was removed. + // currently we invoke leavePlayer because some minigames override leavePlayer. + this.leavePlayer(playername, fullLeave); + + if (!endofGame) + { + if (this.getAllPlayers().size() < 2) + { + if (this.getArenaState() != ArenaState.JOIN) + { + if (this.getArenaState() == ArenaState.STARTING && !this.startedIngameCountdown) + { + // cancel starting + this.setArenaState(ArenaState.JOIN); + Util.updateSign(this.plugin, this); + try + { + Bukkit.getScheduler().cancelTask(this.currenttaskid); + } + catch (@SuppressWarnings("unused") final Exception e) + { + // silently ignore + } + for (final String p_ : this.getAllPlayers()) + { + if (Validator.isPlayerOnline(p_)) + { + Util.sendMessage(this.plugin, Bukkit.getPlayer(p_), this.pli.getMessagesConfig().cancelled_starting); + } + } + return; + } + this.stopArena(); + } + } + } + } + + /** + * Leave the player (real implementation). + * + * @param playername + * name of the player + * @param fullLeave + * {@code true} if the player left the server + */ + private void leavePlayerRaw(final String playername, final boolean fullLeave) + { + if (!this.containsPlayer(playername)) + { + return; + } + final Player p = Bukkit.getPlayer(playername); + final ArenaPlayer ap = ArenaPlayer.getPlayerInstance(playername); + if (p == null) + { + return; + } + if (p.isDead()) + { + this.logger.log(Level.WARNING, p.getName() + " unexpectedly appeared dead! Sending respawn packet."); //$NON-NLS-1$ + Effects.playRespawn(p, this.plugin); + Bukkit.getScheduler().runTaskLater(this.plugin, () -> Arena.this.leavePlayerRaw(playername, fullLeave), 10L); + return; + } + this.players.remove(playername); + if (this.pli.containsGlobalPlayer(playername)) + { + this.pli.global_players.remove(playername); + } + if (fullLeave) + { + this.plugin.getConfig().set("temp.left_players." + playername + ".name", playername); + this.plugin.getConfig().set("temp.left_players." + playername + ".plugin", this.plugin.getName()); + if (this.plugin.getConfig().getBoolean(ArenaConfigStrings.CONFIG_RESET_INV_WHEN_LEAVING_SERVER)) + { + for (final ItemStack i : ap.getInventory()) + { + if (i != null) + { + this.plugin.getConfig().set("temp.left_players." + playername + ".items." + Integer.toString((int) Math.round(Math.random() * 10000)) + i.getType().toString(), i); + } + } + } + this.plugin.saveConfig(); + + try + { + if (this.pli.global_lost.containsKey(playername)) + { + this.pli.getSpectatorManager().showSpectator(p); + this.pli.global_lost.remove(playername); + } + else + { + this.pli.getSpectatorManager().showSpectators(p); + } + if (this.pli.global_arcade_spectator.containsKey(playername)) + { + this.pli.global_arcade_spectator.remove(playername); + } + + p.removePotionEffect(PotionEffectType.JUMP); + p.removePotionEffect(PotionEffectType.INVISIBILITY); + Util.teleportPlayerFixed(p, this.mainlobby); + p.setFireTicks(0); + p.setFlying(false); + if (!p.isOp()) + { + p.setAllowFlight(false); + } + if (this.plugin.getConfig().getBoolean(ArenaConfigStrings.RESET_GAMEMMODE)) + p.setGameMode(ap.getOriginalGamemode()); + if (this.plugin.getConfig().getBoolean(ArenaConfigStrings.RESET_XP)) + p.setLevel(ap.getOriginalXplvl()); + if (this.plugin.getConfig().getBoolean(ArenaConfigStrings.RESET_INVENTORY)) + { + p.getInventory().setContents(ap.getInventory()); + p.getInventory().setArmorContents(ap.getArmorInventory()); + p.updateInventory(); + } + + p.setWalkSpeed(0.2F); + p.addPotionEffect(new PotionEffect(PotionEffectType.SATURATION, 20 * 2, 50)); + p.setHealth(20); + p.removePotionEffect(PotionEffectType.JUMP); + p.removePotionEffect(PotionEffectType.INVISIBILITY); + this.pli.getSpectatorManager().setSpectate(p, false); + this.pli.getStatsInstance().updateSQLKillsDeathsAfter(p, this); + + if (this.pli.getClassesHandler().lasticonm.containsKey(p.getName())) + { + final IconMenu iconm = this.pli.getClassesHandler().lasticonm.get(p.getName()); + iconm.destroy(); + this.pli.getClassesHandler().lasticonm.remove(p.getName()); + } + } + catch (final Exception e) + { + this.logger.log(Level.WARNING, "Failed to log out player out of arena.", e); //$NON-NLS-1$ + } + return; + } + Util.clearInv(p); + p.setWalkSpeed(0.2F); + p.setFoodLevel(20); + p.setFireTicks(0); + p.removePotionEffect(PotionEffectType.JUMP); + this.pli.getSpectatorManager().setSpectate(p, false); + + Bukkit.getServer().getPluginManager().callEvent(new PlayerLeaveArenaEvent(p, this.plugin, this)); + + for (final PotionEffect effect : p.getActivePotionEffects()) + { + if (effect != null) + { + p.removePotionEffect(effect.getType()); + } + } + + for (final Entity e : this.getResetEntitiesOnPlayerLeave(playername)) + { + if (this.isEntityResetOnPlayerLeave(playername, e)) + { + e.remove(); + } + } + + // pli.global_players.remove(playername); + if (this.pli.global_arcade_spectator.containsKey(playername)) + { + this.pli.global_arcade_spectator.remove(playername); + } + + if (this.pli.getPClasses().containsKey(playername)) + { + this.pli.getPClasses().remove(playername); + } + + Util.updateSign(this.plugin, this); + + Bukkit.getScheduler().runTaskLater(this.getPlugin(), () -> { + try + { + Arena.this.pli.getHologramsHandler().sendAllHolograms(p); + } + catch (final Exception e) + { + this.logger.log(Level.WARNING, "Failed playing hologram:", e); //$NON-NLS-1$ + } + }, 10L); + + if (this.pli.getClassesHandler().lasticonm.containsKey(p.getName())) + { + final IconMenu iconm = this.pli.getClassesHandler().lasticonm.get(p.getName()); + iconm.destroy(); + this.pli.getClassesHandler().lasticonm.remove(p.getName()); + } + + final String arenaname = this.getInternalName(); + final Arena a = this; + final boolean started_ = this.started; + Bukkit.getScheduler().runTaskLater(this.plugin, () -> { + if (Arena.this.ai == null || a.isArcadeMain()) + { + if (a.mainlobby != null) + { + Util.teleportPlayerFixed(p, a.mainlobby); + if (Arena.this.hasLeaveCommand()) + { + Bukkit.getScheduler().runTaskLater(Arena.this.plugin, () -> Arena.this.playLeaveCommand(p), 10L); + } + } + else if (a.waitinglobby != null) + { + Util.teleportPlayerFixed(p, a.waitinglobby); + } + } + p.setFireTicks(0); + p.setFlying(false); + if (!p.isOp()) + { + p.setAllowFlight(false); + } + p.setGameMode(ap.getOriginalGamemode()); + p.setLevel(ap.getOriginalXplvl()); + p.getInventory().setContents(ap.getInventory()); + p.getInventory().setArmorContents(ap.getArmorInventory()); + p.updateInventory(); + p.updateInventory(); + + if (started_) + { + Arena.this.pli.getStatsInstance().updateSQLKillsDeathsAfter(p, a); + if (!ap.isNoReward()) + { + Arena.this.pli.getRewardsInstance().giveWinReward(playername, a, Arena.this.temp_players, Arena.this.global_coin_multiplier); + } + else + { + ap.setNoReward(false); + } + } + + if (Arena.this.plugin.getConfig().getBoolean(ArenaConfigStrings.CONFIG_SEND_STATS_ON_STOP)) + { + Util.sendStatsMessage(Arena.this.pli, p); + } + + if (Arena.this.pli.global_lost.containsKey(playername)) + { + Arena.this.pli.getSpectatorManager().showSpectator(p); + Arena.this.pli.global_lost.remove(playername); + } + else + { + Arena.this.pli.getSpectatorManager().showSpectators(p); + } + + try + { + Arena.this.pli.scoreboardManager.removeScoreboard(arenaname, p); + } + catch (final Exception e) + { + this.logger.log(Level.WARNING, "Failed removing scoreboard for player " + p.getName(), e); //$NON-NLS-1$ + } + }, 5L); + + if (this.plugin.getConfig().getBoolean(ArenaConfigStrings.CONFIG_BUNGEE_TELEPORT_ALL_TO_SERVER_ON_STOP_TP)) + { + final String server = this.plugin.getConfig().getString(ArenaConfigStrings.CONFIG_BUNGEE_TELEPORT_ALL_TO_SERVER_ON_STOP_SERVER); + Bukkit.getScheduler().runTaskLater(this.plugin, () -> BungeeUtil.connectToServer(MinigamesAPI.getAPI(), p.getName(), server), 30L); + return; + } + } + + /** + * Plays the leave command for given player. + * + * @param p + * leave command. + */ + void playLeaveCommand(final Player p) + { + final String path = ArenaConfigStrings.ARENAS_PREFIX + this.name + ".leavecommand"; + final String leavecommand = this.pli.getArenasConfig().getConfig().getString(path); + p.getServer().dispatchCommand(p, leavecommand); + } + + /** + * Checks if there is a leave command. + * + * @return {@code true} if there is a leave command. + */ + private boolean hasLeaveCommand() + { + final String path = ArenaConfigStrings.ARENAS_PREFIX + this.name + ".leavecommand"; + return this.pli.getArenasConfig().getConfig().isSet(path); + } + + /** + * Spectate the game generally (not specifically after death) + * + * @param playername + * name of the player + */ + public void spectateGame(final String playername) + { + final Player p = Bukkit.getPlayer(playername); + if (p == null) + { + return; + } + Util.clearInv(p); + p.setAllowFlight(true); + p.setFlying(true); + this.pli.getSpectatorManager().hideSpectator(p, this.getAllPlayers()); + this.pli.scoreboardManager.updateScoreboard(this.plugin, this); + if (!this.pli.last_man_standing) + { + if (this.getPlayerAlive() < 1) + { + final Arena a = this; + Bukkit.getScheduler().runTaskLater(this.plugin, () -> a.stopArena(), 20L); + } + else + { + this.spectateRaw(p); + } + } + else + { + if (this.getPlayerAlive() < 2) + { + final Arena a = this; + Bukkit.getScheduler().runTaskLater(this.plugin, () -> a.stop(), 20L); + } + else + { + this.spectateRaw(p); + } + } + Bukkit.getScheduler().runTaskLater(this.plugin, () -> { + Util.clearInv(p); + Util.giveSpectatorItems(Arena.this.plugin, p); + }, 3L); + } + + /** + * Spectate the game after death + * + * @param playername + * name of the player + */ + public void spectate(final String playername) + { + if (Validator.isPlayerValid(this.plugin, playername, this)) + { + this.onEliminated(playername); + final Player p = Bukkit.getPlayer(playername); + if (p == null) + { + return; + } + + this.pli.global_lost.put(playername, this); + + this.pli.getSpectatorManager().setSpectate(p, true); + if (!this.plugin.getConfig().getBoolean(ArenaConfigStrings.CONFIG_SPECTATOR_AFTER_FALL_OR_DEATH)) + { + this.leavePlayer(playername, false, false); + this.pli.scoreboardManager.updateScoreboard(this.plugin, this); + return; + } + this.spectateGame(playername); + } + } + + /** + * Real implementation of joining the arena to spectate. + * + * @param p + * player that wants to spectate the arena. + */ + private void spectateRaw(final Player p) + { + if (this.pli.dead_in_fake_bed_effects) + { + Effects.playFakeBed(this, p); + } + + if (this.pli.spectator_mode_1_8) + { + Effects.sendGameModeChange(p, 3); + } + + final Location temp = this.spawns.get(0); + try + { + Bukkit.getScheduler().runTaskLater(this.plugin, () -> { + if (Arena.this.specspawn != null) + { + Util.teleportPlayerFixed(p, Arena.this.specspawn); + } + else + { + Util.teleportPlayerFixed(p, temp.clone().add(0D, 30D, 0D)); + } + }, 2L); + } + catch (@SuppressWarnings("unused") final Exception e) + { + if (this.specspawn != null) + { + Util.teleportPlayerFixed(p, this.specspawn); + } + else + { + Util.teleportPlayerFixed(p, temp.clone().add(0D, 30D, 0D)); + } + } + } + + /** + * Let given player spectate the arena; invoked internally by arcade instance. + * + * @param playername + */ + public void spectateArcade(final String playername) + { + // TODO Check why this method is different from spectate + final Player p = Bukkit.getPlayer(playername); + this.pli.global_players.put(playername, this); + this.pli.global_arcade_spectator.put(playername, this); + Util.teleportPlayerFixed(p, this.getSpawns().get(0).clone().add(0D, 30D, 0D)); + p.setAllowFlight(true); + p.setFlying(true); + this.pli.getSpectatorManager().setSpectate(p, true); + } + + /** + * Sets the task id. + * + * @param id + * task id. + * @deprecated will be removed in 1.5.0; replaced by a more helpful task management, for example to perform tasks during lobby countdown etc. + */ + @Deprecated + public void setTaskId(final int id) + { + this.currenttaskid = id; + } + + /** + * Returns the task id + * + * @return task id + * @deprecated will be removed in 1.5.0; replaced by a more helpful task management, for example to perform tasks during lobby countdown etc. + */ + @Deprecated + public int getTaskId() + { + return this.currenttaskid; + } + + /** + * Starts the lobby count down and the arena afterwards + * + * You can instant start an arena by using {@link #start(boolean)}. + */ + public void startLobby() + { + this.startLobby(true); + } + + /** + * Checks if the items should be removed from lobby bounds during lobby startup + * + * @return clears items during arena startup + */ + protected boolean removeItemsOnLobbyStartup() + { + return true; + } + + /** + * Checks if the items should be removed from arena bounds during game startup + * + * @return clears items during arena startup + */ + protected boolean removeItemsOnGameStartup() + { + return true; + } + + /** + * Checks if the items should be removed from arena bounds during game stop + * + * @return clears items during arena stop + */ + protected boolean removeItemsOnGameStop() + { + return true; + } + + /** + * Starts the lobby count down with given amount of seconds. + * + * @param countdown + * lobby count down in seconds. + */ + public void startLobby(final boolean countdown) + { + if (this.currentstate != ArenaState.JOIN) + { + return; + } + if (this.removeItemsOnLobbyStartup()) + { + Util.clearDrops(this.getLobbyBoundaries()); + Util.clearDrops(this.getSpecBoundaries()); + Util.clearDrops(this.getBoundaries()); + } + this.setArenaState(ArenaState.STARTING); + Util.updateSign(this.plugin, this); + this.currentlobbycount = this.pli.getLobbyCountdown(); + final Arena a = this; + + // skip countdown + if (!countdown) + { + Bukkit.getScheduler().runTaskLater(this.plugin, () -> Arena.this.start(true), 10L); + } + + Sound lobbycountdown_sound_ = null; + try + { + lobbycountdown_sound_ = Sound.valueOf(this.plugin.getConfig().getString(ArenaConfigStrings.CONFIG_SOUNDS_LOBBY_COUNTDOWN)); + } + catch (@SuppressWarnings("unused") final Exception e) + { + // silently ignore + } + final Sound lobbycountdown_sound = lobbycountdown_sound_; + + this.currenttaskid = Bukkit.getScheduler().runTaskTimer(MinigamesAPI.getAPI(), () -> { + Arena.this.currentlobbycount--; + if (Arena.this.currentlobbycount == 60 || Arena.this.currentlobbycount == 30 || Arena.this.currentlobbycount == 15 || Arena.this.currentlobbycount == 10 + || Arena.this.currentlobbycount < 6) + { + sendLobbyCountdownMsg(countdown, a, lobbycountdown_sound); + } + setLobbyCountdownLevel(a); + if (Arena.this.currentlobbycount < 1) + { + onLobbyCountdownComplete(); + try + { + Bukkit.getScheduler().cancelTask(Arena.this.currenttaskid); + } + catch (@SuppressWarnings("unused") final Exception e) + { + // silently ignore + } + } + }, 5L, 20).getTaskId(); + } + + protected void onLobbyCountdownComplete() + { + Bukkit.getScheduler().runTaskLater(Arena.this.plugin, () -> Arena.this.start(true), 10L); + } + + protected void setLobbyCountdownLevel(final Arena a) + { + for (final String p_2 : a.getAllPlayers()) + { + if (Validator.isPlayerOnline(p_2)) + { + final Player p2 = Bukkit.getPlayer(p_2); + p2.setExp(1F * ((1F * Arena.this.currentlobbycount) / (1F * Arena.this.pli.getLobbyCountdown()))); + if (Arena.this.pli.use_xp_bar_level) + { + p2.setLevel(Arena.this.currentlobbycount); + } + } + } + } + + protected void sendLobbyCountdownMsg(final boolean countdown, final Arena a, final Sound lobbycountdown_sound) + { + for (final String p_1 : a.getAllPlayers()) + { + if (Validator.isPlayerOnline(p_1)) + { + final Player p1 = Bukkit.getPlayer(p_1); + if (countdown) + { + Util.sendMessage(Arena.this.plugin, p1, + Arena.this.pli.getMessagesConfig().teleporting_to_arena_in.replaceAll(ArenaMessageStrings.COUNT, Integer.toString(Arena.this.currentlobbycount))); + if (lobbycountdown_sound != null) + { + p1.playSound(p1.getLocation(), lobbycountdown_sound, 1F, 0F); + } + } + } + } + } + + /** + * Instantly starts the arena, teleports players and udpates the arena. + * + * @param tp + * {@code true} to teleport players to spawns + */ + public void start(final boolean tp) + { + try + { + Bukkit.getScheduler().cancelTask(this.currenttaskid); + } + catch (@SuppressWarnings("unused") final Exception e) + { + // silently ignore + } + if (this.removeItemsOnGameStartup()) + { + Util.clearDrops(this.getSpecBoundaries()); + Util.clearDrops(this.getBoundaries()); + } + this.currentingamecount = this.pli.getIngameCountdown(); + if (tp) + { + this.pspawnloc = Util.teleportAllPlayers(this.getAllPlayers(), this.spawns); + } + final boolean clearinv = this.plugin.getConfig().getBoolean(ArenaConfigStrings.CONFIG_CLEANINV_WHILE_INGAMECOUNTDOWN); + for (final String p_ : this.getAllPlayers()) + { + final Player p = Bukkit.getPlayer(p_); + p.setWalkSpeed(0.0F); + p.setFoodLevel(5); + p.addPotionEffect(new PotionEffect(PotionEffectType.JUMP, 9999999, -7)); // -5 + this.pli.scoreboardLobbyManager.removeScoreboard(this.getInternalName(), p); + if (clearinv) + { + Util.clearInv(p); + } + } + Bukkit.getScheduler().runTaskLater(this.plugin, () -> Arena.this.pli.scoreboardManager.updateScoreboard(Arena.this.plugin, this), 20L); + this.startedIngameCountdown = true; + if (!this.plugin.getConfig().getBoolean(ArenaConfigStrings.CONFIG_INGAME_COUNTDOWN_ENABLED)) + { + this.startRaw(); + return; + } + + Sound ingamecountdown_sound_ = null; + try + { + ingamecountdown_sound_ = Sound.valueOf(this.plugin.getConfig().getString(ArenaConfigStrings.CONFIG_SOUNDS_INGAME_COUNTDOWN)); + } + catch (@SuppressWarnings("unused") final Exception e) + { + // silently ignore + } + final Sound ingamecountdown_sound = ingamecountdown_sound_; + + this.currenttaskid = Bukkit.getScheduler().runTaskTimer(MinigamesAPI.getAPI(), () -> { + Arena.this.currentingamecount--; + if (Arena.this.currentingamecount == 60 || Arena.this.currentingamecount == 30 || Arena.this.currentingamecount == 15 || Arena.this.currentingamecount == 10 + || Arena.this.currentingamecount < 6) + { + for (final String p_1 : Arena.this.getAllPlayers()) + { + if (Validator.isPlayerOnline(p_1)) + { + final Player p1 = Bukkit.getPlayer(p_1); + Util.sendMessage(Arena.this.plugin, p1, Arena.this.pli.getMessagesConfig().starting_in.replaceAll(ArenaMessageStrings.COUNT, Integer.toString(Arena.this.currentingamecount))); + if (ingamecountdown_sound != null) + { + p1.playSound(p1.getLocation(), ingamecountdown_sound, 1F, 0F); + } + } + } + } + for (final String p_2 : Arena.this.getAllPlayers()) + { + if (Validator.isPlayerOnline(p_2)) + { + final Player p2 = Bukkit.getPlayer(p_2); + p2.setExp(1F * ((1F * Arena.this.currentingamecount) / (1F * Arena.this.pli.getIngameCountdown()))); + if (Arena.this.pli.use_xp_bar_level) + { + p2.setLevel(Arena.this.currentingamecount); + } + } + } + if (Arena.this.currentingamecount < 1) + { + Arena.this.startRaw(); + } + }, 5L, 20).getTaskId(); + + for (final String p_ : this.getAllPlayers()) + { + if (this.pli.getShopHandler().hasItemBought(p_, "coin_boost2")) + { + this.global_coin_multiplier = 2; + break; + } + if (this.pli.getShopHandler().hasItemBought(p_, "coin_boost3")) + { + this.global_coin_multiplier = 3; + break; + } + } + } + + /** + * Real implementation of starting the arena. + */ + void startRaw() + { + this.setArenaState(ArenaState.INGAME); + this.startedIngameCountdown = false; + Util.updateSign(this.plugin, this); + Bukkit.getServer().getPluginManager().callEvent(new ArenaStartEvent(this.plugin, this)); + final boolean send_game_started_msg = this.plugin.getConfig().getBoolean(ArenaConfigStrings.CONFIG_SEND_GAME_STARTED_MSG); + for (final String p_ : this.getAllPlayers()) + { + try + { + if (!this.pli.global_lost.containsKey(p_)) + { + final Player p = Bukkit.getPlayer(p_); + if (this.plugin.getConfig().getBoolean(ArenaConfigStrings.CONFIG_AUTO_ADD_DEFAULT_KIT)) + { + if (!this.pli.getClassesHandler().hasClass(p_)) + { + this.pli.getClassesHandler().setClass("default", p_, false); + } + this.pli.getClassesHandler().getClass(p_); + } + else + { + Util.clearInv(Bukkit.getPlayer(p_)); + this.pli.getClassesHandler().getClass(p_); + } + if (this.plugin.getConfig().getBoolean(ArenaConfigStrings.CONFIG_SHOP_ENABLED)) + { + this.pli.getShopHandler().giveShopItems(p); + } + p.setFlying(false); + p.setAllowFlight(false); + } + } + catch (final Exception e) + { + this.logger.log(Level.WARNING, "Failed to set class", e); //$NON-NLS-1$ + } + final Player p = Bukkit.getPlayer(p_); + p.setWalkSpeed(0.2F); + p.addPotionEffect(new PotionEffect(PotionEffectType.HEAL, 20 * 2, 50)); + p.setFoodLevel(20); + p.removePotionEffect(PotionEffectType.JUMP); + if (send_game_started_msg) + { + p.sendMessage(this.pli.getMessagesConfig().game_started); + } + } + if (this.plugin.getConfig().getBoolean(ArenaConfigStrings.CONFIG_BUNGEE_WHITELIST_WHILE_GAME_RUNNING)) + { + Bukkit.setWhitelist(true); + } + this.started = true; + Bukkit.getServer().getPluginManager().callEvent(new ArenaStartedEvent(this.plugin, this)); + this.started(); + try + { + Bukkit.getScheduler().cancelTask(this.currenttaskid); + } + catch (@SuppressWarnings("unused") final Exception e) + { + // silently ignore + } + + // Maximum game time: + this.timer.onArenaStart(this.plugin); + } + + /** + * Gets executed after an arena started (after ingame countdown); can be overridden by minigames. + */ + public void started() + { + this.logger.info("started"); //$NON-NLS-1$ + } + + /** + * Invoked externally to stop the arena; ensures that it only is called once. + */ + public synchronized void stopArena() + { + // TODO eliminate synchronized but check for the current arena state before actually invoking stop + // TODO check if spigot really invokes the tasks in serial order. + // This is an implementation detail that may break in future versions. + this.stop(); + } + + /** + * Returns the possible entites to be removed for reset + * + * @param player + * @return entites + */ + protected List getResetEntitiesOnPlayerLeave(String player) + { + return this.getResetEntities(player); + } + + /** + * Checks if given entity is removed for resetting the map + * + * @param player + * @param e + * @return {@code true} for removing the entity + */ + protected boolean isEntityResetOnPlayerLeave(String player, Entity e) + { + return this.isEntityReset(player, e); + } + + /** + * Returns the possible entites to be removed for reset + * + * @param player + * @return entites + */ + protected List getResetEntities(String player) + { + return Bukkit.getPlayer(player).getNearbyEntities(50, 50, 50); + } + + /** + * Checks if given entity is removed for resetting the map + * + * @param player + * @param e + * @return {@code true} for removing the entity + */ + protected boolean isEntityReset(String player, Entity e) + { + return e.getType() == EntityType.DROPPED_ITEM || e.getType() == EntityType.ENDERMAN || e.getType() == EntityType.SLIME || e.getType() == EntityType.ZOMBIE || e.getType() == EntityType.SKELETON + || e.getType() == EntityType.SPIDER || e.getType() == EntityType.CREEPER || e.getType() == EntityType.VILLAGER || e.getType() == EntityType.ARMOR_STAND + || e.getType() == EntityType.ARROW; + } + + /** + * Stops the arena and teleports all players to the mainlobby + */ + protected void stop() + { + Bukkit.getServer().getPluginManager().callEvent(new ArenaStopEvent(this.plugin, this)); + final Arena a = this; + this.timer.onArenaStop(); + this.temp_players = new ArrayList<>(this.players); + if (!this.temp_delay_stopped) + { + if (this.plugin.getConfig().getBoolean(ArenaConfigStrings.CONFIG_DELAY_ENABLED)) + { + Bukkit.getScheduler().runTaskLater(this.plugin, () -> { + Arena.this.temp_delay_stopped = true; + a.stopArena(); + }, this.plugin.getConfig().getInt(ArenaConfigStrings.CONFIG_DELAY_AMOUNT_SECONDS) * 20L); + this.setArenaState(ArenaState.RESTARTING); + Util.updateSign(this.plugin, this); + if (this.plugin.getConfig().getBoolean(ArenaConfigStrings.CONFIG_SPAWN_FIREWORKS_FOR_WINNERS)) + { + if (this.getAllPlayers().size() > 0) + { + Util.spawnFirework(Bukkit.getPlayer(this.getAllPlayers().get(0))); + } + } + return; + } + } + this.temp_delay_stopped = false; + + try + { + Bukkit.getScheduler().cancelTask(this.currenttaskid); + } + catch (@SuppressWarnings("unused") final Exception e) + { + // silently ignore + } + + this.setArenaState(ArenaState.RESTARTING); + + final ArrayList temp = new ArrayList<>(this.getAllPlayers()); + for (final String p_ : temp) + { + try + { + Bukkit.getScheduler().runTaskLater(this.plugin, () -> { + if (Validator.isPlayerOnline(p_)) + { + for (final Entity e : Bukkit.getPlayer(p_).getNearbyEntities(50, 50, 50)) + { + if (this.isEntityReset(p_, e)) + { + e.remove(); + } + } + } + }, 10L); + } + catch (final Exception e) + { + this.logger.log(Level.WARNING, "failed clearing entities", e); //$NON-NLS-1$ + } + this.leavePlayer(p_, false, true); + } + + try + { + // TODO: Why setting the drops to air? + // the list contains the drops of dying players + // but why the list is not cleared at end? + for (final ItemStack item : this.global_drops) + { + if (item != null) + { + item.setType(Material.AIR); + } + } + } + catch (final Exception e) + { + this.logger.log(Level.WARNING, "failed clearing entities", e); //$NON-NLS-1$ + } + + if (a.getArenaType() == ArenaType.REGENERATION) + { + this.reset(); + } + else + { + a.setArenaState(ArenaState.JOIN); + Util.updateSign(this.plugin, a); + } + + Bukkit.getScheduler().runTaskLater(this.plugin, () -> { + Arena.this.players.clear(); + for (final IconMenu im : Arena.this.pli.getClassesHandler().lasticonm.values()) + { + im.destroy(); + } + }, 10L); + + this.started = false; + this.startedIngameCountdown = false; + + this.temp_countdown = true; + this.skip_join_lobby = false; + this.currentspawn = 0; + + try + { + this.pli.scoreboardManager.clearScoreboard(this.getInternalName()); + this.pli.scoreboardLobbyManager.clearScoreboard(this.getInternalName()); + } + catch (final Exception e) + { + this.logger.log(Level.WARNING, "failed clearing score boards", e); //$NON-NLS-1$ + } + + /* + * try { pli.getStatsInstance().updateSkulls(); } catch (Exception e) { + * + * } + */ + + if (this.plugin.getConfig().getBoolean(ArenaConfigStrings.CONFIG_BUNGEE_WHITELIST_WHILE_GAME_RUNNING)) + { + Bukkit.setWhitelist(false); + } + + if (this.plugin.getConfig().getBoolean(ArenaConfigStrings.CONFIG_EXECUTE_CMDS_ON_STOP)) + { + final String[] cmds = this.plugin.getConfig().getString(ArenaConfigStrings.CONFIG_CMDS).split(";"); //$NON-NLS-1$ + if (cmds.length > 0) + { + for (final String cmd : cmds) + { + Bukkit.dispatchCommand(Bukkit.getConsoleSender(), cmd); + } + } + } + + if (this.plugin.getConfig().getBoolean(ArenaConfigStrings.CONFIG_BUNGEE_TELEPORT_ALL_TO_SERVER_ON_STOP_TP)) + { + final String server = this.plugin.getConfig().getString(ArenaConfigStrings.CONFIG_BUNGEE_TELEPORT_ALL_TO_SERVER_ON_STOP_SERVER); + Bukkit.getScheduler().runTaskLater(this.plugin, () -> { + for (final Player p : Bukkit.getOnlinePlayers()) + { + BungeeUtil.connectToServer(MinigamesAPI.getAPI(), p.getName(), server); + } + }, 30L); + return; + } + + if (this.plugin.getConfig().getBoolean(ArenaConfigStrings.CONFIG_EXECUTE_CMDS_ON_STOP)) + { + final String[] cmds = this.plugin.getConfig().getString(ArenaConfigStrings.CONFIG_CMDS_AFTER).split(";"); //$NON-NLS-1$ + if (cmds.length > 0) + { + for (final String cmd : cmds) + { + Bukkit.dispatchCommand(Bukkit.getConsoleSender(), cmd); + } + } + } + + if (this.ai != null) + { + Bukkit.getScheduler().runTaskLater(this.plugin, () -> { + if (Arena.this.ai != null) + { + Arena.this.ai.nextMinigame(); + Arena.this.ai = null; + } + }, 10L); + } + else + { + // Map rotation only works without Arcade + // check if there is only one player or none left + if (temp.size() < 2) + { + return; + } + if (this.plugin.getConfig().getBoolean(ArenaConfigStrings.CONFIG_MAP_ROTATION)) + { + Bukkit.getScheduler().runTaskLater(this.plugin, () -> a.nextArenaOnMapRotation(temp), 35L); + } + } + if (this.removeItemsOnGameStop()) + { + Util.clearDrops(this.getSpecBoundaries()); + Util.clearDrops(this.getBoundaries()); + } + + } + + protected void abortStarting() + { + if (this.currentstate == ArenaState.STARTING) + { + this.currentstate = ArenaState.JOIN; + Util.updateSign(this.plugin, this); + } + } + + /** + * Rebuilds an arena from file (only for arenas of REGENERATION type) + */ + public void reset() + { + if (!this.pli.getArenasConfig().getConfig().getBoolean( + ArenaConfigStrings.ARENAS_PREFIX + this.getInternalName() + ArenaConfigStrings.SMART_RESET_SUFFIX, true)) + { + ArenaLogger.debug("Skipping arena smart reset (config)."); //$NON-NLS-1$ + return; + } + + if (this.pli.old_reset) + { + ArenaLogger.debug("Resetting using old method."); //$NON-NLS-1$ + try + { + PrivateUtil.loadArenaFromFileSYNC(this.plugin, this); + } + catch (final Exception e) + { + // TODO Exception log. + ArenaLogger.debug("Error resetting map using old method. " + e.getMessage()); //$NON-NLS-1$ + } + } + else + { + this.sr.reset(); + } + } + + /*** + * Use this when someone got killed/pushed down/eliminated in some way by a player + * + * @param playername + * The player that got eliminated + */ + public void onEliminated(final String playername) + { + if (this.lastdamager.containsKey(playername)) + { + final Player killer = Bukkit.getPlayer(this.lastdamager.get(playername)); + if (killer != null && !playername.equals(killer.getName())) + { + this.pli.getStatsInstance().addDeath(playername); + this.temp_kill_count.put(killer.getName(), this.temp_kill_count.containsKey(killer.getName()) ? this.temp_kill_count.get(killer.getName()) + 1 : 1); + this.temp_death_count.put(playername, this.temp_death_count.containsKey(playername) ? this.temp_death_count.get(playername) + 1 : 1); + this.pli.getRewardsInstance().giveKillReward(killer.getName()); + Util.sendMessage(this.plugin, killer, MinigamesAPI.getAPI().getPluginInstance(this.plugin).getMessagesConfig().you_got_a_kill.replaceAll(ArenaMessageStrings.PLAYER, playername)); + for (final String p_ : this.getAllPlayers()) + { + if (!p_.equalsIgnoreCase(killer.getName())) + { + if (Validator.isPlayerOnline(p_)) + { + Bukkit.getPlayer(p_).sendMessage(MinigamesAPI.getAPI().getPluginInstance(this.plugin).getMessagesConfig().player_was_killed_by + .replaceAll(ArenaMessageStrings.PLAYER, playername).replaceAll(ArenaMessageStrings.KILLER, killer.getName())); + } + } + } + } + this.lastdamager.remove(playername); + } + else + { + this.pli.getStatsInstance().addDeath(playername); + } + } + + /** + * Will shuffle all arenas and join the next available arena + * + * @param players + * @deprecated will be removed in 1.5.0; replaced by some external shuffle support class + */ + public void nextArenaOnMapRotation(final ArrayList players) + { + final ArrayList arenas = new ArrayList<>(this.pli.getArenas()); + Collections.shuffle(arenas); + for (final Arena a : arenas) + { + if (a.getArenaState() == ArenaState.JOIN && a != this) + { + this.logger.info("Next arena on map rotation: " + a.getInternalName()); //$NON-NLS-1$ + for (final String p_ : players) + { + if (!a.containsPlayer(p_)) + { + a.joinPlayerLobby(p_, false); + } + } + } + } + } + + /** + * Returns a string of players left in the game. + * + * @return string: "alive/total" + */ + public String getPlayerCount() + { + return Integer.toString(this.getPlayerAlive()) + "/" + Integer.toString(this.getAllPlayers().size()); //$NON-NLS-1$ + } + + /** + * Returns the amount of players left in the game. + * + * @return amount of players excluding players that already lost. + */ + public int getPlayerAlive() + { + int alive = 0; + for (final String p_ : this.getAllPlayers()) + { + if (this.pli.global_lost.containsKey(p_)) + { + continue; + } + alive++; + } + return alive; + } + + /** + * Returns the waiting lobby location. + * + * @return waiting lobby location; may be {@code null}. + * @deprecated will be removed in 1.5.0; replaced by {@link #getWaitingLobby()} + */ + @Deprecated + public Location getWaitingLobbyTemp() + { + return this.waitinglobby; + } + + /** + * Returns the waiting lobby location. + * + * @return waiting lobby location; may be {@code null}. + */ + public Location getWaitingLobby() + { + return this.waitinglobby; + } + + /** + * Returns the main lobby location. + * + * @return main lobby location; may be {@code null}. + * @deprecated will be removed in 1.5.0; replaced by {@link #getMainLobby()} + */ + @Deprecated + public Location getMainLobbyTemp() + { + return this.mainlobby; + } + + /** + * Returns the main lobby location. + * + * @return main lobby location; may be {@code null}. + */ + public Location getMainLobby() + { + return this.mainlobby; + } + + /** + * Returns the arcade instance if this arena is part of arcade. + * + * @return arcade instance or {@code null} for stand alone arenas. + */ + public ArcadeInstance getArcadeInstance() + { + return this.ai; + } + + /** + * Checks if this is the arcade main arena. + * + * @return {@code true} if this is the arcade main arena. + */ + public boolean isArcadeMain() + { + // TODO review what this flag is meant for. + // currently no one ever sets this so it is always false; but it is used in some other classes. + return this.isArcadeMain; + } + + /** + * Sets the arcade main flag. + * + * @param t + * arcade main flag + */ + public void setArcadeMain(final boolean t) + { + this.isArcadeMain = t; + } + + /** + * Returns the player spawn locations. + * + * @return player spawn locations. + * + * @deprecated will be removed in 1.5.0; seems not very useful; currently only used in SkyWars. + */ + @Deprecated + public HashMap getPSpawnLocs() + { + return this.pspawnloc; + } + + /** + * Returns the java plugin owning this arena. + * + * @return java plugin + */ + public JavaPlugin getPlugin() + { + return this.plugin; + } + + /** + * Returns the plugin instance owning this arena. + * + * @return minigames plugin instance. + */ + public PluginInstance getPluginInstance() + { + return this.pli; + } + + /** + * Returns the ingame countdown time in seconds + * + * @return countdown time in seconds + */ + public int getCurrentIngameCountdownTime() + { + return this.currentingamecount; + } + + /** + * Returns the lobby countdown time in seconds + * + * @return countdown time in seconds + */ + public int getCurrentLobbyCountdownTime() + { + return this.currentlobbycount; + } + + /** + * Returns the ingame countdown started flag. + * + * @return {@code true} if the ingame countdown already started. + */ + public boolean getIngameCountdownStarted() + { + return this.startedIngameCountdown; + } + + /** + * Returns {@code true} if the arena was initialized. + * + * @return {@code true} for successful init. + */ + public boolean isSuccessfullyInit() + { + return this.isSuccessfullyInitialized; + } + + /** + * Sets last damager for fetching kill statistics. + * + * @param targetPlayer + * target player that was hit + * @param damager + * the damager that shot the profile + */ + public void setLastDamager(final String targetPlayer, final String damager) + { + this.lastdamager.put(targetPlayer, damager); + } + + public void joinSpectate(Player p) + { + final String playername = p.getName(); + this.addPlayer(playername); // TODO seems to be a bad hack. Influences the players list; do we really need this? Instead fill a list of spectators. + final ArenaPlayer ap = ArenaPlayer.getPlayerInstance(playername); + ap.setNoReward(true); + ap.setInventories(p.getInventory().getContents(), p.getInventory().getArmorContents()); + ap.setOriginalGamemode(p.getGameMode()); + ap.setOriginalXplvl(p.getLevel()); + this.pli.global_players.put(playername, this); + this.pli.global_lost.put(playername, this); + this.spectateGame(playername); + } + + // match timer + + /** + * Pauses the current match; causing the timer to halt + */ + public void timerPause() + { + this.timer.pause(); + } + + /** + * Resumes the current match; causing the timer to restart after {@link #timerPause()} was called + */ + public void timerResume() + { + this.timer.resume(); + } + + /** + * Resets the timer; starting the timer from zero + */ + public void timerResetAndResume() + { + this.timer.resetAndResume(); + } + + /** + * Resets the timer; pausing the timer at zero + */ + public void timerResetAndPause() + { + this.timer.resetAndPause(); + } + + /** + * Returns the current match time in millis + * + * @return match time; respects any call to the methods on this interface + */ + public long timerGetDurationMillis() + { + return this.timer.getDurationMillis(); + } + + /** + * Returns the maximum time in millis + * + * @return maximum time; respects any call to the methods on this interface + */ + public long timerGetMaxMillis() + { + return this.timer.getMaxMillis(); + } + + /** + * Adds milliseconds to maximum time + * + * @param millis + */ + public void timerAddMaxMillis(long millis) + { + this.timer.addMaxMillis(this.plugin, millis); + } + + /** + * Substracts milliseconds from maximum time; if duration gets below max millis the game ends + * + * @param millis + */ + public void timerSubstractMaxMillis(long millis) + { + this.timer.substractMaxMillis(millis); + } + + /** + * Sets the maximum time milliseconds + * + * @param millis + * new millis; zero or below zero to stop timer; if set to positive value and previous value was set to zero or below zero the timer starts + */ + public void timerSetMaxMillis(long millis) + { + this.timer.setMaxMillis(millis); + } + + /** + * Adds milliseconds to played time + * + * @param millis + */ + public void timerAddDurationMillis(long millis) + { + this.timer.addDurationMillis(millis); + } + + /** + * Substracts milliseconds from played time; if duration gets below max millis the game ends + * + * @param millis + */ + public void timerSubstractDurationMillis(long millis) + { + this.timer.substractDurationMillis(millis); + } + + /** + * Sets the played time milliseconds + * + * @param millis + * new millis + */ + public void timerSetDurationMillis(long millis) + { + this.timer.setDurationMillis(millis); + } + } diff --git a/API/src/main/java/com/comze_instancelabs/minigamesapi/ArenaConfigStrings.java b/API/src/main/java/com/comze_instancelabs/minigamesapi/ArenaConfigStrings.java new file mode 100644 index 00000000..5e7f4e33 --- /dev/null +++ b/API/src/main/java/com/comze_instancelabs/minigamesapi/ArenaConfigStrings.java @@ -0,0 +1,297 @@ +/* + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +package com.comze_instancelabs.minigamesapi; + +/** + * Strings for arenas config. + * + * @author mepeisen + */ +public interface ArenaConfigStrings +{ + + /** arenas lower boundary. */ + String BOUNDS_LOW = "bounds.low"; //$NON-NLS-1$ + + /** arenas higher boundary. */ + String BOUNDS_HIGH = "bounds.high"; //$NON-NLS-1$ + + /** arenas lobby lower boundary. */ + String LOBBY_BOUNDS_LOW = "lobbybounds.bounds.low"; //$NON-NLS-1$ + + /** arenas lobby higher boundary. */ + String LOBBY_BOUNDS_HIGH = "lobbybounds.bounds.high"; //$NON-NLS-1$ + + /** arenas spectator lower boundary. */ + String SPEC_BOUNDS_LOW = "specbounds.bounds.low"; //$NON-NLS-1$ + + /** arenas spectator higher boundary. */ + String SPEC_BOUNDS_HIGH = "specbounds.bounds.high"; //$NON-NLS-1$ + + /** arenas spectator spawn location. */ + String SPEC_SPAWN = "specspawn"; //$NON-NLS-1$ + + + + /** prefix for arenas config. */ + String ARENAS_PREFIX = "arenas."; //$NON-NLS-1$ + + /** suffix for arenas display name. */ + String DISPLAYNAME_SUFFIX = ".displayname"; //$NON-NLS-1$ + + /** suffix for arenas author. */ + String AUTHOR_SUFFIX = ".author"; //$NON-NLS-1$ + + /** suffix for arenas description. */ + String DESCRIPTION_SUFFIX = ".description"; //$NON-NLS-1$ + + /** suffix for smart reset activation. */ + String SMART_RESET_SUFFIX = ".smart_reset"; //$NON-NLS-1$ + + + + /** TODO: describe config option. */ + String CONFIG_CLASS_SELECTION_ITEM = "config.selection_items.classes_selection_item"; //$NON-NLS-1$ + /** TODO: describe config option. */ + String CONFIG_EXIT_ITEM = "config.selection_items.exit_item"; //$NON-NLS-1$ + /** TODO: describe config option. */ + String CONFIG_ACHIEVEMENT_ITEMS = "config.selection_items.achievement_item"; //$NON-NLS-1$ + /** TODO: describe config option. */ + String CONFIG_SPECTATOR_ITEM = "config.selection_items.spectator_item"; //$NON-NLS-1$ + /** TODO: describe config option. */ + String CONFIG_SHOP_SELECTION_ITEM = "config.selection_items.shop_selection_item"; //$NON-NLS-1$ + /** TODO: describe config option. */ + String CONFIG_CLASSES_GUI_ROWS = "config.GUI.classes_gui_rows"; //$NON-NLS-1$ + /** TODO: describe config option. */ + String CONFIG_SHOP_GUI_ROWS = "config.GUI.shop_gui_rows"; //$NON-NLS-1$ + /** TODO: describe config option. */ + String CONFIG_SPECTATOR_AFTER_FALL_OR_DEATH = "config.spectator.spectator_after_fall_or_death"; //$NON-NLS-1$ + /** TODO: describe config option. */ + String CONFIG_SPECTATOR_MOVE_Y_LOCK = "config.spectator.spectator_move_y_lock"; //$NON-NLS-1$ + /** TODO: describe config option. */ + String CONFIG_DEFAULT_MAX_PLAYERS = "config.defaults.default_max_players"; //$NON-NLS-1$ + /** TODO: describe config option. */ + String CONFIG_DEFAULT_MIN_PLAYERS = "config.defaults.default_min_players"; //$NON-NLS-1$ + /** TODO: describe config option. */ + String CONFIG_DEFAULT_MAX_GAME_TIME_IN_MINUTES = "config.defaults.default_max_game_time_in_minutes"; //$NON-NLS-1$ + /** TODO: describe config option. */ + String CONFIG_LOBBY_COUNTDOWN = "config.countdowns.lobby_countdown"; //$NON-NLS-1$ + /** TODO: describe config option. */ + String CONFIG_INGAME_COUNTDOWN = "config.countdowns.ingame_countdown"; //$NON-NLS-1$ + /** TODO: describe config option. */ + String CONFIG_INGAME_COUNTDOWN_ENABLED = "config.countdowns.ingame_countdown_enabled"; //$NON-NLS-1$ + + /** TODO: describe config option. */ + String CONFIG_SKIP_LOBBY = "config.countdowns.skip_lobby"; //$NON-NLS-1$ + + /** TODO: describe config option. */ + String CONFIG_CLEANINV_WHILE_INGAMECOUNTDOWN = "config.countdowns.clearinv_while_ingamecountdown"; //$NON-NLS-1$ + + /** TODO: describe config option. */ + String CONFIG_CLASSES_ENABLED = "config.classes_enabled"; //$NON-NLS-1$ + /** TODO: describe config option. */ + String CONFIG_SHOP_ENABLED = "config.shop_enabled"; //$NON-NLS-1$ + /** TODO: describe config option. */ + String CONFIG_USE_CREADITS_INSTEAD_MONEY_FOR_KITS = "config.use_credits_instead_of_money_for_kits"; //$NON-NLS-1$ + /** TODO: describe config option. */ + String CONFIG_RESET_INV_WHEN_LEAVING_SERVER = "config.reset_inventory_when_players_leave_server"; //$NON-NLS-1$ + /** TODO: describe config option. */ + String CONFIG_COLOR_BACKGROUND_WOOL = "config.color_background_wool_of_signs"; //$NON-NLS-1$ + /** TODO: describe config option. */ + String CONFIG_SHOW_CLASSES_WITHOUT_PERM = "config.show_classes_without_usage_permission"; //$NON-NLS-1$ + + /** {@code true} to gain economy rewards on win. */ + String CONFIG_REWARDS_ECONOMY = "config.rewards.economy"; //$NON-NLS-1$ + /** Amount of money to give for win. */ + String CONFIG_REWARDS_ECONOMY_REWARD = "config.rewards.economy_reward"; //$NON-NLS-1$ + /** {@code true} to gain item rewards on win. */ + String CONFIG_REWARDS_ITEM_REWARD = "config.rewards.item_reward"; //$NON-NLS-1$ + /** the items wo give for win. */ + String CONFIG_REWARDS_ITEM_REWARD_IDS = "config.rewards.item_reward_ids"; //$NON-NLS-1$ + /** {@code true} to execute a command on win. */ + String CONFIG_REWARDS_COMMAND_REWARD = "config.rewards.command_reward"; //$NON-NLS-1$ + /** the command to execute for win. */ + String CONFIG_REWARDS_COMMAND = "config.rewards.command"; //$NON-NLS-1$ + /** {@code true} to gain economy rewards on kills. */ + String CONFIG_REWARDS_ECONOMY_FOR_KILLS = "config.rewards.economy_for_kills"; //$NON-NLS-1$ + /** money to give per kill. */ + String CONFIG_REWARDS_ECONOMY_REWARD_FOR_KILLS = "config.rewards.economy_reward_for_kills"; //$NON-NLS-1$ + /** {@code true} to gain a command for kills. */ + String CONFIG_REWARDS_COMMAND_REWARD_FOR_KILLS = "config.rewards.command_reward_for_kills"; //$NON-NLS-1$ + /** command to execute for kills. */ + String CONFIG_REWARDS_COMMAND_FOR_KILLS = "config.rewards.command_for_kills"; //$NON-NLS-1$ + /** {@code true} to gain economy rewards for participation. */ + String CONFIG_REWARDS_ECONOMY_FOR_PARTICIPATION = "config.rewards.economy_for_participation"; //$NON-NLS-1$ + /** money to give for participation. */ + String CONFIG_REWARDS_ECONOMY_REWARD_FOR_PARTICIPATION = "config.rewards.economy_reward_for_participation"; //$NON-NLS-1$ + /** {@code true} to execute a command for participation. */ + String CONFIG_REWARDS_COMMAND_REWARD_FOR_PARTICIPATION = "config.rewards.command_reward_for_participation"; //$NON-NLS-1$ + /** command to execute for participation. */ + String CONFIG_REWARDS_COMMAND_FOR_PARTICIPATION = "config.rewards.command_for_participation"; //$NON-NLS-1$ + + /** TODO: describe config option. */ + String CONFIG_STATS_POINTS_FOR_KILL = "config.stats.points_for_kill"; //$NON-NLS-1$ + /** TODO: describe config option. */ + String CONFIG_STATS_POINTS_FOR_WIN = "config.stats.points_for_win"; //$NON-NLS-1$ + + /** TODO: describe config option. */ + String CONFIG_ARCADE_ENABLED = "config.arcade.enabled"; //$NON-NLS-1$ + /** TODO: describe config option. */ + String CONFIG_ARCADE_MIN_PLAYERS = "config.arcade.min_players"; //$NON-NLS-1$ + /** TODO: describe config option. */ + String CONFIG_ARCADE_MAX_PLAYERS = "config.arcade.max_players"; //$NON-NLS-1$ + /** TODO: describe config option. */ + String CONFIG_ARCADE_ARENA_TO_PREFER_ENABLED = "config.arcade.arena_to_prefer.enabled"; //$NON-NLS-1$ + /** TODO: describe config option. */ + String CONFIG_ARCADE_ARENA_TO_PREFER_ARENA = "config.arcade.arena_to_prefer.arena"; //$NON-NLS-1$ + /** TODO: describe config option. */ + String CONFIG_ARCADE_LOBBY_COUNTDOWN = "config.arcade.lobby_countdown"; //$NON-NLS-1$ + /** TODO: describe config option. */ + String CONFIG_ARCADE_SHOW_EACH_LOBBY_COUNTDOWN = "config.arcade.show_each_lobby_countdown"; //$NON-NLS-1$ + /** TODO: describe config option. */ + String CONFIG_ARCADE_INFINITE_ENABLED = "config.arcade.infinite_mode.enabled"; //$NON-NLS-1$ + /** TODO: describe config option. */ + String CONFIG_ARCADE_INFINITE_SECONDS_TO_NEW_ROUND = "config.arcade.infinite_mode.seconds_to_new_round"; //$NON-NLS-1$ + /** TODO: describe config option. */ + String CONFIG_BUNGEE_GAME_ON_JOIN = "config.bungee.game_on_join"; //$NON-NLS-1$ + /** TODO: describe config option. */ + String CONFIG_BUNGEE_TELEPORT_ALL_TO_SERVER_ON_STOP_TP = "config.bungee.teleport_all_to_server_on_stop.tp"; //$NON-NLS-1$ + /** TODO: describe config option. */ + String CONFIG_BUNGEE_TELEPORT_ALL_TO_SERVER_ON_STOP_SERVER = "config.bungee.teleport_all_to_server_on_stop.server"; //$NON-NLS-1$ + /** TODO: describe config option. */ + String CONFIG_BUNGEE_WHITELIST_WHILE_GAME_RUNNING = "config.bungee.whitelist_while_game_running"; //$NON-NLS-1$ + /** TODO: describe config option. */ + String CONFIG_EXECUTE_CMDS_ON_STOP = "config.execute_cmds_on_stop"; //$NON-NLS-1$ + /** TODO: describe config option. */ + String CONFIG_CMDS = "config.cmds"; //$NON-NLS-1$ + /** TODO: describe config option. */ + String CONFIG_CMDS_AFTER = "config.cmds_after"; //$NON-NLS-1$ + /** TODO: describe config option. */ + String CONFIG_MAP_ROTATION = "config.map_rotation"; //$NON-NLS-1$ + /** TODO: describe config option. */ + String CONFIG_BROADCAST_WIN = "config.broadcast_win"; //$NON-NLS-1$ + /** TODO: describe config option. */ + String CONFIG_BUY_CLASSES_FOREVER = "config.buy_classes_forever"; //$NON-NLS-1$ + /** TODO: describe config option. */ + String CONFIG_DISABLE_COMMANDS_IN_ARENA = "config.disable_commands_in_arena"; //$NON-NLS-1$ + /** TODO: describe config option. */ + String CONFIG_COMMAND_WHITELIST = "config.command_whitelist"; //$NON-NLS-1$ + /** TODO: describe config option. */ + String CONFIG_LEAVE_COMMAND = "config.leave_command"; //$NON-NLS-1$ + /** TODO: describe config option. */ + String CONFIG_SPAWN_FIREWORKS_FOR_WINNERS = "config.spawn_fireworks_for_winners"; //$NON-NLS-1$ + /** TODO: describe config option. */ + String CONFIG_POWERUP_BROADCAST = "config.powerup_spawning.broadcast"; //$NON-NLS-1$ + /** TODO: describe config option. */ + String CONFIG_POWERUP_FIREWORKS = "config.powerup_spawning.spawn_firework"; //$NON-NLS-1$ + /** TODO: describe config option. */ + String CONFIG_USE_CUSTOM_SCOREBOARD = "config.use_custom_scoreboard"; //$NON-NLS-1$ + /** TODO: describe config option. */ + String CONFIG_USE_SPECTATOR_SCOREBOARD = "config.use_spectator_scoreboard"; //$NON-NLS-1$ + /** TODO: describe config option. */ + String CONFIG_DELAY_ENABLED = "config.delay.enabled"; //$NON-NLS-1$ + /** TODO: describe config option. */ + String CONFIG_DELAY_AMOUNT_SECONDS = "config.delay.amount_seconds"; //$NON-NLS-1$ + /** TODO: describe config option. */ + String CONFIG_SEND_GAME_STARTED_MSG = "config.send_game_started_msg"; //$NON-NLS-1$ + /** TODO: describe config option. */ + String CONFIG_AUTO_ADD_DEFAULT_KIT = "config.auto_add_default_kit"; //$NON-NLS-1$ + /** TODO: describe config option. */ + String CONFIG_LAST_MAN_STANDING_WINS = "config.last_man_standing_wins"; //$NON-NLS-1$ + /** TODO: describe config option. */ + String CONFIG_EFFECTS_BLOOD = "config.effects.blood"; //$NON-NLS-1$ + /** TODO: describe config option. */ + String CONFIG_EFFECTS_DMG_IDENTIFIER_HOLO = "config.effects.damage_identifier_holograms"; //$NON-NLS-1$ + /** TODO: describe config option. */ + String CONFIG_EFFECTS_DEAD_IN_FAKE_BED = "config.effects.dead_in_fake_bed"; //$NON-NLS-1$ + /** TODO: describe config option. */ + String CONFIG_EFFECTS_1_8_TITLES = "config.effects.1_8_titles"; //$NON-NLS-1$ + /** TODO: describe config option. */ + String CONFIG_EFFECTS_1_8_SPECTATOR_MODE = "config.effects.1_8_spectator_mode"; //$NON-NLS-1$ + /** TODO: describe config option. */ + String CONFIG_SOUNDS_LOBBY_COUNTDOWN = "config.sounds.lobby_countdown"; //$NON-NLS-1$ + /** TODO: describe config option. */ + String CONFIG_SOUNDS_INGAME_COUNTDOWN = "config.sounds.ingame_countdown"; //$NON-NLS-1$ + /** TODO: describe config option. */ + String CONFIG_CHAT_PER_ARENA_ONLY = "config.chat_per_arena_only"; //$NON-NLS-1$ + /** TODO: describe config option. */ + String CONFIG_CHAT_SHOW_SCORE_IN_ARENA = "config.chat_show_score_in_arena"; //$NON-NLS-1$ + /** TODO: describe config option. */ + String CONFIG_COMPASS_TRACKING_ENABLED = "config.compass_tracking_enabled"; //$NON-NLS-1$ + /** TODO: describe config option. */ + String CONFIG_ALLOW_CLASSES_SELECTION_OUT_OF_ARENAS = "config.allow_classes_selection_out_of_arenas"; //$NON-NLS-1$ + /** TODO: describe config option. */ + String CONFIG_SEND_STATS_ON_STOP = "config.send_stats_on_stop"; //$NON-NLS-1$ + /** TODO: describe config option. */ + String CONFIG_USE_XP_BAR_LEVEL = "config.use_xp_bar_level"; //$NON-NLS-1$ + + /** + * {@code true} for using old reset (from files); {@code false} for using smart reset + * @deprecated will be removed in 1.4.10 + */ + @Deprecated + String CONFIG_USE_OLD_RESET_METHOD = "config.use_old_reset_method"; //$NON-NLS-1$ + + /** TODO: describe config option. */ + String CONFIG_CHAT_ENABLED = "config.chat_enabled"; //$NON-NLS-1$ + + /** TODO: describe config option. */ + String CONFIG_EXTRA_LOBBY_ITEM_PREFIX = "config.extra_lobby_item."; //$NON-NLS-1$ + /** TODO: describe config option. */ + String CONFIG_EXTRA_LOBBY_ITEM_ENABLED_SUFFIX = ".enabled"; //$NON-NLS-1$ + /** TODO: describe config option. */ + String CONFIG_EXTRA_LOBBY_ITEM_ITEM_SUFFIX = ".item"; //$NON-NLS-1$ + /** TODO: describe config option. */ + String CONFIG_EXTRA_LOBBY_ITEM_NAME_SUFFIX = ".name"; //$NON-NLS-1$ + /** TODO: describe config option. */ + String CONFIG_EXTRA_LOBBY_ITEM_COMMAND_SUFFIX = ".command"; //$NON-NLS-1$ + + /** flag to enable mysql */ + String CONFIG_MYSQL_ENABLED = "mysql.enabled"; //$NON-NLS-1$ + /** host name of mysql server */ + String CONFIG_MYSQL_HOST = "mysql.host"; //$NON-NLS-1$ + /** user name of mysql user */ + String CONFIG_MYSQL_USER = "mysql.user"; //$NON-NLS-1$ + /** password to connect to mysql */ + String CONFIG_MYSQL_PW = "mysql.pw"; //$NON-NLS-1$ + /** mysql database name */ + String CONFIG_MYSQL_DATABASE = "mysql.database"; //$NON-NLS-1$ + + /** flag to enable sqlite */ + String CONFIG_SQLITE_ENABLED = "sqlite.enabled"; //$NON-NLS-1$ + /** sqlite database user name */ + String CONFIG_SQLITE_USER = "sqlite.user"; //$NON-NLS-1$ + /** sqlite database password */ + String CONFIG_SQLITE_PW = "sqlite.pw"; //$NON-NLS-1$ + /** sqlite database name/file. */ + String CONFIG_SQLITE_DATABASE = "sqlite.database"; //$NON-NLS-1$ + + /** + * Activation of inventory reset on leave. + */ + String RESET_INVENTORY = "config.reset_on_leave.inventory"; //$NON-NLS-1$ + + /** + * Activation of xp reset on leave. + */ + String RESET_XP = "config.reset_on_leave.xp"; //$NON-NLS-1$ + + /** + * Activation of gamemode reset on leave. + */ + String RESET_GAMEMMODE = "config.reset_on_leave.gamemode"; //$NON-NLS-1$ + +} diff --git a/API/src/main/java/com/comze_instancelabs/minigamesapi/ArenaListener.java b/API/src/main/java/com/comze_instancelabs/minigamesapi/ArenaListener.java index 8789e193..1ed6b3d1 100644 --- a/API/src/main/java/com/comze_instancelabs/minigamesapi/ArenaListener.java +++ b/API/src/main/java/com/comze_instancelabs/minigamesapi/ArenaListener.java @@ -1,7 +1,23 @@ +/* + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ package com.comze_instancelabs.minigamesapi; +import java.io.IOException; import java.util.ArrayList; import java.util.List; +import java.util.logging.Level; import org.bukkit.Bukkit; import org.bukkit.ChatColor; @@ -11,11 +27,16 @@ import org.bukkit.block.Block; import org.bukkit.block.BlockState; import org.bukkit.block.Sign; +import org.bukkit.entity.ArmorStand; import org.bukkit.entity.Arrow; import org.bukkit.entity.Egg; import org.bukkit.entity.EnderPearl; import org.bukkit.entity.Enderman; import org.bukkit.entity.Entity; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.ItemFrame; +import org.bukkit.entity.Minecart; +import org.bukkit.entity.Painting; import org.bukkit.entity.Player; import org.bukkit.entity.Projectile; import org.bukkit.entity.Snowball; @@ -25,6 +46,7 @@ import org.bukkit.event.block.Action; import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.block.BlockBurnEvent; +import org.bukkit.event.block.BlockExplodeEvent; import org.bukkit.event.block.BlockFadeEvent; import org.bukkit.event.block.BlockFromToEvent; import org.bukkit.event.block.BlockPhysicsEvent; @@ -33,11 +55,13 @@ import org.bukkit.event.block.BlockSpreadEvent; import org.bukkit.event.block.LeavesDecayEvent; import org.bukkit.event.block.SignChangeEvent; +import org.bukkit.event.entity.CreatureSpawnEvent; import org.bukkit.event.entity.EntityChangeBlockEvent; import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.entity.EntityDamageEvent.DamageCause; import org.bukkit.event.entity.EntityExplodeEvent; +import org.bukkit.event.entity.EntityTargetEvent; import org.bukkit.event.entity.FoodLevelChangeEvent; import org.bukkit.event.entity.PlayerDeathEvent; import org.bukkit.event.hanging.HangingBreakByEntityEvent; @@ -46,6 +70,7 @@ import org.bukkit.event.player.PlayerBucketEmptyEvent; import org.bukkit.event.player.PlayerCommandPreprocessEvent; import org.bukkit.event.player.PlayerDropItemEvent; +import org.bukkit.event.player.PlayerInteractEntityEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerMoveEvent; @@ -53,1078 +78,2182 @@ import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.event.player.PlayerTeleportEvent; import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; +import org.bukkit.event.vehicle.VehicleMoveEvent; import org.bukkit.event.world.StructureGrowEvent; import org.bukkit.plugin.java.JavaPlugin; +import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; +import com.comze_instancelabs.minigamesapi.util.ArenaScoreboard; import com.comze_instancelabs.minigamesapi.util.ChangeCause; import com.comze_instancelabs.minigamesapi.util.Cuboid; import com.comze_instancelabs.minigamesapi.util.Util; import com.comze_instancelabs.minigamesapi.util.Util.CompassPlayer; import com.comze_instancelabs.minigamesapi.util.Validator; -public class ArenaListener implements Listener { - - JavaPlugin plugin = null; - PluginInstance pli = null; - private String minigame = "minigame"; - - private ArrayList cmds = new ArrayList(); - private String leave_cmd = "/leave"; - - public int loseY = 4; - - public ArenaListener(JavaPlugin plugin, PluginInstance pinstance, String minigame) { - this.plugin = plugin; - this.pli = pinstance; - this.setName(minigame); - this.leave_cmd = plugin.getConfig().getString("config.leave_command"); - } - - public ArenaListener(JavaPlugin plugin, PluginInstance pinstance, String minigame, ArrayList cmds) { - this(plugin, pinstance, minigame); - this.cmds = cmds; - } - - @EventHandler - public void onPlayerDrop(PlayerDropItemEvent event) { - if (pli.containsGlobalPlayer(event.getPlayer().getName())) { - Arena a = pli.global_players.get(event.getPlayer().getName()); - if (a != null) { - if (a.getArenaState() != ArenaState.INGAME && a.getArcadeInstance() == null && !a.isArcadeMain()) { - event.setCancelled(true); - } - if (a.getArenaState() == ArenaState.INGAME && pli.containsGlobalLost(event.getPlayer().getName())) { - event.setCancelled(true); - } - } - } - } - - @EventHandler - public void onPlayerPickupItem(PlayerPickupItemEvent event) { - // spectators shall not pick up items - if (pli.containsGlobalLost(event.getPlayer().getName()) || pli.getSpectatorManager().isSpectating(event.getPlayer())) { - Arena a = pli.global_lost.get(event.getPlayer().getName()); - if (a != null) { - if (a.getArenaState() == ArenaState.INGAME && a.getArcadeInstance() == null) { - event.setCancelled(true); - } - } - } - } - - @EventHandler - public void onInventoryClick(InventoryClickEvent event) { - if (event.getWhoClicked() instanceof Player) { - Player p = (Player) event.getWhoClicked(); - if (pli.containsGlobalPlayer(p.getName())) { - Arena a = pli.global_players.get(p.getName()); - if (a != null) { - if (a.getArenaState() == ArenaState.STARTING && a.getArcadeInstance() == null && !a.isArcadeMain()) { - event.setCancelled(true); - } - } - } - } - } - - @EventHandler(priority = EventPriority.HIGHEST) - public void onMove(PlayerMoveEvent event) { - try { - final Player p = event.getPlayer(); - if (pli.containsGlobalPlayer(p.getName())) { - final Arena a = pli.global_players.get(p.getName()); - if (!pli.containsGlobalLost(p.getName()) && !pli.global_arcade_spectator.containsKey(p.getName())) { - if (a.getArenaState() == ArenaState.INGAME) { - if (p.getLocation().getBlockY() + loseY < a.getSpawns().get(0).getBlockY()) { - if (a.getArenaType() == ArenaType.JUMPNRUN) { - Util.teleportPlayerFixed(p, a.getSpawns().get(0)); - } else { - a.spectate(p.getName()); - } - return; - } - if (a.getBoundaries() != null) { - if (!a.getBoundaries().containsLocWithoutY(p.getLocation())) { - Util.pushBack(a.getSpawns().get(0), p); - } - } - } else if (a.getArenaState() == ArenaState.STARTING || a.getArenaState() == ArenaState.JOIN) { - if (!a.isArcadeMain()) { - if (!a.startedIngameCountdown) { - if (p.getLocation().getBlockY() < 0) { - try { - Util.teleportPlayerFixed(p, a.getWaitingLobbyTemp()); - } catch (Exception e) { - System.out.println("Waiting lobby for arena " + a.getInternalName() + " missing, please fix by setting it. " + e.getMessage()); - } - } - if (a.getLobbyBoundaries() != null && !a.skip_join_lobby) { - if (!a.getLobbyBoundaries().containsLocWithoutY(p.getLocation())) { - Util.pushBack(a.getWaitingLobbyTemp(), p); - } - } - } - } - } - } else { - if (a.getArenaState() == ArenaState.INGAME) { - if (pli.spectator_move_y_lock && event.getPlayer().getLocation().getBlockY() < (a.getSpawns().get(0).getBlockY() + 30D) || event.getPlayer().getLocation().getBlockY() > (a.getSpawns().get(0).getBlockY() + 30D)) { - final float b = p.getLocation().getYaw(); - final float c = p.getLocation().getPitch(); - Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { - @Override - public void run() { - p.setAllowFlight(true); - p.setFlying(true); - if (p.isInsideVehicle()) { - Entity ent = p.getVehicle(); - p.leaveVehicle(); - ent.eject(); - } - p.teleport(new Location(p.getWorld(), p.getLocation().getBlockX(), (a.getSpawns().get(0).getBlockY() + 30D), p.getLocation().getBlockZ(), b, c)); - } - }, 1); - return; - } - - if (a.getSpecBoundaries() != null) { - if (!a.getSpecBoundaries().containsLocWithoutY(p.getLocation())) { - Util.pushBack(a.getSpawns().get(0).clone().add(0D, 30D, 0D), p); - } - return; - } - if (a.getBoundaries() != null) { - if (!a.getBoundaries().containsLocWithoutY(p.getLocation())) { - Util.pushBack(a.getSpawns().get(0).clone().add(0D, 30D, 0D), p); - } - } - } - } - } - } catch (Exception e) { - if (MinigamesAPI.debug) { - e.printStackTrace(); - } - } - - } - - @EventHandler - public void onHunger(FoodLevelChangeEvent event) { - if (event.getEntity() instanceof Player) { - Player p = (Player) event.getEntity(); - if (pli.containsGlobalPlayer(p.getName())) { - if (!pli.global_players.get(p.getName()).isArcadeMain()) { - event.setCancelled(true); - } - } - } - } - - @EventHandler(priority = EventPriority.MONITOR) - public void onPlayerDeath(PlayerDeathEvent event) { - if (pli.containsGlobalPlayer(event.getEntity().getName())) { - event.setDeathMessage(null); - event.getEntity().setHealth(20D); - final Player p = event.getEntity(); - - final Arena arena = pli.global_players.get(p.getName()); - if (arena.getArenaState() == ArenaState.JOIN || (arena.getArenaState() == ArenaState.STARTING && !arena.startedIngameCountdown)) { - if (arena.isArcadeMain()) { - Util.teleportPlayerFixed(p, arena.getWaitingLobbyTemp()); - } - return; - } - - arena.global_drops.addAll(event.getDrops()); - - arena.spectate(p.getName()); - - pli.global_lost.put(p.getName(), arena); - - int count = 0; - // for (String p_ : pli.global_players.keySet()) { - // if (Validator.isPlayerOnline(p_)) { - // if (pli.global_players.get(p_).getInternalName().equalsIgnoreCase(arena.getInternalName())) { - // if (!pli.containsGlobalLost(p_)) { - // count++; - // } - // } - // } - // } - for (String p_ : arena.getAllPlayers()) { - if (Validator.isPlayerOnline(p_)) { - if (!pli.containsGlobalLost(p_)) { - count++; - } - } - } - final int count_ = count; - - Bukkit.getScheduler().runTaskLater(MinigamesAPI.getAPI(), new Runnable() { - public void run() { - if (pli.containsGlobalPlayer(p.getName()) && count_ > 1) { - arena.spectate(p.getName()); - } - for (String p_ : arena.getAllPlayers()) { - if (Validator.isPlayerOnline(p_)) { - Player p__ = Bukkit.getPlayer(p_); - Util.sendMessage(plugin, p__, pli.getMessagesConfig().broadcast_players_left.replaceAll("", arena.getPlayerCount())); - } - } - } - }, 5); - - if (pli.last_man_standing) { - if (count < 2) { - // last man standing - arena.stop(); - } - } - } - } - - @EventHandler - public void onEntityDamage(EntityDamageEvent event) { - if (event.getEntity() instanceof Player) { - Player p = (Player) event.getEntity(); - if (pli.containsGlobalPlayer(p.getName()) && pli.containsGlobalLost(p.getName())) { - Arena a = pli.global_players.get(p.getName()); - if (a.getArenaState() == ArenaState.INGAME && a.getArcadeInstance() == null && !a.getAlwaysPvP()) { - event.setCancelled(true); - } - } - if (event.getCause().equals(DamageCause.ENTITY_ATTACK)) { - if (pli.containsGlobalPlayer(p.getName())) { - Arena a = pli.global_players.get(p.getName()); - if (a.getArenaState() != ArenaState.INGAME && a.getArcadeInstance() == null && !a.getAlwaysPvP()) { - // System.out.println(pli.getPlugin().getName() + " disallowed a pvp action."); - event.setCancelled(true); - } - if (pli.blood_effects && (a.getArenaState() == ArenaState.INGAME || a.getAlwaysPvP()) && !a.isArcadeMain()) { - Effects.playBloodEffect(p); - } - } - if (pli.containsGlobalLost(p.getName()) || pli.getSpectatorManager().isSpectating(p)) { - // System.out.println(pli.getPlugin().getName() + " disallowed a pvp action."); - event.setCancelled(true); - } - } else if (event.getCause().equals(DamageCause.FALL)) { - if (pli.containsGlobalPlayer(p.getName())) { - Arena a = pli.global_players.get(p.getName()); - if (a.getArenaState() != ArenaState.INGAME && a.getArcadeInstance() != null) { - event.setCancelled(true); - } - } - } - } - } - - @EventHandler - public void onEntityDamageByEntity(EntityDamageByEntityEvent event) { - if (event.getEntity() instanceof Player) { - Player p = (Player) event.getEntity(); - Player attacker = null; - if (event.getDamager() instanceof Projectile) { - Projectile projectile = (Projectile) event.getDamager(); - if (projectile.getShooter() instanceof Player) { - attacker = (Player) projectile.getShooter(); - } - } else if (event.getDamager() instanceof Player) { - attacker = (Player) event.getDamager(); - } else { - return; - } - - if (p != null && attacker != null) { - if (pli.containsGlobalPlayer(p.getName()) && pli.containsGlobalPlayer(attacker.getName())) { - if (pli.getSpectatorManager().isSpectating(p)) { - if (event.getDamager() instanceof Arrow) { - p.teleport(p.getLocation().add(0, 3D, 0)); - - Arrow arr = attacker.launchProjectile(Arrow.class); - arr.setShooter(attacker); - arr.setVelocity(((Arrow) event.getDamager()).getVelocity()); - arr.setBounce(false); - - event.setCancelled(true); - event.getDamager().remove(); - } else if (event.getDamager() instanceof Egg) { - p.teleport(p.getLocation().add(0, 3D, 0)); - - Egg egg = attacker.launchProjectile(Egg.class); - egg.setShooter(attacker); - egg.setVelocity(((Egg) event.getDamager()).getVelocity()); - egg.setBounce(false); - - event.setCancelled(true); - event.getDamager().remove(); - } else if (event.getDamager() instanceof Snowball) { - p.teleport(p.getLocation().add(0, 3D, 0)); - - Snowball sb = attacker.launchProjectile(Snowball.class); - sb.setShooter(attacker); - sb.setVelocity(((Snowball) event.getDamager()).getVelocity()); - sb.setBounce(false); - - event.setCancelled(true); - event.getDamager().remove(); - } else if (event.getDamager() instanceof EnderPearl) { - p.teleport(p.getLocation().add(0, 3D, 0)); - - EnderPearl sb = attacker.launchProjectile(EnderPearl.class); - sb.setShooter(attacker); - sb.setVelocity(((EnderPearl) event.getDamager()).getVelocity()); - sb.setBounce(false); - - event.setCancelled(true); - event.getDamager().remove(); - } - event.setCancelled(true); - return; - } - if (pli.containsGlobalLost(attacker.getName())) { - event.setCancelled(true); - return; - } - Arena a = (Arena) pli.global_players.get(p.getName()); - if (a.getArenaState() == ArenaState.INGAME) { - a.lastdamager.put(p.getName(), attacker.getName()); - if (pli.damage_identifier_effects) { - ChatColor c = ChatColor.YELLOW; - if (event.getDamage() >= 5D) { - c = ChatColor.GOLD; - } - if (event.getDamage() >= 9D) { - c = ChatColor.RED; - } - Effects.playHologram(attacker, p.getLocation(), c + Double.toString(event.getDamage()), true, true); - } - } else if (a.getArenaState() == ArenaState.RESTARTING) { - event.setCancelled(true); - } - } - } - } - } - - @EventHandler - public void onPaintingBreak(HangingBreakByEntityEvent event) { - if (event.getRemover() instanceof Player) { - String p_ = ((Player) event.getRemover()).getName(); - if (pli.containsGlobalPlayer(p_)) { - event.setCancelled(true); - } - } - - } - - @EventHandler - public void onExplode(EntityExplodeEvent event) { - for (Arena a : pli.getArenas()) { - if (a.getArenaType() == ArenaType.REGENERATION) { - Cuboid c = a.getBoundaries(); - if (c != null) { - if (event.getEntity() != null) { - if (c.containsLocWithoutY(event.getEntity().getLocation())) { - for (Block b : event.blockList()) { - a.getSmartReset().addChanged(b, b.getType().equals(Material.CHEST)); - } - } - } - } - } - } - } - - @EventHandler - public void onBlockFromTo(BlockFromToEvent event) { - for (Arena a : pli.getArenas()) { - if (a.getArenaType() == ArenaType.REGENERATION) { - Cuboid c = a.getBoundaries(); - if (c != null) { - if (c.containsLocWithoutYD(event.getBlock().getLocation())) { - if (a.getArenaState() == ArenaState.INGAME) { - a.getSmartReset().addChanged(event.getToBlock(), event.getToBlock().getType().equals(Material.CHEST), ChangeCause.FROM_TO); - } else if (a.getArenaState() == ArenaState.RESTARTING) { - event.setCancelled(true); - } - } - } - } - } - } - - @EventHandler - public void onBlockFade(BlockFadeEvent event) { - for (Arena a : pli.getArenas()) { - if (a.getArenaType() == ArenaType.REGENERATION && a.getArenaState() == ArenaState.INGAME) { - Cuboid c = a.getBoundaries(); - if (c != null) { - if (c.containsLocWithoutY(event.getBlock().getLocation())) { - a.getSmartReset().addChanged(event.getBlock(), event.getBlock().getType().equals(Material.CHEST), ChangeCause.FADE); - } - } - } - } - } - - @EventHandler - public void onLeavesDecay(LeavesDecayEvent event) { - for (Arena a : pli.getArenas()) { - if (a.getArenaType() == ArenaType.REGENERATION && a.getArenaState() == ArenaState.INGAME) { - Cuboid c = a.getBoundaries(); - if (c != null) { - if (c.containsLocWithoutY(event.getBlock().getLocation())) { - a.getSmartReset().addChanged(event.getBlock(), event.getBlock().getType().equals(Material.CHEST)); - } - } - } - } - } - - @EventHandler - public void onBlockPhysics(BlockPhysicsEvent event) { - for (Arena a : pli.getArenas()) { - if (a.getArenaType() == ArenaType.REGENERATION) { - Cuboid c = a.getBoundaries(); - if (c != null) { - if (a.getArenaState() == ArenaState.INGAME) { - if (c.containsLocWithoutY(event.getBlock().getLocation())) { - if (event.getChangedType() == Material.CARPET || event.getChangedType() == Material.BED_BLOCK) { - return; - } - a.getSmartReset().addChanged(event.getBlock(), event.getBlock().getType().equals(Material.CHEST), ChangeCause.PHYSICS); - } - } else if (a.getArenaState() == ArenaState.RESTARTING) { - event.setCancelled(true); - } - } - } - } - } - - @EventHandler - public void onBlockRedstone(BlockRedstoneEvent event) { - for (Arena a : pli.getArenas()) { - if (a.getArenaType() == ArenaType.REGENERATION) { - Cuboid c = a.getBoundaries(); - if (c != null) { - if (a.getArenaState() == ArenaState.INGAME) { - event.getBlock().setData((byte) 0); // Reset redstone before adding it to smartreset index - a.getSmartReset().addChanged(event.getBlock(), false); - } - } - } - } - } - - @EventHandler - public void onBlockSpread(BlockSpreadEvent event) { - // disallow fire spread while the arena restarts - for (Arena a : pli.getArenas()) { - if (a.getArenaType() == ArenaType.REGENERATION) { - Cuboid c = a.getBoundaries(); - if (c != null) { - if (a.getArenaState() == ArenaState.INGAME) { - a.getSmartReset().addChanged(event.getBlock().getLocation(), Material.AIR, (byte) 0); - } else if (a.getArenaState() == ArenaState.RESTARTING) { - event.setCancelled(true); - } - } - } - } - } - - @EventHandler - public void onEntityChangeBlock(EntityChangeBlockEvent event) { - if (event.getEntity() instanceof Enderman) { - for (Arena a : pli.getArenas()) { - if (a.getArenaType() == ArenaType.REGENERATION) { - Cuboid c = a.getBoundaries(); - if (c != null) { - if (c.containsLocWithoutY(event.getEntity().getLocation())) { - a.getSmartReset().addChanged(event.getBlock(), event.getBlock().getType().equals(Material.CHEST), ChangeCause.ENTITY_CHANGE); - } - } - } - } - } - } - - @EventHandler(priority = EventPriority.HIGH) - public void onBlockBreak(BlockBreakEvent event) { - Player p = event.getPlayer(); - if (pli.containsGlobalPlayer(p.getName())) { - Arena a = pli.global_players.get(p.getName()); - if (a.getArenaState() != ArenaState.INGAME || pli.containsGlobalLost(p.getName())) { - event.setCancelled(true); - return; - } - if (pli.getSpectatorManager().isSpectating(p)) { - event.setCancelled(true); - return; - } - a.getSmartReset().addChanged(event.getBlock(), event.getBlock().getType().equals(Material.CHEST), ChangeCause.BREAK); - if (event.getBlock().getType() == Material.DOUBLE_PLANT) { - a.getSmartReset().addChanged(event.getBlock().getLocation().clone().add(0D, -1D, 0D).getBlock(), event.getBlock().getLocation().clone().add(0D, -1D, 0D).getBlock().getType().equals(Material.CHEST)); - a.getSmartReset().addChanged(event.getBlock().getLocation().clone().add(0D, +1D, 0D).getBlock(), event.getBlock().getLocation().clone().add(0D, +1D, 0D).getBlock().getType().equals(Material.CHEST)); - } - if (event.getBlock().getType() == Material.SNOW || event.getBlock().getType() == Material.SNOW_BLOCK) { - a.getSmartReset().addChanged(event.getBlock().getLocation().clone().add(0D, +3D, 0D).getBlock(), event.getBlock().getLocation().clone().add(0D, +3D, 0D).getBlock().getType().equals(Material.CHEST)); - a.getSmartReset().addChanged(event.getBlock().getLocation().clone().add(0D, +2D, 0D).getBlock(), event.getBlock().getLocation().clone().add(0D, +2D, 0D).getBlock().getType().equals(Material.CHEST)); - a.getSmartReset().addChanged(event.getBlock().getLocation().clone().add(0D, +1D, 0D).getBlock(), event.getBlock().getLocation().clone().add(0D, +1D, 0D).getBlock().getType().equals(Material.CHEST)); - } - if (event.getBlock().getType() == Material.CARPET) { - a.getSmartReset().addChanged(event.getBlock().getLocation().clone().add(0D, +3D, 0D).getBlock(), event.getBlock().getLocation().clone().add(0D, +3D, 0D).getBlock().getType().equals(Material.CHEST)); - a.getSmartReset().addChanged(event.getBlock().getLocation().clone().add(0D, +2D, 0D).getBlock(), event.getBlock().getLocation().clone().add(0D, +2D, 0D).getBlock().getType().equals(Material.CHEST)); - a.getSmartReset().addChanged(event.getBlock().getLocation().clone().add(0D, +1D, 0D).getBlock(), event.getBlock().getLocation().clone().add(0D, +1D, 0D).getBlock().getType().equals(Material.CHEST)); - } - if (event.getBlock().getType() == Material.CACTUS) { - a.getSmartReset().addChanged(event.getBlock().getLocation().clone().add(0D, +4D, 0D).getBlock(), event.getBlock().getLocation().clone().add(0D, +4D, 0D).getBlock().getType().equals(Material.CHEST)); - a.getSmartReset().addChanged(event.getBlock().getLocation().clone().add(0D, +3D, 0D).getBlock(), event.getBlock().getLocation().clone().add(0D, +3D, 0D).getBlock().getType().equals(Material.CHEST)); - a.getSmartReset().addChanged(event.getBlock().getLocation().clone().add(0D, +2D, 0D).getBlock(), event.getBlock().getLocation().clone().add(0D, +2D, 0D).getBlock().getType().equals(Material.CHEST)); - a.getSmartReset().addChanged(event.getBlock().getLocation().clone().add(0D, +1D, 0D).getBlock(), event.getBlock().getLocation().clone().add(0D, +1D, 0D).getBlock().getType().equals(Material.CHEST)); - } - if (event.getBlock().getType() == Material.BED_BLOCK) { - a.getSmartReset().addChanged(event.getBlock().getLocation().clone().add(1D, 0D, 0D).getBlock(), event.getBlock().getLocation().clone().add(1D, 0D, 1D).getBlock().getType().equals(Material.CHEST)); - a.getSmartReset().addChanged(event.getBlock().getLocation().clone().add(-1D, 0D, 0D).getBlock(), event.getBlock().getLocation().clone().add(1D, 0D, -1D).getBlock().getType().equals(Material.CHEST)); - a.getSmartReset().addChanged(event.getBlock().getLocation().clone().add(0D, 0D, 1D).getBlock(), event.getBlock().getLocation().clone().add(-1D, 0D, 1D).getBlock().getType().equals(Material.CHEST)); - a.getSmartReset().addChanged(event.getBlock().getLocation().clone().add(0D, 0D, -1D).getBlock(), event.getBlock().getLocation().clone().add(-1D, 0D, -1D).getBlock().getType().equals(Material.CHEST)); - } - } - if (event.getBlock().getType() == Material.SIGN_POST || event.getBlock().getType() == Material.WALL_SIGN) { - Arena arena = Util.getArenaBySignLocation(plugin, event.getBlock().getLocation()); - if (arena != null) { - pli.getArenasConfig().getConfig().set("arenas." + arena.getInternalName() + ".sign", null); - pli.getArenasConfig().saveConfig(); - } - } - } - - @EventHandler - public void onBlockBurn(BlockBurnEvent event) { - for (Arena a : pli.getArenas()) { - if (Validator.isArenaValid(plugin, a) && a.getArenaType() == ArenaType.REGENERATION) { - Cuboid c = new Cuboid(Util.getComponentForArena(plugin, a.getInternalName(), "bounds.low"), Util.getComponentForArena(plugin, a.getInternalName(), "bounds.high")); - if (c != null) { - if (c.containsLocWithoutY(event.getBlock().getLocation())) { - a.getSmartReset().addChanged(event.getBlock(), event.getBlock().getType().equals(Material.CHEST), ChangeCause.BURN); - } - } - } - } - } - - @EventHandler(priority = EventPriority.HIGHEST) - public void onPlayerBucketEmpty(PlayerBucketEmptyEvent event) { - if (pli.containsGlobalPlayer(event.getPlayer().getName())) { - Arena a = pli.global_players.get(event.getPlayer().getName()); - Block start = event.getBlockClicked(); - if (!a.getBoundaries().containsLocWithoutY(start.getLocation())) { - event.setCancelled(true); - return; - } - for (int x = -2; x < 2; x++) { - for (int y = -2; y < 2; y++) { - for (int z = -2; z < 2; z++) { - Block b = start.getLocation().clone().add(x, y, z).getBlock(); - a.getSmartReset().addChanged(b, b.getType().equals(Material.CHEST)); - } - } - } - } - } - - @EventHandler - public void onStructureGrow(StructureGrowEvent event) { - for (Arena a : pli.getArenas()) { - if (a.getArenaType() == ArenaType.REGENERATION && a.getArenaState() == ArenaState.INGAME) { - Cuboid c = new Cuboid(Util.getComponentForArena(plugin, a.getInternalName(), "bounds.low"), Util.getComponentForArena(plugin, a.getInternalName(), "bounds.high")); - if (c != null) { - Location start = event.getLocation(); - if (c.containsLocWithoutY(start)) { - a.getSmartReset().addChanged(start.getBlock(), false); - for (BlockState bs : event.getBlocks()) { - Block b = bs.getBlock(); - a.getSmartReset().addChanged(b.getLocation(), Material.AIR, (byte) 0); - } - } - } - } - } - } - - @EventHandler(priority = EventPriority.HIGH) - public void onBlockPlace(BlockPlaceEvent event) { - Player p = event.getPlayer(); - if (pli.containsGlobalPlayer(p.getName())) { - Arena a = pli.global_players.get(p.getName()); - if (a.getArenaState() != ArenaState.INGAME || pli.containsGlobalLost(p.getName()) || pli.getSpectatorManager().isSpectating(p)) { - event.setCancelled(true); - return; - } - if (event.getBlockReplacedState().getType() != Material.AIR) { - a.getSmartReset().addChanged(event.getBlock().getLocation(), event.getBlockReplacedState().getType(), event.getBlockReplacedState().getData().getData()); - } else { - a.getSmartReset().addChanged(event.getBlock().getLocation(), Material.AIR, (byte) 0); - } - } - if (pli.getStatsInstance().skullsetup.contains(p.getName())) { - if (event.getBlock().getType() == Material.SKULL_ITEM || event.getBlock().getType() == Material.SKULL) { - if (event.getItemInHand().hasItemMeta()) { - pli.getStatsInstance().saveSkull(event.getBlock().getLocation(), Integer.parseInt(event.getItemInHand().getItemMeta().getDisplayName())); - pli.getStatsInstance().skullsetup.remove(p.getName()); - } - } - } - } - - @EventHandler - public void onSignUse(PlayerInteractEvent event) { - if (event.hasBlock()) { - if (event.getClickedBlock().getType() == Material.SIGN_POST || event.getClickedBlock().getType() == Material.WALL_SIGN || event.getClickedBlock().getType() == Material.SIGN) { - if (event.getClickedBlock().getType() == Material.FIRE) { - return; - } - if (event.getAction() != Action.RIGHT_CLICK_BLOCK) { - return; - } - final Sign s = (Sign) event.getClickedBlock().getState(); - // people will most likely do strange formats, so let's just try - // to get signs by location rather than locally by reading the sign - Arena arena = Util.getArenaBySignLocation(plugin, event.getClickedBlock().getLocation()); - if (arena != null) { - Player p = event.getPlayer(); - if (!arena.containsPlayer(p.getName())) { - arena.joinPlayerLobby(p.getName()); - } else { - Util.sendMessage(plugin, p, pli.getMessagesConfig().you_already_are_in_arena.replaceAll("", arena.getInternalName())); - } - } else { - // try getting random sign - Location l = Util.getComponentForArenaRaw(plugin, "random", "sign"); - if (l != null) { - if (l.getWorld() != null) { - if (l.getWorld().getName().equalsIgnoreCase(s.getLocation().getWorld().getName())) { - if (l.distance(s.getLocation()) < 1) { - for (Arena a : pli.getArenas()) { - if (a.getArenaState() == ArenaState.JOIN || a.getArenaState() == ArenaState.STARTING) { - if (!a.containsPlayer(event.getPlayer().getName())) { - a.joinPlayerLobby(event.getPlayer().getName()); - return; - } - } - } - } - } - } - } - // try getting leave sign - if (pli.containsGlobalPlayer(event.getPlayer().getName())) { - int count = 0; - if (pli.getArenasConfig().getConfig().isSet("arenas.leave")) { - for (String str : pli.getArenasConfig().getConfig().getConfigurationSection("arenas.leave.").getKeys(false)) { - Location loc = Util.getComponentForArenaRaw(plugin, "leave." + str, "sign"); - if (loc != null) { - if (loc.getWorld() != null) { - if (loc.getWorld().getName().equalsIgnoreCase(s.getLocation().getWorld().getName())) { - if (loc.distance(s.getLocation()) < 1) { - pli.global_players.get(event.getPlayer().getName()).leavePlayer(event.getPlayer().getName(), false, false); - return; - } - } - } - } - } - } - } - } - } else if (event.getClickedBlock().getType() == Material.CHEST) { - Player p = event.getPlayer(); - if (pli.containsGlobalPlayer(p.getName())) { - Arena a = pli.global_players.get(p.getName()); - if (a.getArenaState() == ArenaState.INGAME) { - a.getSmartReset().addChanged(event.getClickedBlock(), true); - } - } - } else if (event.getClickedBlock().getType() == Material.TNT) { - Player p = event.getPlayer(); - if (pli.containsGlobalPlayer(p.getName())) { - Arena a = pli.global_players.get(p.getName()); - if (a.getArenaState() == ArenaState.INGAME) { - a.getSmartReset().addChanged(event.getClickedBlock(), false); - // TODO maybe add radius of blocks around this tnt manually - } - } - } else if (event.getPlayer().getItemInHand().getType() == Material.WATER_BUCKET || event.getPlayer().getItemInHand().getType() == Material.WATER || event.getPlayer().getItemInHand().getType() == Material.LAVA_BUCKET || event.getPlayer().getItemInHand().getType() == Material.LAVA) { - Player p = event.getPlayer(); - if (pli.containsGlobalPlayer(p.getName())) { - Arena a = pli.global_players.get(p.getName()); - if (!a.getBoundaries().containsLocWithoutY(event.getClickedBlock().getLocation())) { - event.setCancelled(true); - return; - } - if (a.getArenaState() == ArenaState.INGAME) { - a.getSmartReset().addChanged(event.getClickedBlock(), event.getClickedBlock().getType().equals(Material.CHEST)); - // a.getSmartReset().addChanged(event.getClickedBlock().getLocation().add(0D, 1D, 0D)); - } - } - } else if (event.getClickedBlock().getType() == Material.DISPENSER || event.getClickedBlock().getType() == Material.DROPPER) { - Player p = event.getPlayer(); - if (pli.containsGlobalPlayer(p.getName())) { - Arena a = pli.global_players.get(p.getName()); - if (a.getArenaState() == ArenaState.INGAME) { - a.getSmartReset().addChanged(event.getClickedBlock(), false); - } - } - } - } - - if (pli.containsGlobalLost(event.getPlayer().getName()) || pli.getSpectatorManager().isSpectating(event.getPlayer())) { - event.setCancelled(true); - } - - if (event.hasItem()) { - final Player p = event.getPlayer(); - if (!pli.containsGlobalPlayer(p.getName())) { - return; - } - Arena a = pli.global_players.get(p.getName()); - if (a.isArcadeMain()) { - return; - } - if (event.getItem().getTypeId() == plugin.getConfig().getInt("config.selection_items.classes_selection_item")) { - if (a.getArenaState() != ArenaState.INGAME) { - pli.getClassesHandler().openGUI(p.getName()); - event.setCancelled(true); - } - } else if (event.getItem().getTypeId() == plugin.getConfig().getInt("config.selection_items.exit_item")) { - if (a.getArenaState() != ArenaState.INGAME) { - a.leavePlayer(p.getName(), false, false); - event.setCancelled(true); - } else { - if (pli.containsGlobalLost(p.getName())) { - a.leavePlayer(p.getName(), false, false); - event.setCancelled(true); - } - } - } else if (event.getItem().getTypeId() == plugin.getConfig().getInt("config.selection_items.spectator_item")) { - if (pli.containsGlobalLost(p.getName())) { - pli.getSpectatorManager().openSpectatorGUI(p, a); - event.setCancelled(true); - } - } else if (event.getItem().getTypeId() == plugin.getConfig().getInt("config.selection_items.achievement_item")) { - if (pli.isAchievementGuiEnabled()) { - if (a.getArenaState() != ArenaState.INGAME) { - pli.getArenaAchievements().openGUI(p.getName(), false); - event.setCancelled(true); - } - } - } else if (event.getItem().getTypeId() == plugin.getConfig().getInt("config.selection_items.shop_selection_item")) { - if (a.getArenaState() != ArenaState.INGAME) { - pli.getShopHandler().openGUI(p.getName()); - event.setCancelled(true); - } - } else if (event.getItem().getTypeId() == plugin.getConfig().getInt("config.extra_lobby_item.item0.item")) { - if (plugin.getConfig().getBoolean("config.extra_lobby_item.item0.enabled")) { - if (a.getArenaState() != ArenaState.INGAME) { - // Bukkit.dispatchCommand(Bukkit.getConsoleSender(), plugin.getConfig().getString("config.extra_lobby_item.item0.command")); - p.performCommand(plugin.getConfig().getString("config.extra_lobby_item.item0.command")); - } - } - } - if (event.getItem().getType() == Material.COMPASS) { - if (a.getArenaState() == ArenaState.INGAME) { - if (plugin.getConfig().getBoolean("config.compass_tracking_enabled")) { - CompassPlayer temp = Util.getNearestPlayer(p, a); - if (temp.getPlayer() != null) { - p.sendMessage(pli.getMessagesConfig().compass_player_found.replaceAll("", temp.getPlayer().getName()).replaceAll("", Integer.toString((int) Math.round(temp.getDistance())))); - p.setCompassTarget(temp.getPlayer().getLocation()); - } else { - p.sendMessage(pli.getMessagesConfig().compass_no_player_found); - } - } - } - } - } - } - - @EventHandler - public void onSignChange(SignChangeEvent event) { - Player p = event.getPlayer(); - if (event.getLine(0).toLowerCase().equalsIgnoreCase(getName())) { - if (event.getPlayer().hasPermission("mgapi.sign") || event.getPlayer().isOp()) { - if (!event.getLine(1).equalsIgnoreCase("")) { - String arena = event.getLine(1); - if (arena.equalsIgnoreCase("random")) { - pli.getArenasConfig().getConfig().set("arenas." + arena + ".sign.world", p.getWorld().getName()); - pli.getArenasConfig().getConfig().set("arenas." + arena + ".sign.location.x", event.getBlock().getLocation().getBlockX()); - pli.getArenasConfig().getConfig().set("arenas." + arena + ".sign.location.y", event.getBlock().getLocation().getBlockY()); - pli.getArenasConfig().getConfig().set("arenas." + arena + ".sign.location.z", event.getBlock().getLocation().getBlockZ()); - pli.getArenasConfig().saveConfig(); - Util.sendMessage(plugin, p, pli.getMessagesConfig().successfully_set.replaceAll("", "arena (random) sign")); - Util.updateSign(plugin, event, arena); - } else if (arena.equalsIgnoreCase("leave")) { - int count = 0; - if (pli.getArenasConfig().getConfig().isSet("arenas.leave")) { - for (String s : pli.getArenasConfig().getConfig().getConfigurationSection("arenas.leave.").getKeys(false)) { - count++; - } - } - pli.getArenasConfig().getConfig().set("arenas." + arena + "." + count + ".sign.world", p.getWorld().getName()); - pli.getArenasConfig().getConfig().set("arenas." + arena + "." + count + ".sign.location.x", event.getBlock().getLocation().getBlockX()); - pli.getArenasConfig().getConfig().set("arenas." + arena + "." + count + ".sign.location.y", event.getBlock().getLocation().getBlockY()); - pli.getArenasConfig().getConfig().set("arenas." + arena + "." + count + ".sign.location.z", event.getBlock().getLocation().getBlockZ()); - pli.getArenasConfig().saveConfig(); - Util.sendMessage(plugin, p, pli.getMessagesConfig().successfully_set.replaceAll("", "arena (leave) sign")); - Util.updateSign(plugin, event, arena); - } else { - if (Validator.isArenaValid(plugin, arena)) { - pli.getArenasConfig().getConfig().set("arenas." + arena + ".sign.world", p.getWorld().getName()); - pli.getArenasConfig().getConfig().set("arenas." + arena + ".sign.loc.x", event.getBlock().getLocation().getBlockX()); - pli.getArenasConfig().getConfig().set("arenas." + arena + ".sign.loc.y", event.getBlock().getLocation().getBlockY()); - pli.getArenasConfig().getConfig().set("arenas." + arena + ".sign.loc.z", event.getBlock().getLocation().getBlockZ()); - pli.getArenasConfig().saveConfig(); - Util.sendMessage(plugin, p, pli.getMessagesConfig().successfully_set.replaceAll("", "arena sign")); - } else { - Util.sendMessage(plugin, p, pli.getMessagesConfig().arena_invalid.replaceAll("", arena)); - event.getBlock().breakNaturally(); - } - - Arena a = pli.getArenaByName(arena); - if (a != null) { - a.setSignLocation(event.getBlock().getLocation()); - Util.updateSign(plugin, a, event); - } else { - Util.sendMessage(plugin, p, pli.getMessagesConfig().arena_not_initialized); - } - } - } - } - } - } - - @EventHandler - public void onPlayerJoin(PlayerJoinEvent event) { - final Player p = event.getPlayer(); - pli.getStatsInstance().update(p.getName()); - if (pli.containsGlobalPlayer(p.getName())) { - pli.global_players.remove(p.getName()); - } - if (pli.containsGlobalLost(p.getName())) { - pli.global_lost.remove(p.getName()); - } - if (plugin.getConfig().isSet("temp.left_players." + p.getName())) { - Bukkit.getScheduler().runTaskLater(MinigamesAPI.getAPI(), new Runnable() { - public void run() { - Util.teleportPlayerFixed(p, Util.getMainLobby(plugin)); - p.setFlying(false); - try { - p.getInventory().clear(); - p.updateInventory(); - if (plugin.getConfig().isSet("temp.left_players." + p.getName() + ".items")) { - for (String key : plugin.getConfig().getConfigurationSection("temp.left_players." + p.getName() + ".items").getKeys(false)) { - p.getInventory().addItem(plugin.getConfig().getItemStack("temp.left_players." + p.getName() + ".items." + key)); - } - } - p.updateInventory(); - p.setWalkSpeed(0.2F); - p.removePotionEffect(PotionEffectType.JUMP); - p.setGameMode(GameMode.SURVIVAL); - pli.getSpectatorManager().setSpectate(p, false); - } catch (Exception e) { - e.printStackTrace(); - Util.sendMessage(plugin, p, ChatColor.RED + "Failed restoring your stuff. Did the server restart/reload while you were offline?"); - } - plugin.getConfig().set("temp.left_players." + p.getName(), null); - plugin.saveConfig(); - } - }, 5); - } - - if (plugin.getConfig().getBoolean("config.bungee.game_on_join")) { - int c = 0; - final List arenas = new ArrayList(); - for (String arena : pli.getArenasConfig().getConfig().getKeys(false)) { - if (!arena.equalsIgnoreCase("mainlobby") && !arena.equalsIgnoreCase("strings") && !arena.equalsIgnoreCase("config")) { - c++; - arenas.add(arena); - } - } - if (c < 1) { - MinigamesAPI.getAPI().getLogger().severe("Couldn't find any arena even though game_on_join was turned on. Please setup an arena to fix this!"); - return; - } - - Bukkit.getScheduler().runTaskLater(MinigamesAPI.getAPI(), new Runnable() { - public void run() { - if (p != null) { - pli.getArenas().get(0).joinPlayerLobby(p.getName()); - } - } - }, 30L); - } - } - - @EventHandler - public void onPlayerLeave(PlayerQuitEvent event) { - if (pli.containsGlobalPlayer(event.getPlayer().getName())) { - Arena arena = pli.global_players.get(event.getPlayer().getName()); - MinigamesAPI.getAPI().getLogger().info(event.getPlayer().getName() + " quit while in arena " + arena.getInternalName() + "."); - int count = 0; - for (String p_ : pli.global_players.keySet()) { - if (pli.global_players.get(p_).getInternalName().equalsIgnoreCase(arena.getInternalName())) { - count++; - } - } - - arena.leavePlayer(event.getPlayer().getName(), true, false); - - try { - Util.updateSign(plugin, arena); - } catch (Exception e) { - MinigamesAPI.getAPI().getLogger().warning("Error occurred while refreshing sign. " + e.getMessage()); - if (MinigamesAPI.debug) { - e.printStackTrace(); - } - } - } - if (MinigamesAPI.getAPI().global_party.containsKey(event.getPlayer().getName())) { - MinigamesAPI.getAPI().global_party.get(event.getPlayer().getName()).disband(); - } - Party party_ = null; - for (Party party : MinigamesAPI.getAPI().global_party.values()) { - if (party.containsPlayer(event.getPlayer().getName())) { - party_ = party; - break; - } - } - if (party_ != null) { - party_.removePlayer(event.getPlayer().getName()); - } - } - - @EventHandler(priority = EventPriority.MONITOR) - public void onChat(final AsyncPlayerChatEvent event) { - Player p = event.getPlayer(); - if (!pli.chat_enabled) { - if (pli.containsGlobalPlayer(p.getName())) { - event.setCancelled(true); - return; - } - } - if (plugin.getConfig().getBoolean("config.chat_show_score_in_arena")) { - if (pli.containsGlobalPlayer(event.getPlayer().getName())) { - event.setFormat(ChatColor.GRAY + "[" + ChatColor.GREEN + pli.getStatsInstance().getPoints(event.getPlayer().getName()) + ChatColor.GRAY + "] " + event.getFormat()); - } - } - if (plugin.getConfig().getBoolean("config.chat_per_arena_only")) { - if (pli.containsGlobalPlayer(p.getName())) { - String msg = String.format(event.getFormat(), p.getName(), event.getMessage()); - for (Player receiver : event.getRecipients()) { - if (pli.containsGlobalPlayer(receiver.getName())) { - if (pli.global_players.get(receiver.getName()) == pli.global_players.get(p.getName())) { - receiver.sendMessage(msg); - } - } - } - event.setCancelled(true); - } - } - } - - @EventHandler - public void onPlayerCommandPreprocessEvent(PlayerCommandPreprocessEvent event) { - if (event.getMessage().equalsIgnoreCase(leave_cmd) || event.getMessage().equalsIgnoreCase("/l")) { - if (pli.containsGlobalPlayer(event.getPlayer().getName())) { - Arena arena = pli.global_players.get(event.getPlayer().getName()); - arena.leavePlayer(event.getPlayer().getName(), false, false); - event.setCancelled(true); - return; - } - } - if (pli.containsGlobalPlayer(event.getPlayer().getName()) && !event.getPlayer().isOp()) { - if (!plugin.getConfig().getBoolean("config.disable_commands_in_arena")) { - return; - } - if (plugin.getConfig().getString("config.command_whitelist").toLowerCase().contains(event.getMessage().toLowerCase())) { - return; - } - boolean cont = false; - for (String cmd : cmds) { - if (event.getMessage().toLowerCase().startsWith(cmd.toLowerCase())) { - cont = true; - } - } - if (!cont) { - Util.sendMessage(plugin, event.getPlayer(), pli.getMessagesConfig().you_can_leave_with.replaceAll("", leave_cmd)); - event.setCancelled(true); - return; - } - } - } - - // TP Fix start - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onPlayerTeleport(PlayerTeleportEvent event) { - if (event.getCause().equals(TeleportCause.UNKNOWN) && pli.spectator_mode_1_8) { - // Don't hide/show players when 1.8 spectator mode is enabled - return; - } - final Player player = event.getPlayer(); - if (pli.containsGlobalPlayer(player.getName())) { - final int visibleDistance = 16; - Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { - @Override - public void run() { - final List nearby = getPlayersWithin(player, visibleDistance); - updateEntities(nearby, false); - Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { - @Override - public void run() { - updateEntities(nearby, true); - } - }, 1); - } - }, 5L); - } - } - - private void updateEntities(List players, boolean visible) { - for (Player observer : players) { - for (Player player : players) { - if (observer.getEntityId() != player.getEntityId()) { - if (visible && !pli.containsGlobalLost(player.getName())) - observer.showPlayer(player); - else - observer.hidePlayer(player); - } - } - } - } - - private List getPlayersWithin(Player player, int distance) { - List res = new ArrayList(); - int d2 = distance * distance; - for (Player p : Bukkit.getServer().getOnlinePlayers()) { - if (p.getWorld() == player.getWorld() && p.getLocation().distanceSquared(player.getLocation()) <= d2) { - res.add(p); - } - } - return res; - } - - // TP Fix end - - public String getName() { - return minigame; - } - - public void setName(String minigame) { - this.minigame = minigame; - } - +/** + * Bukkit event listener for minigames-lib; one instance per minigame plugin. + * + * @author instancelabs + */ +public class ArenaListener implements Listener +{ + + /** minigame plugin. */ + private JavaPlugin plugin = null; + + /** reference to internal representation of minigames plugin. */ + private PluginInstance pli = null; + + /** name of the minigame. */ + private String minigame = "minigame"; //$NON-NLS-1$ + + /** the commands that we use. */ + private ArrayList cmds = new ArrayList<>(); + + /** the leave command. */ + private String leave_cmd = "/leave"; //$NON-NLS-1$ + + public int loseY = 4; + + /** + * Constructor to create the arena listener. + * + * @param plugin + * minigame plugin + * @param pinstance + * internal representation of minigame plugin + * @param minigame + * name of the minigame. + */ + public ArenaListener(final JavaPlugin plugin, final PluginInstance pinstance, final String minigame) + { + this.plugin = plugin; + this.pli = pinstance; + this.setName(minigame); + this.leave_cmd = plugin.getConfig().getString(ArenaConfigStrings.CONFIG_LEAVE_COMMAND); + } + + /** + * Constructor to create the arena listener. + * + * @param plugin + * minigame plugin + * @param pinstance + * internal representation of minigame plugin + * @param minigame + * name of the minigame. + * @param cmds + * the commands that we use + */ + public ArenaListener(final JavaPlugin plugin, final PluginInstance pinstance, final String minigame, final ArrayList cmds) + { + this(plugin, pinstance, minigame); + this.cmds = cmds; + } + + // ************************* + // ***** smart reset support + // ************************* + + /** + * entity explode event. + * + *

+ * Registers the block changes for smart resets. + * At the end of the game the blocks will reset to original state. + * Only available by REGENERATION arena types and for blocks within the arena boundaries. + *

+ * + * @param event + * event object + */ + @EventHandler(priority = EventPriority.HIGH) + public void onExplode(final EntityExplodeEvent event) + { + for (final Arena a : this.pli.getArenas()) + { + if (a.getArenaType() == ArenaType.REGENERATION) + { + final Cuboid c = a.getBoundaries(); + if (c != null) + { + if (event.getEntity() != null) + { + if (c.containsLocWithoutY(event.getEntity().getLocation())) + { + for (final Block b : event.blockList()) + { + a.getSmartReset().addChanged(b); + } + } + } + } + } + } + } + + /** + * block explode event. + * + *

+ * Registers the block changes for smart resets. + * At the end of the game the blocks will reset to original state. + * Only available by REGENERATION arena types and for blocks within the arena boundaries. + *

+ * + * @param event + * event object + */ + @EventHandler(priority = EventPriority.HIGH) + public void onExplode2(final BlockExplodeEvent event) + { + for (final Arena a : this.pli.getArenas()) + { + if (a.getArenaType() == ArenaType.REGENERATION) + { + final Cuboid c = a.getBoundaries(); + if (c != null) + { + for (final Block b : event.blockList()) + { + if (c.containsLocWithoutY(b.getLocation())) + { + a.getSmartReset().addChanged(b); + } + } + } + } + } + } + + /** + * Block from/to event. + * + *

+ * Registers the block changes for smart resets. + * At the end of the game the blocks will reset to original state. + * Only available by REGENERATION arena types and for blocks within the arena boundaries. + *

+ * + *

+ * Will cancel the event during RESTARTING phase of the arena. + *

+ * + * @param event + * event object + */ + @EventHandler(priority = EventPriority.HIGH) + public void onBlockFromTo(final BlockFromToEvent event) + { + for (final Arena a : this.pli.getArenas()) + { + if (a.getArenaType() == ArenaType.REGENERATION) + { + final Cuboid c = a.getBoundaries(); + if (c != null) + { + if (c.containsLocWithoutYD(event.getBlock().getLocation())) + { + if (a.getArenaState() == ArenaState.INGAME) + { + a.getSmartReset().addChanged(event.getToBlock()); + } + else if (a.getArenaState() == ArenaState.RESTARTING) + { + event.setCancelled(true); + } + } + } + } + } + } + + /** + * Block fade event. + * + *

+ * Registers the block changes for smart resets. + * At the end of the game the blocks will reset to original state. + * Only available by REGENERATION arena types and for blocks within the arena boundaries and while in INGAME arena state. + *

+ * + * @param event + * event object + */ + @EventHandler(priority = EventPriority.HIGH) + public void onBlockFade(final BlockFadeEvent event) + { + for (final Arena a : this.pli.getArenas()) + { + if (a.getArenaType() == ArenaType.REGENERATION && a.getArenaState() == ArenaState.INGAME) + { + final Cuboid c = a.getBoundaries(); + if (c != null) + { + if (c.containsLocWithoutY(event.getBlock().getLocation())) + { + a.getSmartReset().addChanged(event.getBlock()); + } + } + } + } + } + + /** + * Block physics event. + * + *

+ * Registers the block changes for smart resets. + * At the end of the game the blocks will reset to original state. + * Only available by REGENERATION arena types and for blocks within the arena boundaries and while in INGAME arena state. + *

+ * + *

+ * Ignores materials: carpet and red_block (=bed). + *

+ * + *

+ * Will cancel the event during RESTARTING phase of the arena. + *

+ * + * @param event + * event object + */ + @EventHandler(priority = EventPriority.HIGH) + public void onBlockPhysics(final BlockPhysicsEvent event) + { + for (final Arena a : this.pli.getArenas()) + { + if (a.getArenaType() == ArenaType.REGENERATION) + { + final Cuboid c = a.getBoundaries(); + if (c != null) + { + if (a.getArenaState() == ArenaState.INGAME) + { + if (c.containsLocWithoutY(event.getBlock().getLocation())) + { + if (event.getChangedType() == Material.CARPET || event.getChangedType() == Material.BED_BLOCK) + { + return; + } + a.getSmartReset().addChanged(event.getBlock()); + } + } + else if (a.getArenaState() == ArenaState.RESTARTING) + { + event.setCancelled(true); + } + } + } + } + } + + /** + * Block redstone event. + * + *

+ * Registers the block changes for smart resets. + * At the end of the game the blocks will reset to original state. + * Only available by REGENERATION arena types and for blocks within the arena boundaries and while in INGAME arena state. + *

+ * + * @param event + * event object + */ + @EventHandler + public void onBlockRedstone(final BlockRedstoneEvent event) + { + for (final Arena a : this.pli.getArenas()) + { + if (a.getArenaType() == ArenaType.REGENERATION) + { + final Cuboid c = a.getBoundaries(); + if (c != null) + { + if (a.getArenaState() == ArenaState.INGAME) + { + a.getSmartReset().addChanged(event.getBlock()); + } + } + } + } + } + + /** + * Block spread event. + * + *

+ * Registers the block changes for smart resets. + * At the end of the game the blocks will reset to original state. + * Only available by REGENERATION arena types and for blocks within the arena boundaries and while in INGAME arena state. + *

+ * + *

+ * Will cancel the event during RESTARTING phase of the arena. + *

+ * + * @param event + * event object + */ + @EventHandler + public void onBlockSpread(final BlockSpreadEvent event) + { + // disallow fire spread while the arena restarts + for (final Arena a : this.pli.getArenas()) + { + if (a.getArenaType() == ArenaType.REGENERATION) + { + final Cuboid c = a.getBoundaries(); + if (c != null) + { + if (a.getArenaState() == ArenaState.INGAME) + { + a.getSmartReset().addChanged(event.getBlock().getLocation(), Material.AIR, (byte) 0); + } + else if (a.getArenaState() == ArenaState.RESTARTING) + { + event.setCancelled(true); + } + } + } + } + } + + /** + * Entity change block event. + * + *

+ * Registers the block changes for smart resets. + * At the end of the game the blocks will reset to original state. + * Only available by REGENERATION arena types and for blocks within the arena boundaries. + *

+ * + * @param event + * event object + */ + @EventHandler + public void onEntityChangeBlock(final EntityChangeBlockEvent event) + { + if (event.getEntity() instanceof Enderman) + { + for (final Arena a : this.pli.getArenas()) + { + if (a.getArenaType() == ArenaType.REGENERATION) + { + final Cuboid c = a.getBoundaries(); + if (c != null) + { + if (c.containsLocWithoutY(event.getEntity().getLocation())) + { + a.getSmartReset().addChanged(event.getBlock()); + } + } + } + } + } + } + + /** + * Leaves decay event. + * + *

+ * Registers the block changes for smart resets. + * At the end of the game the blocks will reset to original state. + * Only available by REGENERATION arena types and for blocks within the arena boundaries and while in INGAME arena state. + *

+ * + * @param event + * event object + */ + @EventHandler(priority = EventPriority.HIGH) + public void onLeavesDecay(final LeavesDecayEvent event) + { + for (final Arena a : this.pli.getArenas()) + { + if (a.getArenaType() == ArenaType.REGENERATION && a.getArenaState() == ArenaState.INGAME) + { + final Cuboid c = a.getBoundaries(); + if (c != null) + { + if (c.containsLocWithoutY(event.getBlock().getLocation())) + { + a.getSmartReset().addChanged(event.getBlock()); + } + } + } + } + } + + /** + * Block burn event. + * + *

+ * Registers the block changes for smart resets. + * At the end of the game the blocks will reset to original state. + * Only available by REGENERATION arena types and for blocks within the arena boundaries. + *

+ * + * @param event + * event object + */ + @EventHandler + public void onBlockBurn(final BlockBurnEvent event) + { + for (final Arena a : this.pli.getArenas()) + { + if (Validator.isArenaValid(this.plugin, a) && a.getArenaType() == ArenaType.REGENERATION) + { + final Cuboid c = new Cuboid(Util.getComponentForArena(this.plugin, a.getInternalName(), ArenaConfigStrings.BOUNDS_LOW), + Util.getComponentForArena(this.plugin, a.getInternalName(), ArenaConfigStrings.BOUNDS_HIGH)); + if (c != null) + { + if (c.containsLocWithoutY(event.getBlock().getLocation())) + { + a.getSmartReset().addChanged(event.getBlock()); + } + } + } + } + } + + /** + * On Structure grow event. + * + *

+ * Registers the block changes for smart resets. + * At the end of the game the blocks will reset to original state. + * Only available by REGENERATION arena types and for blocks within the arena boundaries. + *

+ * + * @param event + * event object + */ + @EventHandler + public void onStructureGrow(final StructureGrowEvent event) + { + for (final Arena a : this.pli.getArenas()) + { + if (a.getArenaType() == ArenaType.REGENERATION && a.getArenaState() == ArenaState.INGAME) + { + final Cuboid c = new Cuboid(Util.getComponentForArena(this.plugin, a.getInternalName(), ArenaConfigStrings.BOUNDS_LOW), + Util.getComponentForArena(this.plugin, a.getInternalName(), ArenaConfigStrings.BOUNDS_HIGH)); + if (c != null) + { + final Location start = event.getLocation(); + if (c.containsLocWithoutY(start)) + { + a.getSmartReset().addChanged(start.getBlock()); + for (final BlockState bs : event.getBlocks()) + { + final Block b = bs.getBlock(); + a.getSmartReset().addChanged(b.getLocation(), Material.AIR, (byte) 0); + } + } + } + } + } + } + + /** + * Block break event. + * + *

+ * Registers the block changes for smart resets. + * At the end of the game the blocks will reset to original state. + * Only available by REGENERATION arena types and for blocks within the arena boundaries. + *

+ * + * TODO difference to blockbreak2? + * + * @param event + * event object + */ + @EventHandler(priority = EventPriority.HIGH) + public void onBlockBreak2(final BlockBreakEvent event) + { + final Player p = event.getPlayer(); + if (this.pli.containsGlobalPlayer(p.getName())) + { + final Arena a = this.pli.global_players.get(p.getName()); + if (event.getBlock().getType() != Material.AIR) + { + a.getSmartReset().addChanged(event.getBlock()); + } + } + } + + // ******************* + // ***** cancel events + // ******************* + + /** + * Player drop item event. + * + *

+ * Cancelled while ingame and player already lost the game. + *

+ * + *

+ * Cancelled while not ingame and this is not an arcade arena. + * TODO: Any reason why? + *

+ * + * @param event + * event object + */ + @EventHandler + public void onPlayerDrop(final PlayerDropItemEvent event) + { + if (this.pli.containsGlobalPlayer(event.getPlayer().getName())) + { + final Arena a = this.pli.global_players.get(event.getPlayer().getName()); + if (a != null) + { + if (a.getArenaState() != ArenaState.INGAME && a.getArcadeInstance() == null && !a.isArcadeMain()) + { + event.setCancelled(true); + } + if (a.getArenaState() == ArenaState.INGAME && this.pli.containsGlobalLost(event.getPlayer().getName())) + { + event.setCancelled(true); + } + } + } + } + + /** + * Player pickup item event. + * + *

+ * Cancelled while ingame and this is not arcade. + *

+ * + * @param event + * event object + */ + @EventHandler + public void onPlayerPickupItem(final PlayerPickupItemEvent event) + { + this.pli.getSpectatorManager(); + // spectators shall not pick up items + if (this.pli.containsGlobalLost(event.getPlayer().getName()) || SpectatorManager.isSpectating(event.getPlayer())) + { + final Arena a = this.pli.global_lost.get(event.getPlayer().getName()); + if (a != null) + { + if (a.getArenaState() == ArenaState.INGAME && a.getArcadeInstance() == null) + { + event.setCancelled(true); + } + } + } + } + + /** + * Player inventory click event. + * + *

+ * Cancelled while starting and this is not arcade. + *

+ * + * @param event + * event object + */ + @EventHandler + public void onInventoryClick(final InventoryClickEvent event) + { + if (event.getWhoClicked() instanceof Player) + { + final Player p = (Player) event.getWhoClicked(); + if (this.pli.containsGlobalPlayer(p.getName())) + { + final Arena a = this.pli.global_players.get(p.getName()); + if (a != null) + { + if (a.getArenaState() == ArenaState.STARTING && a.getArcadeInstance() == null && !a.isArcadeMain()) + { + event.setCancelled(true); + } + } + } + } + } + + /** + * Player hunger event. + * + *

+ * Cancelled while in arena and not in arcade. + *

+ * + * @param event + * event object + */ + @EventHandler + public void onHunger(final FoodLevelChangeEvent event) + { + if (event.getEntity() instanceof Player) + { + final Player p = (Player) event.getEntity(); + if (this.pli.containsGlobalPlayer(p.getName())) + { + if (!this.pli.global_players.get(p.getName()).isArcadeMain()) + { + event.setCancelled(true); + } + } + } + } + + /** + * Player damage event. + * + *

+ * Cancelled while in lobby (JOIN/STARTING state) + *

+ * + * @param event + * event object + */ + @EventHandler + public void NoDamageEntityInLobby(final EntityDamageByEntityEvent event) + { + if (event.getDamager() instanceof Player) + { + final Player p = (Player) event.getDamager(); + if (this.pli.containsGlobalPlayer(p.getName())) + { + final Arena arena = this.pli.global_players.get(p.getName()); + if (arena.getArenaState() == ArenaState.JOIN || (arena.getArenaState() == ArenaState.STARTING)) + { + final Entity e = event.getEntity(); + if (e instanceof ArmorStand || e instanceof ItemFrame || e instanceof Painting || e instanceof Minecart) + { + event.setCancelled(false); + } + } + } + } + } + + /** + * Player interact entity event. + * + *

+ * Cancelled while in lobby (JOIN/STARTING phase) + *

+ * + * @param event + * event object + */ + @EventHandler + public void NoClickEntityInLobby(final PlayerInteractEntityEvent event) throws IOException + { + final Player p = event.getPlayer(); + final Entity e = event.getRightClicked(); + if (!(e instanceof Player)) + { + final Arena arena = this.pli.global_players.get(p.getName()); + if (arena != null) + { + if (arena.getArenaState() == ArenaState.JOIN || (arena.getArenaState() == ArenaState.STARTING)) + { + if (event.getRightClicked().getType().equals(EntityType.ARMOR_STAND) || event.getRightClicked().getType().equals(EntityType.MINECART) + || event.getRightClicked().getType().equals(EntityType.MINECART_CHEST) || event.getRightClicked().getType().equals(EntityType.MINECART_HOPPER) + || event.getRightClicked().getType().equals(EntityType.ITEM_FRAME) || event.getRightClicked().getType().equals(EntityType.PAINTING)) + { + event.setCancelled(true); + return; + } + } + } + } + } + + /** + * Player painting break event. + * + *

+ * Cancelled while being in arena. + *

+ * + * @param event + * event object + */ + @EventHandler(priority = EventPriority.HIGH) + public void onPaintingBreak(final HangingBreakByEntityEvent event) + { + if (event.getRemover() instanceof Player) + { + final String p_ = ((Player) event.getRemover()).getName(); + if (this.pli.containsGlobalPlayer(p_)) + { + event.setCancelled(true); + } + } + + } + + // ****************** + // ***** other events + // ****************** + + /** + * Fetches player move event. + * + *

+ * TODO describe what this event is doing. Seems to ensure that players cannot collide. + *

+ * + * @param event + * the player move event. + */ + @EventHandler + public void Space(final PlayerMoveEvent event) + { + final Player p = event.getPlayer(); + if (this.pli.containsGlobalPlayer(p.getName())) + { + final Arena a = this.pli.global_players.get(p.getName()); + if (a != null) + { + if (a.getArenaState() == ArenaState.INGAME) + { + if (!ArenaListener.isSpectating(p)) + { + for (final Entity e : this.getEntitiesByLocation(p.getLocation(), 30D)) + { + + if (e instanceof Player) + { + final Player sp = (Player) e; + + if (ArenaListener.isSpectating(sp)) + { + sp.setVelocity(sp.getLocation().getDirection().setY(0.05D)); + sp.setVelocity(sp.getLocation().getDirection().multiply(-2)); + } + + } + } + } + } + } + } + } + + /** + * Fetches player move event. + * + *

+ * TODO describe what this event is doing. + *

+ * + * @param event + * the player move event. + */ + @EventHandler(priority = EventPriority.HIGHEST) + public void onVMove(final VehicleMoveEvent event) + { + if (event.getVehicle().getPassenger() instanceof Player) + { + final Player p = (Player) event.getVehicle().getPassenger(); + if (this.pli.containsGlobalPlayer(p.getName())) + { + final Arena a = this.pli.global_players.get(p.getName()); + if (!this.pli.containsGlobalLost(p.getName()) && !this.pli.global_arcade_spectator.containsKey(p.getName())) + { + if (a.getArenaState() == ArenaState.INGAME) + { +// if (MinigamesAPI.debug) +// { +// plugin.getLogger().log(Level.INFO, "Player " + p + " moved ingame to " + event.getTo()); +// } + if (event.getTo().getBlockY() + this.loseY < a.getSpawns().get(0).getBlockY()) + { +// if (a.getArenaType() == ArenaType.JUMPNRUN) +// { +// Util.teleportPlayerFixed(p, a.getSpawns().get(0)); +// } +// else +// { +// a.spectate(p.getName()); +// } + a.spectate(p.getName()); + return; + } + if (a.getBoundaries() != null) + { + if (!a.getBoundaries().containsLocWithoutY(event.getTo())) + { + if (MinigamesAPI.debug) + { + plugin.getLogger().log(Level.INFO, "Player " + p + " left arena bounds."); + } + a.spectate(p.getName()); + return; + } + } + } + } + } + } + } + + /** + * Fetches player move event. + * + *

+ * TODO describe what this event is doing. + *

+ * + * @param event + * the player move event. + */ + @EventHandler(priority = EventPriority.HIGHEST) + public void onMove(final PlayerMoveEvent event) + { + try + { + final Player p = event.getPlayer(); + if (this.pli.containsGlobalPlayer(p.getName())) + { + final Arena a = this.pli.global_players.get(p.getName()); + if (!this.pli.containsGlobalLost(p.getName()) && !this.pli.global_arcade_spectator.containsKey(p.getName())) + { + if (a.getArenaState() == ArenaState.INGAME) + { +// if (MinigamesAPI.debug) +// { +// plugin.getLogger().log(Level.INFO, "Player " + p + " moved ingame to " + p.getLocation()); +// } + if (p.getLocation().getBlockY() + this.loseY < a.getSpawns().get(0).getBlockY()) + { + if (a.getArenaType() == ArenaType.JUMPNRUN) + { + Util.teleportPlayerFixed(p, a.getSpawns().get(0)); + } + else + { + a.spectate(p.getName()); + } + return; + } + if (a.getBoundaries() != null) + { + if (!a.getBoundaries().containsLocWithoutY(p.getLocation())) + { + if (MinigamesAPI.debug) + { + plugin.getLogger().log(Level.INFO, "Player " + p + " left arena bounds."); + } + Util.pushBack(a.getSpawns().get(0), p); + } + } + } + else if (a.getArenaState() == ArenaState.STARTING || a.getArenaState() == ArenaState.JOIN) + { + if (!a.isArcadeMain()) + { + if (!a.getIngameCountdownStarted()) + { + if (p.getLocation().getBlockY() < 0) + { + try + { + Util.teleportPlayerFixed(p, a.getWaitingLobbyTemp()); + } + catch (final Exception e) + { + this.plugin.getLogger().warning("Waiting lobby for arena " + a.getInternalName() + " missing, please fix by setting it. " + e.getMessage()); + } + } + if (a.getLobbyBoundaries() != null && !a.skip_join_lobby) + { + if (!a.getLobbyBoundaries().containsLocWithoutY(p.getLocation())) + { + Util.pushBack(a.getWaitingLobbyTemp(), p); + } + } + } + } + } + } + else + { + if (a.getArenaState() == ArenaState.INGAME) + { + if (this.pli.spectator_move_y_lock && event.getPlayer().getLocation().getBlockY() < (a.getSpawns().get(0).getBlockY() + 30D) + || event.getPlayer().getLocation().getBlockY() > (a.getSpawns().get(0).getBlockY() + 30D)) + { + final float b = p.getLocation().getYaw(); + final float c = p.getLocation().getPitch(); + Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(this.plugin, () -> { + p.setAllowFlight(true); + p.setFlying(true); + if (p.isInsideVehicle()) + { + final Entity ent = p.getVehicle(); + p.leaveVehicle(); + ent.eject(); + } + p.teleport(new Location(p.getWorld(), p.getLocation().getBlockX(), (a.getSpawns().get(0).getBlockY() + 30D), p.getLocation().getBlockZ(), b, c)); + }, 1); + return; + } + + if (a.getSpecBoundaries() != null) + { + if (!a.getSpecBoundaries().containsLocWithoutY(p.getLocation())) + { + Util.pushBack(a.getSpawns().get(0).clone().add(0D, 30D, 0D), p); + } + return; + } + if (a.getBoundaries() != null) + { + if (!a.getBoundaries().containsLocWithoutY(p.getLocation())) + { + Util.pushBack(a.getSpawns().get(0).clone().add(0D, 30D, 0D), p); + } + } + } + } + } + } + catch (final Exception e) + { + if (MinigamesAPI.debug) + { + MinigamesAPI.getAPI().getLogger().log(Level.WARNING, "exception", e); + } + } + + } + + /** + * Player death event. + * + *

+ * TODO describe what is going on + *

+ * + * @param event + * event object + */ + @EventHandler(priority = EventPriority.MONITOR) + public void onPlayerDeath(final PlayerDeathEvent event) + { + if (this.pli.containsGlobalPlayer(event.getEntity().getName())) + { + event.setDeathMessage(null); + final Player p = event.getEntity(); + + p.addPotionEffect(new PotionEffect(PotionEffectType.HEAL, 20 * 3, 50)); + + final Arena arena = this.pli.global_players.get(p.getName()); + if (arena.getArenaState() == ArenaState.JOIN || (arena.getArenaState() == ArenaState.STARTING && !arena.getIngameCountdownStarted())) + { + if (arena.isArcadeMain()) + { + Util.teleportPlayerFixed(p, arena.getWaitingLobbyTemp()); + } + } + + arena.global_drops.addAll(event.getDrops()); + + arena.spectate(p.getName()); + + this.pli.global_lost.put(p.getName(), arena); + + int count = 0; + // for (String p_ : pli.global_players.keySet()) { + // if (Validator.isPlayerOnline(p_)) { + // if (pli.global_players.get(p_).getInternalName().equalsIgnoreCase(arena.getInternalName())) { + // if (!pli.containsGlobalLost(p_)) { + // count++; + // } + // } + // } + // } + for (final String p_ : arena.getAllPlayers()) + { + if (Validator.isPlayerOnline(p_)) + { + if (!this.pli.containsGlobalLost(p_)) + { + count++; + } + } + } + final int count_ = count; + + Bukkit.getScheduler().runTaskLater(MinigamesAPI.getAPI(), () -> { + if (ArenaListener.this.pli.containsGlobalPlayer(p.getName()) && count_ > 1) + { + arena.spectate(p.getName()); + } + for (final String p_ : arena.getAllPlayers()) + { + if (Validator.isPlayerOnline(p_)) + { + final Player p__ = Bukkit.getPlayer(p_); + Util.sendMessage(ArenaListener.this.plugin, p__, ArenaListener.this.pli.getMessagesConfig().broadcast_players_left.replaceAll("", arena.getPlayerCount())); + } + } + }, 5); + + if (this.pli.last_man_standing) + { + if (count < 2) + { + // last man standing + arena.stopArena(); + } + } + } + } + + /** + * Player entity damage event. + * + *

+ * TODO describe when this event is cancelled + *

+ * + * @param event + * event object + */ + @EventHandler + public void onEntityDamage(final EntityDamageEvent event) + { + if (event.getEntity() instanceof Player) + { + final Player p = (Player) event.getEntity(); + if (this.pli.containsGlobalPlayer(p.getName()) && this.pli.containsGlobalLost(p.getName())) + { + final Arena a = this.pli.global_players.get(p.getName()); + if (a.getArenaState() == ArenaState.INGAME && a.getArcadeInstance() == null && !a.getAlwaysPvP()) + { + event.setCancelled(true); + } + } + if (event.getCause().equals(DamageCause.ENTITY_ATTACK)) + { + if (this.pli.containsGlobalPlayer(p.getName())) + { + final Arena a = this.pli.global_players.get(p.getName()); + if (a.getArenaState() != ArenaState.INGAME && a.getArcadeInstance() == null && !a.getAlwaysPvP()) + { + event.setCancelled(true); + } + if (this.pli.blood_effects && (a.getArenaState() == ArenaState.INGAME || a.getAlwaysPvP()) && !a.isArcadeMain()) + { + Effects.playBloodEffect(p); + } + } + this.pli.getSpectatorManager(); + if (this.pli.containsGlobalLost(p.getName()) || SpectatorManager.isSpectating(p)) + { + event.setCancelled(true); + } + } + else if (event.getCause().equals(DamageCause.FALL)) + { + if (this.pli.containsGlobalPlayer(p.getName())) + { + final Arena a = this.pli.global_players.get(p.getName()); + if (a.getArenaState() != ArenaState.INGAME && a.getArcadeInstance() != null) + { + event.setCancelled(true); + } + } + } + } + } + + /** + * Player entity damage event. + * + *

+ * TODO describe when this event is cancelled + *

+ * + * @param event + * event object + */ + @EventHandler + public void onEntityDamageByEntity(final EntityDamageByEntityEvent event) + { + if (event.getEntity() instanceof Player) + { + final Player p = (Player) event.getEntity(); + Player attacker = null; + if (event.getDamager() instanceof Projectile) + { + final Projectile projectile = (Projectile) event.getDamager(); + if (projectile.getShooter() instanceof Player) + { + attacker = (Player) projectile.getShooter(); + } + } + else if (event.getDamager() instanceof Player) + { + attacker = (Player) event.getDamager(); + } + else + { + return; + } + + if (p != null && attacker != null) + { + if (this.pli.containsGlobalPlayer(p.getName()) && this.pli.containsGlobalPlayer(attacker.getName())) + { + this.pli.getSpectatorManager(); + if (SpectatorManager.isSpectating(p)) + { + if (event.getDamager() instanceof Arrow) + { + p.teleport(p.getLocation().add(0, 3D, 0)); + + final Arrow arr = attacker.launchProjectile(Arrow.class); + arr.setShooter(attacker); + arr.setVelocity(((Arrow) event.getDamager()).getVelocity()); + arr.setBounce(false); + + event.setCancelled(true); + event.getDamager().remove(); + } + else if (event.getDamager() instanceof Egg) + { + p.teleport(p.getLocation().add(0, 3D, 0)); + + final Egg egg = attacker.launchProjectile(Egg.class); + egg.setShooter(attacker); + egg.setVelocity(((Egg) event.getDamager()).getVelocity()); + egg.setBounce(false); + + event.setCancelled(true); + event.getDamager().remove(); + } + else if (event.getDamager() instanceof Snowball) + { + p.teleport(p.getLocation().add(0, 3D, 0)); + + final Snowball sb = attacker.launchProjectile(Snowball.class); + sb.setShooter(attacker); + sb.setVelocity(((Snowball) event.getDamager()).getVelocity()); + sb.setBounce(false); + + event.setCancelled(true); + event.getDamager().remove(); + } + else if (event.getDamager() instanceof EnderPearl) + { + p.teleport(p.getLocation().add(0, 3D, 0)); + + final EnderPearl sb = attacker.launchProjectile(EnderPearl.class); + sb.setShooter(attacker); + sb.setVelocity(((EnderPearl) event.getDamager()).getVelocity()); + sb.setBounce(false); + + event.setCancelled(true); + event.getDamager().remove(); + } + event.setCancelled(true); + return; + } + if (this.pli.containsGlobalLost(attacker.getName())) + { + event.setCancelled(true); + return; + } + final Arena a = this.pli.global_players.get(p.getName()); + if (a.getArenaState() == ArenaState.INGAME) + { + a.setLastDamager(p.getName(), attacker.getName()); + if (this.pli.damage_identifier_effects) + { + ChatColor c = ChatColor.YELLOW; + if (event.getDamage() >= 5D) + { + c = ChatColor.GOLD; + } + if (event.getDamage() >= 9D) + { + c = ChatColor.RED; + } + Effects.playHologram(attacker, p.getLocation(), c + Double.toString(event.getDamage()), true, true); + } + } + else if (a.getArenaState() == ArenaState.RESTARTING) + { + event.setCancelled(true); + } + } + } + } + } + + /** + * Block break event. + * + *

+ * TODO describe when this event is cancelled + *

+ * + * @param event + * event object + */ + @EventHandler(priority = EventPriority.HIGH) + public void onBlockBreak(final BlockBreakEvent event) + { + final Player p = event.getPlayer(); + if (this.pli.containsGlobalPlayer(p.getName())) + { + final Arena a = this.pli.global_players.get(p.getName()); + if (a.getArenaState() != ArenaState.INGAME || this.pli.containsGlobalLost(p.getName())) + { + event.setCancelled(true); + return; + } + this.pli.getSpectatorManager(); + if (SpectatorManager.isSpectating(p)) + { + event.setCancelled(true); + return; + } + a.getSmartReset().addChanged(event.getBlock()); + if (event.getBlock().getType() == Material.DOUBLE_PLANT) + { + a.getSmartReset().addChanged(event.getBlock().getLocation().clone().add(0D, -1D, 0D).getBlock()); + a.getSmartReset().addChanged(event.getBlock().getLocation().clone().add(0D, +1D, 0D).getBlock()); + } + if (event.getBlock().getType() == Material.SNOW || event.getBlock().getType() == Material.SNOW_BLOCK) + { + a.getSmartReset().addChanged(event.getBlock().getLocation().clone().add(0D, +3D, 0D).getBlock()); + a.getSmartReset().addChanged(event.getBlock().getLocation().clone().add(0D, +2D, 0D).getBlock()); + a.getSmartReset().addChanged(event.getBlock().getLocation().clone().add(0D, +1D, 0D).getBlock()); + } + if (event.getBlock().getType() == Material.CARPET) + { + a.getSmartReset().addChanged(event.getBlock().getLocation().clone().add(0D, +3D, 0D).getBlock()); + a.getSmartReset().addChanged(event.getBlock().getLocation().clone().add(0D, +2D, 0D).getBlock()); + a.getSmartReset().addChanged(event.getBlock().getLocation().clone().add(0D, +1D, 0D).getBlock()); + } + if (event.getBlock().getType() == Material.CACTUS) + { + a.getSmartReset().addChanged(event.getBlock().getLocation().clone().add(0D, +4D, 0D).getBlock()); + a.getSmartReset().addChanged(event.getBlock().getLocation().clone().add(0D, +3D, 0D).getBlock()); + a.getSmartReset().addChanged(event.getBlock().getLocation().clone().add(0D, +2D, 0D).getBlock()); + a.getSmartReset().addChanged(event.getBlock().getLocation().clone().add(0D, +1D, 0D).getBlock()); + } + if (event.getBlock().getType() == Material.BED_BLOCK) + { + a.getSmartReset().addChanged(event.getBlock().getLocation().clone().add(1D, 0D, 0D).getBlock()); + a.getSmartReset().addChanged(event.getBlock().getLocation().clone().add(-1D, 0D, 0D).getBlock()); + a.getSmartReset().addChanged(event.getBlock().getLocation().clone().add(0D, 0D, 1D).getBlock()); + a.getSmartReset().addChanged(event.getBlock().getLocation().clone().add(0D, 0D, -1D).getBlock()); + } + } + if (event.getBlock().getType() == Material.SIGN_POST || event.getBlock().getType() == Material.WALL_SIGN) + { + final Arena arena = Util.getArenaBySignLocation(this.plugin, event.getBlock().getLocation()); + if (arena != null) + { + this.pli.getArenasConfig().getConfig().set(ArenaConfigStrings.ARENAS_PREFIX + arena.getInternalName() + ".sign", null); + this.pli.getArenasConfig().saveConfig(); + } + } + } + + /** + * Player bucket empty event. + * + *

+ * TODO describe when this event is cancelled + *

+ * + * @param event + * event object + */ + @EventHandler(priority = EventPriority.HIGHEST) + public void onPlayerBucketEmpty(final PlayerBucketEmptyEvent event) + { + if (this.pli.containsGlobalPlayer(event.getPlayer().getName())) + { + final Arena a = this.pli.global_players.get(event.getPlayer().getName()); + final Block start = event.getBlockClicked(); + if (!a.getBoundaries().containsLocWithoutY(start.getLocation())) + { + event.setCancelled(true); + return; + } + for (int x = -2; x < 2; x++) + { + for (int y = -2; y < 2; y++) + { + for (int z = -2; z < 2; z++) + { + final Block b = start.getLocation().clone().add(x, y, z).getBlock(); + a.getSmartReset().addChanged(b); + } + } + } + } + } + + /** + * Block place event. + * + *

+ * TODO describe when this event is cancelled + *

+ * + * @param event + * event object + */ + @EventHandler(priority = EventPriority.HIGH) + public void onBlockPlace(final BlockPlaceEvent event) + { + final Player p = event.getPlayer(); + if (this.pli.containsGlobalPlayer(p.getName())) + { + final Arena a = this.pli.global_players.get(p.getName()); + this.pli.getSpectatorManager(); + if (a.getArenaState() != ArenaState.INGAME || this.pli.containsGlobalLost(p.getName()) || SpectatorManager.isSpectating(p)) + { + event.setCancelled(true); + return; + } + // TODO Is this clever? We should add every block change to smart reset. + // currently BedWars has its own onBlockPlace + if (event.getBlockReplacedState().getType() != Material.AIR) + { + a.getSmartReset().addChanged(event.getBlock().getLocation(), event.getBlockReplacedState().getType(), event.getBlockReplacedState().getData().getData()); + } + } + if (this.pli.getStatsInstance().skullsetup.contains(p.getName())) + { + if (event.getBlock().getType() == Material.SKULL_ITEM || event.getBlock().getType() == Material.SKULL) + { + if (event.getItemInHand().hasItemMeta()) + { + this.pli.getStatsInstance().saveSkull(event.getBlock().getLocation(), Integer.parseInt(event.getItemInHand().getItemMeta().getDisplayName())); + this.pli.getStatsInstance().skullsetup.remove(p.getName()); + } + } + } + } + + // ***************** + // ***** sign events + // ***************** + + /** + * Sign use event. + * + *

+ * TODO describe when this event is cancelled + *

+ * + * @param event + * event object + */ + @EventHandler + public void onSignUse(final PlayerInteractEvent event) + { + if (event.hasBlock()) + { + if (event.getClickedBlock().getType() == Material.SIGN_POST || event.getClickedBlock().getType() == Material.WALL_SIGN || event.getClickedBlock().getType() == Material.SIGN) + { + if (event.getClickedBlock().getType() == Material.FIRE) + { + return; + } + if (event.getAction() != Action.RIGHT_CLICK_BLOCK) + { + return; + } + final Sign s = (Sign) event.getClickedBlock().getState(); + // people will most likely do strange formats, so let's just try + // to get signs by location rather than locally by reading the sign + final Arena arena = Util.getArenaBySignLocation(this.plugin, event.getClickedBlock().getLocation()); + final Arena specarena = Util.getArenaBySpecSignLocation(this.plugin, event.getClickedBlock().getLocation()); + if (arena != null) + { + final Player p = event.getPlayer(); + if (!arena.containsPlayer(p.getName())) + { + arena.joinPlayerLobby(p.getName()); + Util.updateSign(this.plugin, arena); + } + else + { + Util.sendMessage(this.plugin, p, this.pli.getMessagesConfig().you_already_are_in_arena.replaceAll("", arena.getInternalName())); + } + } + else if (specarena != null) + { + if (specarena.getArenaState() == ArenaState.INGAME) + { + final Player p = event.getPlayer(); + specarena.joinSpectate(p); + } + } + else + { + // try getting random sign + final Location l = Util.getComponentForArenaRaw(this.plugin, "random", "sign"); + if (this.checkLocationMatchesSign(l, s)) + { + for (final Arena a : this.pli.getArenas()) + { + if (a.getArenaState() == ArenaState.JOIN || a.getArenaState() == ArenaState.STARTING) + { + if (!a.containsPlayer(event.getPlayer().getName())) + { + a.joinPlayerLobby(event.getPlayer().getName()); + Util.updateSign(this.plugin, a); + return; + } + } + } + } + // try getting leave sign + if (this.pli.containsGlobalPlayer(event.getPlayer().getName())) + { + if (this.pli.getArenasConfig().getConfig().isSet("arenas.leave")) + { + for (final String str : this.pli.getArenasConfig().getConfig().getConfigurationSection("arenas.leave.").getKeys(false)) + { + final Location loc = Util.getComponentForArenaRaw(this.plugin, "leave." + str, "sign"); + if (this.checkLocationMatchesSign(loc, s)) + { + this.pli.global_players.get(event.getPlayer().getName()).leavePlayer(event.getPlayer().getName(), false, false); + Util.updateSign(this.plugin, this.pli.getArenaByName("leave")); + return; + } + } + } + } + } + } + else if (event.getClickedBlock().getType() == Material.CHEST) + { + final Player p = event.getPlayer(); + if (this.pli.containsGlobalPlayer(p.getName())) + { + final Arena a = this.pli.global_players.get(p.getName()); + if (a.getArenaState() == ArenaState.INGAME) + { + a.getSmartReset().addChanged(event.getClickedBlock()); + } + } + } + else if (event.getClickedBlock().getType() == Material.TNT) + { + final Player p = event.getPlayer(); + if (this.pli.containsGlobalPlayer(p.getName())) + { + final Arena a = this.pli.global_players.get(p.getName()); + if (a.getArenaState() == ArenaState.INGAME) + { + a.getSmartReset().addChanged(event.getClickedBlock()); + // TODO maybe add radius of blocks around this tnt manually + } + } + } + else if (event.getPlayer().getItemInHand().getType() == Material.WATER_BUCKET || event.getPlayer().getItemInHand().getType() == Material.WATER + || event.getPlayer().getItemInHand().getType() == Material.LAVA_BUCKET || event.getPlayer().getItemInHand().getType() == Material.LAVA) + { + final Player p = event.getPlayer(); + if (this.pli.containsGlobalPlayer(p.getName())) + { + final Arena a = this.pli.global_players.get(p.getName()); + if (!a.getBoundaries().containsLocWithoutY(event.getClickedBlock().getLocation())) + { + event.setCancelled(true); + return; + } + if (a.getArenaState() == ArenaState.INGAME) + { + a.getSmartReset().addChanged(event.getClickedBlock()); + // a.getSmartReset().addChanged(event.getClickedBlock().getLocation().add(0D, 1D, 0D)); + } + } + } + else if (event.getClickedBlock().getType() == Material.DISPENSER || event.getClickedBlock().getType() == Material.DROPPER) + { + final Player p = event.getPlayer(); + if (this.pli.containsGlobalPlayer(p.getName())) + { + final Arena a = this.pli.global_players.get(p.getName()); + if (a.getArenaState() == ArenaState.INGAME) + { + a.getSmartReset().addChanged(event.getClickedBlock()); + } + } + } + } + + this.pli.getSpectatorManager(); + if (this.pli.containsGlobalLost(event.getPlayer().getName()) || SpectatorManager.isSpectating(event.getPlayer())) + { + event.setCancelled(true); + } + + if (event.hasItem()) + { + final Player p = event.getPlayer(); + if (!this.pli.containsGlobalPlayer(p.getName())) + { + return; + } + final Arena a = this.pli.global_players.get(p.getName()); + if (a.isArcadeMain()) + { + return; + } + if (event.getItem().getTypeId() == this.plugin.getConfig().getInt(ArenaConfigStrings.CONFIG_CLASS_SELECTION_ITEM)) + { + if (a.getArenaState() != ArenaState.INGAME) + { + this.pli.getClassesHandler().openGUI(p.getName()); + event.setCancelled(true); + } + } + else if (event.getItem().getTypeId() == this.plugin.getConfig().getInt(ArenaConfigStrings.CONFIG_EXIT_ITEM)) + { + if (a.getArenaState() != ArenaState.INGAME) + { + a.leavePlayer(p.getName(), false, false); + event.setCancelled(true); + } + else + { + if (this.pli.containsGlobalLost(p.getName())) + { + a.leavePlayer(p.getName(), false, false); + event.setCancelled(true); + } + } + } + else if (event.getItem().getTypeId() == this.plugin.getConfig().getInt(ArenaConfigStrings.CONFIG_SPECTATOR_ITEM)) + { + if (this.pli.containsGlobalLost(p.getName())) + { + this.pli.getSpectatorManager().openSpectatorGUI(p, a); + event.setCancelled(true); + } + } + else if (event.getItem().getTypeId() == this.plugin.getConfig().getInt(ArenaConfigStrings.CONFIG_ACHIEVEMENT_ITEMS)) + { + if (this.pli.isAchievementGuiEnabled()) + { + if (a.getArenaState() != ArenaState.INGAME) + { + this.pli.getArenaAchievements().openGUI(p.getName(), false); + event.setCancelled(true); + } + } + } + else if (event.getItem().getTypeId() == this.plugin.getConfig().getInt(ArenaConfigStrings.CONFIG_SHOP_SELECTION_ITEM)) + { + if (a.getArenaState() != ArenaState.INGAME) + { + this.pli.getShopHandler().openGUI(p.getName()); + event.setCancelled(true); + } + } + else if (event.getItem().getTypeId() == this.plugin.getConfig() + .getInt(ArenaConfigStrings.CONFIG_EXTRA_LOBBY_ITEM_PREFIX + "item0" + ArenaConfigStrings.CONFIG_EXTRA_LOBBY_ITEM_ITEM_SUFFIX)) + { + if (this.plugin.getConfig().getBoolean(ArenaConfigStrings.CONFIG_EXTRA_LOBBY_ITEM_PREFIX + "item0" + ArenaConfigStrings.CONFIG_EXTRA_LOBBY_ITEM_ENABLED_SUFFIX)) + { + if (a.getArenaState() != ArenaState.INGAME) + { + p.performCommand(this.plugin.getConfig().getString(ArenaConfigStrings.CONFIG_EXTRA_LOBBY_ITEM_PREFIX + "item0" + ArenaConfigStrings.CONFIG_EXTRA_LOBBY_ITEM_COMMAND_SUFFIX)); + } + } + } + if (event.getItem().getType() == Material.COMPASS) + { + if (a.getArenaState() == ArenaState.INGAME) + { + if (this.plugin.getConfig().getBoolean(ArenaConfigStrings.CONFIG_COMPASS_TRACKING_ENABLED)) + { + final CompassPlayer temp = Util.getNearestPlayer(p, a); + if (temp != null && temp.getPlayer() != null) + { + p.sendMessage(this.pli.getMessagesConfig().compass_player_found.replaceAll("", temp.getPlayer().getName()).replaceAll("", + Integer.toString((int) Math.round(temp.getDistance())))); + p.setCompassTarget(temp.getPlayer().getLocation()); + } + else + { + p.sendMessage(this.pli.getMessagesConfig().compass_no_player_found); + } + } + } + } + } + } + + /** + * Sign change event. + * + *

+ * TODO describe when this event is cancelled + *

+ * + * @param event + * event object + */ + @EventHandler + public void onSignChange(final SignChangeEvent event) + { + final Player p = event.getPlayer(); + if (event.getLine(0).toLowerCase().equalsIgnoreCase(this.getName())) + { + if (event.getPlayer().hasPermission(MinigamesAPI.getAPI().getPermissionPrefix() + ".sign") || event.getPlayer().isOp()) + { + if (!event.getLine(1).equalsIgnoreCase("")) + { + final String arena = event.getLine(1); + if (arena.equalsIgnoreCase("random")) + { + this.pli.getArenasConfig().getConfig().set(ArenaConfigStrings.ARENAS_PREFIX + arena + ".sign.world", p.getWorld().getName()); + this.pli.getArenasConfig().getConfig().set(ArenaConfigStrings.ARENAS_PREFIX + arena + ".sign.location.x", event.getBlock().getLocation().getBlockX()); + this.pli.getArenasConfig().getConfig().set(ArenaConfigStrings.ARENAS_PREFIX + arena + ".sign.location.y", event.getBlock().getLocation().getBlockY()); + this.pli.getArenasConfig().getConfig().set(ArenaConfigStrings.ARENAS_PREFIX + arena + ".sign.location.z", event.getBlock().getLocation().getBlockZ()); + this.pli.getArenasConfig().saveConfig(); + Util.sendMessage(this.plugin, p, this.pli.getMessagesConfig().successfully_set.replaceAll("", "arena (random) sign")); + Util.updateSign(this.plugin, event, arena); + } + else if (arena.equalsIgnoreCase("leave")) + { + int count = 0; + if (this.pli.getArenasConfig().getConfig().isSet("arenas.leave")) + { + for (final String s : this.pli.getArenasConfig().getConfig().getConfigurationSection("arenas.leave.").getKeys(false)) + { + count++; + } + } + this.pli.getArenasConfig().getConfig().set(ArenaConfigStrings.ARENAS_PREFIX + arena + "." + count + ".sign.world", p.getWorld().getName()); + this.pli.getArenasConfig().getConfig().set(ArenaConfigStrings.ARENAS_PREFIX + arena + "." + count + ".sign.location.x", event.getBlock().getLocation().getBlockX()); + this.pli.getArenasConfig().getConfig().set(ArenaConfigStrings.ARENAS_PREFIX + arena + "." + count + ".sign.location.y", event.getBlock().getLocation().getBlockY()); + this.pli.getArenasConfig().getConfig().set(ArenaConfigStrings.ARENAS_PREFIX + arena + "." + count + ".sign.location.z", event.getBlock().getLocation().getBlockZ()); + this.pli.getArenasConfig().saveConfig(); + Util.sendMessage(this.plugin, p, this.pli.getMessagesConfig().successfully_set.replaceAll("", "arena (leave) sign")); + Util.updateSign(this.plugin, event, arena); + } + else + { + final String mode = event.getLine(2).equalsIgnoreCase("") ? "join" : "spec"; + switch (mode) + { + case "join": + default: + { + if (Validator.isArenaValid(this.plugin, arena)) + { + this.pli.getArenasConfig().getConfig().set(ArenaConfigStrings.ARENAS_PREFIX + arena + ".sign.world", p.getWorld().getName()); + this.pli.getArenasConfig().getConfig().set(ArenaConfigStrings.ARENAS_PREFIX + arena + ".sign.loc.x", event.getBlock().getLocation().getBlockX()); + this.pli.getArenasConfig().getConfig().set(ArenaConfigStrings.ARENAS_PREFIX + arena + ".sign.loc.y", event.getBlock().getLocation().getBlockY()); + this.pli.getArenasConfig().getConfig().set(ArenaConfigStrings.ARENAS_PREFIX + arena + ".sign.loc.z", event.getBlock().getLocation().getBlockZ()); + this.pli.getArenasConfig().saveConfig(); + Util.sendMessage(this.plugin, p, this.pli.getMessagesConfig().successfully_set.replaceAll("", "arena sign")); + } + else + { + Util.sendMessage(this.plugin, p, this.pli.getMessagesConfig().arena_invalid.replaceAll("", arena)); + event.getBlock().breakNaturally(); + } + + final Arena a = this.pli.getArenaByName(arena); + if (a != null) + { + a.setSignLocation(event.getBlock().getLocation()); + Util.updateSign(this.plugin, a, event); + } + else + { + Util.sendMessage(this.plugin, p, this.pli.getMessagesConfig().arena_not_initialized); + } + } + break; + case "spec": + { + if (Validator.isArenaValid(this.plugin, arena)) + { + this.pli.getArenasConfig().getConfig().set(ArenaConfigStrings.ARENAS_PREFIX + arena + ".specsign.world", p.getWorld().getName()); + this.pli.getArenasConfig().getConfig().set(ArenaConfigStrings.ARENAS_PREFIX + arena + ".specsign.loc.x", event.getBlock().getLocation().getBlockX()); + this.pli.getArenasConfig().getConfig().set(ArenaConfigStrings.ARENAS_PREFIX + arena + ".specsign.loc.y", event.getBlock().getLocation().getBlockY()); + this.pli.getArenasConfig().getConfig().set(ArenaConfigStrings.ARENAS_PREFIX + arena + ".specsign.loc.z", event.getBlock().getLocation().getBlockZ()); + this.pli.getArenasConfig().saveConfig(); + Util.sendMessage(this.plugin, p, this.pli.getMessagesConfig().successfully_set.replaceAll("", "spectator sign")); + } + else + { + Util.sendMessage(this.plugin, p, this.pli.getMessagesConfig().arena_invalid.replaceAll("", arena)); + event.getBlock().breakNaturally(); + } + + final Arena a = this.pli.getArenaByName(arena); + if (a != null) + { + a.setSpecSignLocation(event.getBlock().getLocation()); + Util.updateSpecSign(this.plugin, a, event); + } + else + { + Util.sendMessage(this.plugin, p, this.pli.getMessagesConfig().arena_not_initialized); + } + } + break; + } + } + } + } + } + } + + /** + * Player join event. + * + *

+ * TODO describe when this event is cancelled + *

+ * + * @param event + * event object + */ + @EventHandler + public void onPlayerJoin(final PlayerJoinEvent event) + { + final Player p = event.getPlayer(); + this.pli.getStatsInstance().update(p.getName()); + if (this.pli.containsGlobalPlayer(p.getName())) + { + this.pli.global_players.remove(p.getName()); + } + if (this.pli.containsGlobalLost(p.getName())) + { + this.pli.global_lost.remove(p.getName()); + } + if (this.plugin.getConfig().isSet("temp.left_players." + p.getName())) + { + Bukkit.getScheduler().runTaskLater(MinigamesAPI.getAPI(), () -> { + Util.teleportPlayerFixed(p, Util.getMainLobby(ArenaListener.this.plugin)); + p.setFlying(false); + try + { + p.getInventory().clear(); + p.updateInventory(); + if (ArenaListener.this.plugin.getConfig().isSet("temp.left_players." + p.getName() + ".items")) + { + for (final String key : ArenaListener.this.plugin.getConfig().getConfigurationSection("temp.left_players." + p.getName() + ".items").getKeys(false)) + { + p.getInventory().addItem(ArenaListener.this.plugin.getConfig().getItemStack("temp.left_players." + p.getName() + ".items." + key)); + } + } + final Arena arena = ArenaListener.this.pli.global_players.get(p.getName()); + p.updateInventory(); + p.setWalkSpeed(0.2F); + p.removePotionEffect(PotionEffectType.JUMP); + p.removePotionEffect(PotionEffectType.INVISIBILITY); + p.setGameMode(GameMode.SURVIVAL); + Util.updateSign(ArenaListener.this.plugin, arena); + ArenaListener.this.pli.getSpectatorManager().setSpectate(p, false); + } + catch (final Exception e) + { + MinigamesAPI.getAPI().getLogger().log(Level.WARNING, "exception", e); + Util.sendMessage(ArenaListener.this.plugin, p, ChatColor.RED + "Failed restoring your stuff. Did the server restart/reload while you were offline?"); + } + ArenaListener.this.plugin.getConfig().set("temp.left_players." + p.getName(), null); + ArenaListener.this.plugin.saveConfig(); + }, 5); + } + + if (this.plugin.getConfig().getBoolean(ArenaConfigStrings.CONFIG_BUNGEE_GAME_ON_JOIN)) + { + int c = 0; + final List arenas = new ArrayList<>(); + for (final String arena : this.pli.getArenasConfig().getConfig().getKeys(false)) + { + if (!arena.equalsIgnoreCase("mainlobby") && !arena.equalsIgnoreCase("strings") && !arena.equalsIgnoreCase("config")) + { + c++; + arenas.add(arena); + } + } + if (c < 1) + { + MinigamesAPI.getAPI().getLogger().severe("Couldn't find any arena even though game_on_join was turned on. Please setup an arena to fix this!"); + return; + } + + Bukkit.getScheduler().runTaskLater(MinigamesAPI.getAPI(), () -> { + if (p != null) + { + ArenaListener.this.pli.getArenas().get(0).joinPlayerLobby(p.getName()); + final Arena arena = ArenaListener.this.pli.global_players.get(p.getName()); + Util.updateSign(ArenaListener.this.plugin, arena); + } + }, 30L); + } + } + + /** + * Player leave event. + * + *

+ * TODO describe when this event is cancelled + *

+ * + * @param event + * event object + */ + @EventHandler + public void onPlayerLeave(final PlayerQuitEvent event) + { + if (this.pli.containsGlobalPlayer(event.getPlayer().getName())) + { + final Arena arena = this.pli.global_players.get(event.getPlayer().getName()); + MinigamesAPI.getAPI().getLogger().info(event.getPlayer().getName() + " quit while in arena " + arena.getInternalName() + "."); + int count = 0; + for (final String p_ : this.pli.global_players.keySet()) + { + if (this.pli.global_players.get(p_).getInternalName().equalsIgnoreCase(arena.getInternalName())) + { + count++; + } + } + + arena.leavePlayer(event.getPlayer().getName(), true, false); + + try + { + Util.updateSign(this.plugin, arena); + } + catch (final Exception e) + { + MinigamesAPI.getAPI().getLogger().log(Level.WARNING, "Error occurred while refreshing sign. ", e); + } + } + if (MinigamesAPI.getAPI().hasParty(event.getPlayer().getUniqueId())) + { + MinigamesAPI.getAPI().getParty(event.getPlayer().getUniqueId()).disband(); + } + MinigamesAPI.getAPI().removePartyInvites(event.getPlayer().getUniqueId()); + Party party_ = null; + for (final Party party : MinigamesAPI.getAPI().getParties()) + { + if (party.containsPlayer(event.getPlayer().getUniqueId())) + { + party_ = party; + break; + } + } + if (party_ != null) + { + party_.removePlayer(event.getPlayer().getUniqueId()); + } + } + + /** + * Player chat event. + * + *

+ * TODO describe when this event is cancelled + *

+ * + * @param event + * event object + */ + @EventHandler(priority = EventPriority.MONITOR) + public void onChat(final AsyncPlayerChatEvent event) + { + final Player p = event.getPlayer(); + if (!this.pli.chat_enabled) + { + if (this.pli.containsGlobalPlayer(p.getName())) + { + event.setCancelled(true); + return; + } + } + if (this.plugin.getConfig().getBoolean(ArenaConfigStrings.CONFIG_CHAT_SHOW_SCORE_IN_ARENA)) + { + if (this.pli.containsGlobalPlayer(event.getPlayer().getName())) + { + event.setFormat(ChatColor.GRAY + "[" + ChatColor.GREEN + this.pli.getStatsInstance().getPoints(event.getPlayer().getName()) + ChatColor.GRAY + "] " + event.getFormat()); + } + } + if (this.plugin.getConfig().getBoolean(ArenaConfigStrings.CONFIG_CHAT_PER_ARENA_ONLY)) + { + if (this.pli.containsGlobalPlayer(p.getName())) + { + final String msg = String.format(event.getFormat(), p.getName(), event.getMessage()); + for (final Player receiver : event.getRecipients()) + { + if (this.pli.containsGlobalPlayer(receiver.getName())) + { + if (this.pli.global_players.get(receiver.getName()) == this.pli.global_players.get(p.getName())) + { + receiver.sendMessage("§7" + msg); + } + } + } + event.setCancelled(true); + } + } + } + + /** + * Player command preprocessor event. + * + *

+ * TODO describe when this event is cancelled + *

+ * + * @param event + * event object + */ + @EventHandler + public void onPlayerCommandPreprocessEvent(final PlayerCommandPreprocessEvent event) + { + if (event.getMessage().equalsIgnoreCase(this.leave_cmd) || event.getMessage().equalsIgnoreCase("/l")) + { + if (this.pli.containsGlobalPlayer(event.getPlayer().getName())) + { + final Arena arena = this.pli.global_players.get(event.getPlayer().getName()); + arena.leavePlayer(event.getPlayer().getName(), false, false); + event.setCancelled(true); + return; + } + } + if (this.pli.containsGlobalPlayer(event.getPlayer().getName()) && !event.getPlayer().isOp()) + { + if (!this.plugin.getConfig().getBoolean(ArenaConfigStrings.CONFIG_DISABLE_COMMANDS_IN_ARENA)) + { + return; + } + if (this.plugin.getConfig().getString(ArenaConfigStrings.CONFIG_COMMAND_WHITELIST).toLowerCase().contains(event.getMessage().toLowerCase())) + { + return; + } + boolean cont = false; + for (final String cmd : this.cmds) + { + if (event.getMessage().toLowerCase().startsWith(cmd.toLowerCase())) + { + cont = true; + } + } + if (!cont) + { + Util.sendMessage(this.plugin, event.getPlayer(), this.pli.getMessagesConfig().you_can_leave_with.replaceAll("", this.leave_cmd)); + event.setCancelled(true); + return; + } + } + } + + /** + * Player teleport event. + * + *

+ * TODO describe when this event is cancelled + *

+ * + * @param event + * event object + */ + // TP Fix start + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onPlayerTeleport(final PlayerTeleportEvent event) + { + if (event.getCause().equals(TeleportCause.UNKNOWN) && this.pli.spectator_mode_1_8) + { + // Don't hide/show players when 1.8 spectator mode is enabled + return; + } + final Player player = event.getPlayer(); + if (this.pli.containsGlobalPlayer(player.getName())) + { + final int visibleDistance = 16; + Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(this.plugin, () -> { + final List nearby = ArenaListener.this.getPlayersWithin(player, visibleDistance); + ArenaListener.this.updateEntities(nearby, false); + Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(ArenaListener.this.plugin, () -> ArenaListener.this.updateEntities(nearby, true), 1); + }, 5L); + } + } + + /** + * Deny mob spawn inside arena. + * @param evt create spawn event. + */ + @EventHandler + public void onMobSpawn(CreatureSpawnEvent evt) + { + for (final Arena arena : this.pli.getArenas()) + { + Cuboid c = arena.getBoundaries(); + if (c != null && c.containsLoc(evt.getLocation())) + { + evt.setCancelled(true); + return; + } + c = arena.getLobbyBoundaries(); + if (c != null && c.containsLoc(evt.getLocation())) + { + evt.setCancelled(true); + return; + } + c = arena.getSpecBoundaries(); + if (c != null && c.containsLoc(evt.getLocation())) + { + evt.setCancelled(true); + return; + } + } + } + + /** + * Deny mob movement inside arena. + * @param evt create spawn event. + */ + @EventHandler + public void onMobTarget(EntityTargetEvent evt) + { + if (!(evt.getEntity() instanceof Player) && evt.getTarget() instanceof Player) + { + final Player target = (Player) evt.getTarget(); + if (this.pli.containsGlobalPlayer(target.getName())) + { + evt.setCancelled(true); + } + } + } + + // ************************* + // ***** helpers / utilities + // ************************* + + /** + * Checks if a player is in spectation mode. + * + * @param p + * player object + * @return {@code true} if player is spectating + * @deprecated TODO replacement? + */ + @Deprecated + public static boolean isSpectating(final Player p) + { + return ArenaScoreboard.mainScoreboardHasPlayer("spectators", p); + } + + /** + * Finds entities by location and squared distance. + * + * @param loc + * base + * @param d + * maximum squared distance + * @return list of entities. + */ + private List getEntitiesByLocation(final Location loc, final double d) + { + final List ent = new ArrayList<>(); + for (final Entity e : loc.getWorld().getEntities()) + { + if (e.getLocation().distanceSquared(loc) <= d) + { + ent.add(e); + } + } + return ent; + } + + /** + * Check if given location matches given sign. + * + * @param l + * the location to be checked + * @param s + * the sign to be checked + * @return {@code true} if the location matches given sign. + */ + private boolean checkLocationMatchesSign(final Location l, final Sign s) + { + if (l != null) + { + if (l.getWorld() != null) + { + if (l.getWorld().getName().equalsIgnoreCase(s.getLocation().getWorld().getName())) + { + if (l.distance(s.getLocation()) < 1) + { + return true; + } + } + } + } + return false; + } + + private void updateEntities(final List players, final boolean visible) + { + for (final Player observer : players) + { + for (final Player player : players) + { + if (observer.getEntityId() != player.getEntityId()) + { + if (visible && !this.pli.containsGlobalLost(player.getName())) + { + observer.showPlayer(player); + } + else + { + observer.hidePlayer(player); + } + } + } + } + } + + private List getPlayersWithin(final Player player, final int distance) + { + final List res = new ArrayList<>(); + final int d2 = distance * distance; + for (final Player p : Bukkit.getServer().getOnlinePlayers()) + { + if (p.getWorld() == player.getWorld() && p.getLocation().distanceSquared(player.getLocation()) <= d2) + { + res.add(p); + } + } + return res; + } + + public String getName() + { + return this.minigame; + } + + public void setName(final String minigame) + { + this.minigame = minigame; + } + } diff --git a/API/src/main/java/com/comze_instancelabs/minigamesapi/ArenaLogger.java b/API/src/main/java/com/comze_instancelabs/minigamesapi/ArenaLogger.java index 728dbe97..cfde87a4 100644 --- a/API/src/main/java/com/comze_instancelabs/minigamesapi/ArenaLogger.java +++ b/API/src/main/java/com/comze_instancelabs/minigamesapi/ArenaLogger.java @@ -1,13 +1,691 @@ -package com.comze_instancelabs.minigamesapi; +/* + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. -import org.bukkit.Bukkit; + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -public class ArenaLogger { + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ +package com.comze_instancelabs.minigamesapi; - public static void debug(String msg) { - if (MinigamesAPI.debug) { - Bukkit.getConsoleSender().sendMessage("[" + System.currentTimeMillis() + " MGLIB-DBG] " + msg); - } - } +import java.util.function.Supplier; +import java.util.logging.Level; +import java.util.logging.LogRecord; +import java.util.logging.Logger; + +import org.bukkit.Bukkit; +/** + * Logging helper for arenas. + * + * @author instancelabs + */ +public class ArenaLogger +{ + + /** the plugin logger. */ + private Logger pluginLogger; + + /** the arena name to be used. */ + private String arenaName; + + /** + * The plugin logger to be used. + * + * @param logger + * logger to be used. + * @param arenaName + * arena name to use for logging. + */ + public ArenaLogger(Logger logger, String arenaName) + { + this.pluginLogger = logger; + this.arenaName = arenaName; + } + + /** + * Returns the arena prefix string. + * + * @return arena prefix string for logging. + */ + private String getArenaPrefix() + { + return "[arena:" + this.arenaName + "] "; //$NON-NLS-1$//$NON-NLS-2$ + } + + /** + * Log a SEVERE message. + *

+ * If the logger is currently enabled for the SEVERE message level then the given message is forwarded to all the registered output Handler objects. + *

+ * + * @param msg + * The string message (or a key in the message catalog) + */ + public void severe(String msg) + { + log(Level.SEVERE, msg); + } + + /** + * Log a WARNING message. + *

+ * If the logger is currently enabled for the WARNING message level then the given message is forwarded to all the registered output Handler objects. + *

+ * + * @param msg + * The string message (or a key in the message catalog) + */ + public void warning(String msg) + { + log(Level.WARNING, msg); + } + + /** + * Log an INFO message. + *

+ * If the logger is currently enabled for the INFO message level then the given message is forwarded to all the registered output Handler objects. + *

+ * + * @param msg + * The string message (or a key in the message catalog) + */ + public void info(String msg) + { + log(Level.INFO, msg); + } + + /** + * Log a CONFIG message. + *

+ * If the logger is currently enabled for the CONFIG message level then the given message is forwarded to all the registered output Handler objects. + *

+ * + * @param msg + * The string message (or a key in the message catalog) + */ + public void config(String msg) + { + log(Level.CONFIG, msg); + } + + /** + * Log a FINE message. + *

+ * If the logger is currently enabled for the FINE message level then the given message is forwarded to all the registered output Handler objects. + *

+ * + * @param msg + * The string message (or a key in the message catalog) + */ + public void fine(String msg) + { + log(Level.FINE, msg); + } + + /** + * Log a FINER message. + *

+ * If the logger is currently enabled for the FINER message level then the given message is forwarded to all the registered output Handler objects. + *

+ * + * @param msg + * The string message (or a key in the message catalog) + */ + public void finer(String msg) + { + log(Level.FINER, msg); + } + + /** + * Log a FINEST message. + *

+ * If the logger is currently enabled for the FINEST message level then the given message is forwarded to all the registered output Handler objects. + *

+ * + * @param msg + * The string message (or a key in the message catalog) + */ + public void finest(String msg) + { + log(Level.FINEST, msg); + } + + /** + * Log a message, with no arguments. + *

+ * If the logger is currently enabled for the given message level then the given message is forwarded to all the registered output Handler objects. + *

+ * + * @param level + * One of the message level identifiers, e.g., SEVERE + * @param msg + * The string message (or a key in the message catalog) + */ + public void log(Level level, String msg) + { + this.pluginLogger.log(level, getArenaPrefix() + msg); + } + + /** + * Log a message, which is only to be constructed if the logging level is such that the message will actually be logged. + *

+ * If the logger is currently enabled for the given message level then the message is constructed by invoking the provided supplier function and forwarded to all the registered output Handler + * objects. + *

+ * + * @param level + * One of the message level identifiers, e.g., SEVERE + * @param msgSupplier + * A function, which when called, produces the desired log message + */ + public void log(Level level, Supplier msgSupplier) + { + this.pluginLogger.log(level, () -> (getArenaPrefix() + msgSupplier.get())); + } + + /** + * Log a message, with one object parameter. + *

+ * If the logger is currently enabled for the given message level then a corresponding LogRecord is created and forwarded to all the registered output Handler objects. + *

+ * + * @param level + * One of the message level identifiers, e.g., SEVERE + * @param msg + * The string message (or a key in the message catalog) + * @param param1 + * parameter to the message + */ + public void log(Level level, String msg, Object param1) + { + this.pluginLogger.log(level, getArenaPrefix() + msg, param1); + } + + /** + * Log a message, with an array of object arguments. + *

+ * If the logger is currently enabled for the given message level then a corresponding LogRecord is created and forwarded to all the registered output Handler objects. + *

+ * + * @param level + * One of the message level identifiers, e.g., SEVERE + * @param msg + * The string message (or a key in the message catalog) + * @param params + * array of parameters to the message + */ + public void log(Level level, String msg, Object params[]) + { + this.pluginLogger.log(level, getArenaPrefix() + msg, params); + } + + /** + * Log a message, with associated Throwable information. + *

+ * If the logger is currently enabled for the given message level then the given arguments are stored in a LogRecord which is forwarded to all registered output handlers. + *

+ * Note that the thrown argument is stored in the LogRecord thrown property, rather than the LogRecord parameters property. Thus it is processed specially by output Formatters and is not treated + * as a formatting parameter to the LogRecord message property. + *

+ * + * @param level + * One of the message level identifiers, e.g., SEVERE + * @param msg + * The string message (or a key in the message catalog) + * @param thrown + * Throwable associated with log message. + */ + public void log(Level level, String msg, Throwable thrown) + { + this.pluginLogger.log(level, getArenaPrefix() + msg, thrown); + } + + /** + * Log a lazily constructed message, with associated Throwable information. + *

+ * If the logger is currently enabled for the given message level then the message is constructed by invoking the provided supplier function. The message and the given {@link Throwable} are then + * stored in a {@link LogRecord} which is forwarded to all registered output handlers. + *

+ * Note that the thrown argument is stored in the LogRecord thrown property, rather than the LogRecord parameters property. Thus it is processed specially by output Formatters and is not treated + * as a formatting parameter to the LogRecord message property. + *

+ * + * @param level + * One of the message level identifiers, e.g., SEVERE + * @param thrown + * Throwable associated with log message. + * @param msgSupplier + * A function, which when called, produces the desired log message + * @since 1.8 + */ + public void log(Level level, Throwable thrown, Supplier msgSupplier) + { + this.pluginLogger.log(level, thrown, () -> (getArenaPrefix() + msgSupplier.get())); + } + + /** + * Log a message, specifying source class and method, with no arguments. + *

+ * If the logger is currently enabled for the given message level then the given message is forwarded to all the registered output Handler objects. + *

+ * + * @param level + * One of the message level identifiers, e.g., SEVERE + * @param sourceClass + * name of class that issued the logging request + * @param sourceMethod + * name of method that issued the logging request + * @param msg + * The string message (or a key in the message catalog) + */ + public void logp(Level level, String sourceClass, String sourceMethod, String msg) + { + this.pluginLogger.logp(level, sourceClass, sourceMethod, getArenaPrefix() + msg); + } + + /** + * Log a lazily constructed message, specifying source class and method, with no arguments. + *

+ * If the logger is currently enabled for the given message level then the message is constructed by invoking the provided supplier function and forwarded to all the registered output Handler + * objects. + *

+ * + * @param level + * One of the message level identifiers, e.g., SEVERE + * @param sourceClass + * name of class that issued the logging request + * @param sourceMethod + * name of method that issued the logging request + * @param msgSupplier + * A function, which when called, produces the desired log message + * @since 1.8 + */ + public void logp(Level level, String sourceClass, String sourceMethod, Supplier msgSupplier) + { + this.pluginLogger.logp(level, sourceClass, sourceMethod, () -> (getArenaPrefix() + msgSupplier.get())); + } + + /** + * Log a message, specifying source class and method, with a single object parameter to the log message. + *

+ * If the logger is currently enabled for the given message level then a corresponding LogRecord is created and forwarded to all the registered output Handler objects. + *

+ * + * @param level + * One of the message level identifiers, e.g., SEVERE + * @param sourceClass + * name of class that issued the logging request + * @param sourceMethod + * name of method that issued the logging request + * @param msg + * The string message (or a key in the message catalog) + * @param param1 + * Parameter to the log message. + */ + public void logp(Level level, String sourceClass, String sourceMethod, String msg, Object param1) + { + this.pluginLogger.logp(level, sourceClass, sourceMethod, getArenaPrefix() + msg, param1); + } + + /** + * Log a message, specifying source class and method, with an array of object arguments. + *

+ * If the logger is currently enabled for the given message level then a corresponding LogRecord is created and forwarded to all the registered output Handler objects. + *

+ * + * @param level + * One of the message level identifiers, e.g., SEVERE + * @param sourceClass + * name of class that issued the logging request + * @param sourceMethod + * name of method that issued the logging request + * @param msg + * The string message (or a key in the message catalog) + * @param params + * Array of parameters to the message + */ + public void logp(Level level, String sourceClass, String sourceMethod, String msg, Object params[]) + { + this.pluginLogger.logp(level, sourceClass, sourceMethod, getArenaPrefix() + msg, params); + } + + /** + * Log a message, specifying source class and method, with associated Throwable information. + *

+ * If the logger is currently enabled for the given message level then the given arguments are stored in a LogRecord which is forwarded to all registered output handlers. + *

+ * Note that the thrown argument is stored in the LogRecord thrown property, rather than the LogRecord parameters property. Thus it is processed specially by output Formatters and is not treated + * as a formatting parameter to the LogRecord message property. + *

+ * + * @param level + * One of the message level identifiers, e.g., SEVERE + * @param sourceClass + * name of class that issued the logging request + * @param sourceMethod + * name of method that issued the logging request + * @param msg + * The string message (or a key in the message catalog) + * @param thrown + * Throwable associated with log message. + */ + public void logp(Level level, String sourceClass, String sourceMethod, String msg, Throwable thrown) + { + this.pluginLogger.logp(level, sourceClass, sourceMethod, getArenaPrefix() + msg, thrown); + } + + /** + * Log a lazily constructed message, specifying source class and method, with associated Throwable information. + *

+ * If the logger is currently enabled for the given message level then the message is constructed by invoking the provided supplier function. The message and the given {@link Throwable} are then + * stored in a {@link LogRecord} which is forwarded to all registered output handlers. + *

+ * Note that the thrown argument is stored in the LogRecord thrown property, rather than the LogRecord parameters property. Thus it is processed specially by output Formatters and is not treated + * as a formatting parameter to the LogRecord message property. + *

+ * + * @param level + * One of the message level identifiers, e.g., SEVERE + * @param sourceClass + * name of class that issued the logging request + * @param sourceMethod + * name of method that issued the logging request + * @param thrown + * Throwable associated with log message. + * @param msgSupplier + * A function, which when called, produces the desired log message + * @since 1.8 + */ + public void logp(Level level, String sourceClass, String sourceMethod, Throwable thrown, Supplier msgSupplier) + { + this.pluginLogger.logp(level, sourceClass, sourceMethod, thrown, () -> (getArenaPrefix() + msgSupplier.get())); + } + + /** + * Log a method entry. + *

+ * This is a convenience method that can be used to log entry to a method. A LogRecord with message "ENTRY", log level FINER, and the given sourceMethod and sourceClass is logged. + *

+ * + * @param sourceClass + * name of class that issued the logging request + * @param sourceMethod + * name of method that is being entered + */ + public void entering(String sourceClass, String sourceMethod) + { + this.pluginLogger.logp(Level.FINER, sourceClass, sourceMethod, getArenaPrefix() + "ENTRY"); //$NON-NLS-1$ + } + + /** + * Log a method entry, with one parameter. + *

+ * This is a convenience method that can be used to log entry to a method. A LogRecord with message "ENTRY {0}", log level FINER, and the given sourceMethod, sourceClass, and parameter is logged. + *

+ * + * @param sourceClass + * name of class that issued the logging request + * @param sourceMethod + * name of method that is being entered + * @param param1 + * parameter to the method being entered + */ + public void entering(String sourceClass, String sourceMethod, Object param1) + { + this.pluginLogger.logp(Level.FINER, sourceClass, sourceMethod, getArenaPrefix() + "ENTRY {0}", param1); //$NON-NLS-1$ + } + + /** + * Log a method entry, with an array of parameters. + *

+ * This is a convenience method that can be used to log entry to a method. A LogRecord with message "ENTRY" (followed by a format {N} indicator for each entry in the parameter array), log level + * FINER, and the given sourceMethod, sourceClass, and parameters is logged. + *

+ * + * @param sourceClass + * name of class that issued the logging request + * @param sourceMethod + * name of method that is being entered + * @param params + * array of parameters to the method being entered + */ + public void entering(String sourceClass, String sourceMethod, Object params[]) + { + String msg = getArenaPrefix() + "ENTRY"; //$NON-NLS-1$ + if (params == null) + { + logp(Level.FINER, sourceClass, sourceMethod, msg); + return; + } + if (!isLoggable(Level.FINER)) + return; + for (int i = 0; i < params.length; i++) + { + msg = msg + " {" + i + "}"; //$NON-NLS-1$ //$NON-NLS-2$ + } + this.pluginLogger.logp(Level.FINER, sourceClass, sourceMethod, msg, params); + } + + /** + * Log a method return. + *

+ * This is a convenience method that can be used to log returning from a method. A LogRecord with message "RETURN", log level FINER, and the given sourceMethod and sourceClass is logged. + *

+ * + * @param sourceClass + * name of class that issued the logging request + * @param sourceMethod + * name of the method + */ + public void exiting(String sourceClass, String sourceMethod) + { + this.pluginLogger.logp(Level.FINER, sourceClass, sourceMethod, getArenaPrefix() + "RETURN"); //$NON-NLS-1$ + } + + /** + * Log a method return, with result object. + *

+ * This is a convenience method that can be used to log returning from a method. A LogRecord with message "RETURN {0}", log level FINER, and the gives sourceMethod, sourceClass, and result object + * is logged. + *

+ * + * @param sourceClass + * name of class that issued the logging request + * @param sourceMethod + * name of the method + * @param result + * Object that is being returned + */ + public void exiting(String sourceClass, String sourceMethod, Object result) + { + this.pluginLogger.logp(Level.FINER, sourceClass, sourceMethod, getArenaPrefix() + "RETURN {0}", result); //$NON-NLS-1$ + } + + /** + * Log throwing an exception. + *

+ * This is a convenience method to log that a method is terminating by throwing an exception. The logging is done using the FINER level. + *

+ * If the logger is currently enabled for the given message level then the given arguments are stored in a LogRecord which is forwarded to all registered output handlers. The LogRecord's message + * is set to "THROW". + *

+ * Note that the thrown argument is stored in the LogRecord thrown property, rather than the LogRecord parameters property. Thus it is processed specially by output Formatters and is not treated + * as a formatting parameter to the LogRecord message property. + *

+ * + * @param sourceClass + * name of class that issued the logging request + * @param sourceMethod + * name of the method. + * @param thrown + * The Throwable that is being thrown. + */ + public void throwing(String sourceClass, String sourceMethod, Throwable thrown) + { + if (!isLoggable(Level.FINER)) + { + return; + } + LogRecord lr = new LogRecord(Level.FINER, getArenaPrefix() + "THROW"); //$NON-NLS-1$ + lr.setSourceClassName(sourceClass); + lr.setSourceMethodName(sourceMethod); + lr.setThrown(thrown); + this.pluginLogger.log(lr); + } + + /** + * Log a SEVERE message, which is only to be constructed if the logging level is such that the message will actually be logged. + *

+ * If the logger is currently enabled for the SEVERE message level then the message is constructed by invoking the provided supplier function and forwarded to all the registered output Handler + * objects. + *

+ * + * @param msgSupplier + * A function, which when called, produces the desired log message + * @since 1.8 + */ + public void severe(Supplier msgSupplier) + { + log(Level.SEVERE, msgSupplier); + } + + /** + * Log a WARNING message, which is only to be constructed if the logging level is such that the message will actually be logged. + *

+ * If the logger is currently enabled for the WARNING message level then the message is constructed by invoking the provided supplier function and forwarded to all the registered output Handler + * objects. + *

+ * + * @param msgSupplier + * A function, which when called, produces the desired log message + * @since 1.8 + */ + public void warning(Supplier msgSupplier) + { + log(Level.WARNING, msgSupplier); + } + + /** + * Log a INFO message, which is only to be constructed if the logging level is such that the message will actually be logged. + *

+ * If the logger is currently enabled for the INFO message level then the message is constructed by invoking the provided supplier function and forwarded to all the registered output Handler + * objects. + *

+ * + * @param msgSupplier + * A function, which when called, produces the desired log message + * @since 1.8 + */ + public void info(Supplier msgSupplier) + { + log(Level.INFO, msgSupplier); + } + + /** + * Log a CONFIG message, which is only to be constructed if the logging level is such that the message will actually be logged. + *

+ * If the logger is currently enabled for the CONFIG message level then the message is constructed by invoking the provided supplier function and forwarded to all the registered output Handler + * objects. + *

+ * + * @param msgSupplier + * A function, which when called, produces the desired log message + * @since 1.8 + */ + public void config(Supplier msgSupplier) + { + log(Level.CONFIG, msgSupplier); + } + + /** + * Log a FINE message, which is only to be constructed if the logging level is such that the message will actually be logged. + *

+ * If the logger is currently enabled for the FINE message level then the message is constructed by invoking the provided supplier function and forwarded to all the registered output Handler + * objects. + *

+ * + * @param msgSupplier + * A function, which when called, produces the desired log message + * @since 1.8 + */ + public void fine(Supplier msgSupplier) + { + log(Level.FINE, msgSupplier); + } + + /** + * Log a FINER message, which is only to be constructed if the logging level is such that the message will actually be logged. + *

+ * If the logger is currently enabled for the FINER message level then the message is constructed by invoking the provided supplier function and forwarded to all the registered output Handler + * objects. + *

+ * + * @param msgSupplier + * A function, which when called, produces the desired log message + * @since 1.8 + */ + public void finer(Supplier msgSupplier) + { + log(Level.FINER, msgSupplier); + } + + /** + * Log a FINEST message, which is only to be constructed if the logging level is such that the message will actually be logged. + *

+ * If the logger is currently enabled for the FINEST message level then the message is constructed by invoking the provided supplier function and forwarded to all the registered output Handler + * objects. + *

+ * + * @param msgSupplier + * A function, which when called, produces the desired log message + * @since 1.8 + */ + public void finest(Supplier msgSupplier) + { + log(Level.FINEST, msgSupplier); + } + + /** + * Get the log Level that has been specified for this Logger. The result may be null, which means that this logger's effective level will be inherited from its parent. + * + * @return this Logger's level + */ + public Level getLevel() + { + return this.pluginLogger.getLevel(); + } + + /** + * Check if a message of the given level would actually be logged by this logger. This check is based on the Loggers effective level, which may be inherited from its parent. + * + * @param level + * a message logging level + * @return true if the given message level is currently being logged. + */ + public boolean isLoggable(Level level) + { + return this.pluginLogger.isLoggable(level); + } + + /** + * Debug some string. + * + * @param msg + * debug message. + */ + public static void debug(final String msg) + { + if (MinigamesAPI.debug) + { + Bukkit.getConsoleSender().sendMessage("[" + System.currentTimeMillis() + " MGLIB-DBG] " + msg); //$NON-NLS-1$ //$NON-NLS-2$ + } + } + } diff --git a/API/src/main/java/com/comze_instancelabs/minigamesapi/ArenaMessageStrings.java b/API/src/main/java/com/comze_instancelabs/minigamesapi/ArenaMessageStrings.java new file mode 100644 index 00000000..55640cf5 --- /dev/null +++ b/API/src/main/java/com/comze_instancelabs/minigamesapi/ArenaMessageStrings.java @@ -0,0 +1,50 @@ +/* + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +package com.comze_instancelabs.minigamesapi; + +/** + * Strings for messages. + * + * @author mepeisen + */ +public interface ArenaMessageStrings +{ + + /** ARENA replacement. */ + String ARENA = ""; //$NON-NLS-1$ + + /** ACTION replacement. */ + String ACTION = ""; //$NON-NLS-1$ + + /** AUTHOR replacement. */ + String AUTHOR = ""; //$NON-NLS-1$ + + /** DESCRIPTION replacement. */ + String DESCRIPTION = ""; //$NON-NLS-1$ + + /** PLAYER replacement. */ + String PLAYER = ""; //$NON-NLS-1$ + + /** KILLER replacement. */ + String KILLER = ""; //$NON-NLS-1$ + + /** COUNT replacement. */ + String COUNT = ""; //$NON-NLS-1$ + + /** MAXCOUNT replacement. */ + String MAXCOUNT = ""; //$NON-NLS-1$ + +} diff --git a/API/src/main/java/com/comze_instancelabs/minigamesapi/ArenaPermissionStrings.java b/API/src/main/java/com/comze_instancelabs/minigamesapi/ArenaPermissionStrings.java new file mode 100644 index 00000000..2fee7cad --- /dev/null +++ b/API/src/main/java/com/comze_instancelabs/minigamesapi/ArenaPermissionStrings.java @@ -0,0 +1,32 @@ +/* + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +package com.comze_instancelabs.minigamesapi; + +/** + * Strings for arenas permissions. + * + * @author mepeisen + */ +public interface ArenaPermissionStrings +{ + + /** arenas vip permission. */ + String VIP = ".vip"; //$NON-NLS-1$ + + /** arena prefix for permission. */ + String PREFIX = ".arenas."; //$NON-NLS-1$ + +} diff --git a/API/src/main/java/com/comze_instancelabs/minigamesapi/ArenaPlayer.java b/API/src/main/java/com/comze_instancelabs/minigamesapi/ArenaPlayer.java index d024654c..8dd03943 100644 --- a/API/src/main/java/com/comze_instancelabs/minigamesapi/ArenaPlayer.java +++ b/API/src/main/java/com/comze_instancelabs/minigamesapi/ArenaPlayer.java @@ -1,3 +1,17 @@ +/* + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ package com.comze_instancelabs.minigamesapi; import java.util.HashMap; @@ -9,87 +23,217 @@ import com.comze_instancelabs.minigamesapi.util.AClass; -public class ArenaPlayer { - - String playername; - ItemStack[] inv; - ItemStack[] armor_inv; - GameMode original_gamemode = GameMode.SURVIVAL; - int original_xplvl = 0; - boolean noreward = false; - Arena currentArena; - AClass currentClass; - - private static HashMap players = new HashMap(); - - public static ArenaPlayer getPlayerInstance(String playername) { - if (!players.containsKey(playername)) { - return new ArenaPlayer(playername); - } else { - return players.get(playername); - } - } - - public ArenaPlayer(String playername) { - this.playername = playername; - players.put(playername, this); - } - - public Player getPlayer() { - return Bukkit.getPlayer(playername); - } - - public void setInventories(ItemStack[] inv, ItemStack[] armor_inv) { - this.inv = inv; - this.armor_inv = armor_inv; - } - - public ItemStack[] getInventory() { - return inv; - } - - public ItemStack[] getArmorInventory() { - return armor_inv; - } - - public GameMode getOriginalGamemode() { - return original_gamemode; - } - - public void setOriginalGamemode(GameMode original_gamemode) { - this.original_gamemode = original_gamemode; - } - - public int getOriginalXplvl() { - return original_xplvl; - } - - public void setOriginalXplvl(int original_xplvl) { - this.original_xplvl = original_xplvl; - } - - public boolean isNoReward() { - return noreward; - } - - public void setNoReward(boolean noreward) { - this.noreward = noreward; - } - - public Arena getCurrentArena() { - return currentArena; - } - - public void setCurrentArena(Arena currentArena) { - this.currentArena = currentArena; - } - - public AClass getCurrentClass() { - return currentClass; - } - - public void setCurrentClass(AClass currentClass) { - this.currentClass = currentClass; - } - +/** + * Internal minigames representation of a player being present in any arena. + * + *

+ * TODO: Remove from hashmap players as soon as a player leaves the server. + *

+ * + *

+ * TODO: Clear inventories as soon as it was re set while leaving. + *

+ * + * @author instancelabs + */ +public class ArenaPlayer +{ + + /** The players name. */ + private String playername; + /** the inventory stack. */ + private ItemStack[] inv; + /** the armor inventory stack. */ + private ItemStack[] armor_inv; + /** the original game mode of the player. */ + private GameMode original_gamemode = GameMode.SURVIVAL; + /** the original xp level of the player. */ + private int original_xplvl = 0; + /** the no-reward flag. */ + private boolean noreward = false; + /** the current arena. */ + private Arena currentArena; + /** the current class. */ + private AClass currentClass; + + /** the map holding the known arena player instances. */ + private static final HashMap players = new HashMap<>(); + + /** + * Returns the player instance for given player name; creates it on demand. + * + * @param playername + * name of the player. + * @return arena player instance. + */ + public static ArenaPlayer getPlayerInstance(final String playername) + { + if (!ArenaPlayer.players.containsKey(playername)) + { + return new ArenaPlayer(playername); + } + return ArenaPlayer.players.get(playername); + } + + /** + * Constructor to create the arena player. + * + * @param playername + * players name. + */ + public ArenaPlayer(final String playername) + { + this.playername = playername; + ArenaPlayer.players.put(playername, this); + } + + /** + * Returns the bukkit player. + * + * @return bukkit player. + */ + public Player getPlayer() + { + return Bukkit.getPlayer(this.playername); + } + + /** + * Sets the inventories being present befor the player joins the lobby. + * + * @param inv + * inventory of the player. + * @param armor_inv + * armor inventory of the player. + */ + public void setInventories(final ItemStack[] inv, final ItemStack[] armor_inv) + { + this.inv = inv; + this.armor_inv = armor_inv; + } + + /** + * Returns the players inventory before joining the lobby. + * + * @return player inventory. + */ + public ItemStack[] getInventory() + { + return this.inv; + } + + /** + * Returns the players armor inventory before joining the lobby. + * + * @return players armo inventory. + */ + public ItemStack[] getArmorInventory() + { + return this.armor_inv; + } + + /** + * Returns the original game mode before joining the lobby. + * + * @return original game mode. + */ + public GameMode getOriginalGamemode() + { + return this.original_gamemode; + } + + /** + * Sets the original game mode before joining the lobby. + * + * @param original_gamemode + * the players original game mode. + */ + public void setOriginalGamemode(final GameMode original_gamemode) + { + this.original_gamemode = original_gamemode; + } + + /** + * Returns the original xp level before joining the lobby. + * + * @return original xp mode before joining the lobby. + */ + public int getOriginalXplvl() + { + return this.original_xplvl; + } + + /** + * Sets the original xp level of the player. + * + * @param original_xplvl + * cp level before joining the lobby. + */ + public void setOriginalXplvl(final int original_xplvl) + { + this.original_xplvl = original_xplvl; + } + + /** + * Returns the is no reward flag. + * + * @return {@code true} if the player does not receive rewards. + */ + public boolean isNoReward() + { + return this.noreward; + } + + /** + * Sets the no-reward flag. + * + * @param noreward + * {@code true} if the player does not receive rewards. + */ + public void setNoReward(final boolean noreward) + { + this.noreward = noreward; + } + + /** + * Returns the current arena the player is located in. + * + * @return current arena or {@code null} if the player is not in any arena. + */ + public Arena getCurrentArena() + { + return this.currentArena; + } + + /** + * Sets the current arena the player is located in. + * + * @param currentArena + * current arena. + */ + public void setCurrentArena(final Arena currentArena) + { + this.currentArena = currentArena; + } + + /** + * Returns the current player class. + * + * @return player class. + */ + public AClass getCurrentClass() + { + return this.currentClass; + } + + /** + * Sets the current player class. + * + * @param currentClass + * player class. + */ + public void setCurrentClass(final AClass currentClass) + { + this.currentClass = currentClass; + } + } diff --git a/API/src/main/java/com/comze_instancelabs/minigamesapi/ArenaSetup.java b/API/src/main/java/com/comze_instancelabs/minigamesapi/ArenaSetup.java index bbff53fc..8db99d07 100644 --- a/API/src/main/java/com/comze_instancelabs/minigamesapi/ArenaSetup.java +++ b/API/src/main/java/com/comze_instancelabs/minigamesapi/ArenaSetup.java @@ -1,7 +1,22 @@ +/* + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ package com.comze_instancelabs.minigamesapi; import java.lang.reflect.Method; import java.util.ArrayList; +import java.util.logging.Level; import org.bukkit.Bukkit; import org.bukkit.ChatColor; @@ -13,229 +28,272 @@ import com.comze_instancelabs.minigamesapi.util.Util; import com.comze_instancelabs.minigamesapi.util.Validator; -public class ArenaSetup { - - // actually the most basic arena just needs a spawn and a lobby - - /** - * Sets the spawn for a single-spawn arena - * - * @param arenaname - * @param l - * Location of the spawn - */ - public void setSpawn(JavaPlugin plugin, String arenaname, Location l) { - Util.saveComponentForArena(plugin, arenaname, "spawns.spawn0", l); - } - - /** - * Sets a new spawn for a multi-spawn arena without the need of a given index - * - * @param plugin - * @param arenaname - * @param l - * Location of the spawn - * @return the automatically used index - */ - public int autoSetSpawn(JavaPlugin plugin, String arenaname, Location l) { - int count = Util.getAllSpawns(plugin, arenaname).size(); - Util.saveComponentForArena(plugin, arenaname, "spawns.spawn" + Integer.toString(count), l); - return count; - } - - /** - * Sets one of multiple spawns for a multi-spawn arena - * - * @param arenaname - * @param l - * Location of the spawn - * @param count - * Index of the spawn; if the given index is already set, the spawn location will be overwritten - */ - public void setSpawn(JavaPlugin plugin, String arenaname, Location l, int count) { - Util.saveComponentForArena(plugin, arenaname, "spawns.spawn" + Integer.toString(count), l); - } - - /** - * Removes a spawn at the given index - * - * @param plugin - * @param arenaname - * @param count - * Index of the spawn - */ - public boolean removeSpawn(JavaPlugin plugin, String arenaname, int count) { - ArenasConfig config = MinigamesAPI.getAPI().getPluginInstance(plugin).getArenasConfig(); - String path = "arenas." + arenaname + ".spawns.spawn" + Integer.toString(count); - boolean ret = false; - if (config.getConfig().isSet(path)) { - ret = true; - } - config.getConfig().set(path, null); - config.saveConfig(); - return ret; - } - - /** - * Sets the waiting lobby for an arena - * - * @param arenaname - * @param l - * Location of the lobby - */ - public void setLobby(JavaPlugin plugin, String arenaname, Location l) { - Util.saveComponentForArena(plugin, arenaname, "lobby", l); - } - - /** - * Sets the main lobby - * - * @param l - * Location of the lobby - */ - public void setMainLobby(JavaPlugin plugin, Location l) { - Util.saveMainLobby(plugin, l); - } - - /** - * Sets low and high boundaries for later blocks resetting - * - * @param plugin - * @param arenaname - * @param l - * Location to save - * @param low - * True if it's the low boundary, false if it's the high boundary - */ - public void setBoundaries(JavaPlugin plugin, String arenaname, Location l, boolean low) { - if (low) { - Util.saveComponentForArena(plugin, arenaname, "bounds.low", l); - } else { - Util.saveComponentForArena(plugin, arenaname, "bounds.high", l); - } - } - - /** - * Sets low and high boundaries for later blocks resetting for a sub component - * - * @param plugin - * @param arenaname - * @param l - * Location to save - * @param low - * True if it's the low boundary, false if it's the high boundary - * @param extra_component - * Sub component string - */ - public void setBoundaries(JavaPlugin plugin, String arenaname, Location l, boolean low, String extra_component) { - if (low) { - Util.saveComponentForArena(plugin, arenaname, extra_component + ".bounds.low", l); - } else { - Util.saveComponentForArena(plugin, arenaname, extra_component + ".bounds.high", l); - } - } - - /** - * Saves a given arena if it was set up properly. - * - * @return Arena or null if setup failed - */ - public Arena saveArena(JavaPlugin plugin, String arenaname) { - if (!Validator.isArenaValid(plugin, arenaname)) { - Bukkit.getConsoleSender().sendMessage(ChatColor.RED + "Arena " + arenaname + " appears to be invalid."); - return null; - } - PluginInstance pli = MinigamesAPI.getAPI().getPluginInstance(plugin); - if (pli.getArenaByName(arenaname) != null) { - pli.removeArenaByName(arenaname); - } - Arena a = Util.initArena(plugin, arenaname); - if (a.getArenaType() == ArenaType.REGENERATION) { - if (Util.isComponentForArenaValid(plugin, arenaname, "bounds")) { - Util.saveArenaToFile(plugin, arenaname); - } else { - Bukkit.getConsoleSender().sendMessage(ChatColor.RED + "Could not save arena to file because boundaries were not set up."); - } - } - this.setArenaVIP(plugin, arenaname, false); - pli.addArena(a); - - // experimental: - Class clazz = plugin.getClass(); - try { - Method method = clazz.getDeclaredMethod("loadArenas", JavaPlugin.class, pli.getArenasConfig().getClass()); - if (method != null) { - method.setAccessible(true); - Object ret = method.invoke(this, plugin, pli.getArenasConfig()); - System.out.println(ret); - pli.clearArenas(); - pli.addLoadedArenas((ArrayList) ret); - } - } catch (Exception e) { - System.out.println("Failed to update Arena list, please reload the server."); - e.printStackTrace(); - } - - String path = "arenas." + arenaname + ".displayname"; - if (!pli.getArenasConfig().getConfig().isSet(path)) { - pli.getArenasConfig().getConfig().set(path, arenaname); - pli.getArenasConfig().saveConfig(); - } - - return a; - } - - public void setPlayerCount(JavaPlugin plugin, String arena, int count, boolean max) { - String component = "max_players"; - if (!max) { - component = "min_players"; - } - String base = "arenas." + arena + "." + component; - MinigamesAPI.getAPI().getPluginInstance(plugin).getArenasConfig().getConfig().set(base, count); - MinigamesAPI.getAPI().getPluginInstance(plugin).getArenasConfig().saveConfig(); - } - - public int getPlayerCount(JavaPlugin plugin, String arena, boolean max) { - if (!max) { - if (!MinigamesAPI.getAPI().getPluginInstance(plugin).getArenasConfig().getConfig().isSet("arenas." + arena + ".min_players")) { - setPlayerCount(plugin, arena, plugin.getConfig().getInt("config.defaults.default_min_players"), max); - return plugin.getConfig().getInt("config.defaults.default_min_players"); - } - return MinigamesAPI.getAPI().getPluginInstance(plugin).getArenasConfig().getConfig().getInt("arenas." + arena + ".min_players"); - } - if (!MinigamesAPI.getAPI().getPluginInstance(plugin).getArenasConfig().getConfig().isSet("arenas." + arena + ".max_players")) { - setPlayerCount(plugin, arena, plugin.getConfig().getInt("config.defaults.default_max_players"), max); - return plugin.getConfig().getInt("config.defaults.default_max_players"); - } - return MinigamesAPI.getAPI().getPluginInstance(plugin).getArenasConfig().getConfig().getInt("arenas." + arena + ".max_players"); - } - - public void setArenaVIP(JavaPlugin plugin, String arena, boolean vip) { - MinigamesAPI.getAPI().getPluginInstance(plugin).getArenasConfig().getConfig().set("arenas." + arena + ".is_vip", vip); - MinigamesAPI.getAPI().getPluginInstance(plugin).getArenasConfig().saveConfig(); - } - - public boolean getArenaVIP(JavaPlugin plugin, String arena) { - return MinigamesAPI.getAPI().getPluginInstance(plugin).getArenasConfig().getConfig().getBoolean("arenas." + arena + ".is_vip"); - } - - public void setArenaEnabled(JavaPlugin plugin, String arena, boolean enabled) { - MinigamesAPI.getAPI().getPluginInstance(plugin).getArenasConfig().getConfig().set("arenas." + arena + ".enabled", enabled); - MinigamesAPI.getAPI().getPluginInstance(plugin).getArenasConfig().saveConfig(); - } - - public boolean getArenaEnabled(JavaPlugin plugin, String arena) { - FileConfiguration config = MinigamesAPI.getAPI().getPluginInstance(plugin).getArenasConfig().getConfig(); - return config.isSet("arenas." + arena + ".enabled") ? config.getBoolean("arenas." + arena + ".enabled") : true; - } - - public void setShowScoreboard(JavaPlugin plugin, String arena, boolean enabled) { - MinigamesAPI.getAPI().getPluginInstance(plugin).getArenasConfig().getConfig().set("arenas." + arena + ".showscoreboard", enabled); - MinigamesAPI.getAPI().getPluginInstance(plugin).getArenasConfig().saveConfig(); - } - - public boolean getShowScoreboard(JavaPlugin plugin, String arena) { - FileConfiguration config = MinigamesAPI.getAPI().getPluginInstance(plugin).getArenasConfig().getConfig(); - return config.isSet("arenas." + arena + ".showscoreboard") ? config.getBoolean("arenas." + arena + ".showscoreboard") : true; - } +/** + * Arena setup helper. + * + * @author instancelabs + */ +public class ArenaSetup +{ + + // actually the most basic arena just needs a spawn and a lobby + + /** + * Sets the spawn for a single-spawn arena + * + * @param arenaname + * @param l + * Location of the spawn + */ + public void setSpawn(final JavaPlugin plugin, final String arenaname, final Location l) + { + Util.saveComponentForArena(plugin, arenaname, "spawns.spawn0", l); + } + + /** + * Sets a new spawn for a multi-spawn arena without the need of a given index + * + * @param plugin + * @param arenaname + * @param l + * Location of the spawn + * @return the automatically used index + */ + public int autoSetSpawn(final JavaPlugin plugin, final String arenaname, final Location l) + { + final int count = Util.getAllSpawns(plugin, arenaname).size(); + Util.saveComponentForArena(plugin, arenaname, "spawns.spawn" + Integer.toString(count), l); + return count; + } + + /** + * Sets one of multiple spawns for a multi-spawn arena + * + * @param arenaname + * @param l + * Location of the spawn + * @param count + * Index of the spawn; if the given index is already set, the spawn location will be overwritten + */ + public void setSpawn(final JavaPlugin plugin, final String arenaname, final Location l, final int count) + { + Util.saveComponentForArena(plugin, arenaname, "spawns.spawn" + Integer.toString(count), l); + } + + /** + * Removes a spawn at the given index + * + * @param plugin + * @param arenaname + * @param count + * Index of the spawn + */ + public boolean removeSpawn(final JavaPlugin plugin, final String arenaname, final int count) + { + final ArenasConfig config = MinigamesAPI.getAPI().getPluginInstance(plugin).getArenasConfig(); + final String path = ArenaConfigStrings.ARENAS_PREFIX + arenaname + ".spawns.spawn" + Integer.toString(count); + boolean ret = false; + if (config.getConfig().isSet(path)) + { + ret = true; + } + config.getConfig().set(path, null); + config.saveConfig(); + return ret; + } + + /** + * Sets the waiting lobby for an arena + * + * @param arenaname + * @param l + * Location of the lobby + */ + public void setLobby(final JavaPlugin plugin, final String arenaname, final Location l) + { + Util.saveComponentForArena(plugin, arenaname, "lobby", l); + } + + /** + * Sets the main lobby + * + * @param l + * Location of the lobby + */ + public void setMainLobby(final JavaPlugin plugin, final Location l) + { + Util.saveMainLobby(plugin, l); + } + + /** + * Sets low and high boundaries for later blocks resetting + * + * @param plugin + * @param arenaname + * @param l + * Location to save + * @param low + * True if it's the low boundary, false if it's the high boundary + */ + public void setBoundaries(final JavaPlugin plugin, final String arenaname, final Location l, final boolean low) + { + if (low) + { + Util.saveComponentForArena(plugin, arenaname, ArenaConfigStrings.BOUNDS_LOW, l); + } + else + { + Util.saveComponentForArena(plugin, arenaname, ArenaConfigStrings.BOUNDS_HIGH, l); + } + } + + /** + * Sets low and high boundaries for later blocks resetting for a sub component + * + * @param plugin + * @param arenaname + * @param l + * Location to save + * @param low + * True if it's the low boundary, false if it's the high boundary + * @param extra_component + * Sub component string + */ + public void setBoundaries(final JavaPlugin plugin, final String arenaname, final Location l, final boolean low, final String extra_component) + { + if (low) + { + Util.saveComponentForArena(plugin, arenaname, extra_component + ".bounds.low", l); + } + else + { + Util.saveComponentForArena(plugin, arenaname, extra_component + ".bounds.high", l); + } + } + + /** + * Saves a given arena if it was set up properly. + * + * @return Arena or null if setup failed + */ + public Arena saveArena(final JavaPlugin plugin, final String arenaname) + { + if (!Validator.isArenaValid(plugin, arenaname)) + { + Bukkit.getConsoleSender().sendMessage(ChatColor.RED + "Arena " + arenaname + " appears to be invalid."); + return null; + } + final PluginInstance pli = MinigamesAPI.getAPI().getPluginInstance(plugin); + if (pli.getArenaByName(arenaname) != null) + { + pli.removeArenaByName(arenaname); + } + final Arena a = Util.initArena(plugin, arenaname); + if (a.getArenaType() == ArenaType.REGENERATION) + { + if (Util.isComponentForArenaValid(plugin, arenaname, "bounds")) + { + Util.saveArenaToFile(plugin, arenaname); + } + else + { + Bukkit.getConsoleSender().sendMessage(ChatColor.RED + "Could not save arena to file because boundaries were not set up."); + } + } + this.setArenaVIP(plugin, arenaname, false); + pli.addArena(a); + + // experimental: + final Class clazz = plugin.getClass(); + try + { + final Method method = clazz.getDeclaredMethod("loadArenas", JavaPlugin.class, pli.getArenasConfig().getClass()); + if (method != null) + { + method.setAccessible(true); + final Object ret = method.invoke(this, plugin, pli.getArenasConfig()); + pli.clearArenas(); + pli.addLoadedArenas((ArrayList) ret); + } + } + catch (final Exception e) + { + MinigamesAPI.getAPI().getLogger().log(Level.WARNING, "Failed to update Arena list, please reload the server.", e); + } + + final String path = ArenaConfigStrings.ARENAS_PREFIX + arenaname + ArenaConfigStrings.DISPLAYNAME_SUFFIX; + if (!pli.getArenasConfig().getConfig().isSet(path)) + { + pli.getArenasConfig().getConfig().set(path, arenaname); + pli.getArenasConfig().saveConfig(); + } + + return a; + } + + public void setPlayerCount(final JavaPlugin plugin, final String arena, final int count, final boolean max) + { + String component = "max_players"; + if (!max) + { + component = "min_players"; + } + final String base = ArenaConfigStrings.ARENAS_PREFIX + arena + "." + component; + MinigamesAPI.getAPI().getPluginInstance(plugin).getArenasConfig().getConfig().set(base, count); + MinigamesAPI.getAPI().getPluginInstance(plugin).getArenasConfig().saveConfig(); + } + + public int getPlayerCount(final JavaPlugin plugin, final String arena, final boolean max) + { + if (!max) + { + if (!MinigamesAPI.getAPI().getPluginInstance(plugin).getArenasConfig().getConfig().isSet(ArenaConfigStrings.ARENAS_PREFIX + arena + ".min_players")) + { + this.setPlayerCount(plugin, arena, plugin.getConfig().getInt(ArenaConfigStrings.CONFIG_DEFAULT_MIN_PLAYERS), max); + return plugin.getConfig().getInt(ArenaConfigStrings.CONFIG_DEFAULT_MIN_PLAYERS); + } + return MinigamesAPI.getAPI().getPluginInstance(plugin).getArenasConfig().getConfig().getInt(ArenaConfigStrings.ARENAS_PREFIX + arena + ".min_players"); + } + if (!MinigamesAPI.getAPI().getPluginInstance(plugin).getArenasConfig().getConfig().isSet(ArenaConfigStrings.ARENAS_PREFIX + arena + ".max_players")) + { + this.setPlayerCount(plugin, arena, plugin.getConfig().getInt(ArenaConfigStrings.CONFIG_DEFAULT_MAX_PLAYERS), max); + return plugin.getConfig().getInt(ArenaConfigStrings.CONFIG_DEFAULT_MAX_PLAYERS); + } + return MinigamesAPI.getAPI().getPluginInstance(plugin).getArenasConfig().getConfig().getInt(ArenaConfigStrings.ARENAS_PREFIX + arena + ".max_players"); + } + + public void setArenaVIP(final JavaPlugin plugin, final String arena, final boolean vip) + { + MinigamesAPI.getAPI().getPluginInstance(plugin).getArenasConfig().getConfig().set(ArenaConfigStrings.ARENAS_PREFIX + arena + ".is_vip", vip); + MinigamesAPI.getAPI().getPluginInstance(plugin).getArenasConfig().saveConfig(); + } + + public boolean getArenaVIP(final JavaPlugin plugin, final String arena) + { + return MinigamesAPI.getAPI().getPluginInstance(plugin).getArenasConfig().getConfig().getBoolean(ArenaConfigStrings.ARENAS_PREFIX + arena + ".is_vip"); + } + + public void setArenaEnabled(final JavaPlugin plugin, final String arena, final boolean enabled) + { + MinigamesAPI.getAPI().getPluginInstance(plugin).getArenasConfig().getConfig().set(ArenaConfigStrings.ARENAS_PREFIX + arena + ".enabled", enabled); + MinigamesAPI.getAPI().getPluginInstance(plugin).getArenasConfig().saveConfig(); + } + + public boolean getArenaEnabled(final JavaPlugin plugin, final String arena) + { + final FileConfiguration config = MinigamesAPI.getAPI().getPluginInstance(plugin).getArenasConfig().getConfig(); + return config.isSet(ArenaConfigStrings.ARENAS_PREFIX + arena + ".enabled") ? config.getBoolean(ArenaConfigStrings.ARENAS_PREFIX + arena + ".enabled") : true; + } + + public void setShowScoreboard(final JavaPlugin plugin, final String arena, final boolean enabled) + { + MinigamesAPI.getAPI().getPluginInstance(plugin).getArenasConfig().getConfig().set(ArenaConfigStrings.ARENAS_PREFIX + arena + ".showscoreboard", enabled); + MinigamesAPI.getAPI().getPluginInstance(plugin).getArenasConfig().saveConfig(); + } + + public boolean getShowScoreboard(final JavaPlugin plugin, final String arena) + { + final FileConfiguration config = MinigamesAPI.getAPI().getPluginInstance(plugin).getArenasConfig().getConfig(); + return config.isSet(ArenaConfigStrings.ARENAS_PREFIX + arena + ".showscoreboard") ? config.getBoolean(ArenaConfigStrings.ARENAS_PREFIX + arena + ".showscoreboard") : true; + } } diff --git a/API/src/main/java/com/comze_instancelabs/minigamesapi/ArenaState.java b/API/src/main/java/com/comze_instancelabs/minigamesapi/ArenaState.java index 69c7c6e1..d350c946 100644 --- a/API/src/main/java/com/comze_instancelabs/minigamesapi/ArenaState.java +++ b/API/src/main/java/com/comze_instancelabs/minigamesapi/ArenaState.java @@ -1,26 +1,95 @@ +/* + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ package com.comze_instancelabs.minigamesapi; import java.util.ArrayList; -import java.util.Arrays; import java.util.HashMap; +import java.util.List; +import java.util.Map; -public enum ArenaState { - - JOIN, STARTING, INGAME, RESTARTING; - - public static ArrayList getAllStateNames() { - return new ArrayList(Arrays.asList("JOIN", "STARTING", "INGAME", "RESTARTING")); - } - - public static HashMap getAllStateNameColors() { - HashMap ret = new HashMap() { - { - put("JOIN", "&a"); - put("STARTING", "&a"); - put("INGAME", "&4"); - put("RESTARTING", "&e"); - } - }; - return ret; - } +/** + * The states for an arena. + * + * @author instancelabs + */ +public enum ArenaState +{ + + /** the default state; players can join. */ + JOIN("&a"), //$NON-NLS-1$ + + /** the game is starting. */ + STARTING("&a"), //$NON-NLS-1$ + + /** the game is running. */ + INGAME("&4"), //$NON-NLS-1$ + + /** the arena is restarting after game ended; for example the broken blocks are replaced. */ + RESTARTING("&e"); //$NON-NLS-1$ + + /** the states color code. */ + private String colorCode; + + /** + * Constructor. + * + * @param colorCode + * the states color code + */ + private ArenaState(String colorCode) + { + this.colorCode = colorCode; + } + + /** + * Returns the color code for this state. + * + * @return color code used to display this state. + */ + public String getColorCode() + { + return this.colorCode; + } + + /** + * Returns a list with all state names. + * + * @return list with all state names. + */ + public static Iterable getAllStateNames() + { + final List result = new ArrayList<>(); + for (final ArenaState state : ArenaState.values()) + { + result.add(state.name()); + } + return result; + } + + /** + * Returns a map from state name to color code. + * + * @return map from state name to color code. + */ + public static Map getAllStateNameColors() + { + final Map result = new HashMap<>(); + for (final ArenaState state : ArenaState.values()) + { + result.put(state.name(), state.getColorCode()); + } + return result; + } } diff --git a/API/src/main/java/com/comze_instancelabs/minigamesapi/ArenaType.java b/API/src/main/java/com/comze_instancelabs/minigamesapi/ArenaType.java index 4d6b541d..eb8436b5 100644 --- a/API/src/main/java/com/comze_instancelabs/minigamesapi/ArenaType.java +++ b/API/src/main/java/com/comze_instancelabs/minigamesapi/ArenaType.java @@ -1,20 +1,38 @@ -package com.comze_instancelabs.minigamesapi; - -public enum ArenaType { +/* + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - /** - * Standard arena with lobby + spawn and lobby countdown; can have multiple spawns too - */ - DEFAULT, + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. - /** - * Players just join the game whenever they like, no lobby countdowns or arena/sign states; doesn't allow multiple spawns - */ - JUMPNRUN, - - /** - * Default arena + automatic regeneration - */ - REGENERATION + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ +package com.comze_instancelabs.minigamesapi; +/** + * Arena types. + */ +public enum ArenaType +{ + + /** + * Standard arena with lobby + spawn and lobby countdown; can have multiple spawns too + */ + DEFAULT, + + /** + * Players just join the game whenever they like, no lobby countdowns or arena/sign states; doesn't allow multiple spawns + */ + JUMPNRUN, + + /** + * Default arena + automatic regeneration + */ + REGENERATION + } diff --git a/API/src/main/java/com/comze_instancelabs/minigamesapi/ChannelStrings.java b/API/src/main/java/com/comze_instancelabs/minigamesapi/ChannelStrings.java new file mode 100644 index 00000000..f9676112 --- /dev/null +++ b/API/src/main/java/com/comze_instancelabs/minigamesapi/ChannelStrings.java @@ -0,0 +1,44 @@ +/* + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +package com.comze_instancelabs.minigamesapi; + +/** + * Pluginc hannel strings. + * + * @author mepeisen + */ +public interface ChannelStrings +{ + + /** bungee cord plugin channel. */ + String CHANNEL_BUNGEE_CORD = "BungeeCord"; //$NON-NLS-1$ + + /** + * Bungee-cord sub channel for minigames lib. + */ + String SUBCHANNEL_MINIGAMESLIB_BACK = "MinigamesLibBack"; //$NON-NLS-1$ + + /** + * Bungee-cord sub channel for minigames lib. + */ + String SUBCHANNEL_MINIGAMESLIB_REQUEST = "MinigamesLibRequest"; //$NON-NLS-1$ + + /** + * Bungee-cord sub channel for minigames lib. + */ + String SUBCHANNEL_MINIGAMESLIB_SIGN = "MinigamesLibSign"; //$NON-NLS-1$ + +} diff --git a/API/src/main/java/com/comze_instancelabs/minigamesapi/Classes.java b/API/src/main/java/com/comze_instancelabs/minigamesapi/Classes.java index ca18bade..6102f63a 100644 --- a/API/src/main/java/com/comze_instancelabs/minigamesapi/Classes.java +++ b/API/src/main/java/com/comze_instancelabs/minigamesapi/Classes.java @@ -1,11 +1,23 @@ +/* + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ package com.comze_instancelabs.minigamesapi; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; -import net.milkbowl.vault.economy.EconomyResponse; - import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Color; @@ -25,444 +37,600 @@ import com.comze_instancelabs.minigamesapi.util.Validator; import com.shampaggon.crackshot.CSUtility; -public class Classes { - - JavaPlugin plugin; - PluginInstance pli; - public HashMap lasticonm = new HashMap(); - - public Classes(JavaPlugin plugin) { - this.plugin = plugin; - this.pli = MinigamesAPI.getAPI().getPluginInstance(plugin); - } - - public Classes(PluginInstance pli, JavaPlugin plugin) { - this.plugin = plugin; - this.pli = pli; - } - - public void openGUI(final String p) { - final Classes cl = this; - IconMenu iconm; - int mincount = pli.getAClasses().keySet().size(); - if (!Validator.isPlayerOnline(p)) { - return; - } - Player player = Bukkit.getPlayerExact(p); - if (lasticonm.containsKey(p)) { - iconm = lasticonm.get(p); - } else { - iconm = new IconMenu(pli.getMessagesConfig().classes_item, (9 * plugin.getConfig().getInt("config.GUI.classes_gui_rows") > mincount - 1) ? 9 * plugin.getConfig().getInt("config.GUI.classes_gui_rows") : Math.round(mincount / 9) * 9 + 9, new IconMenu.OptionClickEventHandler() { - @Override - public void onOptionClick(IconMenu.OptionClickEvent event) { - if (event.getPlayer().getName().equalsIgnoreCase(p)) { - if (pli.global_players.containsKey(p)) { - if (pli.getArenas().contains(pli.global_players.get(p))) { - String d = event.getName(); - Player p = event.getPlayer(); - if (pli.getAClasses().containsKey(d)) { - cl.setClass(pli.getClassesHandler().getInternalNameByName(d), p.getName(), true); - } - } - } - } - event.setWillClose(true); - } - }, plugin); - - int c = 0; - for (String ac : pli.getAClasses().keySet()) { - AClass ac_ = pli.getAClasses().get(ac); - if (ac_.isEnabled()) { - if (!pli.show_classes_without_usage_permission) { - if (!kitPlayerHasPermission(ac_.getInternalName(), player)) { - continue; - } - } - int slot = c; - if (pli.getClassesConfig().getConfig().isSet("config.kits." + ac_.getInternalName() + ".slot")) { - slot = pli.getClassesConfig().getConfig().getInt("config.kits." + ac_.getInternalName() + ".slot"); - if (slot < 0 || slot > iconm.getSize() - 1) { - slot = c; - } - } - iconm.setOption(slot, ac_.getIcon().clone(), ac_.getName(), pli.getClassesConfig().getConfig().getString("config.kits." + ac_.getInternalName() + ".lore").split(";")); - c++; - } - } - } - - iconm.open(player); - lasticonm.put(p, iconm); - } - - public void getClass(String player) { - if (!pli.getPClasses().containsKey(player)) { - ArenaLogger.debug(player + " didn't select any kit and the auto_add_default_kit option might be turned off, thus he won't get any starting items."); - return; - } - AClass c = pli.getPClasses().get(player); - final Player p = Bukkit.getServer().getPlayer(player); - Util.clearInv(p); - ArrayList items = new ArrayList(Arrays.asList(c.getItems())); - ArrayList temp = new ArrayList(Arrays.asList(c.getItems())); - ArrayList tempguns = new ArrayList(); - final ArrayList temppotions = new ArrayList(); - final ArrayList temppotions_lv = new ArrayList(); - final ArrayList temppotions_duration = new ArrayList(); - - // crackshot support - for (ItemStack item : temp) { - if (item != null) { - if (item.hasItemMeta()) { - if (item.getItemMeta().hasDisplayName()) { - if (item.getItemMeta().getDisplayName().startsWith("crackshot:")) { - items.remove(item); - tempguns.add(item.getItemMeta().getDisplayName().split(":")[1]); - } else if (item.getItemMeta().getDisplayName().startsWith("potioneffect:")) { - items.remove(item); - String potioneffect = item.getItemMeta().getDisplayName().split(":")[1]; - String data = item.getItemMeta().getDisplayName().split(":")[2]; - Integer time = Integer.parseInt(data.substring(0, data.indexOf("#"))); - Integer lv = Integer.parseInt(data.split("#")[1]); - if (PotionEffectType.getByName(potioneffect) != null) { - temppotions.add(PotionEffectType.getByName(potioneffect)); - temppotions_lv.add(lv); - temppotions_duration.add(time); - } - } - } - } - } - } - - for (ItemStack item : items) { - if (item != null) { - Color c_ = null; - if (item.hasItemMeta()) { - if (item.getItemMeta().hasDisplayName()) { - if (item.getItemMeta().getDisplayName().startsWith("#") && item.getItemMeta().getDisplayName().length() == 7) { - c_ = Util.hexToRgb(item.getItemMeta().getDisplayName()); - } - } - } - if (item.getTypeId() == 298 || item.getTypeId() == 302 || item.getTypeId() == 306 || item.getTypeId() == 310 || item.getTypeId() == 314) { - if (item.getTypeId() == 298) { - LeatherArmorMeta lam = (LeatherArmorMeta) item.getItemMeta(); - if (c_ != null) { - lam.setColor(c_); - } - item.setItemMeta(lam); - } - p.getInventory().setHelmet(item); - continue; - } - if (item.getTypeId() == 299 || item.getTypeId() == 303 || item.getTypeId() == 307 || item.getTypeId() == 311 || item.getTypeId() == 315) { - if (item.getTypeId() == 299) { - LeatherArmorMeta lam = (LeatherArmorMeta) item.getItemMeta(); - if (c_ != null) { - lam.setColor(c_); - } - item.setItemMeta(lam); - } - p.getInventory().setChestplate(item); - continue; - } - if (item.getTypeId() == 300 || item.getTypeId() == 304 || item.getTypeId() == 308 || item.getTypeId() == 312 || item.getTypeId() == 316) { - if (item.getTypeId() == 300) { - LeatherArmorMeta lam = (LeatherArmorMeta) item.getItemMeta(); - if (c_ != null) { - lam.setColor(c_); - } - item.setItemMeta(lam); - } - p.getInventory().setLeggings(item); - continue; - } - if (item.getTypeId() == 301 || item.getTypeId() == 305 || item.getTypeId() == 309 || item.getTypeId() == 313 || item.getTypeId() == 317) { - if (item.getTypeId() == 301) { - LeatherArmorMeta lam = (LeatherArmorMeta) item.getItemMeta(); - if (c_ != null) { - lam.setColor(c_); - } - item.setItemMeta(lam); - } - p.getInventory().setBoots(item); - continue; - } - if (item.getType() != Material.AIR) { - p.getInventory().addItem(item); - } - } - } - // p.getInventory().setContents((ItemStack[]) items.toArray(new ItemStack[items.size()])); - p.updateInventory(); - - if (MinigamesAPI.getAPI().crackshot) { - for (String t : tempguns) { - CSUtility cs = new CSUtility(); - cs.giveWeapon(p, t, 1); - } - } - - Bukkit.getScheduler().runTaskLater(plugin, new Runnable() { - public void run() { - if (p != null) { - int index = 0; - for (PotionEffectType t : temppotions) { - p.addPotionEffect(new PotionEffect(t, temppotions_duration.get(index), temppotions_lv.get(index))); - index++; - } - } - } - }, 10L); - - } - - /** - * Sets the current class of a player - * - * @param classname - * the INTERNAL classname - * @param player - */ - public void setClass(String internalname, String player, boolean money) { - for (String c : pli.getAClasses().keySet()) { - if (c.toLowerCase().equalsIgnoreCase(internalname.toLowerCase())) { - internalname = c; - } - } - if (!kitPlayerHasPermission(internalname, Bukkit.getPlayer(player))) { - Bukkit.getPlayer(player).sendMessage(pli.getMessagesConfig().no_perm); - return; - } - boolean continue_ = true; - if (money) { - if (kitRequiresMoney(internalname)) { - continue_ = kitTakeMoney(Bukkit.getPlayer(player), internalname); - } - } - if (continue_) { - pli.setPClass(player, this.getClassByInternalname(internalname)); - Bukkit.getPlayer(player).sendMessage(pli.getMessagesConfig().set_kit.replaceAll("", ChatColor.translateAlternateColorCodes('&', getClassByInternalname(internalname).getName()))); - } - } - - public String getInternalNameByName(String name) { - for (AClass ac : pli.getAClasses().values()) { - if (ac.getName().equalsIgnoreCase(name)) { - return ac.getInternalName(); - } - } - return "default"; - } - - public AClass getClassByInternalname(String internalname) { - for (AClass ac : pli.getAClasses().values()) { - if (ac.getInternalName().equalsIgnoreCase(internalname)) { - return ac; - } - } - return null; - } - - public boolean hasClass(String player) { - return pli.getPClasses().containsKey(player); - } - - public String getSelectedClass(String player) { - if (hasClass(player)) { - return pli.getPClasses().get(player).getInternalName(); - } - return "default"; - } - - public void loadClasses() { - Bukkit.getScheduler().runTaskLater(plugin, new Runnable() { - public void run() { - FileConfiguration config = pli.getClassesConfig().getConfig(); - if (config.isSet("config.kits")) { - for (String aclass : config.getConfigurationSection("config.kits.").getKeys(false)) { - AClass n; - if (config.isSet("config.kits." + aclass + ".icon")) { - n = new AClass(plugin, config.getString("config.kits." + aclass + ".name"), aclass, config.isSet("config.kits." + aclass + ".enabled") ? config.getBoolean("config.kits." + aclass + ".enabled") : true, Util.parseItems(config.getString("config.kits." + aclass + ".items")), Util.parseItems(config.getString("config.kits." + aclass + ".icon")).get(0)); - } else { - n = new AClass(plugin, config.getString("config.kits." + aclass + ".name"), aclass, config.isSet("config.kits." + aclass + ".enabled") ? config.getBoolean("config.kits." + aclass + ".enabled") : true, Util.parseItems(config.getString("config.kits." + aclass + ".items"))); - } - pli.addAClass(config.getString("config.kits." + aclass + ".name"), n); - if (!config.isSet("config.kits." + aclass + ".items") || !config.isSet("config.kits." + aclass + ".lore")) { - plugin.getLogger().warning("One of the classes found in the config file is invalid: " + aclass + ". Missing itemid or lore!"); - } - } - } - } - }, 20L); - } - - /** - * Please use new Classes().loadClasses(); - * - * @param plugin - */ - @Deprecated - public static void loadClasses(final JavaPlugin plugin) { - Bukkit.getScheduler().runTaskLater(plugin, new Runnable() { - public void run() { - FileConfiguration config = MinigamesAPI.getAPI().getPluginInstance(plugin).getClassesConfig().getConfig(); - if (config.isSet("config.kits")) { - for (String aclass : config.getConfigurationSection("config.kits.").getKeys(false)) { - AClass n; - if (config.isSet("config.kits." + aclass + ".icon")) { - n = new AClass(plugin, config.getString("config.kits." + aclass + ".name"), aclass, config.isSet("config.kits." + aclass + ".enabled") ? config.getBoolean("config.kits." + aclass + ".enabled") : true, Util.parseItems(config.getString("config.kits." + aclass + ".items")), Util.parseItems(config.getString("config.kits." + aclass + ".icon")).get(0)); - } else { - n = new AClass(plugin, config.getString("config.kits." + aclass + ".name"), aclass, config.isSet("config.kits." + aclass + ".enabled") ? config.getBoolean("config.kits." + aclass + ".enabled") : true, Util.parseItems(config.getString("config.kits." + aclass + ".items"))); - } - // pli.addAClass(aclass, n); - MinigamesAPI.getAPI().getPluginInstance(plugin).addAClass(config.getString("config.kits." + aclass + ".name"), n); - if (!config.isSet("config.kits." + aclass + ".items") || !config.isSet("config.kits." + aclass + ".lore")) { - plugin.getLogger().warning("One of the classes found in the config file is invalid: " + aclass + ". Missing itemid or lore!"); - } - } - } - } - }, 20L); - } - - /** - * Returns whether the kit requires money to use it - * - * @param kit - * Internal name of the kit - * @return - */ - public boolean kitRequiresMoney(String kit) { - return pli.getClassesConfig().getConfig().getBoolean("config.kits." + kit + ".requires_money"); - } - - /** - * Gives the player the kit if he has enough money to buy it - * - * @param p - * Player to give the kit to - * @param kit - * Internal name of the kit - * @return - */ - public boolean kitTakeMoney(Player p, String kit) { - // Credits - if (plugin.getConfig().getBoolean("config.use_credits_instead_of_money_for_kits")) { - String uuid = p.getUniqueId().toString(); - int points = 0; - if (!MinigamesAPI.getAPI().statsglobal.getConfig().isSet("players." + uuid + ".points")) { - points = pli.getStatsInstance().getPoints(p.getName()); - MinigamesAPI.getAPI().statsglobal.getConfig().set("players." + uuid + ".points", points); - MinigamesAPI.getAPI().statsglobal.saveConfig(); - } else { - points = MinigamesAPI.getAPI().statsglobal.getConfig().getInt("players." + uuid + ".points"); - } - if (plugin.getConfig().getBoolean("config.buy_classes_forever")) { - ClassesConfig cl = pli.getClassesConfig(); - if (!cl.getConfig().isSet("players.bought_kits." + p.getName() + "." + kit)) { - int money = pli.getClassesConfig().getConfig().getInt("config.kits." + kit + ".money_amount"); - if (points >= money) { - MinigamesAPI.getAPI().statsglobal.getConfig().set("players." + uuid + ".points", points - money); - MinigamesAPI.getAPI().statsglobal.saveConfig(); - cl.getConfig().set("players.bought_kits." + p.getName() + "." + kit, true); - cl.saveConfig(); - p.sendMessage(pli.getMessagesConfig().successfully_bought_kit.replaceAll("", ChatColor.translateAlternateColorCodes('&', getClassByInternalname(kit).getName())).replaceAll("", Integer.toString(money))); - } else { - p.sendMessage(pli.getMessagesConfig().not_enough_money); - return false; - } - } else { - return true; - } - } else { - if (hasClass(p.getName())) { - if (getSelectedClass(p.getName()).equalsIgnoreCase(kit)) { - return false; - } - } - ClassesConfig config = pli.getClassesConfig(); - int money = config.getConfig().getInt("config.kits." + kit + ".money_amount"); - if (points >= money) { - MinigamesAPI.getAPI().statsglobal.getConfig().set("players." + uuid + ".points", points - money); - MinigamesAPI.getAPI().statsglobal.saveConfig(); - p.sendMessage(pli.getMessagesConfig().successfully_bought_kit.replaceAll("", ChatColor.translateAlternateColorCodes('&', getClassByInternalname(kit).getName())).replaceAll("", Integer.toString(money))); - } else { - p.sendMessage(pli.getMessagesConfig().not_enough_money); - return false; - } - } - return true; - } - - // Money (economy) - if (!MinigamesAPI.getAPI().economy) { - plugin.getLogger().warning("Economy is turned OFF. You can turn it on in the config."); - return false; - } - if (MinigamesAPI.economy) { - if (plugin.getConfig().getBoolean("config.buy_classes_forever")) { - ClassesConfig cl = pli.getClassesConfig(); - if (!cl.getConfig().isSet("players.bought_kits." + p.getName() + "." + kit)) { - int money = pli.getClassesConfig().getConfig().getInt("config.kits." + kit + ".money_amount"); - if (MinigamesAPI.getAPI().econ.getBalance(p.getName()) >= money) { - EconomyResponse r = MinigamesAPI.getAPI().econ.withdrawPlayer(p.getName(), money); - if (!r.transactionSuccess()) { - p.sendMessage(String.format("An error occured: %s", r.errorMessage)); - return false; - } - cl.getConfig().set("players.bought_kits." + p.getName() + "." + kit, true); - cl.saveConfig(); - p.sendMessage(pli.getMessagesConfig().successfully_bought_kit.replaceAll("", ChatColor.translateAlternateColorCodes('&', getClassByInternalname(kit).getName())).replaceAll("", Integer.toString(money))); - } else { - p.sendMessage(pli.getMessagesConfig().not_enough_money); - return false; - } - } else { - return true; - } - } else { - if (hasClass(p.getName())) { - if (getSelectedClass(p.getName()).equalsIgnoreCase(kit)) { - return false; - } - if (kitRequiresMoney(kit)) { - Util.sendMessage(plugin, p, pli.getMessagesConfig().kit_warning); - } - } - ClassesConfig config = pli.getClassesConfig(); - int money = config.getConfig().getInt("config.kits." + kit + ".money_amount"); - if (MinigamesAPI.getAPI().econ.getBalance(p.getName()) >= money) { - EconomyResponse r = MinigamesAPI.getAPI().econ.withdrawPlayer(p.getName(), money); - if (!r.transactionSuccess()) { - p.sendMessage(String.format("An error occured: %s", r.errorMessage)); - return false; - } - p.sendMessage(pli.getMessagesConfig().successfully_bought_kit.replaceAll("", ChatColor.translateAlternateColorCodes('&', getClassByInternalname(kit).getName())).replaceAll("", Integer.toString(money))); - } else { - p.sendMessage(pli.getMessagesConfig().not_enough_money); - return false; - } - } - return true; - } else { - return false; - } - - } - - public boolean kitPlayerHasPermission(String kit, Player p) { - if (!pli.getClassesConfig().getConfig().getBoolean("config.kits." + kit + ".requires_permission")) { - return true; - } else { - if (p.hasPermission(pli.getClassesConfig().getConfig().getString("config.kits." + kit + ".permission_node"))) { - return true; - } else { - return false; - } - } - } +import net.milkbowl.vault.economy.EconomyResponse; +/** + * Classes helper. + * + * @author instancelabs + */ +public class Classes +{ + + JavaPlugin plugin; + PluginInstance pli; + public HashMap lasticonm = new HashMap<>(); + + public Classes(final JavaPlugin plugin) + { + this.plugin = plugin; + this.pli = MinigamesAPI.getAPI().getPluginInstance(plugin); + } + + public Classes(final PluginInstance pli, final JavaPlugin plugin) + { + this.plugin = plugin; + this.pli = pli; + } + + public void openGUI(final String p) + { + final Classes cl = this; + IconMenu iconm; + final int mincount = this.pli.getAClasses().keySet().size(); + if (!Validator.isPlayerOnline(p)) + { + return; + } + final Player player = Bukkit.getPlayerExact(p); + if (this.lasticonm.containsKey(p)) + { + iconm = this.lasticonm.get(p); + } + else + { + iconm = new IconMenu(this.pli.getMessagesConfig().classes_item, (9 * this.plugin.getConfig().getInt(ArenaConfigStrings.CONFIG_CLASSES_GUI_ROWS) > mincount - 1) + ? 9 * this.plugin.getConfig().getInt(ArenaConfigStrings.CONFIG_CLASSES_GUI_ROWS) : Math.round(mincount / 9) * 9 + 9, event -> { + if (event.getPlayer().getName().equalsIgnoreCase(p)) + { + if (Classes.this.pli.global_players.containsKey(p)) + { + if (Classes.this.pli.getArenas().contains(Classes.this.pli.global_players.get(p))) + { + final String d = event.getName(); + final Player p1 = event.getPlayer(); + if (Classes.this.pli.getAClasses().containsKey(d)) + { + cl.setClass(Classes.this.pli.getClassesHandler().getInternalNameByName(d), p1.getName(), true); + } + } + } + } + event.setWillClose(true); + }, this.plugin); + + int c = 0; + for (final String ac : this.pli.getAClasses().keySet()) + { + final AClass ac_ = this.pli.getAClasses().get(ac); + if (ac_.isEnabled()) + { + if (!this.pli.show_classes_without_usage_permission) + { + if (!this.kitPlayerHasPermission(ac_.getInternalName(), player)) + { + continue; + } + } + int slot = c; + if (this.pli.getClassesConfig().getConfig().isSet("config.kits." + ac_.getInternalName() + ".slot")) + { + slot = this.pli.getClassesConfig().getConfig().getInt("config.kits." + ac_.getInternalName() + ".slot"); + if (slot < 0 || slot > iconm.getSize() - 1) + { + slot = c; + } + } + iconm.setOption(slot, ac_.getIcon().clone(), ac_.getName(), this.pli.getClassesConfig().getConfig().getString("config.kits." + ac_.getInternalName() + ".lore").split(";")); + c++; + } + } + } + + iconm.open(player); + this.lasticonm.put(p, iconm); + } + + public void getClass(final String player) + { + if (!this.pli.getPClasses().containsKey(player)) + { + ArenaLogger.debug(player + " didn't select any kit and the auto_add_default_kit option might be turned off, thus he won't get any starting items."); + return; + } + final AClass c = this.pli.getPClasses().get(player); + if (c == null) + { + ArenaLogger.debug(player + " didn't select any kit and the auto_add_default_kit option might be turned off, thus he won't get any starting items."); + return; + } + final Player p = Bukkit.getServer().getPlayer(player); + Util.clearInv(p); + final ArrayList items = new ArrayList<>(Arrays.asList(c.getItems())); + final ArrayList temp = new ArrayList<>(Arrays.asList(c.getItems())); + final ArrayList tempguns = new ArrayList<>(); + final ArrayList temppotions = new ArrayList<>(); + final ArrayList temppotions_lv = new ArrayList<>(); + final ArrayList temppotions_duration = new ArrayList<>(); + + // crackshot support + for (final ItemStack item : temp) + { + if (item != null) + { + if (item.hasItemMeta()) + { + if (item.getItemMeta().hasDisplayName()) + { + if (item.getItemMeta().getDisplayName().startsWith("crackshot:")) + { + items.remove(item); + tempguns.add(item.getItemMeta().getDisplayName().split(":")[1]); + } + else if (item.getItemMeta().getDisplayName().startsWith("potioneffect:")) + { + items.remove(item); + final String potioneffect = item.getItemMeta().getDisplayName().split(":")[1]; + final String data = item.getItemMeta().getDisplayName().split(":")[2]; + final Integer time = Integer.parseInt(data.substring(0, data.indexOf("#"))); + final Integer lv = Integer.parseInt(data.split("#")[1]); + if (PotionEffectType.getByName(potioneffect) != null) + { + temppotions.add(PotionEffectType.getByName(potioneffect)); + temppotions_lv.add(lv); + temppotions_duration.add(time); + } + } + } + } + } + } + + for (final ItemStack item : items) + { + if (item != null) + { + Color c_ = null; + if (item.hasItemMeta()) + { + if (item.getItemMeta().hasDisplayName()) + { + if (item.getItemMeta().getDisplayName().startsWith("#") && item.getItemMeta().getDisplayName().length() == 7) + { + c_ = Util.hexToRgb(item.getItemMeta().getDisplayName()); + } + } + } + if (item.getTypeId() == 298 || item.getTypeId() == 302 || item.getTypeId() == 306 || item.getTypeId() == 310 || item.getTypeId() == 314) + { + if (item.getTypeId() == 298) + { + final LeatherArmorMeta lam = (LeatherArmorMeta) item.getItemMeta(); + if (c_ != null) + { + lam.setColor(c_); + } + item.setItemMeta(lam); + } + p.getInventory().setHelmet(item); + continue; + } + if (item.getTypeId() == 299 || item.getTypeId() == 303 || item.getTypeId() == 307 || item.getTypeId() == 311 || item.getTypeId() == 315) + { + if (item.getTypeId() == 299) + { + final LeatherArmorMeta lam = (LeatherArmorMeta) item.getItemMeta(); + if (c_ != null) + { + lam.setColor(c_); + } + item.setItemMeta(lam); + } + p.getInventory().setChestplate(item); + continue; + } + if (item.getTypeId() == 300 || item.getTypeId() == 304 || item.getTypeId() == 308 || item.getTypeId() == 312 || item.getTypeId() == 316) + { + if (item.getTypeId() == 300) + { + final LeatherArmorMeta lam = (LeatherArmorMeta) item.getItemMeta(); + if (c_ != null) + { + lam.setColor(c_); + } + item.setItemMeta(lam); + } + p.getInventory().setLeggings(item); + continue; + } + if (item.getTypeId() == 301 || item.getTypeId() == 305 || item.getTypeId() == 309 || item.getTypeId() == 313 || item.getTypeId() == 317) + { + if (item.getTypeId() == 301) + { + final LeatherArmorMeta lam = (LeatherArmorMeta) item.getItemMeta(); + if (c_ != null) + { + lam.setColor(c_); + } + item.setItemMeta(lam); + } + p.getInventory().setBoots(item); + continue; + } + if (item.getType() != Material.AIR) + { + p.getInventory().addItem(item); + } + } + } + // p.getInventory().setContents((ItemStack[]) items.toArray(new ItemStack[items.size()])); + p.updateInventory(); + + if (MinigamesAPI.getAPI().crackshotAvailable()) + { + for (final String t : tempguns) + { + final CSUtility cs = new CSUtility(); + cs.giveWeapon(p, t, 1); + } + } + + Bukkit.getScheduler().runTaskLater(this.plugin, () -> { + if (p != null) + { + int index = 0; + for (final PotionEffectType t : temppotions) + { + p.addPotionEffect(new PotionEffect(t, temppotions_duration.get(index), temppotions_lv.get(index))); + index++; + } + } + }, 10L); + + } + + /** + * Sets the current class of a player + * + * @param iname + * the INTERNAL classname + * @param player + */ + public void setClass(String iname, final String player, final boolean money) + { + String internalname = iname; + for (final String c : this.pli.getAClasses().keySet()) + { + if (c.toLowerCase().equalsIgnoreCase(internalname.toLowerCase())) + { + internalname = c; + } + } + if (!this.kitPlayerHasPermission(internalname, Bukkit.getPlayer(player))) + { + Bukkit.getPlayer(player).sendMessage(this.pli.getMessagesConfig().no_perm); + return; + } + boolean continue_ = true; + if (money) + { + if (this.kitRequiresMoney(internalname)) + { + continue_ = this.kitTakeMoney(Bukkit.getPlayer(player), internalname); + } + } + if (continue_) + { + final AClass classByInternalname = this.getClassByInternalname(internalname); + this.pli.setPClass(player, classByInternalname); + if (classByInternalname != null) + { + final String set_kit_msg = this.pli.getMessagesConfig().set_kit; + Bukkit.getPlayer(player) + .sendMessage(set_kit_msg.replaceAll("", ChatColor.translateAlternateColorCodes('&', classByInternalname.getName()))); + } + } + } + + public String getInternalNameByName(final String name) + { + for (final AClass ac : this.pli.getAClasses().values()) + { + if (ac.getName().equalsIgnoreCase(name)) + { + return ac.getInternalName(); + } + } + return "default"; + } + + public AClass getClassByInternalname(final String internalname) + { + for (final AClass ac : this.pli.getAClasses().values()) + { + if (ac.getInternalName().equalsIgnoreCase(internalname)) + { + return ac; + } + } + return null; + } + + public boolean hasClass(final String player) + { + return this.pli.getPClasses().containsKey(player); + } + + public String getSelectedClass(final String player) + { + if (this.hasClass(player)) + { + return this.pli.getPClasses().get(player).getInternalName(); + } + return "default"; + } + + public void loadClasses() + { + Bukkit.getScheduler().runTaskLater(this.plugin, () -> { + final FileConfiguration config = Classes.this.pli.getClassesConfig().getConfig(); + if (config.isSet("config.kits")) + { + for (final String aclass : config.getConfigurationSection("config.kits.").getKeys(false)) + { + AClass n; + if (config.isSet("config.kits." + aclass + ".icon")) + { + n = new AClass(Classes.this.plugin, config.getString("config.kits." + aclass + ".name"), aclass, + config.isSet("config.kits." + aclass + ".enabled") ? config.getBoolean("config.kits." + aclass + ".enabled") : true, + Util.parseItems(config.getString("config.kits." + aclass + ".items")), Util.parseItems(config.getString("config.kits." + aclass + ".icon")).get(0)); + } + else + { + n = new AClass(Classes.this.plugin, config.getString("config.kits." + aclass + ".name"), aclass, + config.isSet("config.kits." + aclass + ".enabled") ? config.getBoolean("config.kits." + aclass + ".enabled") : true, + Util.parseItems(config.getString("config.kits." + aclass + ".items"))); + } + Classes.this.pli.addAClass(config.getString("config.kits." + aclass + ".name"), n); + if (!config.isSet("config.kits." + aclass + ".items") || !config.isSet("config.kits." + aclass + ".lore")) + { + Classes.this.plugin.getLogger().warning("One of the classes found in the config file is invalid: " + aclass + ". Missing itemid or lore!"); + } + } + } + }, 20L); + } + + /** + * Please use new Classes().loadClasses(); + * + * @param plugin + */ + @Deprecated + public static void loadClasses(final JavaPlugin plugin) + { + Bukkit.getScheduler().runTaskLater(plugin, () -> { + final FileConfiguration config = MinigamesAPI.getAPI().getPluginInstance(plugin).getClassesConfig().getConfig(); + if (config.isSet("config.kits")) + { + for (final String aclass : config.getConfigurationSection("config.kits.").getKeys(false)) + { + AClass n; + if (config.isSet("config.kits." + aclass + ".icon")) + { + n = new AClass(plugin, config.getString("config.kits." + aclass + ".name"), aclass, + config.isSet("config.kits." + aclass + ".enabled") ? config.getBoolean("config.kits." + aclass + ".enabled") : true, + Util.parseItems(config.getString("config.kits." + aclass + ".items")), Util.parseItems(config.getString("config.kits." + aclass + ".icon")).get(0)); + } + else + { + n = new AClass(plugin, config.getString("config.kits." + aclass + ".name"), aclass, + config.isSet("config.kits." + aclass + ".enabled") ? config.getBoolean("config.kits." + aclass + ".enabled") : true, + Util.parseItems(config.getString("config.kits." + aclass + ".items"))); + } + // pli.addAClass(aclass, n); + MinigamesAPI.getAPI().getPluginInstance(plugin).addAClass(config.getString("config.kits." + aclass + ".name"), n); + if (!config.isSet("config.kits." + aclass + ".items") || !config.isSet("config.kits." + aclass + ".lore")) + { + plugin.getLogger().warning("One of the classes found in the config file is invalid: " + aclass + ". Missing itemid or lore!"); + } + } + } + }, 20L); + } + + /** + * Returns whether the kit requires money to use it + * + * @param kit + * Internal name of the kit + * @return + */ + public boolean kitRequiresMoney(final String kit) + { + return this.pli.getClassesConfig().getConfig().getBoolean("config.kits." + kit + ".requires_money"); + } + + /** + * Gives the player the kit if he has enough money to buy it + * + * @param p + * Player to give the kit to + * @param kit + * Internal name of the kit + * @return + */ + public boolean kitTakeMoney(final Player p, final String kit) + { + // Credits + if (this.plugin.getConfig().getBoolean(ArenaConfigStrings.CONFIG_USE_CREADITS_INSTEAD_MONEY_FOR_KITS)) + { + final String uuid = p.getUniqueId().toString(); + int points = 0; + if (!MinigamesAPI.getAPI().statsglobal.getConfig().isSet("players." + uuid + ".points")) + { + points = this.pli.getStatsInstance().getPoints(p.getName()); + MinigamesAPI.getAPI().statsglobal.getConfig().set("players." + uuid + ".points", points); + MinigamesAPI.getAPI().statsglobal.saveConfig(); + } + else + { + points = MinigamesAPI.getAPI().statsglobal.getConfig().getInt("players." + uuid + ".points"); + } + if (this.plugin.getConfig().getBoolean(ArenaConfigStrings.CONFIG_BUY_CLASSES_FOREVER)) + { + final ClassesConfig cl = this.pli.getClassesConfig(); + if (!cl.getConfig().isSet("players.bought_kits." + p.getName() + "." + kit)) + { + final int money = this.pli.getClassesConfig().getConfig().getInt("config.kits." + kit + ".money_amount"); + if (points >= money) + { + MinigamesAPI.getAPI().statsglobal.getConfig().set("players." + uuid + ".points", points - money); + MinigamesAPI.getAPI().statsglobal.saveConfig(); + cl.getConfig().set("players.bought_kits." + p.getName() + "." + kit, true); + cl.saveConfig(); + p.sendMessage(this.pli.getMessagesConfig().successfully_bought_kit.replaceAll("", ChatColor.translateAlternateColorCodes('&', this.getClassByInternalname(kit).getName())) + .replaceAll("", Integer.toString(money))); + } + else + { + p.sendMessage(this.pli.getMessagesConfig().not_enough_money); + return false; + } + } + else + { + return true; + } + } + else + { + if (this.hasClass(p.getName())) + { + if (this.getSelectedClass(p.getName()).equalsIgnoreCase(kit)) + { + return false; + } + } + final ClassesConfig config = this.pli.getClassesConfig(); + final int money = config.getConfig().getInt("config.kits." + kit + ".money_amount"); + if (points >= money) + { + MinigamesAPI.getAPI().statsglobal.getConfig().set("players." + uuid + ".points", points - money); + MinigamesAPI.getAPI().statsglobal.saveConfig(); + p.sendMessage(this.pli.getMessagesConfig().successfully_bought_kit.replaceAll("", ChatColor.translateAlternateColorCodes('&', this.getClassByInternalname(kit).getName())) + .replaceAll("", Integer.toString(money))); + } + else + { + p.sendMessage(this.pli.getMessagesConfig().not_enough_money); + return false; + } + } + return true; + } + + MinigamesAPI.getAPI(); + // Money (economy) + if (!MinigamesAPI.getAPI().economyAvailable()) + { + this.plugin.getLogger().warning("Economy is turned OFF. You can turn it on in the config."); + return false; + } + if (MinigamesAPI.getAPI().economyAvailable()) + { + if (this.plugin.getConfig().getBoolean(ArenaConfigStrings.CONFIG_BUY_CLASSES_FOREVER)) + { + final ClassesConfig cl = this.pli.getClassesConfig(); + if (!cl.getConfig().isSet("players.bought_kits." + p.getName() + "." + kit)) + { + final int money = this.pli.getClassesConfig().getConfig().getInt("config.kits." + kit + ".money_amount"); + MinigamesAPI.getAPI(); + if (MinigamesAPI.econ.getBalance(p.getName()) >= money) + { + MinigamesAPI.getAPI(); + final EconomyResponse r = MinigamesAPI.econ.withdrawPlayer(p.getName(), money); + if (!r.transactionSuccess()) + { + p.sendMessage(String.format("An error occured: %s", r.errorMessage)); + return false; + } + cl.getConfig().set("players.bought_kits." + p.getName() + "." + kit, true); + cl.saveConfig(); + p.sendMessage(this.pli.getMessagesConfig().successfully_bought_kit.replaceAll("", ChatColor.translateAlternateColorCodes('&', this.getClassByInternalname(kit).getName())) + .replaceAll("", Integer.toString(money))); + } + else + { + p.sendMessage(this.pli.getMessagesConfig().not_enough_money); + return false; + } + } + else + { + return true; + } + } + else + { + if (this.hasClass(p.getName())) + { + if (this.getSelectedClass(p.getName()).equalsIgnoreCase(kit)) + { + return false; + } + if (this.kitRequiresMoney(kit)) + { + Util.sendMessage(this.plugin, p, this.pli.getMessagesConfig().kit_warning); + } + } + final ClassesConfig config = this.pli.getClassesConfig(); + final int money = config.getConfig().getInt("config.kits." + kit + ".money_amount"); + MinigamesAPI.getAPI(); + if (MinigamesAPI.econ.getBalance(p.getName()) >= money) + { + MinigamesAPI.getAPI(); + final EconomyResponse r = MinigamesAPI.econ.withdrawPlayer(p.getName(), money); + if (!r.transactionSuccess()) + { + p.sendMessage(String.format("An error occured: %s", r.errorMessage)); + return false; + } + p.sendMessage(this.pli.getMessagesConfig().successfully_bought_kit.replaceAll("", ChatColor.translateAlternateColorCodes('&', this.getClassByInternalname(kit).getName())) + .replaceAll("", Integer.toString(money))); + } + else + { + p.sendMessage(this.pli.getMessagesConfig().not_enough_money); + return false; + } + } + return true; + } + else + { + return false; + } + + } + + public boolean kitPlayerHasPermission(final String kit, final Player p) + { + if (!this.pli.getClassesConfig().getConfig().getBoolean("config.kits." + kit + ".requires_permission")) + { + return true; + } + else + { + if (p.hasPermission(this.pli.getClassesConfig().getConfig().getString("config.kits." + kit + ".permission_node"))) + { + return true; + } + else + { + return false; + } + } + } + } diff --git a/API/src/main/java/com/comze_instancelabs/minigamesapi/CommandStrings.java b/API/src/main/java/com/comze_instancelabs/minigamesapi/CommandStrings.java new file mode 100644 index 00000000..4369b288 --- /dev/null +++ b/API/src/main/java/com/comze_instancelabs/minigamesapi/CommandStrings.java @@ -0,0 +1,359 @@ +/* + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +package com.comze_instancelabs.minigamesapi; + +/** + * Common command strings. + * + * @author mepeisen + */ +public interface CommandStrings +{ + + /** + * "/start" command. + */ + String START = "start"; //$NON-NLS-1$ + + /** + * Command action: "/minigame <start> ... + */ + String GAME_START = "start"; //$NON-NLS-1$ + + /** + * Command action: "/minigame <setspawn> ... + */ + String GAME_SET_SPAWN = "setspawn"; //$NON-NLS-1$ + + /** + * Command action: "/minigame <setspecspawn> ... + */ + String GAME_SET_SPEC_SPAWN = "setspecspawn"; //$NON-NLS-1$ + + /** + * Command action: "/minigame <setlobby> ... + */ + String GAME_SET_LOBBY = "setlobby"; //$NON-NLS-1$ + + /** + * Command action: "/minigame <setmainlobby> ... + */ + String GAME_SET_MAINLOBBY = "setmainlobby"; //$NON-NLS-1$ + + /** + * Command action: "/minigame <setbounds> ... + */ + String GAME_SET_BOUNDS = "setbounds"; //$NON-NLS-1$ + + /** + * Command action: "/minigame <setlobbybounds> ... + */ + String GAME_SET_LOBBY_BOUNDS = "setlobbybounds"; //$NON-NLS-1$ + + /** + * Command action: "/minigame <setspecbounds> ... + */ + String GAME_SET_SPEC_BOUNDS = "setspecbounds"; //$NON-NLS-1$ + + /** + * Command action: "/minigame <savearena> ... + */ + String GAME_SAVE_ARENA = "savearena"; //$NON-NLS-1$ + + /** + * Command action: "/minigame <save> ... + */ + @Deprecated + String GAME_SAVE = "save"; //$NON-NLS-1$ + + /** + * Command action: "/minigame <setmaxplayers> ... + */ + String GAME_SET_MAX_PLAYERS = "setmaxplayers"; //$NON-NLS-1$ + + /** + * Command action: "/minigame <setminplayers> ... + */ + String GAME_SET_MIN_PLAYERS = "setminplayers"; //$NON-NLS-1$ + + /** + * Command action: "/minigame <setarenavip> ... + */ + String GAME_SET_ARENA_VIP = "setarenavip"; //$NON-NLS-1$ + + /** + * Command action: "/minigame <setvip> ... + */ + @Deprecated + String GAME_SET_VIP = "setvip"; //$NON-NLS-1$ + + /** + * Command action: "/minigame <join> ... + */ + String GAME_JOIN = "join"; //$NON-NLS-1$ + + /** + * Command action: "/minigame <leave> ... + */ + String GAME_LEAVE = "leave"; //$NON-NLS-1$ + + /** + * Command action: "/minigame <stop> ... + */ + String GAME_STOP = "stop"; //$NON-NLS-1$ + + /** + * Command action: "/minigame <stopall> ... + */ + String GAME_STOP_ALL = "stopall"; //$NON-NLS-1$ + + /** + * Command action: "/minigame <removearena> ... + */ + String GAME_REMOVE_ARENA = "removearena"; //$NON-NLS-1$ + + /** + * Command action: "/minigame <removespawn> ... + */ + String GAME_REMOVE_SPAWN = "removespawn"; //$NON-NLS-1$ + + /** + * Command action: "/minigame <setskull> ... + */ + String GAME_SET_SKULL = "setskull"; //$NON-NLS-1$ + + /** + * Command action: "/minigame <setenabled> ... + */ + String GAME_SET_ENABLED = "setenabled"; //$NON-NLS-1$ + + /** + * Command action: "/minigame <setshowscoreboard> ... + */ + String GAME_SET_SHOW_SCOREBOARD = "setshowscoreboard"; //$NON-NLS-1$ + + /** + * Command action: "/minigame <reset> ... + */ + String GAME_RESET = "reset"; //$NON-NLS-1$ + + /** + * Command action: "/minigame <setauthor> ... + */ + String GAME_SET_AUTHOR = "setauthor"; //$NON-NLS-1$ + + /** + * Command action: "/minigame <setdescription> ... + */ + String GAME_SET_DESCRIPTION = "setdescription"; //$NON-NLS-1$ + + /** + * Command action: "/minigame <setdisplayname> ... + */ + String GAME_SET_DISPLAYNAME = "setdisplayname"; //$NON-NLS-1$ + + /** + * Command action: "/minigame <kit> ... + */ + String GAME_KIT = "kit"; //$NON-NLS-1$ + + /** + * Command action: "/minigame <spectate> ... + */ + String GAME_SPECTATE = "spectate"; //$NON-NLS-1$ + + /** + * Command action: "/minigame <shop> ... + */ + String GAME_SHOP = "shop"; //$NON-NLS-1$ + + /** + * Command action: "/minigame <leaderboards> ... + */ + String GAME_LEADER_BOARDS = "leaderboards"; //$NON-NLS-1$ + + /** + * Command action: "/minigame <lb> ... + */ + String GAME_LB = "lb"; //$NON-NLS-1$ + + /** + * Command action: "/minigame <top> ... + */ + @Deprecated + String GAME_TOP = "top"; //$NON-NLS-1$ + + /** + * Command action: "/minigame <stats> ... + */ + String GAME_STATS = "stats"; //$NON-NLS-1$ + + /** + * Command action: "/minigame <sethologram> ... + */ + String GAME_SET_HOLOGRAM = "sethologram"; //$NON-NLS-1$ + + /** + * Command action: "/minigame <listholograms> ... + */ + String GAME_LIST_HOLOGRAMS = "listholograms"; //$NON-NLS-1$ + + /** + * Command action: "/minigame <removehologram> ... + */ + String GAME_REMOVE_HOLOGRAM = "removehologram"; //$NON-NLS-1$ + + /** + * Command action: "/minigame <help> ... + */ + String GAME_HELP = "help"; //$NON-NLS-1$ + + /** + * Command action: "/minigame <list> ... + */ + String GAME_LIST = "list"; //$NON-NLS-1$ + + /** + * Command action: "/minigame <reload> ... + */ + String GAME_RELOAD = "reload"; //$NON-NLS-1$ + + // old commands + + /** + * Command action: "/minigame <createarena> ... + * @deprecated removed in 1.5.0 + */ + @Deprecated + String GAME_CREATE_ARENA = "createarena"; //$NON-NLS-1$ + + /** + * Command action: "/minigame <endall> ... + * @deprecated removed in 1.5.0 + */ + @Deprecated + String GAME_END_ALL = "endall"; //$NON-NLS-1$ + + // party commands + + /** + * "/party" command. + */ + String PARTY = "party"; //$NON-NLS-1$ + + /** + * Command action: "/party <invite> ... + */ + String PARTY_INVITE = "invite"; //$NON-NLS-1$ + + /** + * Command action: "/party <accept> ... + */ + String PARTY_ACCEPT = "accept"; //$NON-NLS-1$ + + /** + * Command action: "/party <kick> ... + */ + String PARTY_KICK = "kick"; //$NON-NLS-1$ + + /** + * Command action: "/party <list> ... + */ + String PARTY_LIST = "list"; //$NON-NLS-1$ + + /** + * Command action: "/party <disband> ... + */ + String PARTY_DISBAND = "disband"; //$NON-NLS-1$ + + /** + * Command action: "/party <leave> ... + */ + String PARTY_LEAVE = "leave"; //$NON-NLS-1$ + + // minigames api commands + + /** + * "/mapi" command. + */ + String MAPI = "mapi"; //$NON-NLS-1$ + + /** + * "/mgapi" command. + */ + String MGAPI = "mgapi"; //$NON-NLS-1$ + + /** + * "/mglib" command. + */ + String MGLIB = "mglib"; //$NON-NLS-1$ + + /** + * Command action: "/mglib <info> ... + */ + String MGLIB_INFO = "info"; //$NON-NLS-1$ + + /** + * Command action: "/mglib <debug> ... + */ + String MGLIB_DEBUG = "debug"; //$NON-NLS-1$ + + /** + * Command action: "/mglib <list> ... + */ + String MGLIB_LIST = "list"; //$NON-NLS-1$ + + /** + * Command action: "/mglib <title> ... + */ + String MGLIB_TITLE = "title"; //$NON-NLS-1$ + + /** + * Command action: "/mglib <subtitle> ... + */ + String MGLIB_SUBTITLE = "subtitle"; //$NON-NLS-1$ + + /** + * Command action: "/mglib <signs> ... + */ + String MGLIB_SIGNS = "signs"; //$NON-NLS-1$ + + /** + * Command action: "/mglib <hologram> ... + */ + String MGLIB_HOLOGRAM = "hologram"; //$NON-NLS-1$ + + /** + * Command action: "/mglib <statshologram> ... + */ + String MGLIB_STATS_HOLOGRAM = "statshologram"; //$NON-NLS-1$ + + /** + * Command action: "/mglib <gamemodetest> ... + */ + String MGLIB_GAMEMODE_TEST = "gamemodetest"; //$NON-NLS-1$ + + /** + * Command action: "/mglib <bungeetest> ... + */ + String MGLIB_BUNGEE_TEST = "bungeetest"; //$NON-NLS-1$ + + /** + * Command action: "/mglib <join> ... + */ + String MGLIB_JOIN = "join"; //$NON-NLS-1$ + +} diff --git a/API/src/main/java/com/comze_instancelabs/minigamesapi/Effects.java b/API/src/main/java/com/comze_instancelabs/minigamesapi/Effects.java index e5484142..a5c63c26 100644 --- a/API/src/main/java/com/comze_instancelabs/minigamesapi/Effects.java +++ b/API/src/main/java/com/comze_instancelabs/minigamesapi/Effects.java @@ -1,3 +1,17 @@ +/* + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ package com.comze_instancelabs.minigamesapi; import java.lang.reflect.Constructor; @@ -6,6 +20,7 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.Map; +import java.util.logging.Level; import org.bukkit.Bukkit; import org.bukkit.Effect; @@ -19,452 +34,561 @@ import com.comze_instancelabs.minigamesapi.util.ParticleEffectNew; import com.comze_instancelabs.minigamesapi.util.Validator; -public class Effects { - - public static int getClientProtocolVersion(Player p) { - int ret = 0; - try { - if (!MinigamesAPI.getAPI().version.equalsIgnoreCase("v1_8_r1")) { - Method getHandle = Class.forName("org.bukkit.craftbukkit." + MinigamesAPI.getAPI().version + ".entity.CraftPlayer").getMethod("getHandle"); - Field playerConnection = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().version + ".EntityPlayer").getField("playerConnection"); - playerConnection.setAccessible(true); - Object playerConInstance = playerConnection.get(getHandle.invoke(p)); - Field networkManager = playerConInstance.getClass().getField("networkManager"); - networkManager.setAccessible(true); - Object networkManagerInstance = networkManager.get(playerConInstance); - Method getVersion = networkManagerInstance.getClass().getMethod("getVersion"); - Object version = getVersion.invoke(networkManagerInstance); - ret = (Integer) version; - } - } catch (Exception e) { - if (MinigamesAPI.debug) { - e.printStackTrace(); - } - } - return ret; - } - - /** - * Shows the particles of a redstone block breaking - * - * @param p - */ - public static void playBloodEffect(Player p) { - p.getWorld().playEffect(p.getLocation().add(0D, 1D, 0D), Effect.STEP_SOUND, 152); - } - - public static void playEffect(Arena a, Location l, String effectname) { - for (String p_ : a.getAllPlayers()) { - if (Validator.isPlayerOnline(p_)) { - Player p = Bukkit.getPlayer(p_); - ParticleEffectNew eff = ParticleEffectNew.valueOf(effectname); - eff.setId(152); - eff.animateReflected(p, l, 1F, 3); - } - } - } - - public static BukkitTask playFakeBed(Arena a, Player p) { - return playFakeBed(a, p, p.getLocation().getBlockX(), p.getLocation().getBlockY(), p.getLocation().getBlockZ()); - } - - public static BukkitTask playFakeBed(final Arena a, final Player p, int x, int y, int z) { - try { - final Method getHandle = Class.forName("org.bukkit.craftbukkit." + MinigamesAPI.getAPI().version + ".entity.CraftPlayer").getMethod("getHandle"); - final Field playerConnection = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().version + ".EntityPlayer").getField("playerConnection"); - playerConnection.setAccessible(true); - final Method sendPacket = playerConnection.getType().getMethod("sendPacket", Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().version + ".Packet")); - - Constructor packetPlayOutNamedEntityConstr = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().version + ".PacketPlayOutNamedEntitySpawn").getConstructor(Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().version + ".EntityHuman")); - Constructor packetPlayOutBedConstr = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().version + ".PacketPlayOutBed").getConstructor(); - - final int id = -p.getEntityId() - 1000; - - final Object packet = packetPlayOutNamedEntityConstr.newInstance(getHandle.invoke(p)); - setValue(packet, "a", id); - - final Object packet_ = packetPlayOutBedConstr.newInstance(); - setValue(packet_, "a", id); - setValue(packet_, "b", x); - setValue(packet_, "c", y); - setValue(packet_, "d", z); - - for (String p_ : a.getAllPlayers()) { - Player p__ = Bukkit.getPlayer(p_); - sendPacket.invoke(playerConnection.get(getHandle.invoke(p__)), packet); - sendPacket.invoke(playerConnection.get(getHandle.invoke(p__)), packet_); - } - - // Move the effect (fake player) to 0 0 0 after 4 seconds - final ArrayList tempp = new ArrayList(a.getAllPlayers()); - final World currentworld = p.getWorld(); - return Bukkit.getScheduler().runTaskLater(MinigamesAPI.getAPI(), new Runnable() { - public void run() { - try { - setValue(packet_, "a", id); - setValue(packet_, "b", 0); - setValue(packet_, "c", 0); - setValue(packet_, "d", 0); - for (String p_ : tempp) { - if (Validator.isPlayerOnline(p_)) { - Player p__ = Bukkit.getPlayer(p_); - if (p__.getWorld() == currentworld) { - sendPacket.invoke(playerConnection.get(getHandle.invoke(p__)), packet); - sendPacket.invoke(playerConnection.get(getHandle.invoke(p__)), packet_); - } - } - } - } catch (Exception e) { - e.printStackTrace(); - } - } - }, 20L * 4); - } catch (Exception e) { - System.out.println("Failed playing fakebed effect: " + e.getMessage()); - } - return null; - } - - public static void setValue(Object instance, String fieldName, Object value) throws Exception { - Field field = instance.getClass().getDeclaredField(fieldName); - field.setAccessible(true); - field.set(instance, value); - } - - /** - * Respawns a player using moveToWorld (which among others also sends a respawn packet) - * - * @param p - * Player to send it to - * @param plugin - */ - public static void playRespawn(final Player p, JavaPlugin plugin) { - Bukkit.getScheduler().runTaskLater(plugin, new Runnable() { - public void run() { - try { - final Method getHandle = Class.forName("org.bukkit.craftbukkit." + MinigamesAPI.getAPI().version + ".entity.CraftPlayer").getMethod("getHandle"); - final Field playerConnection = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().version + ".EntityPlayer").getField("playerConnection"); - final Field minecraftServer = playerConnection.get(getHandle.invoke(p)).getClass().getDeclaredField("minecraftServer"); - minecraftServer.setAccessible(true); - - Object nmsMcServer = minecraftServer.get(playerConnection.get(getHandle.invoke(p))); - Object playerlist = nmsMcServer.getClass().getDeclaredMethod("getPlayerList").invoke(nmsMcServer); - Method moveToWorld = playerlist.getClass().getMethod("moveToWorld", Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().version + ".EntityPlayer"), int.class, boolean.class); - moveToWorld.invoke(playerlist, getHandle.invoke(p), 0, false); - } catch (Exception e) { - System.out.println("Failed additional respawn packet: " + e.getMessage()); - } - } - }, 1L); - } - - // TODO Unused right now - public void playAura(Player p, int cr) { - int cradius_s = cr * cr; - Location start = p.getLocation(); - int x = start.getBlockX(); - int y = start.getBlockY(); - int z = start.getBlockZ(); - for (int x_ = -cr; x_ <= cr; x_++) { - for (int z_ = -cr; z_ <= cr; z_++) { - int t = (x_ * x_) + (z_ * z_); - if (t >= cradius_s && t <= (cradius_s + 90)) { - p.playEffect(new Location(start.getWorld(), x - x_, y, z - z_), Effect.POTION_BREAK, 5); - } - } - } - } - - /** - * Plays a title/subtitle - * - * @param player - * Player to play the title to - * @param title - * The title string - * @param enumindex - * The enum index, can be 0 for title, 1 for subtitle, 4 for reset - */ - public static void playTitle(Player player, String title, int enumindex) { - if (enumindex > 4) { - enumindex = 0; - } - try { - final Method getHandle = Class.forName("org.bukkit.craftbukkit." + MinigamesAPI.getAPI().version + ".entity.CraftPlayer").getMethod("getHandle"); - final Field playerConnection = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().version + ".EntityPlayer").getField("playerConnection"); - playerConnection.setAccessible(true); - final Method sendPacket = playerConnection.getType().getMethod("sendPacket", Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().version + ".Packet")); - final Method a = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().version + ".ChatSerializer").getMethod("a", String.class); - - Constructor packetPlayOutTitleConstr = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().version + ".PacketPlayOutTitle").getConstructor(); - - final Object packet = packetPlayOutTitleConstr.newInstance(); - setValue(packet, "a", Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().version + ".EnumTitleAction").getEnumConstants()[enumindex]); - setValue(packet, "b", a.invoke(null, "{text:\"" + title + "\"}")); - - sendPacket.invoke(playerConnection.get(getHandle.invoke(player)), packet); - } catch (Exception e) { - System.out.println("Failed sending title packet: " + e.getMessage()); - } - } - - static HashMap effectlocd = new HashMap(); - static HashMap effectlocd_taskid = new HashMap(); - - /** - * Sends a hologram to a player - * - * @param p - * Player to send the hologram to - * @param l - * Location where the hologram will spawn (and slowly move down) - * @param text - * Hologram text - * @param moveDown - * Whether to play a moving down animation - * @param removeAfterCooldown - * Whether to remove the hologram after a few seconds or not - * @return - */ - public static ArrayList playHologram(final Player p, final Location l, String text, boolean moveDown, boolean removeAfterCooldown) { - ArrayList ret = new ArrayList(); - if (MinigamesAPI.getAPI().version.equalsIgnoreCase("v1_8_r1")) { - try { - final Method getPlayerHandle = Class.forName("org.bukkit.craftbukkit." + MinigamesAPI.getAPI().version + ".entity.CraftPlayer").getMethod("getHandle"); - final Field playerConnection = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().version + ".EntityPlayer").getField("playerConnection"); - playerConnection.setAccessible(true); - final Method sendPacket = playerConnection.getType().getMethod("sendPacket", Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().version + ".Packet")); - - Class craftw = Class.forName("org.bukkit.craftbukkit." + MinigamesAPI.getAPI().version + ".CraftWorld"); - Class w = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().version + ".World"); - Class entity = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().version + ".Entity"); - Method getWorldHandle = craftw.getDeclaredMethod("getHandle"); - Object worldServer = getWorldHandle.invoke(craftw.cast(l.getWorld())); - final Constructor packetPlayOutSpawnEntityConstr = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().version + ".PacketPlayOutSpawnEntity").getConstructor(entity, int.class); - final Constructor packetPlayOutSpawnEntityLivingConstr = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().version + ".PacketPlayOutSpawnEntityLiving").getConstructor(Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().version + ".EntityLiving")); - final Constructor packetPlayOutAttachEntityConstr = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().version + ".PacketPlayOutAttachEntity").getConstructor(int.class, entity, entity); - final Constructor packetPlayOutEntityDestroyConstr = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().version + ".PacketPlayOutEntityDestroy").getConstructor(int[].class); - final Constructor packetPlayOutEntityVelocity = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().version + ".PacketPlayOutEntityVelocity").getConstructor(int.class, double.class, double.class, double.class); - - // EntityArmorStand - Constructor entityArmorStandConstr = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().version + ".EntityArmorStand").getConstructor(w); - final Object entityArmorStand = entityArmorStandConstr.newInstance(worldServer); - final Method setLoc2 = entityArmorStand.getClass().getSuperclass().getSuperclass().getDeclaredMethod("setLocation", double.class, double.class, double.class, float.class, float.class); - setLoc2.invoke(entityArmorStand, l.getX(), l.getY() - 1D, l.getZ(), 0F, 0F); - Method setCustomName = entityArmorStand.getClass().getSuperclass().getSuperclass().getDeclaredMethod("setCustomName", String.class); - setCustomName.invoke(entityArmorStand, text); - Method setCustomNameVisible = entityArmorStand.getClass().getSuperclass().getSuperclass().getDeclaredMethod("setCustomNameVisible", boolean.class); - setCustomNameVisible.invoke(entityArmorStand, true); - Method getArmorStandId = entityArmorStand.getClass().getSuperclass().getSuperclass().getDeclaredMethod("getId"); - final int armorstandId = (Integer) (getArmorStandId.invoke(entityArmorStand)); - Method setInvisble = entityArmorStand.getClass().getSuperclass().getSuperclass().getDeclaredMethod("setInvisible", boolean.class); - setInvisble.invoke(entityArmorStand, true); - - effectlocd.put(armorstandId, 12); // send move packet 12 times - - // Send EntityArmorStand packet - Object horsePacket = packetPlayOutSpawnEntityLivingConstr.newInstance(entityArmorStand); - sendPacket.invoke(playerConnection.get(getPlayerHandle.invoke(p)), horsePacket); - - // Send velocity packets to move the entities slowly down - if (moveDown) { - effectlocd_taskid.put(armorstandId, Bukkit.getScheduler().runTaskTimer(MinigamesAPI.getAPI(), new Runnable() { - public void run() { - try { - int i = effectlocd.get(armorstandId); - Object packet = packetPlayOutEntityVelocity.newInstance(armorstandId, 0D, -0.05D, 0D); - sendPacket.invoke(playerConnection.get(getPlayerHandle.invoke(p)), packet); - if (i < -1) { - int taskid = effectlocd_taskid.get(armorstandId); - effectlocd_taskid.remove(armorstandId); - effectlocd.remove(armorstandId); - Bukkit.getScheduler().cancelTask(taskid); - return; - } - effectlocd.put(armorstandId, effectlocd.get(armorstandId) - 1); - } catch (Exception e) { - if (MinigamesAPI.debug) { - e.printStackTrace(); - } - } - } - }, 2L, 2L).getTaskId()); - } - - // Remove both entities (and thus the hologram) after 2 seconds - if (removeAfterCooldown) { - Bukkit.getScheduler().runTaskLater(MinigamesAPI.getAPI(), new Runnable() { - public void run() { - try { - Object destroyPacket = packetPlayOutEntityDestroyConstr.newInstance((Object) new int[] { armorstandId }); - sendPacket.invoke(playerConnection.get(getPlayerHandle.invoke(p)), destroyPacket); - } catch (Exception e) { - if (MinigamesAPI.debug) { - e.printStackTrace(); - } - } - } - }, 20L * 2); - } - - ret.add(armorstandId); - - } catch (Exception e) { - if (MinigamesAPI.debug) { - e.printStackTrace(); - } - } - return ret; - } - try { - // If player is on 1.8, we'll have to use armor stands, otherwise just use the old 1.7 technique - final boolean playerIs1_8 = getClientProtocolVersion(p) > 5; - - final Method getPlayerHandle = Class.forName("org.bukkit.craftbukkit." + MinigamesAPI.getAPI().version + ".entity.CraftPlayer").getMethod("getHandle"); - final Field playerConnection = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().version + ".EntityPlayer").getField("playerConnection"); - playerConnection.setAccessible(true); - final Method sendPacket = playerConnection.getType().getMethod("sendPacket", Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().version + ".Packet")); - - Class craftw = Class.forName("org.bukkit.craftbukkit." + MinigamesAPI.getAPI().version + ".CraftWorld"); - Class w = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().version + ".World"); - Class entity = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().version + ".Entity"); - Method getWorldHandle = craftw.getDeclaredMethod("getHandle"); - Object worldServer = getWorldHandle.invoke(craftw.cast(l.getWorld())); - final Constructor packetPlayOutSpawnEntityConstr = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().version + ".PacketPlayOutSpawnEntity").getConstructor(entity, int.class); - final Constructor packetPlayOutSpawnEntityLivingConstr = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().version + ".PacketPlayOutSpawnEntityLiving").getConstructor(Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().version + ".EntityLiving")); - final Constructor packetPlayOutAttachEntityConstr = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().version + ".PacketPlayOutAttachEntity").getConstructor(int.class, entity, entity); - final Constructor packetPlayOutEntityDestroyConstr = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().version + ".PacketPlayOutEntityDestroy").getConstructor(int[].class); - final Constructor packetPlayOutEntityVelocity = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().version + ".PacketPlayOutEntityVelocity").getConstructor(int.class, double.class, double.class, double.class); - - // WitherSkull - Constructor witherSkullConstr = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().version + ".EntityWitherSkull").getConstructor(w); - final Object witherSkull = witherSkullConstr.newInstance(worldServer); - final Method setLoc = witherSkull.getClass().getSuperclass().getSuperclass().getDeclaredMethod("setLocation", double.class, double.class, double.class, float.class, float.class); - setLoc.invoke(witherSkull, l.getX(), l.getY() + 33D, l.getZ(), 0F, 0F); - Method getWitherSkullId = witherSkull.getClass().getSuperclass().getSuperclass().getDeclaredMethod("getId"); - final int witherSkullId = (Integer) (getWitherSkullId.invoke(witherSkull)); - - // EntityHorse - Constructor entityHorseConstr = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().version + ".EntityHorse").getConstructor(w); - final Object entityHorse = entityHorseConstr.newInstance(worldServer); - final Method setLoc2 = entityHorse.getClass().getSuperclass().getSuperclass().getSuperclass().getSuperclass().getSuperclass().getSuperclass().getDeclaredMethod("setLocation", double.class, double.class, double.class, float.class, float.class); - setLoc2.invoke(entityHorse, l.getX(), l.getY() + (playerIs1_8 ? -1D : 33D), l.getZ(), 0F, 0F); - Method setAge = entityHorse.getClass().getSuperclass().getSuperclass().getDeclaredMethod("setAge", int.class); - setAge.invoke(entityHorse, -1000000); - Method setCustomName = entityHorse.getClass().getSuperclass().getSuperclass().getSuperclass().getSuperclass().getDeclaredMethod("setCustomName", String.class); - setCustomName.invoke(entityHorse, text); - Method setCustomNameVisible = entityHorse.getClass().getSuperclass().getSuperclass().getSuperclass().getSuperclass().getDeclaredMethod("setCustomNameVisible", boolean.class); - setCustomNameVisible.invoke(entityHorse, true); - Method getHorseId = entityHorse.getClass().getSuperclass().getSuperclass().getSuperclass().getSuperclass().getSuperclass().getSuperclass().getDeclaredMethod("getId"); - final int horseId = (Integer) (getHorseId.invoke(entityHorse)); - - if (playerIs1_8) { - // Set horse (later armor stand) invisible - Method setInvisble = entityHorse.getClass().getSuperclass().getSuperclass().getSuperclass().getSuperclass().getSuperclass().getSuperclass().getDeclaredMethod("setInvisible", boolean.class); - setInvisble.invoke(entityHorse, true); - } - - effectlocd.put(horseId, 12); // send move packet 12 times - - // Send Witherskull+EntityHorse packet - Object horsePacket = packetPlayOutSpawnEntityLivingConstr.newInstance(entityHorse); - if (playerIs1_8) { - // Set entity id to 30 (armor stand): - setValue(horsePacket, "b", 30); - // Fix datawatcher values to prevent crashes (ofc armor stands expect other data than horses): - Field datawatcher = entityHorse.getClass().getSuperclass().getSuperclass().getSuperclass().getSuperclass().getSuperclass().getSuperclass().getDeclaredField("datawatcher"); - datawatcher.setAccessible(true); - Object datawatcherInstance = datawatcher.get(entityHorse); - Field d = datawatcherInstance.getClass().getDeclaredField("d"); - d.setAccessible(true); - Map dmap = (Map) d.get(datawatcherInstance); - dmap.remove(10); - // These are the Rotation ones - dmap.remove(11); - dmap.remove(12); - dmap.remove(13); - dmap.remove(14); - dmap.remove(15); - dmap.remove(16); - Method a = datawatcherInstance.getClass().getDeclaredMethod("a", int.class, Object.class); - a.invoke(datawatcherInstance, 10, (byte) 0); - } - sendPacket.invoke(playerConnection.get(getPlayerHandle.invoke(p)), horsePacket); - if (!playerIs1_8) { - Object witherPacket = packetPlayOutSpawnEntityConstr.newInstance(witherSkull, 64); - sendPacket.invoke(playerConnection.get(getPlayerHandle.invoke(p)), witherPacket); - } - - // Send attach packet - if (!playerIs1_8) { - Object attachPacket = packetPlayOutAttachEntityConstr.newInstance(0, entityHorse, witherSkull); - sendPacket.invoke(playerConnection.get(getPlayerHandle.invoke(p)), attachPacket); - } - - // Send velocity packets to move the entities slowly down - if (moveDown) { - effectlocd_taskid.put(horseId, Bukkit.getScheduler().runTaskTimer(MinigamesAPI.getAPI(), new Runnable() { - public void run() { - try { - int i = effectlocd.get(horseId); - Object packet = packetPlayOutEntityVelocity.newInstance(horseId, 0D, -0.05D, 0D); - sendPacket.invoke(playerConnection.get(getPlayerHandle.invoke(p)), packet); - if (!playerIs1_8) { - Object packet2 = packetPlayOutEntityVelocity.newInstance(witherSkullId, 0D, -0.05D, 0D); - sendPacket.invoke(playerConnection.get(getPlayerHandle.invoke(p)), packet2); - } - if (i < -1) { - int taskid = effectlocd_taskid.get(horseId); - effectlocd_taskid.remove(horseId); - effectlocd.remove(horseId); - Bukkit.getScheduler().cancelTask(taskid); - return; - } - effectlocd.put(horseId, effectlocd.get(horseId) - 1); - } catch (Exception e) { - if (MinigamesAPI.debug) { - e.printStackTrace(); - } - } - } - }, 2L, 2L).getTaskId()); - } - - // Remove both entities (and thus the hologram) after 2 seconds - if (removeAfterCooldown) { - Bukkit.getScheduler().runTaskLater(MinigamesAPI.getAPI(), new Runnable() { - public void run() { - try { - Object destroyPacket = packetPlayOutEntityDestroyConstr.newInstance((Object) new int[] { witherSkullId, horseId }); - sendPacket.invoke(playerConnection.get(getPlayerHandle.invoke(p)), destroyPacket); - } catch (Exception e) { - if (MinigamesAPI.debug) { - e.printStackTrace(); - } - } - } - }, 20L * 2); - } - - ret.add(witherSkullId); - ret.add(horseId); - - } catch (Exception e) { - if (MinigamesAPI.debug) { - e.printStackTrace(); - } - } - return ret; - } - - public static void sendGameModeChange(Player p, int gamemode) { - // NOT_SET(-1, ""), SURVIVAL(0, "survival"), CREATIVE(1, "creative"), ADVENTURE(2, "adventure"), SPECTATOR(3, "spectator"); - - if (!MinigamesAPI.getAPI().version.startsWith("v1_8") && gamemode == 3) { - return; - } - - p.setGameMode(GameMode.getByValue(gamemode)); - - } +/** + * Particle/Animation helper. + * + * @author instancelabs + */ +public class Effects +{ + + /** + * Shows the particles of a redstone block breaking, simulating a blood effect. + * + * @param p + * target player. + */ + public static void playBloodEffect(final Player p) + { + p.getWorld().playEffect(p.getLocation().add(0D, 1D, 0D), Effect.STEP_SOUND, 152); + } + + /** + * Plays an effect by name. + * + * @param a + * arena + * @param l + * target location + * @param effectname + * effect name. + */ + public static void playEffect(final Arena a, final Location l, final String effectname) + { + for (final String p_ : a.getAllPlayers()) + { + if (Validator.isPlayerOnline(p_)) + { + final Player p = Bukkit.getPlayer(p_); + final ParticleEffectNew eff = ParticleEffectNew.valueOf(effectname); + eff.setId(55); + eff.animateReflected(p, l, 1F, 2); + } + } + } + + /** + * Places a fake bed on the current player position. + * + * @param a + * arena + * @param p + * target player + * @return bukkit task that can be cancelled. + */ + public static BukkitTask playFakeBed(final Arena a, final Player p) + { + return Effects.playFakeBed(a, p, p.getLocation().getBlockX(), p.getLocation().getBlockY(), p.getLocation().getBlockZ()); + } + + /** + * Places a fake bed on the given position. + * + * @param a + * arena + * @param p + * target player + * @param x + * x-position + * @param y + * y-position + * @param z + * z-position + * @return bukkit task that can be cancelled. + */ + public static BukkitTask playFakeBed(final Arena a, final Player p, final int x, final int y, final int z) + { + try + { + final Method getHandle = Class.forName("org.bukkit.craftbukkit." + MinigamesAPI.getAPI().internalServerVersion + ".entity.CraftPlayer").getMethod("getHandle"); + final Field playerConnection = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().internalServerVersion + ".EntityPlayer").getField("playerConnection"); + playerConnection.setAccessible(true); + final Method sendPacket = playerConnection.getType().getMethod("sendPacket", Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().internalServerVersion + ".Packet")); + + final Constructor packetPlayOutNamedEntityConstr = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().internalServerVersion + ".PacketPlayOutNamedEntitySpawn") + .getConstructor(Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().internalServerVersion + ".EntityHuman")); + final Constructor packetPlayOutBedConstr = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().internalServerVersion + ".PacketPlayOutBed").getConstructor(); + + final int id = -p.getEntityId() - 1000; + + final Object packetNamedEntity = packetPlayOutNamedEntityConstr.newInstance(getHandle.invoke(p)); + Effects.setValue(packetNamedEntity, "a", id); + + final Object packetFakeBed = packetPlayOutBedConstr.newInstance(); + Effects.setValue(packetFakeBed, "a", id); + final Object packetFakeBed2 = packetPlayOutBedConstr.newInstance(); + Effects.setValue(packetFakeBed2, "a", id); + if (MinigamesAPI.SERVER_VERSION.isAtLeast(MinecraftVersionsType.V1_8_R1)) + { + final Class bpClazz = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().internalServerVersion + ".BlockPosition"); + final Constructor ctor = bpClazz.getDeclaredConstructor(int.class, int.class, int.class); + Effects.setValue(packetFakeBed, "b", ctor.newInstance(x, y, z)); + + Effects.setValue(packetFakeBed2, "b", ctor.newInstance(0, 0, 0)); + } + else + { + Effects.setValue(packetFakeBed, "b", x); + Effects.setValue(packetFakeBed, "c", y); + Effects.setValue(packetFakeBed, "d", z); + Effects.setValue(packetFakeBed2, "b", 0); + Effects.setValue(packetFakeBed2, "c", 0); + Effects.setValue(packetFakeBed2, "d", 0); + } + + for (final String p_ : a.getAllPlayers()) + { + final Player p__ = Bukkit.getPlayer(p_); + sendPacket.invoke(playerConnection.get(getHandle.invoke(p__)), packetNamedEntity); + sendPacket.invoke(playerConnection.get(getHandle.invoke(p__)), packetFakeBed); + } + + // Move the effect (fake player) to 0 0 0 after 4 seconds + final ArrayList tempp = new ArrayList<>(a.getAllPlayers()); + final World currentworld = p.getWorld(); + return Bukkit.getScheduler().runTaskLater(MinigamesAPI.getAPI(), () -> { + try + { + for (final String p_ : tempp) + { + if (Validator.isPlayerOnline(p_)) + { + final Player p__ = Bukkit.getPlayer(p_); + if (p__.getWorld() == currentworld) + { + sendPacket.invoke(playerConnection.get(getHandle.invoke(p__)), packetNamedEntity); + sendPacket.invoke(playerConnection.get(getHandle.invoke(p__)), packetFakeBed2); + } + } + } + } + catch (final Exception e) + { + MinigamesAPI.getAPI().getLogger().log(Level.WARNING, "exception", e); + } + }, 20L * 4); + } + catch (final Exception e) + { + MinigamesAPI.getAPI().getLogger().log(Level.WARNING, "Failed playing fakebed effect", e); + } + return null; + } + + /** + * Sets private object value. + * + * @param instance + * object instance + * @param fieldName + * field name + * @param value + * new value + * @throws Exception + * thrown on problems setting the field. + */ + private static void setValue(final Object instance, final String fieldName, final Object value) throws Exception + { + final Field field = instance.getClass().getDeclaredField(fieldName); + field.setAccessible(true); + field.set(instance, value); + } + + /** + * Respawns a player using moveToWorld (which among others also sends a respawn packet) + * + * @param p + * Player to send it to + * @param plugin + */ + public static void playRespawn(final Player p, final JavaPlugin plugin) + { + Bukkit.getScheduler().runTaskLater(plugin, () -> { + try + { + final Method getHandle = Class.forName("org.bukkit.craftbukkit." + MinigamesAPI.getAPI().internalServerVersion + ".entity.CraftPlayer").getMethod("getHandle"); + final Field playerConnection = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().internalServerVersion + ".EntityPlayer").getField("playerConnection"); + final Field minecraftServer = playerConnection.get(getHandle.invoke(p)).getClass().getDeclaredField("minecraftServer"); + minecraftServer.setAccessible(true); + + final Object nmsMcServer = minecraftServer.get(playerConnection.get(getHandle.invoke(p))); + final Object playerlist = nmsMcServer.getClass().getDeclaredMethod("getPlayerList").invoke(nmsMcServer); + final Method moveToWorld = playerlist.getClass().getMethod("moveToWorld", Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().internalServerVersion + ".EntityPlayer"), + int.class, boolean.class); + moveToWorld.invoke(playerlist, getHandle.invoke(p), 0, false); + } + catch (final Exception e) + { + MinigamesAPI.getAPI().getLogger().log(Level.WARNING, "Failed additional respawn packet", e); + } + }, 1L); + } + + /** + * Plays a title/subtitle + * + * @param player + * Player to play the title to + * @param title + * The title string + * @param eindex + * The enum index, can be 0 for title, 1 for subtitle, 4 for reset + */ + public static void playTitle(final Player player, final String title, int eindex) + { + int enumindex = eindex; + if (enumindex > 4) + { + enumindex = 0; + } + try + { + final Method getHandle = Class.forName("org.bukkit.craftbukkit." + MinigamesAPI.getAPI().internalServerVersion + ".entity.CraftPlayer").getMethod("getHandle"); + final Field playerConnection = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().internalServerVersion + ".EntityPlayer").getField("playerConnection"); + playerConnection.setAccessible(true); + final Method sendPacket = playerConnection.getType().getMethod("sendPacket", Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().internalServerVersion + ".Packet")); + Class enumClass = null; + Object chatComp = null; + if (MinigamesAPI.SERVER_VERSION.isBelow(MinecraftVersionsType.V1_8_R2)) + { + Method a = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().internalServerVersion + ".ChatSerializer").getMethod("a", String.class); + enumClass = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().internalServerVersion + ".EnumTitleAction"); + chatComp = a.invoke(null, "{text:\"" + title + "\"}"); + } + else + { + enumClass = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().internalServerVersion + ".PacketPlayOutTitle$EnumTitleAction"); + chatComp = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().internalServerVersion + ".ChatComponentText").getConstructor(String.class).newInstance(title); + } + + final Constructor packetPlayOutTitleConstr = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().internalServerVersion + ".PacketPlayOutTitle").getConstructor(); + final Object packet = packetPlayOutTitleConstr.newInstance(); + Effects.setValue(packet, "a", enumClass.getEnumConstants()[enumindex]); + Effects.setValue(packet, "b", chatComp); + + sendPacket.invoke(playerConnection.get(getHandle.invoke(player)), packet); + } + catch (final Exception e) + { + MinigamesAPI.getAPI().getLogger().log(Level.WARNING, "Failed sending title packet", e); + } + } + + static HashMap effectlocd = new HashMap<>(); + static HashMap effectlocd_taskid = new HashMap<>(); + + /** + * Sends a hologram to a player + * + * @param p + * Player to send the hologram to + * @param l + * Location where the hologram will spawn (and slowly move down) + * @param text + * Hologram text + * @param moveDown + * Whether to play a moving down animation + * @param removeAfterCooldown + * Whether to remove the hologram after a few seconds or not + * @return ids + */ + public static ArrayList playHologram(final Player p, final Location l, final String text, final boolean moveDown, final boolean removeAfterCooldown) + { + final ArrayList ret = new ArrayList<>(); + if (MinigamesAPI.SERVER_VERSION.isAfter(MinecraftVersionsType.V1_7)) + { + try + { + final Method getPlayerHandle = Class.forName("org.bukkit.craftbukkit." + MinigamesAPI.getAPI().internalServerVersion + ".entity.CraftPlayer").getMethod("getHandle"); + final Field playerConnection = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().internalServerVersion + ".EntityPlayer").getField("playerConnection"); + playerConnection.setAccessible(true); + final Method sendPacket = playerConnection.getType().getMethod("sendPacket", Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().internalServerVersion + ".Packet")); + + final Class craftw = Class.forName("org.bukkit.craftbukkit." + MinigamesAPI.getAPI().internalServerVersion + ".CraftWorld"); + final Class w = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().internalServerVersion + ".World"); + final Class entity = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().internalServerVersion + ".Entity"); + final Method getWorldHandle = craftw.getDeclaredMethod("getHandle"); + final Object worldServer = getWorldHandle.invoke(craftw.cast(l.getWorld())); +// Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().internalServerVersion + ".PacketPlayOutSpawnEntity").getConstructor(entity, int.class); + final Constructor packetPlayOutSpawnEntityLivingConstr = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().internalServerVersion + ".PacketPlayOutSpawnEntityLiving") + .getConstructor(Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().internalServerVersion + ".EntityLiving")); +// Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().internalServerVersion + ".PacketPlayOutAttachEntity").getConstructor(int.class, entity, entity); + final Constructor packetPlayOutEntityDestroyConstr = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().internalServerVersion + ".PacketPlayOutEntityDestroy") + .getConstructor(int[].class); + final Constructor packetPlayOutEntityVelocity = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().internalServerVersion + ".PacketPlayOutEntityVelocity") + .getConstructor(int.class, double.class, double.class, double.class); + + // EntityArmorStand + final Constructor entityArmorStandConstr = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().internalServerVersion + ".EntityArmorStand").getConstructor(w); + final Object entityArmorStand = entityArmorStandConstr.newInstance(worldServer); + final Method setLoc2 = entityArmorStand.getClass().getSuperclass().getSuperclass().getDeclaredMethod("setLocation", double.class, double.class, double.class, float.class, float.class); + setLoc2.invoke(entityArmorStand, l.getX(), l.getY() - 1D, l.getZ(), 0F, 0F); + final Method setCustomName = entityArmorStand.getClass().getSuperclass().getSuperclass().getDeclaredMethod("setCustomName", String.class); + setCustomName.invoke(entityArmorStand, text); + final Method setCustomNameVisible = entityArmorStand.getClass().getSuperclass().getSuperclass().getDeclaredMethod("setCustomNameVisible", boolean.class); + setCustomNameVisible.invoke(entityArmorStand, true); + final Method getArmorStandId = entityArmorStand.getClass().getSuperclass().getSuperclass().getDeclaredMethod("getId"); + final int armorstandId = (Integer) (getArmorStandId.invoke(entityArmorStand)); + final Method setInvisble = entityArmorStand.getClass().getSuperclass().getSuperclass().getDeclaredMethod("setInvisible", boolean.class); + setInvisble.invoke(entityArmorStand, true); + + Effects.effectlocd.put(armorstandId, 12); // send move packet 12 times + + // Send EntityArmorStand packet + final Object horsePacket = packetPlayOutSpawnEntityLivingConstr.newInstance(entityArmorStand); + sendPacket.invoke(playerConnection.get(getPlayerHandle.invoke(p)), horsePacket); + + // Send velocity packets to move the entities slowly down + if (moveDown) + { + Effects.effectlocd_taskid.put(armorstandId, Bukkit.getScheduler().runTaskTimer(MinigamesAPI.getAPI(), () -> { + try + { + final int i = Effects.effectlocd.get(armorstandId); + final Object packet = packetPlayOutEntityVelocity.newInstance(armorstandId, 0D, -0.05D, 0D); + sendPacket.invoke(playerConnection.get(getPlayerHandle.invoke(p)), packet); + if (i < -1) + { + final int taskid = Effects.effectlocd_taskid.get(armorstandId); + Effects.effectlocd_taskid.remove(armorstandId); + Effects.effectlocd.remove(armorstandId); + Bukkit.getScheduler().cancelTask(taskid); + return; + } + Effects.effectlocd.put(armorstandId, Effects.effectlocd.get(armorstandId) - 1); + } + catch (final Exception e) + { + if (MinigamesAPI.debug) + { + MinigamesAPI.getAPI().getLogger().log(Level.WARNING, "exception", e); + } + } + }, 2L, 2L).getTaskId()); + } + + // Remove both entities (and thus the hologram) after 2 seconds + if (removeAfterCooldown) + { + Bukkit.getScheduler().runTaskLater(MinigamesAPI.getAPI(), () -> { + try + { + final Object destroyPacket = packetPlayOutEntityDestroyConstr.newInstance(new int[] { armorstandId }); + sendPacket.invoke(playerConnection.get(getPlayerHandle.invoke(p)), destroyPacket); + } + catch (final Exception e) + { + if (MinigamesAPI.debug) + { + MinigamesAPI.getAPI().getLogger().log(Level.WARNING, "exception", e); + } + } + }, 20L * 2); + } + + ret.add(armorstandId); + + } + catch (final Exception e) + { + if (MinigamesAPI.debug) + { + MinigamesAPI.getAPI().getLogger().log(Level.WARNING, "exception", e); + } + } + return ret; + } + try + { + // If player is on 1.8, we'll have to use armor stands, otherwise just use the old 1.7 technique + final boolean playerIs1_8 = MinigamesAPI.SERVER_VERSION.isAtLeast(MinecraftVersionsType.V1_8); + + final Method getPlayerHandle = Class.forName("org.bukkit.craftbukkit." + MinigamesAPI.getAPI().internalServerVersion + ".entity.CraftPlayer").getMethod("getHandle"); + final Field playerConnection = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().internalServerVersion + ".EntityPlayer").getField("playerConnection"); + playerConnection.setAccessible(true); + final Method sendPacket = playerConnection.getType().getMethod("sendPacket", Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().internalServerVersion + ".Packet")); + + final Class craftw = Class.forName("org.bukkit.craftbukkit." + MinigamesAPI.getAPI().internalServerVersion + ".CraftWorld"); + final Class w = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().internalServerVersion + ".World"); + final Class entity = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().internalServerVersion + ".Entity"); + final Method getWorldHandle = craftw.getDeclaredMethod("getHandle"); + final Object worldServer = getWorldHandle.invoke(craftw.cast(l.getWorld())); + final Constructor packetPlayOutSpawnEntityConstr = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().internalServerVersion + ".PacketPlayOutSpawnEntity") + .getConstructor(entity, int.class); + final Constructor packetPlayOutSpawnEntityLivingConstr = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().internalServerVersion + ".PacketPlayOutSpawnEntityLiving") + .getConstructor(Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().internalServerVersion + ".EntityLiving")); + final Constructor packetPlayOutAttachEntityConstr = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().internalServerVersion + ".PacketPlayOutAttachEntity") + .getConstructor(int.class, entity, entity); + final Constructor packetPlayOutEntityDestroyConstr = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().internalServerVersion + ".PacketPlayOutEntityDestroy") + .getConstructor(int[].class); + final Constructor packetPlayOutEntityVelocity = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().internalServerVersion + ".PacketPlayOutEntityVelocity") + .getConstructor(int.class, double.class, double.class, double.class); + + // WitherSkull + final Constructor witherSkullConstr = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().internalServerVersion + ".EntityWitherSkull").getConstructor(w); + final Object witherSkull = witherSkullConstr.newInstance(worldServer); + final Method setLoc = witherSkull.getClass().getSuperclass().getSuperclass().getDeclaredMethod("setLocation", double.class, double.class, double.class, float.class, float.class); + setLoc.invoke(witherSkull, l.getX(), l.getY() + 33D, l.getZ(), 0F, 0F); + final Method getWitherSkullId = witherSkull.getClass().getSuperclass().getSuperclass().getDeclaredMethod("getId"); + final int witherSkullId = (Integer) (getWitherSkullId.invoke(witherSkull)); + + // EntityHorse + final Constructor entityHorseConstr = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().internalServerVersion + ".EntityHorse").getConstructor(w); + final Object entityHorse = entityHorseConstr.newInstance(worldServer); + final Method setLoc2 = entityHorse.getClass().getSuperclass().getSuperclass().getSuperclass().getSuperclass().getSuperclass().getSuperclass().getDeclaredMethod("setLocation", double.class, + double.class, double.class, float.class, float.class); + setLoc2.invoke(entityHorse, l.getX(), l.getY() + (playerIs1_8 ? -1D : 33D), l.getZ(), 0F, 0F); + final Method setAge = entityHorse.getClass().getSuperclass().getSuperclass().getDeclaredMethod("setAge", int.class); + setAge.invoke(entityHorse, -1000000); + final Method setCustomName = entityHorse.getClass().getSuperclass().getSuperclass().getSuperclass().getSuperclass().getDeclaredMethod("setCustomName", String.class); + setCustomName.invoke(entityHorse, text); + final Method setCustomNameVisible = entityHorse.getClass().getSuperclass().getSuperclass().getSuperclass().getSuperclass().getDeclaredMethod("setCustomNameVisible", boolean.class); + setCustomNameVisible.invoke(entityHorse, true); + final Method getHorseId = entityHorse.getClass().getSuperclass().getSuperclass().getSuperclass().getSuperclass().getSuperclass().getSuperclass().getDeclaredMethod("getId"); + final int horseId = (Integer) (getHorseId.invoke(entityHorse)); + + if (playerIs1_8) + { + // Set horse (later armor stand) invisible + final Method setInvisble = entityHorse.getClass().getSuperclass().getSuperclass().getSuperclass().getSuperclass().getSuperclass().getSuperclass().getDeclaredMethod("setInvisible", + boolean.class); + setInvisble.invoke(entityHorse, true); + } + + Effects.effectlocd.put(horseId, 12); // send move packet 12 times + + // Send Witherskull+EntityHorse packet + final Object horsePacket = packetPlayOutSpawnEntityLivingConstr.newInstance(entityHorse); + if (playerIs1_8) + { + // Set entity id to 30 (armor stand): + Effects.setValue(horsePacket, "b", 30); + // Fix datawatcher values to prevent crashes (ofc armor stands expect other data than horses): + final Field datawatcher = entityHorse.getClass().getSuperclass().getSuperclass().getSuperclass().getSuperclass().getSuperclass().getSuperclass().getDeclaredField("datawatcher"); + datawatcher.setAccessible(true); + final Object datawatcherInstance = datawatcher.get(entityHorse); + final Field d = datawatcherInstance.getClass().getDeclaredField("d"); + d.setAccessible(true); + final Map dmap = (Map) d.get(datawatcherInstance); + dmap.remove(10); + // These are the Rotation ones + dmap.remove(11); + dmap.remove(12); + dmap.remove(13); + dmap.remove(14); + dmap.remove(15); + dmap.remove(16); + final Method a = datawatcherInstance.getClass().getDeclaredMethod("a", int.class, Object.class); + a.invoke(datawatcherInstance, 10, (byte) 0); + } + sendPacket.invoke(playerConnection.get(getPlayerHandle.invoke(p)), horsePacket); + if (!playerIs1_8) + { + final Object witherPacket = packetPlayOutSpawnEntityConstr.newInstance(witherSkull, 64); + sendPacket.invoke(playerConnection.get(getPlayerHandle.invoke(p)), witherPacket); + } + + // Send attach packet + if (!playerIs1_8) + { + final Object attachPacket = packetPlayOutAttachEntityConstr.newInstance(0, entityHorse, witherSkull); + sendPacket.invoke(playerConnection.get(getPlayerHandle.invoke(p)), attachPacket); + } + + // Send velocity packets to move the entities slowly down + if (moveDown) + { + Effects.effectlocd_taskid.put(horseId, Bukkit.getScheduler().runTaskTimer(MinigamesAPI.getAPI(), () -> { + try + { + final int i = Effects.effectlocd.get(horseId); + final Object packet = packetPlayOutEntityVelocity.newInstance(horseId, 0D, -0.05D, 0D); + sendPacket.invoke(playerConnection.get(getPlayerHandle.invoke(p)), packet); + if (!playerIs1_8) + { + final Object packet2 = packetPlayOutEntityVelocity.newInstance(witherSkullId, 0D, -0.05D, 0D); + sendPacket.invoke(playerConnection.get(getPlayerHandle.invoke(p)), packet2); + } + if (i < -1) + { + final int taskid = Effects.effectlocd_taskid.get(horseId); + Effects.effectlocd_taskid.remove(horseId); + Effects.effectlocd.remove(horseId); + Bukkit.getScheduler().cancelTask(taskid); + return; + } + Effects.effectlocd.put(horseId, Effects.effectlocd.get(horseId) - 1); + } + catch (final Exception e) + { + if (MinigamesAPI.debug) + { + MinigamesAPI.getAPI().getLogger().log(Level.WARNING, "exception", e); + } + } + }, 2L, 2L).getTaskId()); + } + + // Remove both entities (and thus the hologram) after 2 seconds + if (removeAfterCooldown) + { + Bukkit.getScheduler().runTaskLater(MinigamesAPI.getAPI(), () -> { + try + { + final Object destroyPacket = packetPlayOutEntityDestroyConstr.newInstance(new int[] { witherSkullId, horseId }); + sendPacket.invoke(playerConnection.get(getPlayerHandle.invoke(p)), destroyPacket); + } + catch (final Exception e) + { + if (MinigamesAPI.debug) + { + MinigamesAPI.getAPI().getLogger().log(Level.WARNING, "exception", e); + } + } + }, 20L * 2); + } + + ret.add(witherSkullId); + ret.add(horseId); + + } + catch (final Exception e) + { + if (MinigamesAPI.debug) + { + MinigamesAPI.getAPI().getLogger().log(Level.WARNING, "exception", e); + } + } + return ret; + } + + /** + * Sends a game mode change to given player. + * + * @param p + * target player + * @param gamemode + * new game mode. + */ + public static void sendGameModeChange(final Player p, final int gamemode) + { + // NOT_SET(-1, ""), SURVIVAL(0, "survival"), CREATIVE(1, "creative"), ADVENTURE(2, "adventure"), SPECTATOR(3, "spectator"); + + if (MinigamesAPI.SERVER_VERSION.isAfter(MinecraftVersionsType.V1_7) && gamemode == 3) + { + return; + } + + p.setGameMode(GameMode.getByValue(gamemode)); + } } diff --git a/API/src/main/java/com/comze_instancelabs/minigamesapi/LobbySignManager.java b/API/src/main/java/com/comze_instancelabs/minigamesapi/LobbySignManager.java new file mode 100644 index 00000000..cd102ddd --- /dev/null +++ b/API/src/main/java/com/comze_instancelabs/minigamesapi/LobbySignManager.java @@ -0,0 +1,339 @@ +/* + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +package com.comze_instancelabs.minigamesapi; + +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.time.LocalDateTime; +import java.time.temporal.ChronoUnit; +import java.util.HashMap; +import java.util.Map; +import java.util.logging.Level; + +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.block.BlockState; +import org.bukkit.block.Sign; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.event.block.SignChangeEvent; +import org.bukkit.plugin.Plugin; + +import com.comze_instancelabs.minigamesapi.util.Signs; +import com.google.common.io.ByteArrayDataOutput; +import com.google.common.io.ByteStreams; + +/** + * Manager for cross server lobby signs. + * + * @author mepeisen + * + */ +public class LobbySignManager +{ + + /** + * hash map for signs. + */ + private final Map signs = new HashMap<>(); + + /** + * minigames api. + */ + final Plugin plugin; + + /** + * Constructor. + * + * @param plugin + */ + public LobbySignManager(Plugin plugin) + { + this.plugin = plugin; + } + + /** + * Attaches a new sign to the sign manager, + * + * @param location + * location + * @param serverName + * server name + * @param minigameName + * minigame name + * @param arenaName + * arena name + * @param spec + * true for spectator sign, false for join sign + */ + public void attachSign(Location location, String serverName, String minigameName, String arenaName, boolean spec) + { + final SignData data = new SignData(location, serverName, minigameName, arenaName, spec); + this.signs.put(location, data); + data.setSignData(null); + } + + /** + * Attaches a new sign to the sign manager, + * + * @param location + * location + * @param serverName + * server name + * @param minigameName + * minigame name + * @param arenaName + * arena name + * @param spec + * true for spectator sign, false for join sign + * @param evt + * sign change event + */ + public void attachSign(Location location, String serverName, String minigameName, String arenaName, boolean spec, SignChangeEvent evt) + { + final SignData data = new SignData(location, serverName, minigameName, arenaName, spec); + this.signs.put(location, data); + data.setSignData(evt); + } + + /** + * request sign updates. + * + * @param location + */ + public void requestSignUpdate(Location location) + { + final SignData data = this.signs.get(location); + if (data != null) + { + data.requestServerSign(); + } + } + + /** + * Detaches a sign from manager. + * + * @param location + */ + public void detachSign(Location location) + { + this.signs.remove(location); + } + + /** + * @param location + * @param arenastate + * @param count + * @param maxcount + */ + public void updateSign(Location location, String arenastate, int count, int maxcount) + { + final SignData data = this.signs.get(location); + if (data != null) + { + data.setSignData(count, maxcount, arenastate, null); + data.updateResponseDate(); + } + } + + /** + * private sign data. + */ + private final class SignData + { + + /** sign location. */ + private final Location location; + + /** server name. */ + private final String serverName; + + /** arena name. */ + private final String arenaName; + + /** minigame name. */ + private final String minigameName; + + /** spectate sign? */ + private final boolean spec; + + /** + * last max players info. + */ + int lastMaxPlayers = 10; + + /** last request of sign update. */ + LocalDateTime lastRequest = LocalDateTime.now(); + + /** last response of sign update. */ + LocalDateTime lastResponse = this.lastRequest; + + /** + * timestamp a log warning was posted + */ + LocalDateTime lastSignWarning = null; + + /** + * @param location + * @param serverName + * @param minigameName + * @param arenaName + * @param spec + */ + public SignData(Location location, String serverName, String minigameName, String arenaName, boolean spec) + { + this.location = location; + this.serverName = serverName; + this.minigameName = minigameName; + this.arenaName = arenaName; + this.spec = spec; + } + + /** + * Updates the last response data. + */ + public void updateResponseDate() + { + this.lastResponse = LocalDateTime.now(); + } + + /** + * Request server sign update. + */ + public void requestServerSign() + { + this.lastRequest = LocalDateTime.now(); + try + { + ByteArrayDataOutput out = ByteStreams.newDataOutput(); + try + { + out.writeUTF("Forward"); //$NON-NLS-1$ + out.writeUTF(this.serverName); + out.writeUTF(ChannelStrings.SUBCHANNEL_MINIGAMESLIB_REQUEST); + + ByteArrayOutputStream msgbytes = new ByteArrayOutputStream(); + DataOutputStream msgout = new DataOutputStream(msgbytes); + msgout.writeUTF(this.minigameName + ":" + this.arenaName); //$NON-NLS-1$ + + out.writeShort(msgbytes.toByteArray().length); + out.write(msgbytes.toByteArray()); + + Bukkit.getServer().sendPluginMessage(LobbySignManager.this.plugin, ChannelStrings.CHANNEL_BUNGEE_CORD, out.toByteArray()); + + // TODO if no answer after 2 seconds, server empty! + + } + catch (Exception e) + { + MinigamesAPI.getAPI().getLogger().log(Level.WARNING, "exception", e); //$NON-NLS-1$ + } + } + catch (Exception e) + { + LobbySignManager.this.plugin.getLogger().log(Level.WARNING, "Error occurred while sending extra sign request: ", e); //$NON-NLS-1$ + } + } + + /** + * Sets initial sign data. + * + * @param evt + */ + public void setSignData(SignChangeEvent evt) + { + this.setSignData(0, 10, this.spec ? "SPEC" : "JOIN", evt); //$NON-NLS-1$ //$NON-NLS-2$ + } + + /** + * Sets sign data. + * + * @param count + * @param maxcount + * @param arenastate + * @param evt + */ + public void setSignData(int count, int maxcount, String arenastate, SignChangeEvent evt) + { + this.lastMaxPlayers = maxcount; + final FileConfiguration cfg = LobbySignManager.this.plugin.getConfig(); + final String line0 = Signs.format(cfg.getString("signs." + arenastate.toLowerCase() + ".0").replace("", Integer.toString(count)).replace("", Integer.toString(maxcount)) //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + .replace("", this.arenaName).replace("", this.minigameName)); //$NON-NLS-1$ //$NON-NLS-2$ + final String line1 = Signs.format(cfg.getString("signs." + arenastate.toLowerCase() + ".1").replace("", Integer.toString(count)).replace("", Integer.toString(maxcount)) //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + .replace("", this.arenaName).replace("", this.minigameName)); //$NON-NLS-1$ //$NON-NLS-2$ + final String line2 = Signs.format(cfg.getString("signs." + arenastate.toLowerCase() + ".2").replace("", Integer.toString(count)).replace("", Integer.toString(maxcount)) //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + .replace("", this.arenaName).replace("", this.minigameName)); //$NON-NLS-1$ //$NON-NLS-2$ + final String line3 = Signs.format(cfg.getString("signs." + arenastate.toLowerCase() + ".3").replace("", Integer.toString(count)).replace("", Integer.toString(maxcount)) //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + .replace("", this.arenaName).replace("", this.minigameName)); //$NON-NLS-1$ //$NON-NLS-2$ + if (evt == null) + { + final BlockState state = this.location.getBlock().getState(); + if (state instanceof Sign) + { + final Sign sign = (Sign) state; + sign.setLine(0, line0); + sign.setLine(1, line1); + sign.setLine(2, line2); + sign.setLine(3, line3); + sign.getBlock().getChunk().load(); + sign.update(); + } + else + { + if (this.lastSignWarning == null || this.lastSignWarning.until(LocalDateTime.now(), ChronoUnit.SECONDS) > 30) + { + this.lastSignWarning = LocalDateTime.now(); + LobbySignManager.this.plugin.getLogger().log(Level.WARNING, "Cannot find lobby sign for " + this.minigameName + "/" + this.arenaName + " at position " + this.location); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + } + } + } + else + { + evt.setLine(0, line0); + evt.setLine(1, line1); + evt.setLine(2, line2); + evt.setLine(3, line3); + } + } + + } + + /** + * + */ + public void ping() + { + for (final SignData data : this.signs.values()) + { + if (data.lastResponse.isBefore(data.lastRequest)) + { + if (data.lastResponse.until(data.lastRequest, ChronoUnit.SECONDS) > 5) + { + // assume there are no more players + data.setSignData(0, data.lastMaxPlayers, "JOIN", null); //$NON-NLS-1$ + data.updateResponseDate(); + } + } + else + { + if (data.lastResponse.until(LocalDateTime.now(), ChronoUnit.SECONDS) > 60) + { + data.requestServerSign(); + } + } + } + } + +} diff --git a/API/src/main/java/com/comze_instancelabs/minigamesapi/MatchTimer.java b/API/src/main/java/com/comze_instancelabs/minigamesapi/MatchTimer.java new file mode 100644 index 00000000..42f84cda --- /dev/null +++ b/API/src/main/java/com/comze_instancelabs/minigamesapi/MatchTimer.java @@ -0,0 +1,341 @@ +/* + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +package com.comze_instancelabs.minigamesapi; + +import java.time.LocalDateTime; +import java.time.temporal.ChronoUnit; +import java.util.function.Consumer; +import java.util.logging.Logger; + +import org.bukkit.plugin.Plugin; +import org.bukkit.scheduler.BukkitRunnable; +import org.bukkit.scheduler.BukkitTask; + +/** + * Backport of v2 BasicMatchTimer rule + * + * @author mepeisen + * + */ +public class MatchTimer +{ + + + /** + * maximum seconds + */ + private int seconds; + + /** + * the current match duration in millis + */ + private long matchDuration; + + /** + * the current match maxmimum time + */ + private long matchTime; + + /** + * Flag for paused or running timers; {@code true} if timer is paused + */ + private boolean paused; + + /** + * Last start of timer + */ + private LocalDateTime lastStart = LocalDateTime.now(); + + /** + * The timer task + */ + private BukkitTask timerTask; + + private Runnable arenaAbort; + + private Consumer arenaNotify; + + private boolean warn60 = true; + + private boolean warn30 = true; + + private boolean warn20 = true; + + private boolean warn10 = true; + + private boolean warn5 = true; + + private boolean warn4 = true; + + private boolean warn3 = true; + + private boolean warn2 = true; + + private boolean warn1 = true; + + /** logger. */ + private static final Logger LOGGER = Logger.getLogger(MatchTimer.class.getName()); + + /** + */ + public MatchTimer(int maxSeconds, Runnable arenaAbort, Consumer arenaNotify) + { + this.setMaxSeconds(maxSeconds); + this.arenaAbort = arenaAbort; + this.arenaNotify = arenaNotify; + } + + public int getMaxSeconds() + { + return this.seconds; + } + + public void setMaxSeconds(int seconds) + { + this.seconds = seconds; + this.matchTime = this.seconds * 1000L; + } + + public void pause() + { + if (!this.paused) + { + this.paused = true; + this.matchDuration += this.lastStart.until(LocalDateTime.now(), ChronoUnit.MILLIS); + } + } + + public void resume() + { + if (this.paused) + { + this.paused = false; + this.lastStart = LocalDateTime.now(); + } + } + + public void resetAndResume() + { + this.paused = false; + this.lastStart = LocalDateTime.now(); + this.matchDuration = 0; + this.fixWarnings(); + } + + public void resetAndPause() + { + this.paused = true; + this.matchDuration = 0; + this.fixWarnings(); + } + + public long getDurationMillis() + { + if (this.paused) + { + return this.matchDuration; + } + return this.matchDuration + this.lastStart.until(LocalDateTime.now(), ChronoUnit.MILLIS); + } + + public long getMaxMillis() + { + return this.matchTime; + } + + public void addMaxMillis(Plugin plugin, long millis) + { + this.matchTime += millis; + if (this.matchTime > 0 && this.timerTask == null) + { + this.startTimer(plugin); + } + this.fixWarnings(); + } + + public void substractMaxMillis(long millis) + { + this.matchTime -= millis; + if (this.matchTime <= 0) + { + this.stopTimer(); + } + this.fixWarnings(); + } + + public void setMaxMillis(long millis) + { + this.matchTime = millis; + if (this.matchTime <= 0) + { + this.stopTimer(); + } + this.fixWarnings(); + } + + public void addDurationMillis(long millis) + { + this.matchDuration += millis; + this.fixWarnings(); + } + + public void substractDurationMillis(long millis) + { + this.matchDuration -= millis; + this.fixWarnings(); + } + + public void setDurationMillis(long millis) + { + this.matchDuration = millis; + this.fixWarnings(); + } + + public void onArenaStart(Plugin plugin) + { + this.matchTime = this.seconds * 1000L; + this.matchDuration = 0; + this.lastStart = LocalDateTime.now(); + this.paused = false; + if (this.matchTime > 0) + { + this.startTimer(plugin); + } + this.fixWarnings(); + } + + + public void onArenaStop() + { + this.stopTimer(); + } + + /** + * Starts the bukkit timer task + */ + private void startTimer(Plugin plugin) + { + if (this.timerTask == null) + { + this.timerTask = new BukkitRunnable() { + + @Override + public void run() + { + MatchTimer.this.onTimer(MatchTimer.this.timerTask); + } + }.runTaskTimer(plugin, 20L, 20L); + } + } + + /** + * Stops the bukkit timer task + */ + private void stopTimer() + { + if (this.timerTask != null) + { + this.timerTask.cancel(); + this.timerTask = null; + } + } + + /** + * Fixes warnings depending on remaining game time + */ + private void fixWarnings() + { + long delta = this.getMaxMillis() - this.getDurationMillis(); + final int sec = (int) (delta / 1000); + this.warn60 = sec >= 60; + this.warn30 = sec >= 30; + this.warn20 = sec >= 20; + this.warn10 = sec >= 10; + this.warn5 = sec >= 5; + this.warn4 = sec >= 4; + this.warn3 = sec >= 3; + this.warn2 = sec >= 2; + this.warn1 = sec >= 1; + } + + /** + * On timer tick + * + * @param task + */ + private void onTimer(BukkitTask task) + { + if (!this.paused) + { + long delta = this.getMaxMillis() - this.getDurationMillis(); + if (delta <= 0) + { + this.timerTask.cancel(); + this.timerTask = null; + this.arenaAbort.run(); + } + else + { + final int sec = (int) (delta / 1000); + if (this.warn60 && sec <= 60) + { + this.arenaNotify.accept(60); + this.warn60 = false; + } + else if (this.warn30 && sec <= 30) + { + this.arenaNotify.accept(30); + this.warn30 = false; + } + else if (this.warn20 && sec <= 20) + { + this.arenaNotify.accept(20); + this.warn20 = false; + } + else if (this.warn10 && sec <= 10) + { + this.arenaNotify.accept(10); + this.warn10 = false; + } + else if (this.warn5 && sec <= 5) + { + this.arenaNotify.accept(5); + this.warn5 = false; + } + else if (this.warn4 && sec <= 4) + { + this.arenaNotify.accept(4); + this.warn4 = false; + } + else if (this.warn3 && sec <= 3) + { + this.arenaNotify.accept(3); + this.warn3 = false; + } + else if (this.warn2 && sec <= 2) + { + this.arenaNotify.accept(2); + this.warn2 = false; + } + else if (this.warn1 && sec <= 1) + { + this.arenaNotify.accept(1); + this.warn1 = false; + } + } + } + } +} diff --git a/API/src/main/java/com/comze_instancelabs/minigamesapi/Messages.java b/API/src/main/java/com/comze_instancelabs/minigamesapi/Messages.java new file mode 100644 index 00000000..5c2b86b8 --- /dev/null +++ b/API/src/main/java/com/comze_instancelabs/minigamesapi/Messages.java @@ -0,0 +1,79 @@ +/* + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +package com.comze_instancelabs.minigamesapi; + +import java.util.Locale; +import java.util.Map; +import java.util.MissingResourceException; +import java.util.ResourceBundle; +import java.util.concurrent.ConcurrentHashMap; + +/** + * Localized message helper. + * + * @author mepeisen + */ +public class Messages +{ + + /** the resource bundle name. */ + private static final String BUNDLE_NAME = "com.comze_instancelabs.minigamesapi.messages"; //$NON-NLS-1$ + + /** the default resource bundle; used as fallback. */ + private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle(BUNDLE_NAME); + + /** the bundles by locales. */ + private static final Map BUNDLES = new ConcurrentHashMap<>(); + + /** + * hidden constructor. + */ + private Messages() + { + } + + /** + * Returns the localized string + * + * @param key + * string key + * @param locale + * locale to be used. + * @return localized string. + */ + public static String getString(String key, Locale locale) + { + try + { + final ResourceBundle res = BUNDLES.computeIfAbsent(locale, (l) -> { + try + { + return ResourceBundle.getBundle(BUNDLE_NAME, l); + } + catch (@SuppressWarnings("unused") MissingResourceException ex) + { + return RESOURCE_BUNDLE; + } + }); + return res.getString(key); + } + catch (@SuppressWarnings("unused") MissingResourceException e) + { + return '!' + key + '!'; + } + } + +} diff --git a/API/src/main/java/com/comze_instancelabs/minigamesapi/MinecraftVersionsType.java b/API/src/main/java/com/comze_instancelabs/minigamesapi/MinecraftVersionsType.java new file mode 100644 index 00000000..566fc669 --- /dev/null +++ b/API/src/main/java/com/comze_instancelabs/minigamesapi/MinecraftVersionsType.java @@ -0,0 +1,238 @@ +/* + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ +package com.comze_instancelabs.minigamesapi; + +/** + * Supported versions of minecraft. + * + * @author mepeisen + */ +public enum MinecraftVersionsType +{ + /** an unknown version/ not supported. */ + Unknown(false, "invalid"), //$NON-NLS-1$ + + /** any 1.7 version. */ + V1_7(true, "v1_7_R1"), //$NON-NLS-1$ + + /** V1.7 R1 */ + V1_7_R1(true, "v1_7_R1"), //$NON-NLS-1$ + + /** V1.7 R2 */ + V1_7_R2(true, "v1_7_R2"), //$NON-NLS-1$ + + /** V1.7 R3 */ + V1_7_R3(true, "v1_7_R3"), //$NON-NLS-1$ + + /** V1.7 R4 */ + V1_7_R4(true, "v1_7_R4"), //$NON-NLS-1$ + + /** any 1.8 version. */ + V1_8(true, "v1_8_R1"), //$NON-NLS-1$ + + /** V1.8 R1 */ + V1_8_R1(true, "v1_8_R1"), //$NON-NLS-1$ + + /** V1.8 R2 */ + V1_8_R2(true, "v1_8_R2"), //$NON-NLS-1$ + + /** V1.8 R3 */ + V1_8_R3(true, "v1_8_R3"), //$NON-NLS-1$ + + /** any 1.9 version. */ + V1_9(true, "v1_9_R1"), //$NON-NLS-1$ + + /** V1.9 R1 */ + V1_9_R1(true, "v1_9_R1"), //$NON-NLS-1$ + + /** V1.9 R2 */ + V1_9_R2(true, "v1_9_R2"), //$NON-NLS-1$ + + /** any 1.10 version. */ + V1_10(true, "v1_10_R1"), //$NON-NLS-1$ + + /** V1.10 R1 */ + V1_10_R1(true, "v1_10_R1"), //$NON-NLS-1$ + + /** any 1.11 version. */ + V1_11(true, "v1_11_R1"), //$NON-NLS-1$ + + /** V1.11 R1 */ + V1_11_R1(true, "v1_11_R1"), //$NON-NLS-1$ + + /** any 1.12 version. */ + V1_12(true, "v1_12_R1"), //$NON-NLS-1$ + + /** V1.12 R1 */ + V1_12_R1(true, "v1_12_R1"), //$NON-NLS-1$ + + ; + + /** + * {@code true} if this version is still supported. + */ + private final boolean isSupported; + + /** the maven version string for update requests. */ + private final String mavenVersion; + + /** + * Constructor to create a version. + * + * @param supported + * true for support. + * @param mavenVersion + * the maven version string for update queries. + */ + private MinecraftVersionsType(final boolean supported, final String mavenVersion) + { + this.isSupported = supported; + this.mavenVersion = mavenVersion; + } + + /** + * {@code true} if this version is still supported. + * + * @return {@code true} if this version is still supported. + */ + public boolean isSupported() + { + return this.isSupported; + } + + /** + * Checks if this version equals given version. + * + *

+ * Notice: Pseudo versions (V1_7) will match every V1_7_R* version. + *

+ * + * @param type + * version to compare to. + * @return {@code true} if this version matches given version. + */ + public boolean isEqual(final MinecraftVersionsType type) + { + switch (this) + { + case V1_12: + return type == V1_12 || type == V1_12_R1; + case V1_11: + return type == V1_11 || type == V1_11_R1; + case V1_10: + return type == V1_10 || type == V1_10_R1; + case V1_7: + return type == V1_7 || type == V1_7_R1 || type == V1_7_R2 || type == V1_7_R3 || type == V1_7_R4; + case V1_8: + return type == V1_8 || type == V1_8_R1 || type == V1_8_R2 || type == V1_8_R3; + case V1_9: + return type == V1_9 || type == V1_9_R1 || type == V1_9_R2; + // $CASES-OMITTED$ + default: + switch (type) + { + case V1_12: + return this == V1_12 || this == V1_12_R1; + case V1_11: + return this == V1_11 || this == V1_11_R1; + case V1_10: + return this == V1_10 || this == V1_10_R1; + case V1_7: + return this == V1_7 || this == V1_7_R1 || this == V1_7_R2 || this == V1_7_R3 || this == V1_7_R4; + case V1_8: + return this == V1_8 || this == V1_8_R1 || this == V1_8_R2 || this == V1_8_R3; + case V1_9: + return this == V1_9 || this == V1_9_R1 || this == V1_9_R2; + // $CASES-OMITTED$ + default: + return type == this; + } + } + } + + /** + * Checks if this version is below given version. + * + *
    + *
  • V1_7 will be below V1_8*.
  • + *
  • V1_7_R3 will be below V1_7_R4.
  • + *
+ * + * @param type + * version to compare to. + * @return {@code true} if this version matches given version. + */ + public boolean isBelow(final MinecraftVersionsType type) + { + if (this.isEqual(type)) + { + return false; + } + return this.ordinal() < type.ordinal(); + } + + /** + * Checks if this version is after given version. + * + *
    + *
  • V1_8 will be after V1_7*.
  • + *
  • V1_7_R4 will be after V1_7_R3.
  • + *
+ * + * @param type + * version to compare to. + * @return {@code true} if this version matches given version. + */ + public boolean isAfter(final MinecraftVersionsType type) + { + if (this.isEqual(type)) + { + return false; + } + return this.ordinal() > type.ordinal(); + } + + /** + * Checks if this version is at least given version. + * + *
    + *
  • V1_7_R4 will be at least V1_7.
  • + *
  • V1_7_R3 will be after V1_7_R2.
  • + *
+ * + * @param type + * version to compare to. + * @return {@code true} if this version matches given version. + */ + public boolean isAtLeast(final MinecraftVersionsType type) + { + if (this.isEqual(type)) + { + return true; + } + return this.ordinal() > type.ordinal(); + } + + /** + * Returns the maven version string for update queries. + * + * @return maven version string. + */ + public String mavenVersionString() + { + return this.mavenVersion; + } + +} diff --git a/API/src/main/java/com/comze_instancelabs/minigamesapi/MinigamesAPI.java b/API/src/main/java/com/comze_instancelabs/minigamesapi/MinigamesAPI.java index d9c1a9fb..cb9f6c42 100644 --- a/API/src/main/java/com/comze_instancelabs/minigamesapi/MinigamesAPI.java +++ b/API/src/main/java/com/comze_instancelabs/minigamesapi/MinigamesAPI.java @@ -1,24 +1,56 @@ +/* + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ package com.comze_instancelabs.minigamesapi; import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; import java.io.DataInputStream; +import java.io.DataOutputStream; import java.io.IOException; import java.util.ArrayList; +import java.util.Collections; import java.util.HashMap; - -import net.milkbowl.vault.economy.Economy; +import java.util.Iterator; +import java.util.List; +import java.util.Locale; +import java.util.UUID; +import java.util.function.Supplier; +import java.util.logging.Level; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Effect; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.block.BlockState; +import org.bukkit.block.Sign; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; +import org.bukkit.configuration.ConfigurationSection; import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.block.Action; +import org.bukkit.event.block.BlockBreakEvent; +import org.bukkit.event.block.SignChangeEvent; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.event.server.ServerListPingEvent; import org.bukkit.plugin.RegisteredServiceProvider; import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.plugin.messaging.PluginMessageListener; -import com.comze_instancelabs.minigamesapi.bungee.BungeeSocket; import com.comze_instancelabs.minigamesapi.commands.CommandHandler; import com.comze_instancelabs.minigamesapi.config.ArenasConfig; import com.comze_instancelabs.minigamesapi.config.ClassesConfig; @@ -33,549 +65,1932 @@ import com.comze_instancelabs.minigamesapi.util.Metrics; import com.comze_instancelabs.minigamesapi.util.Metrics.Graph; import com.comze_instancelabs.minigamesapi.util.ParticleEffectNew; -import com.comze_instancelabs.minigamesapi.util.Updater; +import com.comze_instancelabs.minigamesapi.util.UpdaterNexus; import com.comze_instancelabs.minigamesapi.util.Util; +import com.comze_instancelabs.minigamesapi.util.Validator; import com.google.common.io.ByteArrayDataInput; +import com.google.common.io.ByteArrayDataOutput; import com.google.common.io.ByteStreams; -public class MinigamesAPI extends JavaPlugin implements PluginMessageListener { - - static MinigamesAPI instance = null; - public static Economy econ = null; - public static boolean economy = true; - public boolean crackshot = false; - public static boolean debug = false; - - public HashMap global_party = new HashMap(); - public HashMap> global_party_invites = new HashMap>(); - - public static HashMap pinstances = new HashMap(); - - public PartyMessagesConfig partymessages; - public StatsGlobalConfig statsglobal; - - public String version = ""; - public boolean below1710 = false; // Used for scoreboard function (wether to use getScore(OfflinePlayer) or getScore(String)) - - Metrics metrics; - - public void onEnable() { - instance = this; - - this.version = Bukkit.getServer().getClass().getPackage().getName().substring(Bukkit.getServer().getClass().getPackage().getName().lastIndexOf(".") + 1); - this.below1710 = version.startsWith("v1_7_R3") || version.startsWith("v1_7_R2") || version.startsWith("v1_7_R1") || version.startsWith("v1_6") || version.startsWith("v1_5"); - Bukkit.getConsoleSender().sendMessage(ChatColor.RED + "" + ChatColor.BOLD + "Loaded MinigamesAPI. We're on " + version + "."); - - this.getServer().getMessenger().registerOutgoingPluginChannel(this, "BungeeCord"); - this.getServer().getMessenger().registerIncomingPluginChannel(this, "BungeeCord", this); - - if (economy) { - if (!setupEconomy()) { - getLogger().severe(String.format("[%s] - No Economy (Vault) dependency found! Disabling Economy.", getDescription().getName())); - economy = false; - } - } - - getConfig().options().header("Want bugfree versions? Set this to true:"); - getConfig().addDefault("config.auto_updating", true); - getConfig().addDefault("config.party_command_enabled", true); - getConfig().addDefault("config.debug", false); - - getConfig().options().copyDefaults(true); - this.saveConfig(); - - partymessages = new PartyMessagesConfig(this); - statsglobal = new StatsGlobalConfig(this, false); - - this.debug = getConfig().getBoolean("config.debug"); - - Bukkit.getScheduler().runTaskLater(this, new Runnable() { - public void run() { - try { - metrics = new Metrics(instance); - - Graph components = metrics.createGraph("Minigames"); - for (PluginInstance pli : pinstances.values()) { - components.addPlotter(new Metrics.Plotter(pli.getPlugin().getName()) { - @Override - public int getValue() { - return 1; - } - }); - if (MinigamesAPI.debug) { - System.out.println("Loaded Graph for: " + pli.getPlugin().getName()); - } - } - - metrics.start(); - } catch (IOException e) { - System.out.println("# " + e.getMessage()); - } - } - }, 60L); - - if (getConfig().getBoolean("config.auto_updating")) { - Updater updater = new Updater(this, 83025, this.getFile(), Updater.UpdateType.DEFAULT, false); - } - - if (getServer().getPluginManager().getPlugin("CrackShot") != null) { - crackshot = true; - } - - Bukkit.getScheduler().runTaskLater(this, new Runnable() { - public void run() { - // Reset all arena signs and check if any arena was interrupted - int i = 0; - for (PluginInstance pli : MinigamesAPI.getAPI().pinstances.values()) { - for (Arena a : pli.getArenas()) { - if (a != null) { - if (a.isSuccessfullyInit()) { - Util.updateSign(pli.getPlugin(), a); - a.getSmartReset().loadSmartBlocksFromFile(); - } else { - System.out.println(a.getInternalName() + " not initialized at onEnable."); - } - } - i++; - } - } - System.out.println("Found " + i + " arenas."); - } - }, 50L); - } - - public void onDisable() { - for (PluginInstance pli : this.pinstances.values()) { - // Reset arenas - for (Arena a : pli.getArenas()) { - if (a != null) { - if (a.isSuccessfullyInit()) { - if (a.getArenaState() != ArenaState.JOIN) { - a.getSmartReset().saveSmartBlocksToFile(); - } - ArrayList temp = new ArrayList(a.getAllPlayers()); - for (String p_ : temp) { - a.leavePlayer(p_, true); - } - try { - a.getSmartReset().resetRaw(); - } catch (Exception e) { - System.out.println("Failed resetting arena at onDisable. " + e.getMessage()); - } - } else { - System.out.println(a.getName() + " not initialized thus not reset at onDisable."); - } - } - } - - // Save important configs - pli.getArenasConfig().saveConfig(); - pli.getPlugin().saveConfig(); - pli.getMessagesConfig().saveConfig(); - pli.getClassesConfig().saveConfig(); - } - - } - - /** - * Sets up the API allowing to override all configs - * - * @param plugin_ - * @param arenaclass - * @param arenasconfig - * @param messagesconfig - * @param classesconfig - * @param statsconfig - * @return - */ - public static MinigamesAPI setupAPI(JavaPlugin plugin_, String minigame, Class arenaclass, ArenasConfig arenasconfig, MessagesConfig messagesconfig, ClassesConfig classesconfig, StatsConfig statsconfig, DefaultConfig defaultconfig, boolean customlistener) { - pinstances.put(plugin_, new PluginInstance(plugin_, arenasconfig, messagesconfig, classesconfig, statsconfig, new ArrayList())); - if (!customlistener) { - ArenaListener al = new ArenaListener(plugin_, pinstances.get(plugin_), minigame); - pinstances.get(plugin_).setArenaListener(al); - Bukkit.getPluginManager().registerEvents(al, plugin_); - } - Classes.loadClasses(plugin_); - Guns.loadGuns(plugin_); - pinstances.get(plugin_).getShopHandler().loadShopItems(); - return instance; - } - - public static void registerArenaListenerLater(JavaPlugin plugin_, ArenaListener arenalistener) { - Bukkit.getPluginManager().registerEvents(arenalistener, plugin_); - } - - public static void registerArenaSetup(JavaPlugin plugin_, ArenaSetup arenasetup) { - pinstances.get(plugin_).arenaSetup = arenasetup; - } - - public static void registerScoreboard(JavaPlugin plugin_, ArenaScoreboard board) { - pinstances.get(plugin_).scoreboardManager = board; - } - - /** - * Sets up the API, stuff won't work without that - * - * @param plugin_ - * @return - */ - // Allow loading of arenas with own extended arena class into - // PluginInstance: - // after this setup, get the PluginInstance, load the arenas by yourself - // and add the loaded arenas w/ custom arena class into the PluginInstance - public static MinigamesAPI setupAPI(JavaPlugin plugin_, String minigame, Class arenaclass) { - setupRaw(plugin_, minigame); - return instance; - } - - /** - * Sets up the API, stuff won't work without that - * - * @param plugin_ - * @return - */ - public static MinigamesAPI setupAPI(JavaPlugin plugin_, String minigame) { - PluginInstance pli = setupRaw(plugin_, minigame); - pli.addLoadedArenas(Util.loadArenas(plugin_, pli.getArenasConfig())); - return instance; - } - - public static PluginInstance setupRaw(JavaPlugin plugin_, String minigame) { - ArenasConfig arenasconfig = new ArenasConfig(plugin_); - MessagesConfig messagesconfig = new MessagesConfig(plugin_); - ClassesConfig classesconfig = new ClassesConfig(plugin_, false); - StatsConfig statsconfig = new StatsConfig(plugin_, false); - DefaultConfig.init(plugin_, false); - PluginInstance pli = new PluginInstance(plugin_, arenasconfig, messagesconfig, classesconfig, statsconfig); - pinstances.put(plugin_, pli); - ArenaListener al = new ArenaListener(plugin_, pinstances.get(plugin_), minigame); - pinstances.get(plugin_).setArenaListener(al); - Bukkit.getPluginManager().registerEvents(al, plugin_); - Classes.loadClasses(plugin_); - pli.getShopHandler().loadShopItems(); - Guns.loadGuns(plugin_); - return pli; - } - - public static MinigamesAPI getAPI() { - return instance; - } - - public static CommandHandler getCommandHandler() { - return new CommandHandler(); - } - - private boolean setupEconomy() { - if (getServer().getPluginManager().getPlugin("Vault") == null) { - return false; - } - RegisteredServiceProvider rsp = getServer().getServicesManager().getRegistration(Economy.class); - if (rsp == null) { - return false; - } - econ = rsp.getProvider(); - return econ != null; - } - - public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { - if (cmd.getName().equalsIgnoreCase("start")) { - if (!(sender instanceof Player)) { - sender.sendMessage("Please execute this command ingame."); - return true; - } - if (!sender.hasPermission("minigamesapi.start")) { - // TODO no_perm message - return true; - } - Player p = (Player) sender; - for (PluginInstance pli : MinigamesAPI.getAPI().pinstances.values()) { - if (pli.containsGlobalPlayer(p.getName())) { - Arena a = pli.global_players.get(p.getName()); - System.out.println(a.getName()); - if (a.getArenaState() == ArenaState.JOIN || (a.getArenaState() == ArenaState.STARTING && !a.getIngameCountdownStarted())) { - a.start(true); - sender.sendMessage(pli.getMessagesConfig().arena_action.replaceAll("", a.getDisplayName()).replaceAll("", "started")); - break; - } - } - } - return true; - } - if (cmd.getName().equalsIgnoreCase("party")) { - if (!getConfig().getBoolean("config.party_command_enabled")) { - return true; - } - CommandHandler cmdhandler = this.getCommandHandler(); - if (!(sender instanceof Player)) { - sender.sendMessage("Please execute this command ingame."); - return true; - } - Player p = (Player) sender; - if (args.length > 0) { - String action = args[0]; - if (action.equalsIgnoreCase("invite")) { - cmdhandler.partyInvite(sender, args, "minigamesapi.party", "/" + cmd.getName(), action, this, p); - } else if (action.equalsIgnoreCase("accept")) { - cmdhandler.partyAccept(sender, args, "minigamesapi.party", "/" + cmd.getName(), action, this, p); - } else if (action.equalsIgnoreCase("kick")) { - cmdhandler.partyKick(sender, args, "minigamesapi.party", "/" + cmd.getName(), action, this, p); - } else if (action.equalsIgnoreCase("list")) { - cmdhandler.partyList(sender, args, "minigamesapi.party", "/" + cmd.getName(), action, this, p); - } else if (action.equalsIgnoreCase("disband")) { - cmdhandler.partyDisband(sender, args, "minigamesapi.party", "/" + cmd.getName(), action, this, p); - } else if (action.equalsIgnoreCase("leave")) { - cmdhandler.partyLeave(sender, args, "minigamesapi.party", "/" + cmd.getName(), action, this, p); - } else { - cmdhandler.sendPartyHelp("/" + cmd.getName(), sender); - } - } else { - cmdhandler.sendPartyHelp("/" + cmd.getName(), sender); - } - } else { - if (args.length > 0) { - if (args[0].equalsIgnoreCase("info")) { - if (args.length > 1) { - String p = args[1]; - sender.sendMessage("Debug info about " + p); - sender.sendMessage("~ global_players: "); - for (PluginInstance pli : pinstances.values()) { - if (pli.global_players.containsKey(p)) { - sender.sendMessage(" " + pli.getPlugin().getName()); - } - } - sender.sendMessage("~ global_lost: "); - for (PluginInstance pli : pinstances.values()) { - if (pli.global_lost.containsKey(p)) { - sender.sendMessage(" " + pli.getPlugin().getName()); - } - } - sender.sendMessage("~ SpectatorManager: "); - for (PluginInstance pli : pinstances.values()) { - if (pli.getSpectatorManager().isSpectating(Bukkit.getPlayer(p))) { - sender.sendMessage(" " + pli.getPlugin().getName()); - } - } - sender.sendMessage("~ Arenas: "); - for (PluginInstance pli : pinstances.values()) { - if (pli.global_players.containsKey(p)) { - sender.sendMessage(" " + pli.global_players.get(p).getInternalName() + " - " + pli.global_players.get(p).getArenaState()); - } - } - } else { - for (PluginInstance pli : pinstances.values()) { - sender.sendMessage("~ All players for " + pli.getPlugin().getName() + ": "); - for (Arena a : pli.getArenas()) { - if (a != null) { - for (String p_ : a.getAllPlayers()) { - sender.sendMessage(ChatColor.GRAY + " " + pli.getPlugin().getName() + " " + a.getInternalName() + " " + p_); - } - } - } - } - } - } else if (args[0].equalsIgnoreCase("debug")) { - debug = !debug; - this.getConfig().set("config.debug", debug); - this.saveConfig(); - sender.sendMessage(ChatColor.GOLD + "Debug mode is now: " + debug); - } else if (args[0].equalsIgnoreCase("list")) { - int c = 0; - for (PluginInstance pli : MinigamesAPI.getAPI().pinstances.values()) { - c++; - sender.sendMessage("~ " + pli.getPlugin().getName() + ": " + pli.getArenas().size() + " Arenas"); - } - if (c < 1) { - sender.sendMessage("~ No installed minigames found! Download/Install some from the project page."); - } - } else if (args[0].equalsIgnoreCase("restartserver")) { - if (sender.isOp()) { - Util.restartServer(); - } - } else if (args[0].equalsIgnoreCase("title")) { - if (args.length > 1) { - if (sender instanceof Player) { - Effects.playTitle((Player) sender, args[1], 0); - } - } - } else if (args[0].equalsIgnoreCase("subtitle")) { - if (args.length > 1) { - if (sender instanceof Player) { - Effects.playTitle((Player) sender, args[1], 1); - } - } - } else if (args[0].equalsIgnoreCase("hologram")) { - if (sender instanceof Player) { - Player p = (Player) sender; - p.sendMessage("Playing hologram."); - Effects.playHologram(p, p.getLocation(), ChatColor.values()[(int) (Math.random() * ChatColor.values().length - 1)] + "TEST", true, true); - } - } else if (args[0].equalsIgnoreCase("statshologram")) { - if (sender instanceof Player) { - Player p = (Player) sender; - if (args.length > 1) { - PluginInstance pli = getPluginInstance((JavaPlugin) Bukkit.getPluginManager().getPlugin(args[1])); - p.sendMessage("Playing statistics hologram."); - - Effects.playHologram(p, p.getLocation().add(0D, 1D, 0D), ChatColor.values()[(int) (Math.random() * ChatColor.values().length - 1)] + "Wins: " + pli.getStatsInstance().getWins(p.getName()), false, false); - Effects.playHologram(p, p.getLocation().add(0D, 0.75D, 0D), ChatColor.values()[(int) (Math.random() * ChatColor.values().length - 1)] + "Points: " + pli.getStatsInstance().getPoints(p.getName()), false, false); - Effects.playHologram(p, p.getLocation().add(0D, 0.5D, 0D), ChatColor.values()[(int) (Math.random() * ChatColor.values().length - 1)] + "Kills: " + pli.getStatsInstance().getKills(p.getName()), false, false); - Effects.playHologram(p, p.getLocation().add(0D, 0.25D, 0D), ChatColor.values()[(int) (Math.random() * ChatColor.values().length - 1)] + "Deaths: " + pli.getStatsInstance().getDeaths(p.getName()), false, false); - - } - } - } else if (args[0].equalsIgnoreCase("protocol")) { - if (sender instanceof Player) { - Player p = (Player) sender; - if (args.length > 1) { - p = Bukkit.getPlayer(args[1]); - } - if (p != null) { - int version = Effects.getClientProtocolVersion(p); - sender.sendMessage("Protocol version of " + p.getName() + ": " + version); - } - } - } else if (args[0].equalsIgnoreCase("gamemodetest")) { - if (sender instanceof Player) { - Player p = (Player) sender; - if (p.isOp()) { - Effects.sendGameModeChange(p, 3); - } - } - } else if (args[0].equalsIgnoreCase("bungeetest")) { - if (sender instanceof Player) { - Player p = (Player) sender; - if (p.isOp()) { - PluginInstance pli = this.pinstances.get(Bukkit.getPluginManager().getPlugin("MGSkyWars")); - BungeeSocket.sendSignUpdate(pli, pli.getArenas().get(0)); - } - } - } - return true; - } - if (args.length < 1) { - sender.sendMessage(ChatColor.GOLD + "" + ChatColor.BOLD + "MinigamesLib <3 " + this.getDescription().getVersion()); - int c = 0; - for (PluginInstance pli : MinigamesAPI.getAPI().pinstances.values()) { - c++; - sender.sendMessage("~ " + ChatColor.GRAY + pli.getPlugin().getName() + ": " + ChatColor.WHITE + pli.getArenas().size() + " Arenas"); - } - if (c < 1) { - sender.sendMessage("~ No installed minigames found! Download/Install some from the project page."); - } - sender.sendMessage(ChatColor.GOLD + "Subcommands: "); - sender.sendMessage("/mapi info "); - sender.sendMessage("/mapi debug"); - sender.sendMessage("/mapi list"); - sender.sendMessage("/mapi title "); - sender.sendMessage("/mapi subtitle <subtitle>"); - sender.sendMessage("/mapi restartserver"); - sender.sendMessage("/mapi hologram"); - sender.sendMessage("/mapi protocol <player>"); - sender.sendMessage("/mapi <potioneffect>"); - sender.sendMessage("/mapi setstatshologram"); - } - if (sender instanceof Player && args.length > 0) { - Player p = (Player) sender; - boolean cont = false; - for (ParticleEffectNew f : ParticleEffectNew.values()) { - if (f.name().equalsIgnoreCase(args[0])) { - cont = true; - } - } - if (!cont) { - sender.sendMessage(ChatColor.RED + "Couldn't find particle effect."); - return true; - } - ParticleEffectNew eff = ParticleEffectNew.valueOf(args[0]); - eff.setId(152); - - for (float i = 0; i < 10; i++) { - eff.animateReflected(p, p.getLocation().clone().add(i / 5F, i / 5F, i / 5F), 1F, 2); - } - - p.getWorld().playEffect(p.getLocation(), Effect.STEP_SOUND, 152); - p.getWorld().playEffect(p.getLocation().add(0D, 1D, 0D), Effect.STEP_SOUND, 152); - } - } - return true; - } +import net.milkbowl.vault.economy.Economy; - @Override - public void onPluginMessageReceived(String channel, Player player, byte[] message) { - if (!channel.equals("BungeeCord")) { - return; - } - ByteArrayDataInput in = ByteStreams.newDataInput(message); - String subchannel = in.readUTF(); - System.out.println(subchannel); - if (subchannel.equals("MinigamesLibBack")) { - short len = in.readShort(); - byte[] msgbytes = new byte[len]; - in.readFully(msgbytes); +/** + * Main minigames API; plugin mplementation. + * + * @author instancelabs + * + */ +public class MinigamesAPI extends JavaPlugin implements PluginMessageListener, Listener +{ + + /** the overall minecraft server versioon. */ + public static final MinecraftVersionsType SERVER_VERSION = MinigamesAPI.getServerVersion(); + + /** the locale to be used. TODO: Change via config */ + public static Locale LOCALE = Locale.ENGLISH; + + /** the minigames plugin instance. */ + private static MinigamesAPI instance = null; + + /** + * Vault economy instance. + * + * @deprecated will be private and non-static in 1.5.0; replaced by new method + */ + @Deprecated + public static Economy econ = null; + + /** + * {@code true} if economy is installed. + * + * @deprecated will be private and non-static in 1.5.0, replace by {@link #economyAvailable()} + */ + @Deprecated + public static boolean economy = true; + + /** + * {@code true} if crackshot is installed. + * + * @deprecated will be private in 1.5.0, replace by {@link #crackshotAvailable()} + */ + @Deprecated + public boolean crackshot = false; + + /** a global debug flag; controls the output of finer debug messages. */ + public static boolean debug = false; + + /** + * @deprecated will be removed in 1.5.0 + */ + @Deprecated + int updatetime = 20 * 10; + + /** + * Party per owning player + */ + private HashMap<UUID, Party> global_party = new HashMap<>(); + + /** + * Invites per player + */ + private HashMap<UUID, ArrayList<Party>> global_party_invites = new HashMap<>(); + + /** + * Hash map with internal plugin representations of each registered minigame. + * + * @deprecated will be private in 1.5.0; replaced by {@link #getPluginInstance(JavaPlugin)} + */ + @Deprecated + public static HashMap<JavaPlugin, PluginInstance> pinstances = new HashMap<>(); + + /** + * The party messages. + * + * @deprecated will be private in 1.5.0; replaced by new methods. + */ + @Deprecated + public PartyMessagesConfig partymessages; + + /** + * The stats config. + * + * @deprecated will be private in 1.5.0; replaced by new methods. + */ + @Deprecated + public StatsGlobalConfig statsglobal; + + /** + * textual server version. + * + * @deprecated will be removed in 1.5.0; replaced by SERVER_VERSION enumeration. + */ + @Deprecated + public String internalServerVersion = ""; //$NON-NLS-1$ + + /** + * {@code true} if this is below 1.7.10 + * + * @deprecated will be removed in 1.5.0; replaced by SERVER_VERSION enumeration. + */ + public boolean below1710 = false; + + /** + * The plugin metrics report. + */ + Metrics metrics; + + /** the current motd */ + private String motd; + + /** suppliers or the motd strings. */ + private Iterator<Supplier<String>> motdStrings = Collections.emptyIterator(); + + /** the lobby sign manager. */ + private final LobbySignManager signManager = new LobbySignManager(this); + + @Override + public void onEnable() + { + MinigamesAPI.instance = this; + + this.internalServerVersion = Bukkit.getServer().getClass().getPackage().getName().substring(Bukkit.getServer().getClass().getPackage().getName().lastIndexOf(".") + 1); //$NON-NLS-1$ + this.below1710 = MinigamesAPI.SERVER_VERSION.isBelow(MinecraftVersionsType.V1_7_R4); + this.getLogger().info(String.format("§c§lLoaded MinigamesAPI. We're on %0$s.", MinigamesAPI.SERVER_VERSION.name())); //$NON-NLS-1$ + + this.getServer().getMessenger().registerOutgoingPluginChannel(this, ChannelStrings.CHANNEL_BUNGEE_CORD); + this.getServer().getMessenger().registerIncomingPluginChannel(this, ChannelStrings.CHANNEL_BUNGEE_CORD, this); + + if (!this.setupEconomy()) + { + this.getLogger().severe(String.format("[%s] - No Economy (Vault) dependency found! Disabling Economy.", this.getDescription().getName())); //$NON-NLS-1$ + MinigamesAPI.economy = false; + } + + this.getConfig().options().header("Want bugfree versions? Set this to true for automatic updates:"); //$NON-NLS-1$ + this.getConfig().addDefault(PluginConfigStrings.AUTO_UPDATING, true); + this.getConfig().addDefault(PluginConfigStrings.POST_METRICS, true); + this.getConfig().addDefault(PluginConfigStrings.SIGNS_UPDATE_TIME, 20); + this.getConfig().addDefault(PluginConfigStrings.PARTY_COMMAND_ENABLED, true); + this.getConfig().addDefault(PluginConfigStrings.DEBUG, false); + + this.getConfig().addDefault(PluginConfigStrings.PERMISSION_PREFIX, "ancient.core"); //$NON-NLS-1$ + this.getConfig().addDefault(PluginConfigStrings.PERMISSION_KITS_PREFIX, "ancient.core.kits"); //$NON-NLS-1$ + this.getConfig().addDefault(PluginConfigStrings.PERMISSION_GUN_PREFIX, "ancient.core.guns"); //$NON-NLS-1$ + this.getConfig().addDefault(PluginConfigStrings.PERMISSION_SHOP_PREFIX, "ancient.core.shopitems"); //$NON-NLS-1$ + this.getConfig().addDefault(PluginConfigStrings.PERMISSION_GAME_PREFIX, "ancient."); //$NON-NLS-1$ + + this.getConfig().addDefault(PluginConfigStrings.MOTD_ENABLED, false); + this.getConfig().addDefault(PluginConfigStrings.MOTD_ROTATION_SECONDS, 15); + this.getConfig().addDefault(PluginConfigStrings.MOTD_TEXT, "<minigame> arena <arena> <state>: <players>/<maxplayers>"); //$NON-NLS-1$ + this.getConfig().addDefault(PluginConfigStrings.MOTD_STATE_JOIN, "JOIN"); //$NON-NLS-1$ + this.getConfig().addDefault(PluginConfigStrings.MOTD_STATE_STARTING, "STARTING"); //$NON-NLS-1$ + this.getConfig().addDefault(PluginConfigStrings.MOTD_STATE_INGAME, "INGAME"); //$NON-NLS-1$ + this.getConfig().addDefault(PluginConfigStrings.MOTD_STATE_RESTARTING, "RESTARTING"); //$NON-NLS-1$ + this.getConfig().addDefault(PluginConfigStrings.MOTD_STATE_DISABLED, "DISABLED"); //$NON-NLS-1$ + + for (final ArenaState state : ArenaState.values()) + { + this.getConfig().addDefault("signs." + state.name().toLowerCase() + ".0", state.getColorCode() + "<minigame>"); + this.getConfig().addDefault("signs." + state.name().toLowerCase() + ".1", state.getColorCode() + "<arena>"); + this.getConfig().addDefault("signs." + state.name().toLowerCase() + ".2", state.getColorCode() + "<count>/<maxcount>"); + this.getConfig().addDefault("signs." + state.name().toLowerCase() + ".3", state.getColorCode() + ""); + } + this.getConfig().addDefault("signs.spec.0", "&aSPECTATE"); + this.getConfig().addDefault("signs.spec.1", "&a<minigame>"); + this.getConfig().addDefault("signs.spec.2", "&a<arena>"); + this.getConfig().addDefault("signs.spec.3", "&a<count>/<maxcount>"); + + this.getConfig().options().copyDefaults(true); + this.saveConfig(); + + this.partymessages = new PartyMessagesConfig(this); + this.statsglobal = new StatsGlobalConfig(this, false); + + MinigamesAPI.debug = this.getConfig().getBoolean(PluginConfigStrings.DEBUG); + + if (this.getConfig().getBoolean(PluginConfigStrings.POST_METRICS, true)) + { + Bukkit.getScheduler().runTaskLater(this, () -> { + try + { + MinigamesAPI.this.metrics = new Metrics(MinigamesAPI.instance); + + final Graph components = MinigamesAPI.this.metrics.createGraph("Minigames"); //$NON-NLS-1$ + for (final PluginInstance pli : MinigamesAPI.pinstances.values()) + { + components.addPlotter(new Metrics.Plotter(pli.getPlugin().getName()) { + @Override + public int getValue() + { + return 1; + } + }); + if (MinigamesAPI.debug) + { + this.getLogger().fine("Loaded Graph for: " + pli.getPlugin().getName()); //$NON-NLS-1$ + } + } + + MinigamesAPI.this.metrics.start(); + } + catch (final IOException e) + { + this.getLogger().log(Level.WARNING, "Exception while updating metrics", e); //$NON-NLS-1$ + } + }, 60L); + } + + if (this.getConfig().getBoolean(PluginConfigStrings.AUTO_UPDATING)) + { + // new UpdaterBukkit(this, 83025, this.getFile(), UpdaterBukkit.UpdateType.DEFAULT, false); + new UpdaterNexus(this, this.getFile()); + } + + if (this.getServer().getPluginManager().getPlugin("CrackShot") != null) //$NON-NLS-1$ + { + this.crackshot = true; + } + + Bukkit.getScheduler().runTaskLater(this, () -> { + // Reset all arena signs and check if any arena was interrupted + int i = 0; + MinigamesAPI.getAPI(); + for (final PluginInstance pli : MinigamesAPI.pinstances.values()) + { + for (final Arena a : pli.getArenas()) + { + if (a != null) + { + if (a.isSuccessfullyInit()) + { + Util.updateSign(pli.getPlugin(), a); + a.getSmartReset().loadSmartBlocksFromFile(); + } + else + { + this.getLogger().log(Level.WARNING, "Arena " + pli.getPlugin().getName() + "/" + a.getInternalName() + " not initialized at onEnable."); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + } + } + i++; + } + } + this.getLogger().info("Found " + i + " arenas."); //$NON-NLS-1$//$NON-NLS-2$ + }, 50L); + Bukkit.getScheduler().scheduleSyncRepeatingTask(this, () -> { + MinigamesAPI.getAPI(); + for (final PluginInstance pli : MinigamesAPI.pinstances.values()) + { + for (final Arena a : pli.getArenas()) + { + Util.updateSign(pli.getPlugin(), a); + + } + } + }, 0, 20 * this.getConfig().getInt(PluginConfigStrings.SIGNS_UPDATE_TIME)); + + if (this.getConfig().getBoolean(PluginConfigStrings.MOTD_ENABLED)) + { + Bukkit.getScheduler().scheduleSyncRepeatingTask(this, () -> { + if (this.motdStrings.hasNext()) + { + this.motd = this.motdStrings.next().get(); + } + else + { + final List<Supplier<String>> suppliers = new ArrayList<>(); + for (final PluginInstance pli : MinigamesAPI.pinstances.values()) + { + for (final Arena arena : pli.getArenas()) + { + suppliers.add(() -> { + String motdString = getConfig().getString(PluginConfigStrings.MOTD_TEXT); + String stateString = null; + if (arena.isSuccessfullyInit() && pli.arenaSetup.getArenaEnabled(pli.getPlugin(), arena.getInternalName())) + { + switch (arena.getArenaState()) + { + case INGAME: + stateString = getConfig().getString(PluginConfigStrings.MOTD_STATE_INGAME); + break; + case JOIN: + stateString = getConfig().getString(PluginConfigStrings.MOTD_STATE_JOIN); + break; + case RESTARTING: + stateString = getConfig().getString(PluginConfigStrings.MOTD_STATE_RESTARTING); + break; + case STARTING: + stateString = getConfig().getString(PluginConfigStrings.MOTD_STATE_STARTING); + break; + default: + stateString = getConfig().getString(PluginConfigStrings.MOTD_STATE_DISABLED); + break; + } + } + else + { + stateString = getConfig().getString(PluginConfigStrings.MOTD_STATE_DISABLED); + } + motdString = motdString.replace("<minigame>", arena.getPluginInstance().getPlugin().getDescription().getName()); + motdString = motdString.replace("<arena>", arena.getDisplayName()); + motdString = motdString.replace("<state>", stateString); + motdString = motdString.replace("<players>", String.valueOf(arena.getAllPlayers().size())); + motdString = motdString.replace("<minplayers>", String.valueOf(arena.getMinPlayers())); + motdString = motdString.replace("<maxplayers>", String.valueOf(arena.getMaxPlayers())); + return motdString; + }); + } + } + this.motdStrings = suppliers.iterator(); + if (this.motdStrings.hasNext()) + { + this.motd = this.motdStrings.next().get(); + } + else + { + this.motd = null; + } + } + }, 0, 20 * this.getConfig().getInt(PluginConfigStrings.MOTD_ROTATION_SECONDS)); + } + + Bukkit.getPluginManager().registerEvents(this, this); + + Bukkit.getScheduler().runTaskLater(this, () -> { + final ConfigurationSection configurationSection = getConfig().getConfigurationSection("arenas"); //$NON-NLS-1$ + if (configurationSection != null) + { + for (final String mg : configurationSection.getKeys(false)) + { + for (final String arena : getConfig().getConfigurationSection(ArenaConfigStrings.ARENAS_PREFIX + mg).getKeys(false)) + { + final String server = getConfig().getString(ArenaConfigStrings.ARENAS_PREFIX + mg + "." + arena + ".server"); //$NON-NLS-1$ //$NON-NLS-2$ + if (server != null) + { + final String world = getConfig().getString(ArenaConfigStrings.ARENAS_PREFIX + mg + "." + arena + ".world"); //$NON-NLS-1$ //$NON-NLS-2$ + final int x = getConfig().getInt(ArenaConfigStrings.ARENAS_PREFIX + mg + "." + arena + ".loc.x"); //$NON-NLS-1$ //$NON-NLS-2$ + final int y = getConfig().getInt(ArenaConfigStrings.ARENAS_PREFIX + mg + "." + arena + ".loc.y"); //$NON-NLS-1$ //$NON-NLS-2$ + final int z = getConfig().getInt(ArenaConfigStrings.ARENAS_PREFIX + mg + "." + arena + ".loc.z"); //$NON-NLS-1$ //$NON-NLS-2$ + this.signManager.attachSign(new Location(Bukkit.getWorld(world), x, y, z), server, mg, arena, false); + } + final String specserver = getConfig().getString(ArenaConfigStrings.ARENAS_PREFIX + mg + "." + arena + ".specserver"); //$NON-NLS-1$ //$NON-NLS-2$ + if (specserver != null) + { + final String world = getConfig().getString(ArenaConfigStrings.ARENAS_PREFIX + mg + "." + arena + ".specworld"); //$NON-NLS-1$ //$NON-NLS-2$ + final int x = getConfig().getInt(ArenaConfigStrings.ARENAS_PREFIX + mg + "." + arena + ".specloc.x"); //$NON-NLS-1$ //$NON-NLS-2$ + final int y = getConfig().getInt(ArenaConfigStrings.ARENAS_PREFIX + mg + "." + arena + ".specloc.y"); //$NON-NLS-1$ //$NON-NLS-2$ + final int z = getConfig().getInt(ArenaConfigStrings.ARENAS_PREFIX + mg + "." + arena + ".specloc.z"); //$NON-NLS-1$ //$NON-NLS-2$ + this.signManager.attachSign(new Location(Bukkit.getWorld(world), x, y, z), server, mg, arena, true); + } + } + } + } + }, 1L); + Bukkit.getScheduler().scheduleSyncRepeatingTask(this, () -> { + this.signManager.ping(); + }, 60L, 26L); + } + + /** + * Returns the arena for player if already playing + * + * @param playerName + * players name + * @return arena or {@code null} if not inside an arena + */ + public Arena getArenaForPlayer(String playerName) + { + for (final PluginInstance pli : this.pinstances.values()) + { + final Arena arena = pli.global_players.get(playerName); + if (arena != null) + return arena; + } + return null; + } + + /** + * Checks if crackshot is available. + * + * @return {@code true} if crackshot is available. + */ + public boolean crackshotAvailable() + { + return this.crackshot; + } + + /** + * Checks if economy is available. + * + * @return {@code true} if economy is available. + */ + public boolean economyAvailable() + { + return this.economy; + } + + /** + * Returns the permission prefix for minigames lib itself. + * + * @return permission prefix minigames lib. + */ + public String getPermissionPrefix() + { + return this.getConfig().getString(PluginConfigStrings.PERMISSION_PREFIX, "minigames.core"); //$NON-NLS-1$ + } + + /** + * Returns the permission prefix for minigames lib itself. + * + * @return permission prefix minigames lib. + */ + public String getPermissionKitPrefix() + { + return this.getConfig().getString(PluginConfigStrings.PERMISSION_KITS_PREFIX, "minigames.core.kits"); //$NON-NLS-1$ + } + + /** + * Returns the permission prefix for minigames lib itself. + * + * @return permission prefix minigames lib. + */ + public String getPermissionGunPrefix() + { + return this.getConfig().getString(PluginConfigStrings.PERMISSION_GUN_PREFIX, "minigames.core.guns"); //$NON-NLS-1$ + } + + /** + * Returns the permission prefix for minigames lib itself. + * + * @return permission prefix minigames lib. + */ + public String getPermissionShopPrefix() + { + return this.getConfig().getString(PluginConfigStrings.PERMISSION_SHOP_PREFIX, "minigames.core.shopitems"); //$NON-NLS-1$ + } + + /** + * Returns the permission prefix for a minigame. + * + * @param game + * the minigame name. + * @return permission prefix + */ + public String getPermissionGamePrefix(String game) + { + return this.getConfig().getString(PluginConfigStrings.PERMISSION_GAME_PREFIX, "minigames.") + game; //$NON-NLS-1$ + } + + /** + * Calculates the minecraft server version. + * + * @return Minecraft server version. + */ + private static MinecraftVersionsType getServerVersion() + { + try + { + final String v = Bukkit.getServer().getClass().getPackage().getName().substring(Bukkit.getServer().getClass().getPackage().getName().lastIndexOf(".") + 1); //$NON-NLS-1$ + if (v.startsWith("v1_7_R1")) //$NON-NLS-1$ + { + return MinecraftVersionsType.V1_7_R1; + } + if (v.startsWith("v1_7_R2")) //$NON-NLS-1$ + { + return MinecraftVersionsType.V1_7_R2; + } + if (v.startsWith("v1_7_R3")) //$NON-NLS-1$ + { + return MinecraftVersionsType.V1_7_R3; + } + if (v.startsWith("v1_7_R4")) //$NON-NLS-1$ + { + return MinecraftVersionsType.V1_7_R4; + } + if (v.startsWith("v1_8_R1")) //$NON-NLS-1$ + { + return MinecraftVersionsType.V1_8_R1; + } + if (v.startsWith("v1_8_R2")) //$NON-NLS-1$ + { + return MinecraftVersionsType.V1_8_R2; + } + if (v.startsWith("v1_8_R3")) //$NON-NLS-1$ + { + return MinecraftVersionsType.V1_8_R3; + } + if (v.startsWith("v1_9_R1")) //$NON-NLS-1$ + { + return MinecraftVersionsType.V1_9_R1; + } + if (v.startsWith("v1_9_R2")) //$NON-NLS-1$ + { + return MinecraftVersionsType.V1_9_R2; + } + if (v.startsWith("v1_10_R1")) //$NON-NLS-1$ + { + return MinecraftVersionsType.V1_10_R1; + } + if (v.startsWith("v1_11_R1")) //$NON-NLS-1$ + { + return MinecraftVersionsType.V1_11_R1; + } + if (v.startsWith("v1_12_R1")) //$NON-NLS-1$ + { + return MinecraftVersionsType.V1_12_R1; + } + } + catch (@SuppressWarnings("unused") Exception ex) + { + // silently ignore + } + return MinecraftVersionsType.Unknown; + } + + @Override + public void onDisable() + { + for (final PluginInstance pli : MinigamesAPI.pinstances.values()) + { + // Reset arenas + for (final Arena a : pli.getArenas()) + { + if (a != null) + { + if (a.isSuccessfullyInit()) + { + if (a.getArenaState() != ArenaState.JOIN) + { + a.getSmartReset().saveSmartBlocksToFile(); + } + final ArrayList<String> temp = new ArrayList<>(a.getAllPlayers()); + for (final String p_ : temp) + { + a.leavePlayer(p_, true); + } + try + { + a.getSmartReset().resetRaw(); + } + catch (final Exception e) + { + this.getLogger().log(Level.WARNING, "Failed resetting arena " + pli.getPlugin().getName() + "/" + a.getInternalName() + " at onDisable.", e); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + } + } + else + { + this.getLogger().log(Level.WARNING, "Arena " + pli.getPlugin().getName() + "/" + a.getInternalName() + " not initialized thus not reset at onDisable."); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + } + } + } + + // Save important configs + pli.getArenasConfig().saveConfig(); + pli.getPlugin().saveConfig(); + pli.getMessagesConfig().saveConfig(); + pli.getClassesConfig().saveConfig(); + } + + } + + /** + * Sets up the API allowing to override all configs. + * + * <p> + * This method is meant to be called within concrete minigame plugin onEable. + * </p> + * + * @param plugin_ + * the java plugin representing the minigame. + * @param minigame + * internal name of the minigame. + * @param arenaclass + * the class implementing/ overriding the arena class; {@link Arena}. TODO currently not in use + * @param arenasconfig + * the arenas config store. + * @param messagesconfig + * the messages config store. + * @param classesconfig + * the classes config store. + * @param statsconfig + * the statistics store. + * @param defaultconfig + * the default plugin config. TODO variable is never read? + * @param customlistener + * {@code true} if there is a custom listener handling the arenas; {@code false} to register the default arena listener; {@link ArenaListener}. + * @return the api instance (this plugin). + */ + public static MinigamesAPI setupAPI(final JavaPlugin plugin_, final String minigame, final Class<?> arenaclass, final ArenasConfig arenasconfig, final MessagesConfig messagesconfig, + final ClassesConfig classesconfig, final StatsConfig statsconfig, final DefaultConfig defaultconfig, final boolean customlistener) + { + MinigamesAPI.pinstances.put(plugin_, new PluginInstance(plugin_, arenasconfig, messagesconfig, classesconfig, statsconfig, new ArrayList<Arena>())); + if (!customlistener) + { + final ArenaListener al = new ArenaListener(plugin_, MinigamesAPI.pinstances.get(plugin_), minigame); + MinigamesAPI.pinstances.get(plugin_).setArenaListener(al); + Bukkit.getPluginManager().registerEvents(al, plugin_); + } + Classes.loadClasses(plugin_); + Guns.loadGuns(plugin_); + MinigamesAPI.pinstances.get(plugin_).getShopHandler().loadShopItems(); + return MinigamesAPI.instance; + } + + /** + * Use this to register your custom arena listener. + * + * @param plugin_ + * the minigames plugin. + * @param arenalistener + * the arena listener. + */ + public static void registerArenaListenerLater(final JavaPlugin plugin_, final ArenaListener arenalistener) + { + // TODO check plugin code; should we invoke MinigamesAPI.pinstances.get(plugin_).setArenaListener(arenalistener); + Bukkit.getPluginManager().registerEvents(arenalistener, plugin_); + } + + /** + * registers additional arena setup + * + * <p> + * TODO: Do we still need this? + * </p> + * + * @param plugin_ + * the minigames plugin. + * @param arenasetup + * the arena setup. + */ + public static void registerArenaSetup(final JavaPlugin plugin_, final ArenaSetup arenasetup) + { + MinigamesAPI.pinstances.get(plugin_).arenaSetup = arenasetup; + } + + /** + * registers additional scoreboard + * + * <p> + * TODO: Do we still need this? + * </p> + * + * @param plugin_ + * the minigames plugin. + * @param board + * the arena scoreboard. + */ + public static void registerScoreboard(final JavaPlugin plugin_, final ArenaScoreboard board) + { + MinigamesAPI.pinstances.get(plugin_).scoreboardManager = board; + } + + /** + * Sets up the API and prepare for manual setup. + * + * <p> + * This method is meant to be called within concrete minigame plugin onEable. + * </p> + * + * <p> + * Allow loading of arenas with own extended arena class into PluginInstance: after this setup, get the PluginInstance, load the arenas by yourself and add the loaded arenas w/ custom arena class + * into the PluginInstance + * </p> + * + * @param plugin_ + * the java plugin representing the minigame. + * @param minigame + * internal name of the minigame. + * @param arenaclass + * the class implementing/ overriding the arena class; {@link Arena}. + * @return the api instance (this plugin). + * @deprecated will be removed in 1.5.0 + */ + @Deprecated + public static MinigamesAPI setupAPI(final JavaPlugin plugin_, final String minigame, final Class<?> arenaclass) + { + MinigamesAPI.setupRaw(plugin_, minigame); + return MinigamesAPI.instance; + } + + /** + * Sets up the API. + * + * <p> + * This method is meant to be called within concrete minigame plugin onEable. Loads all arenas (default implementation). + * </p> + * + * <p> + * TODO: Compare to {@link #setupAPI(JavaPlugin, String, Class, ArenasConfig, MessagesConfig, ClassesConfig, StatsConfig, DefaultConfig, boolean)} + * </p> + * + * @param plugin_ + * the java plugin representing the minigame. + * @param minigame + * internal name of the minigame. + * @return the api instance (this plugin). + * @deprecated will be removed in 1.5.0 + */ + @Deprecated + public static MinigamesAPI setupAPI(final JavaPlugin plugin_, final String minigame) + { + final PluginInstance pli = MinigamesAPI.setupRaw(plugin_, minigame); + pli.addLoadedArenas(Util.loadArenas(plugin_, pli.getArenasConfig())); + return MinigamesAPI.instance; + } + + /** + * Raw (internal) setup method. + * + * @param plugin_ + * the java plugin representing the minigame. + * @param minigame + * internal name of the minigame. + * @return internal plugin representation of the minigame. + * @deprecated will be removed in 1.5.0 + */ + @Deprecated + public static PluginInstance setupRaw(final JavaPlugin plugin_, final String minigame) + { + final ArenasConfig arenasconfig = new ArenasConfig(plugin_); + final MessagesConfig messagesconfig = new MessagesConfig(plugin_); + final ClassesConfig classesconfig = new ClassesConfig(plugin_, false); + final StatsConfig statsconfig = new StatsConfig(plugin_, false); + DefaultConfig.init(plugin_, false); + final PluginInstance pli = new PluginInstance(plugin_, arenasconfig, messagesconfig, classesconfig, statsconfig); + MinigamesAPI.pinstances.put(plugin_, pli); + final ArenaListener al = new ArenaListener(plugin_, MinigamesAPI.pinstances.get(plugin_), minigame); + MinigamesAPI.pinstances.get(plugin_).setArenaListener(al); + Bukkit.getPluginManager().registerEvents(al, plugin_); + Classes.loadClasses(plugin_); + pli.getShopHandler().loadShopItems(); + Guns.loadGuns(plugin_); + new DefaultConfig(plugin_, false); // force initialization of config.yml + return pli; + } + + /** + * Returns the minigames API plugin. + * + * @return minigames API plugin. + */ + public static MinigamesAPI getAPI() + { + return MinigamesAPI.instance; + } + + /** + * Creates a new Command handler. + * + * @return command handler. + * @deprecated removed in 1.5.0 + */ + @Deprecated + public static CommandHandler getCommandHandler() + { + return new CommandHandler(); + } + + /** + * Setup the economy vault. + * + * @return {@code true} if vault was initialized. + */ + private boolean setupEconomy() + { + if (this.getServer().getPluginManager().getPlugin("Vault") == null) //$NON-NLS-1$ + { + return false; + } + final RegisteredServiceProvider<Economy> rsp = this.getServer().getServicesManager().getRegistration(Economy.class); + if (rsp == null) + { + return false; + } + MinigamesAPI.econ = rsp.getProvider(); + return MinigamesAPI.econ != null; + } + + @Override + public boolean onCommand(final CommandSender sender, final Command cmd, final String label, final String[] args) + { + if (cmd.getName().equalsIgnoreCase(CommandStrings.START)) + { + if (!(sender instanceof Player)) + { + sender.sendMessage(Messages.getString("MinigamesAPI.ExecuteIngame", LOCALE)); //$NON-NLS-1$ + return true; + } + if (!sender.hasPermission(getPermissionPrefix() + PermissionStrings.MINIGAMES_START)) + { + sender.sendMessage(Messages.getString("MinigamesAPI.NoPermissionForStart", LOCALE)); //$NON-NLS-1$ + return true; + } + final Player p = (Player) sender; + MinigamesAPI.getAPI(); + for (final PluginInstance pli : MinigamesAPI.pinstances.values()) + { + if (pli.containsGlobalPlayer(p.getName())) + { + final Arena a = pli.global_players.get(p.getName()); + this.getLogger().info("Arena " + a.getInternalName() + " started because of start command from player " + p.getName()); //$NON-NLS-1$//$NON-NLS-2$ + if (a.getArenaState() == ArenaState.JOIN || (a.getArenaState() == ArenaState.STARTING && !a.getIngameCountdownStarted())) + { + a.start(true); + sender.sendMessage(pli.getMessagesConfig().arena_action.replaceAll(ArenaMessageStrings.ARENA, a.getDisplayName()).replaceAll(ArenaMessageStrings.ACTION, + Messages.getString("MinigamesAPI.Started", LOCALE))); //$NON-NLS-1$ + return true; + } + } + } + sender.sendMessage(Messages.getString("MinigamesAPI.StartNotWithinArena", LOCALE)); //$NON-NLS-1$ + return true; + } + + if (cmd.getName().equalsIgnoreCase(CommandStrings.PARTY)) + { + if (!this.getConfig().getBoolean(PluginConfigStrings.PARTY_COMMAND_ENABLED)) + { + return true; + } + final CommandHandler cmdhandler = new CommandHandler(); + if (!(sender instanceof Player)) + { + sender.sendMessage(Messages.getString("MinigamesAPI.ExecuteIngame", LOCALE)); //$NON-NLS-1$ + return true; + } + final Player p = (Player) sender; + if (args.length > 0) + { + final String action = args[0]; + if (action.equalsIgnoreCase(CommandStrings.PARTY_INVITE)) + { + cmdhandler.partyInvite(sender, args, getPermissionPrefix() + PermissionStrings.MINIGAMES_PARTY, "/" + cmd.getName(), action, this, p); //$NON-NLS-1$ + } + else if (action.equalsIgnoreCase(CommandStrings.PARTY_ACCEPT)) + { + cmdhandler.partyAccept(sender, args, getPermissionPrefix() + PermissionStrings.MINIGAMES_PARTY, "/" + cmd.getName(), action, this, p); //$NON-NLS-1$ + } + else if (action.equalsIgnoreCase(CommandStrings.PARTY_KICK)) + { + cmdhandler.partyKick(sender, args, getPermissionPrefix() + PermissionStrings.MINIGAMES_PARTY, "/" + cmd.getName(), action, this, p); //$NON-NLS-1$ + } + else if (action.equalsIgnoreCase(CommandStrings.PARTY_LIST)) + { + cmdhandler.partyList(sender, args, getPermissionPrefix() + PermissionStrings.MINIGAMES_PARTY, "/" + cmd.getName(), action, this, p); //$NON-NLS-1$ + } + else if (action.equalsIgnoreCase(CommandStrings.PARTY_DISBAND)) + { + cmdhandler.partyDisband(sender, args, getPermissionPrefix() + PermissionStrings.MINIGAMES_PARTY, "/" + cmd.getName(), action, this, p); //$NON-NLS-1$ + } + else if (action.equalsIgnoreCase(CommandStrings.PARTY_LEAVE)) + { + cmdhandler.partyLeave(sender, args, getPermissionPrefix() + PermissionStrings.MINIGAMES_PARTY, "/" + cmd.getName(), action, this, p); //$NON-NLS-1$ + } + else + { + CommandHandler.sendPartyHelp("/" + cmd.getName(), sender); //$NON-NLS-1$ + } + } + else + { + CommandHandler.sendPartyHelp("/" + cmd.getName(), sender); //$NON-NLS-1$ + } + return true; + } + + if (cmd.getName().equalsIgnoreCase(CommandStrings.MGAPI) || cmd.getName().equalsIgnoreCase(CommandStrings.MGLIB) || cmd.getName().equalsIgnoreCase(CommandStrings.MAPI)) + { + if (args.length > 0) + { + if (args[0].equalsIgnoreCase(CommandStrings.MGLIB_INFO)) + { + if (args.length > 1) + { + final String p = args[1]; + sender.sendMessage(Messages.getString("MinigamesAPI.DebugInfoHeader", LOCALE) + p); //$NON-NLS-1$ + sender.sendMessage(Messages.getString("MinigamesAPI.DebugGlobalPlayers", LOCALE)); //$NON-NLS-1$ + for (final PluginInstance pli : MinigamesAPI.pinstances.values()) + { + if (pli.global_players.containsKey(p)) + { + sender.sendMessage(String.format(Messages.getString("MinigamesAPI.DebugGlobalPlayersLine", LOCALE), pli.getPlugin().getName())); //$NON-NLS-1$ + } + } + sender.sendMessage(Messages.getString("MinigamesAPI.DebugGlobalLost", LOCALE)); //$NON-NLS-1$ + for (final PluginInstance pli : MinigamesAPI.pinstances.values()) + { + if (pli.global_lost.containsKey(p)) + { + sender.sendMessage(String.format(Messages.getString("MinigamesAPI.DebugGlobalLostLine", LOCALE), pli.getPlugin().getName())); //$NON-NLS-1$ + } + } + sender.sendMessage(Messages.getString("MinigamesAPI.DebugSpectatorManager", LOCALE)); //$NON-NLS-1$ + for (final PluginInstance pli : MinigamesAPI.pinstances.values()) + { + pli.getSpectatorManager(); + if (SpectatorManager.isSpectating(Bukkit.getPlayer(p))) + { + sender.sendMessage(String.format(Messages.getString("MinigamesAPI.DebugSpectatorManagerLine", LOCALE), pli.getPlugin().getName())); //$NON-NLS-1$ + } + } + sender.sendMessage(Messages.getString("MinigamesAPI.DebugArenas", LOCALE)); //$NON-NLS-1$ + for (final PluginInstance pli : MinigamesAPI.pinstances.values()) + { + if (pli.global_players.containsKey(p)) + { + sender.sendMessage(String.format(Messages.getString("MinigamesAPI.DebugArenasLine", LOCALE), pli.global_players.get(p).getInternalName(), //$NON-NLS-1$ + pli.global_players.get(p).getArenaState().name())); + } + } + } + else + { + for (final PluginInstance pli : MinigamesAPI.pinstances.values()) + { + sender.sendMessage(String.format(Messages.getString("MinigamesAPI.DebugAllPlayers", LOCALE), pli.getPlugin().getName())); //$NON-NLS-1$ + for (final Arena a : pli.getArenas()) + { + if (a != null) + { + for (final String p_ : a.getAllPlayers()) + { + sender.sendMessage(String.format(Messages.getString("MinigamesAPI.DebugAllPlayersLine", LOCALE), pli.getPlugin().getName(), a.getInternalName(), p_)); //$NON-NLS-1$ + } + } + } + } + } + } + else if (args[0].equalsIgnoreCase(CommandStrings.MGLIB_DEBUG)) + { + MinigamesAPI.debug = !MinigamesAPI.debug; + this.getConfig().set(PluginConfigStrings.DEBUG, MinigamesAPI.debug); + this.saveConfig(); + sender.sendMessage(String.format(Messages.getString("MinigamesAPI.SetDebugMode", LOCALE), String.valueOf(MinigamesAPI.debug))); //$NON-NLS-1$ + } + else if (args[0].equalsIgnoreCase(CommandStrings.MGLIB_LIST)) + { + int c = 0; + MinigamesAPI.getAPI(); + for (final PluginInstance pli : MinigamesAPI.pinstances.values()) + { + c++; + sender.sendMessage(String.format(Messages.getString("MinigamesAPI.ListArenasLine", LOCALE), pli.getPlugin().getName(), pli.getArenas().size())); //$NON-NLS-1$ + return false; + } + if (c < 1) + { + sender.sendMessage(Messages.getString("MinigamesAPI.NoMinigamesFound", LOCALE)); //$NON-NLS-1$ + } + } + else if (args[0].equalsIgnoreCase(CommandStrings.MGLIB_TITLE)) + { + if (args.length > 1) + { + if (sender instanceof Player) + { + Effects.playTitle((Player) sender, args[1], 0); + return false; + } + } + } + else if (args[0].equalsIgnoreCase(CommandStrings.MGLIB_SUBTITLE)) + { + if (args.length > 1) + { + if (sender instanceof Player) + { + Effects.playTitle((Player) sender, args[1], 1); + return false; + } + } + } + else if (args[0].equalsIgnoreCase(CommandStrings.MGLIB_SIGNS)) + { + if (sender instanceof Player) + { + MinigamesAPI.getAPI(); + for (final PluginInstance pli : MinigamesAPI.pinstances.values()) + { + for (final Arena a : pli.getArenas()) + { + Util.updateSign(pli.getPlugin(), a); + sender.sendMessage(Messages.getString("MinigamesAPI.AllSignsUpdated", LOCALE)); //$NON-NLS-1$ + return false; + } + } + } + else if (args[0].equalsIgnoreCase(CommandStrings.MGLIB_HOLOGRAM)) + { + if (sender instanceof Player) + { + final Player p = (Player) sender; + p.sendMessage(Messages.getString("MinigamesAPI.PlayingHologram", LOCALE)); //$NON-NLS-1$ + Effects.playHologram(p, p.getLocation(), ChatColor.values()[(int) (Math.random() * ChatColor.values().length - 1)] + "TEST", true, true); //$NON-NLS-1$ + return false; + } + } + else if (args[0].equalsIgnoreCase(CommandStrings.MGLIB_STATS_HOLOGRAM)) + { + if (sender instanceof Player) + { + final Player p = (Player) sender; + if (args.length > 1) + { + final PluginInstance pli = this.getPluginInstance((JavaPlugin) Bukkit.getPluginManager().getPlugin(args[1])); + p.sendMessage(Messages.getString("MinigamesAPI.PlayingStatsHologram", LOCALE)); //$NON-NLS-1$ + + Effects.playHologram(p, p.getLocation().add(0D, 1D, 0D), ChatColor.values()[(int) (Math.random() * ChatColor.values().length - 1)] + + Messages.getString("MinigamesAPI.StatsWins", LOCALE) + pli.getStatsInstance().getWins(p.getName()), false, false); //$NON-NLS-1$ + Effects.playHologram(p, p.getLocation().add(0D, 0.75D, 0D), ChatColor.values()[(int) (Math.random() * ChatColor.values().length - 1)] + + Messages.getString("MinigamesAPI.StatsPotions", LOCALE) + pli.getStatsInstance().getPoints(p.getName()), false, false); //$NON-NLS-1$ + Effects.playHologram(p, p.getLocation().add(0D, 0.5D, 0D), ChatColor.values()[(int) (Math.random() * ChatColor.values().length - 1)] + + Messages.getString("MinigamesAPI.StatsKills", LOCALE) + pli.getStatsInstance().getKills(p.getName()), false, false); //$NON-NLS-1$ + Effects.playHologram(p, p.getLocation().add(0D, 0.25D, 0D), ChatColor.values()[(int) (Math.random() * ChatColor.values().length - 1)] + + Messages.getString("MinigamesAPI.StatsDeaths", LOCALE) + pli.getStatsInstance().getDeaths(p.getName()), false, false); //$NON-NLS-1$ + return false; + } + } + } + else if (args[0].equalsIgnoreCase(CommandStrings.MGLIB_JOIN)) + { + if (args.length > 3) + { + String game = args[1]; + String arena = args[2]; + String server = args[3]; + + Player p = null; + + if (sender instanceof Player) + { + p = (Player) sender; + } + if (args.length > 3) + { + // TODO permission to teleport foreign players + p = Bukkit.getPlayer(args[3]); + } + if (p == null) + { + return true; + } + + ByteArrayDataOutput out = ByteStreams.newDataOutput(); + try + { + out.writeUTF("Forward"); + out.writeUTF("ALL"); + out.writeUTF(ChannelStrings.SUBCHANNEL_MINIGAMESLIB_BACK); + + ByteArrayOutputStream msgbytes = new ByteArrayOutputStream(); + DataOutputStream msgout = new DataOutputStream(msgbytes); + String info = game + ":" + arena + ":" + p.getName(); + getLogger().info("player join: " + info); //$NON-NLS-1$ + msgout.writeUTF(info); + + out.writeShort(msgbytes.toByteArray().length); + out.write(msgbytes.toByteArray()); + + Bukkit.getServer().sendPluginMessage(this, ChannelStrings.CHANNEL_BUNGEE_CORD, out.toByteArray()); + } + catch (Exception e) + { + MinigamesAPI.getAPI().getLogger().log(Level.WARNING, "exception", e); + } + connectToServer(this, p.getName(), server); + } + else + { + sender.sendMessage(ChatColor.GRAY + "Usage: /join <game> <arena> <server> [player]"); + sender.sendMessage(ChatColor.GRAY + "[player] is optional."); + } + } + else if (args[0].equalsIgnoreCase(CommandStrings.MGLIB_GAMEMODE_TEST)) // TODO remove + { + if (sender instanceof Player) + { + final Player p = (Player) sender; + if (p.isOp()) + { + Effects.sendGameModeChange(p, 3); + return false; + } + } + } + else if (args[0].equalsIgnoreCase(CommandStrings.MGLIB_BUNGEE_TEST)) // TODO remove + { + if (sender instanceof Player) + { + final Player p = (Player) sender; + if (p.isOp()) + { + // final PluginInstance pli = MinigamesAPI.pinstances.get(Bukkit.getPluginManager().getPlugin("MGSkyWars")); //$NON-NLS-1$ + // BungeeSocket.sendSignUpdate(pli, pli.getArenas().get(0)); + return false; + } + } + } + return true; + } + if (args.length < 1) + { + sender.sendMessage(String.format(Messages.getString("MinigamesAPI.MinigamesLibHeader", LOCALE), this.getDescription().getVersion())); //$NON-NLS-1$ + int c = 0; + MinigamesAPI.getAPI(); + for (final PluginInstance pli : MinigamesAPI.pinstances.values()) + { + c++; + sender.sendMessage(String.format(Messages.getString("MinigamesAPI.PluginArenaCount", LOCALE), pli.getPlugin().getName(), pli.getArenas().size())); //$NON-NLS-1$ + } + if (c < 1) + { + sender.sendMessage(Messages.getString("MinigamesAPI.NoMinigamesFound", LOCALE)); //$NON-NLS-1$ + } + sender.sendMessage(Messages.getString("MinigamesAPI.MgApiSubcommands", LOCALE)); //$NON-NLS-1$ + sender.sendMessage(Messages.getString("MinigamesAPI.MgApiSubcommandInfo", LOCALE)); //$NON-NLS-1$ + sender.sendMessage(Messages.getString("MinigamesAPI.MgApiSubcommandDebug", LOCALE)); //$NON-NLS-1$ + sender.sendMessage(Messages.getString("MinigamesAPI.MgApiSubcommandList", LOCALE)); //$NON-NLS-1$ + sender.sendMessage(Messages.getString("MinigamesAPI.MgApiSubcommandTitle", LOCALE)); //$NON-NLS-1$ + sender.sendMessage(Messages.getString("MinigamesAPI.MgApiSubcommandSubtitle", LOCALE)); //$NON-NLS-1$ + sender.sendMessage(Messages.getString("MinigamesAPI.MgApiSubcommandHologram", LOCALE)); //$NON-NLS-1$ + sender.sendMessage(Messages.getString("MinigamesAPI.MgApiSubcommandSigns", LOCALE)); //$NON-NLS-1$ + sender.sendMessage(Messages.getString("MinigamesAPI.MgApiSubcommandPotionEffect", LOCALE)); //$NON-NLS-1$ + sender.sendMessage(Messages.getString("MinigamesAPI.MgApiSubcommandStatsHologram", LOCALE)); //$NON-NLS-1$ + // TODO Subcommand join + } + if (sender instanceof Player && args.length > 0) + { + final Player p = (Player) sender; + boolean cont = false; + for (final ParticleEffectNew f : ParticleEffectNew.values()) + { + if (f.name().equalsIgnoreCase(args[0])) + { + cont = true; + } + } + if (!cont) + { + sender.sendMessage(Messages.getString("MinigamesAPI.CannotFindParticleEffect", LOCALE)); //$NON-NLS-1$ + return true; + } + final ParticleEffectNew eff = ParticleEffectNew.valueOf(args[0]); + eff.setId(152); + + for (float i = 0; i < 10; i++) + { + eff.animateReflected(p, p.getLocation().clone().add(i / 5F, i / 5F, i / 5F), 1F, 2); + } + + p.getWorld().playEffect(p.getLocation(), Effect.STEP_SOUND, 152); + p.getWorld().playEffect(p.getLocation().add(0D, 1D, 0D), Effect.STEP_SOUND, 152); + } + } + return true; + } + return false; + } + + private void connectToServer(JavaPlugin plugin, String player, String server) + { + ByteArrayOutputStream stream = new ByteArrayOutputStream(); + DataOutputStream out = new DataOutputStream(stream); + try + { + out.writeUTF("Connect"); + out.writeUTF(server); + } + catch (IOException e) + { + MinigamesAPI.getAPI().getLogger().log(Level.WARNING, "exception", e); + } + Bukkit.getPlayer(player).sendPluginMessage(plugin, ChannelStrings.CHANNEL_BUNGEE_CORD, stream.toByteArray()); + } + + @Override + public void onPluginMessageReceived(final String channel, final Player player, final byte[] message) + { + if (!channel.equals(ChannelStrings.CHANNEL_BUNGEE_CORD)) + { + return; + } + final ByteArrayDataInput in = ByteStreams.newDataInput(message); + final String subchannel = in.readUTF(); + if (subchannel.equals(ChannelStrings.SUBCHANNEL_MINIGAMESLIB_BACK)) + { + final short len = in.readShort(); + final byte[] msgbytes = new byte[len]; + in.readFully(msgbytes); + + final DataInputStream msgin = new DataInputStream(new ByteArrayInputStream(msgbytes)); + try + { + final String playerData = msgin.readUTF(); + final String[] split = playerData.split(":"); //$NON-NLS-1$ + final String plugin_ = split[0]; + final String arena = split[1]; + final String playername = split.length >= 4 ? split[3] : split[2]; + final String mode = split.length >= 4 ? split[2] : "join"; + + if (debug) + { + this.getLogger().info("channel message: " + ChannelStrings.SUBCHANNEL_MINIGAMESLIB_BACK + " -> " + playerData); //$NON-NLS-1$ //$NON-NLS-2$ + } + + JavaPlugin plugin = null; + for (final JavaPlugin pl : MinigamesAPI.pinstances.keySet()) + { + if (pl.getName().contains(plugin_)) + { + plugin = pl; + break; + } + } + if (plugin != null) + { + final Arena a = MinigamesAPI.pinstances.get(plugin).getArenaByName(arena); + if (a != null) + { + if (a.getArenaState() != ArenaState.INGAME && a.getArenaState() != ArenaState.RESTARTING && !a.containsPlayer(playername)) + { + Bukkit.getScheduler().runTaskLater(this, () -> { + switch (mode) + { + case "join": + default: + if (!a.containsPlayer(playername)) + { + a.joinPlayerLobby(playername); + } + break; + case "spec": + if (!a.containsPlayer(playername)) + { + final ArenaPlayer ap = ArenaPlayer.getPlayerInstance(playername); + a.joinSpectate(ap.getPlayer()); + } + } + }, 20L); + } + } + else + { + this.getLogger().warning("Arena " + arena + " for MINIGAMESLIB_BACK couldn't be found, please fix your setup."); //$NON-NLS-1$//$NON-NLS-2$ + } + } + } + catch (final IOException e) + { + MinigamesAPI.getAPI().getLogger().log(Level.WARNING, "exception", e); + } + } + else if (subchannel.equals(ChannelStrings.SUBCHANNEL_MINIGAMESLIB_REQUEST)) + { + // Lobby requests sign data + final short len = in.readShort(); + final byte[] msgbytes = new byte[len]; + in.readFully(msgbytes); + + final DataInputStream msgin = new DataInputStream(new ByteArrayInputStream(msgbytes)); + try + { + final String requestData = msgin.readUTF(); + final String[] split = requestData.split(":"); //$NON-NLS-1$ + final String plugin_ = split[0]; + final String arena = split[1]; + + if (debug) + { + this.getLogger().info("channel message: " + ChannelStrings.SUBCHANNEL_MINIGAMESLIB_REQUEST + " -> " + requestData); //$NON-NLS-1$ //$NON-NLS-2$ + } + + for (final JavaPlugin pl : MinigamesAPI.pinstances.keySet()) + { + if (pl.getName().contains(plugin_)) + { + final Arena a = MinigamesAPI.pinstances.get(pl).getArenaByName(arena); + if (a != null) + { + BungeeUtil.sendSignUpdateRequest(pl, pl.getName(), a); + } + else + { + this.getLogger().warning("Arena " + arena + " for MINIGAMESLIB_REQUEST couldn't be found, please fix your setup."); //$NON-NLS-1$//$NON-NLS-2$ + } + break; + } + } + } + catch (final IOException e) + { + MinigamesAPI.getAPI().getLogger().log(Level.WARNING, "exception", e); + } + } + else if (subchannel.equals(ChannelStrings.SUBCHANNEL_MINIGAMESLIB_SIGN)) + { + short len = in.readShort(); + byte[] msgbytes = new byte[len]; + in.readFully(msgbytes); + + DataInputStream msgin = new DataInputStream(new ByteArrayInputStream(msgbytes)); + try + { + final String signData = msgin.readUTF(); + final String[] splitted = signData.split(":"); //$NON-NLS-1$ + final String plugin_ = splitted[0]; + final String arena = splitted[1]; + final String arenastate = splitted[2]; + final int count = Integer.parseInt(splitted[3]); + final int maxcount = Integer.parseInt(splitted[4]); + + if (debug) + { + this.getLogger().info("channel message: " + ChannelStrings.SUBCHANNEL_MINIGAMESLIB_SIGN + " -> " + signData); //$NON-NLS-1$ //$NON-NLS-2$ + } + + Bukkit.getScheduler().runTaskLater(this, new Runnable() { + public void run() + { + updateSign(plugin_, arena, arenastate, count, maxcount); + } + }, 10L); + } + catch (IOException e) + { + MinigamesAPI.getAPI().getLogger().log(Level.WARNING, "exception", e); + } + } + } + + /** + * Returns the minigames lib representation of a minigame plugin. + * + * @param plugin + * minigame java plugin. + * @return plugin instance or {@code null} if this is not a minigames plugin or if setupAPI was not called. + */ + public PluginInstance getPluginInstance(final JavaPlugin plugin) + { + return MinigamesAPI.pinstances.get(plugin); + } + + /** + * Version safe conversion utility (temporary workaround) + * + * @param playername + * @return uuid of the player + * @deprecated starting with 1.5.0 (and by dropping support for spigot 1.7.x) you should directly use {@link Player#getUniqueId()} + */ + @Deprecated + public static UUID playerToUUID(String playername) + { + final Player player = Bukkit.getPlayer(playername); + if (player != null) + { + return playerToUUID(player); + } + return null; + } + + /** + * Version safe conversion utility (temporary workaround) + * + * @param player + * @return uuid of the player + * @deprecated starting with 1.5.0 (and by dropping support for spigot 1.7.x) you should directly use {@link Player#getUniqueId()} + */ + @Deprecated + public static UUID playerToUUID(Player player) + { + if (SERVER_VERSION.isAfter(MinecraftVersionsType.V1_7)) + { + return player.getUniqueId(); + } + + try + { + final Object handle = player.getClass().getDeclaredMethod("getHandle").invoke(player); //$NON-NLS-1$ + return (UUID) handle.getClass().getDeclaredMethod("getUniqueID").invoke(handle); //$NON-NLS-1$ + } + catch (Exception ex) + { + instance.getLogger().log(Level.SEVERE, "Problems converting player to uuid.", ex); //$NON-NLS-1$ + return null; + } + } + + /** + * Version safe conversion utility (temporary workaround) + * + * @param uuid + * @return player object + * @deprecated starting with 1.5.0 (and by dropping support for spigot 1.7.x) you should directly use {@link Bukkit#getPlayer(UUID)} + */ + @Deprecated + public static Player uuidToPlayer(UUID uuid) + { + if (SERVER_VERSION.isAfter(MinecraftVersionsType.V1_7)) + { + return Bukkit.getPlayer(uuid); + } + + for (Player p : Bukkit.getServer().getOnlinePlayers()) + { + if (uuid.equals(playerToUUID(p))) + { + return p; + } + } + return null; + } + + // Bungee-support + + /** + * Sign break event. + * + * <p> + * TODO description. + * </p> + * + * @param event + */ + @EventHandler + public void onBreak(BlockBreakEvent event) + { + if (event.getBlock().getType() == Material.SIGN_POST || event.getBlock().getType() == Material.WALL_SIGN) + { + if (getConfig().isSet(ArenaConfigStrings.ARENAS_PREFIX)) + { + for (String mg_key : getConfig().getConfigurationSection(ArenaConfigStrings.ARENAS_PREFIX).getKeys(false)) + { + for (String arena_key : getConfig().getConfigurationSection(ArenaConfigStrings.ARENAS_PREFIX + mg_key + ".").getKeys(false)) + { + final ConfigurationSection section = getConfig().getConfigurationSection(ArenaConfigStrings.ARENAS_PREFIX + mg_key + "." + arena_key); + if (section.contains("world")) + { + Location l = new Location(Bukkit.getWorld(getConfig().getString(ArenaConfigStrings.ARENAS_PREFIX + mg_key + "." + arena_key + ".world")), + getConfig().getInt(ArenaConfigStrings.ARENAS_PREFIX + mg_key + "." + arena_key + ".loc.x"), + getConfig().getInt(ArenaConfigStrings.ARENAS_PREFIX + mg_key + "." + arena_key + ".loc.y"), + getConfig().getInt(ArenaConfigStrings.ARENAS_PREFIX + mg_key + "." + arena_key + ".loc.z")); + if (l.distance(event.getBlock().getLocation()) < 1) + { + getConfig().set(ArenaConfigStrings.ARENAS_PREFIX + mg_key + "." + arena_key + ".server", null); + getConfig().set(ArenaConfigStrings.ARENAS_PREFIX + mg_key + "." + arena_key + ".world", null); + getConfig().set(ArenaConfigStrings.ARENAS_PREFIX + mg_key + "." + arena_key + ".loc", null); + saveConfig(); + return; + } + } + if (section.contains("specworld")) + { + Location l = new Location(Bukkit.getWorld(getConfig().getString(ArenaConfigStrings.ARENAS_PREFIX + mg_key + "." + arena_key + ".specworld")), + getConfig().getInt(ArenaConfigStrings.ARENAS_PREFIX + mg_key + "." + arena_key + ".specloc.x"), + getConfig().getInt(ArenaConfigStrings.ARENAS_PREFIX + mg_key + "." + arena_key + ".specloc.y"), + getConfig().getInt(ArenaConfigStrings.ARENAS_PREFIX + mg_key + "." + arena_key + ".specloc.z")); + if (l.distance(event.getBlock().getLocation()) < 1) + { + getConfig().set(ArenaConfigStrings.ARENAS_PREFIX + mg_key + "." + arena_key + ".specserver", null); + getConfig().set(ArenaConfigStrings.ARENAS_PREFIX + mg_key + "." + arena_key + ".specworld", null); + getConfig().set(ArenaConfigStrings.ARENAS_PREFIX + mg_key + "." + arena_key + ".specloc", null); + saveConfig(); + return; + } + } + } + } + } + } + } + + /** + * Sign use event. + * + * <p> + * TODO description. + * </p> + * + * @param event + */ + @EventHandler + public void onSignUse(PlayerInteractEvent event) + { + if (event.hasBlock()) + { + if (event.getClickedBlock().getType() == Material.SIGN_POST || event.getClickedBlock().getType() == Material.WALL_SIGN) + { + if (event.getAction() != Action.RIGHT_CLICK_BLOCK) + { + return; + } + final Sign s = (Sign) event.getClickedBlock().getState(); + String server = getServerBySignLocation(s.getLocation()); + if (server != null && server != "") + { + final Player player = event.getPlayer(); + final String signInfo = getInfoBySignLocation(s.getLocation()); + + if (MinigamesAPI.getAPI().global_party.containsKey(player.getUniqueId())) + { + final Party party = MinigamesAPI.getAPI().global_party.remove(player.getUniqueId()); + for (final UUID p_ : party.getPlayers()) + { + if (Validator.isPlayerOnline(p_)) + { + boolean cont = true; + MinigamesAPI.getAPI(); + for (final PluginInstance pli_ : MinigamesAPI.pinstances.values()) + { + if (pli_.containsGlobalPlayer(Bukkit.getPlayer(p_).getName())) + { + cont = false; + } + } + if (cont) + { + letPlayerJoinServer(server, Bukkit.getPlayer(p_), signInfo); + } + } + } + } + + letPlayerJoinServer(server, player, signInfo); + } + } + } + + } + + /** + * Let a player join a server over bungeecord network + * + * @param server + * @param player + * @param signInfo + */ + private void letPlayerJoinServer(String server, final Player player, final String signInfo) + { + try + { + ByteArrayDataOutput out = ByteStreams.newDataOutput(); + try + { + out.writeUTF("Forward"); + out.writeUTF("ALL"); + out.writeUTF(ChannelStrings.SUBCHANNEL_MINIGAMESLIB_BACK); + + ByteArrayOutputStream msgbytes = new ByteArrayOutputStream(); + DataOutputStream msgout = new DataOutputStream(msgbytes); + String info = signInfo + ":" + player.getName(); + msgout.writeUTF(info); + + out.writeShort(msgbytes.toByteArray().length); + out.write(msgbytes.toByteArray()); + + Bukkit.getServer().sendPluginMessage(this, ChannelStrings.CHANNEL_BUNGEE_CORD, out.toByteArray()); + } + catch (Exception e) + { + this.getLogger().log(Level.WARNING, "error sending message", e); + } + } + catch (Exception e) + { + this.getLogger().log(Level.WARNING, "Error occurred while sending first sign request - Invalid server/minigame/arena?", e); + } + connectToServer(this, player.getName(), server); + } + + @EventHandler + public void onSignBreak(BlockBreakEvent event) + { + if (event.getBlock().getType() == Material.SIGN_POST || event.getBlock().getType() == Material.WALL_SIGN) + { + String server = getServerBySignLocation(event.getBlock().getLocation()); + if (server != null) + { + this.signManager.detachSign(event.getBlock().getLocation()); + final String[] splitted = getInfoBySignLocation(event.getBlock().getLocation()).split(":"); + getConfig().set(ArenaConfigStrings.ARENAS_PREFIX + splitted[0] + "." + splitted[1], null); + } + } + } + + @EventHandler + public void onSignChange(SignChangeEvent event) + { + Player p = event.getPlayer(); + if (event.getLine(0).toLowerCase().equalsIgnoreCase("mglib")) //$NON-NLS-1$ + { + if (event.getPlayer().hasPermission(getPermissionPrefix() + ".sign") || event.getPlayer().isOp()) //$NON-NLS-1$ + { + if (!event.getLine(1).equalsIgnoreCase("") && !event.getLine(2).equalsIgnoreCase("") && !event.getLine(3).equalsIgnoreCase("")) //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + { + String mg = event.getLine(1); + String arena = event.getLine(2); + String server = event.getLine(3); + + getConfig().set(ArenaConfigStrings.ARENAS_PREFIX + mg + "." + arena + ".server", server); //$NON-NLS-1$ //$NON-NLS-2$ + getConfig().set(ArenaConfigStrings.ARENAS_PREFIX + mg + "." + arena + ".world", p.getWorld().getName()); //$NON-NLS-1$ //$NON-NLS-2$ + getConfig().set(ArenaConfigStrings.ARENAS_PREFIX + mg + "." + arena + ".loc.x", event.getBlock().getLocation().getBlockX()); //$NON-NLS-1$ //$NON-NLS-2$ + getConfig().set(ArenaConfigStrings.ARENAS_PREFIX + mg + "." + arena + ".loc.y", event.getBlock().getLocation().getBlockY()); //$NON-NLS-1$ //$NON-NLS-2$ + getConfig().set(ArenaConfigStrings.ARENAS_PREFIX + mg + "." + arena + ".loc.z", event.getBlock().getLocation().getBlockZ()); //$NON-NLS-1$ //$NON-NLS-2$ + saveConfig(); + + p.sendMessage(ChatColor.GREEN + "Successfully set sign."); //$NON-NLS-1$ + + this.signManager.attachSign(event.getBlock().getLocation(), server, mg, arena, false, event); + this.signManager.requestSignUpdate(event.getBlock().getLocation()); + } + } + } + else if (event.getLine(0).toLowerCase().equalsIgnoreCase("mglibspec")) //$NON-NLS-1$ + { + if (event.getPlayer().hasPermission(getPermissionPrefix() + ".sign") || event.getPlayer().isOp()) //$NON-NLS-1$ + { + if (!event.getLine(1).equalsIgnoreCase("") && !event.getLine(2).equalsIgnoreCase("") && !event.getLine(3).equalsIgnoreCase("")) //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + { + String mg = event.getLine(1); + String arena = event.getLine(2); + String server = event.getLine(3); + + getConfig().set(ArenaConfigStrings.ARENAS_PREFIX + mg + "." + arena + ".specserver", server); //$NON-NLS-1$ //$NON-NLS-2$ + getConfig().set(ArenaConfigStrings.ARENAS_PREFIX + mg + "." + arena + ".specworld", p.getWorld().getName()); //$NON-NLS-1$ //$NON-NLS-2$ + getConfig().set(ArenaConfigStrings.ARENAS_PREFIX + mg + "." + arena + ".specloc.x", event.getBlock().getLocation().getBlockX()); //$NON-NLS-1$ //$NON-NLS-2$ + getConfig().set(ArenaConfigStrings.ARENAS_PREFIX + mg + "." + arena + ".specloc.y", event.getBlock().getLocation().getBlockY()); //$NON-NLS-1$ //$NON-NLS-2$ + getConfig().set(ArenaConfigStrings.ARENAS_PREFIX + mg + "." + arena + ".specloc.z", event.getBlock().getLocation().getBlockZ()); //$NON-NLS-1$ //$NON-NLS-2$ + saveConfig(); + + p.sendMessage(ChatColor.GREEN + "Successfully set sign."); //$NON-NLS-1$ + + this.signManager.attachSign(event.getBlock().getLocation(), server, mg, arena, true, event); + this.signManager.requestSignUpdate(event.getBlock().getLocation()); + } + } + } + } + + private Sign getSignFromArena(String mg, String arena) + { + if (!getConfig().isSet(ArenaConfigStrings.ARENAS_PREFIX + mg + "." + arena + ".world")) + { + return null; + } + Location b_ = new Location(Bukkit.getServer().getWorld(getConfig().getString(ArenaConfigStrings.ARENAS_PREFIX + mg + "." + arena + ".world")), + getConfig().getInt(ArenaConfigStrings.ARENAS_PREFIX + mg + "." + arena + ".loc.x"), getConfig().getInt(ArenaConfigStrings.ARENAS_PREFIX + mg + "." + arena + ".loc.y"), + getConfig().getInt(ArenaConfigStrings.ARENAS_PREFIX + mg + "." + arena + ".loc.z")); + if (b_ != null) + { + if (b_.getWorld() != null) + { + if (b_.getBlock().getState() != null) + { + BlockState bs = b_.getBlock().getState(); + Sign s_ = null; + if (bs instanceof Sign) + { + s_ = (Sign) bs; + } + return s_; + } + } + } + return null; + } + + private Sign getSpecSignFromArena(String mg, String arena) + { + if (!getConfig().isSet(ArenaConfigStrings.ARENAS_PREFIX + mg + "." + arena + ".specworld")) + { + return null; + } + Location b_ = new Location(Bukkit.getServer().getWorld(getConfig().getString(ArenaConfigStrings.ARENAS_PREFIX + mg + "." + arena + ".specworld")), + getConfig().getInt(ArenaConfigStrings.ARENAS_PREFIX + mg + "." + arena + ".specloc.x"), getConfig().getInt(ArenaConfigStrings.ARENAS_PREFIX + mg + "." + arena + ".specloc.y"), + getConfig().getInt(ArenaConfigStrings.ARENAS_PREFIX + mg + "." + arena + ".specloc.z")); + if (b_ != null) + { + if (b_.getWorld() != null) + { + if (b_.getBlock().getState() != null) + { + BlockState bs = b_.getBlock().getState(); + Sign s_ = null; + if (bs instanceof Sign) + { + s_ = (Sign) bs; + } + return s_; + } + } + } + return null; + } + + public void updateSign(String mg, String arenaname, String arenastate, int count, int maxcount) + { + Sign s = getSignFromArena(mg, arenaname); + if (s != null) + { + this.signManager.updateSign(s.getLocation(), arenastate, count, maxcount); + } + s = getSpecSignFromArena(mg, arenaname); + if (s != null) + { + this.signManager.updateSign(s.getLocation(), "SPEC", count, maxcount); + } + } + + public void sendSignUpdate(final PluginInstance pli, final Arena a) + { + String signString; + + if (a == null) + { + signString = pli.getPlugin().getName() + ":null:JOIN:0:0"; + } + else + { + signString = pli.getPlugin().getName() + ":" + a.getInternalName() + ":" + a.getArenaState().toString() + ":" + a.getAllPlayers().size() + ":" + a.getMaxPlayers(); + } + + try + { + ByteArrayDataOutput out = ByteStreams.newDataOutput(); + try + { + out.writeUTF("Forward"); + out.writeUTF("ALL"); + out.writeUTF(ChannelStrings.SUBCHANNEL_MINIGAMESLIB_SIGN); + + ByteArrayOutputStream msgbytes = new ByteArrayOutputStream(); + DataOutputStream msgout = new DataOutputStream(msgbytes); + msgout.writeUTF(signString); + + out.writeShort(msgbytes.toByteArray().length); + out.write(msgbytes.toByteArray()); + + Bukkit.getServer().sendPluginMessage(this, ChannelStrings.CHANNEL_BUNGEE_CORD, out.toByteArray()); + } + catch (Exception e) + { + MinigamesAPI.getAPI().getLogger().log(Level.WARNING, "exception", e); + } + } + catch (Exception e) + { + this.getLogger().log(Level.WARNING, "Error occurred while sending extra sign request: ", e); + } + } + + public String getServerBySignLocation(Location sign) + { + if (getConfig().isSet(ArenaConfigStrings.ARENAS_PREFIX)) + { + for (String mg_key : getConfig().getConfigurationSection(ArenaConfigStrings.ARENAS_PREFIX).getKeys(false)) + { + for (String arena_key : getConfig().getConfigurationSection(ArenaConfigStrings.ARENAS_PREFIX + mg_key + ".").getKeys(false)) + { + if (getConfig().isString(ArenaConfigStrings.ARENAS_PREFIX + mg_key + "." + arena_key + ".world")) + { + Location l = new Location(Bukkit.getWorld(getConfig().getString(ArenaConfigStrings.ARENAS_PREFIX + mg_key + "." + arena_key + ".world")), + getConfig().getInt(ArenaConfigStrings.ARENAS_PREFIX + mg_key + "." + arena_key + ".loc.x"), + getConfig().getInt(ArenaConfigStrings.ARENAS_PREFIX + mg_key + "." + arena_key + ".loc.y"), + getConfig().getInt(ArenaConfigStrings.ARENAS_PREFIX + mg_key + "." + arena_key + ".loc.z")); + if (l.distance(sign) < 1) + { + return getConfig().getString(ArenaConfigStrings.ARENAS_PREFIX + mg_key + "." + arena_key + ".server"); + } + } + if (getConfig().isString(ArenaConfigStrings.ARENAS_PREFIX + mg_key + "." + arena_key + ".specworld")) + { + Location l = new Location(Bukkit.getWorld(getConfig().getString(ArenaConfigStrings.ARENAS_PREFIX + mg_key + "." + arena_key + ".specworld")), + getConfig().getInt(ArenaConfigStrings.ARENAS_PREFIX + mg_key + "." + arena_key + ".specloc.x"), + getConfig().getInt(ArenaConfigStrings.ARENAS_PREFIX + mg_key + "." + arena_key + ".specloc.y"), + getConfig().getInt(ArenaConfigStrings.ARENAS_PREFIX + mg_key + "." + arena_key + ".specloc.z")); + if (l.distance(sign) < 1) + { + return getConfig().getString(ArenaConfigStrings.ARENAS_PREFIX + mg_key + "." + arena_key + ".specserver"); + } + } + } + } + } + return null; + } + + public String getInfoBySignLocation(Location sign) + { + if (getConfig().isSet(ArenaConfigStrings.ARENAS_PREFIX)) + { + for (String mg_key : getConfig().getConfigurationSection(ArenaConfigStrings.ARENAS_PREFIX).getKeys(false)) + { + for (String arena_key : getConfig().getConfigurationSection(ArenaConfigStrings.ARENAS_PREFIX + mg_key + ".").getKeys(false)) + { + final ConfigurationSection section = getConfig().getConfigurationSection(ArenaConfigStrings.ARENAS_PREFIX + mg_key + "." + arena_key); + if (section.contains("world")) + { + Location l = new Location(Bukkit.getWorld(getConfig().getString(ArenaConfigStrings.ARENAS_PREFIX + mg_key + "." + arena_key + ".world")), + getConfig().getInt(ArenaConfigStrings.ARENAS_PREFIX + mg_key + "." + arena_key + ".loc.x"), + getConfig().getInt(ArenaConfigStrings.ARENAS_PREFIX + mg_key + "." + arena_key + ".loc.y"), + getConfig().getInt(ArenaConfigStrings.ARENAS_PREFIX + mg_key + "." + arena_key + ".loc.z")); + if (l.distance(sign) < 1) + { + return mg_key + ":" + arena_key + ":join"; + } + } + if (section.contains("specworld")) + { + Location l = new Location(Bukkit.getWorld(getConfig().getString(ArenaConfigStrings.ARENAS_PREFIX + mg_key + "." + arena_key + ".specworld")), + getConfig().getInt(ArenaConfigStrings.ARENAS_PREFIX + mg_key + "." + arena_key + ".specloc.x"), + getConfig().getInt(ArenaConfigStrings.ARENAS_PREFIX + mg_key + "." + arena_key + ".specloc.y"), + getConfig().getInt(ArenaConfigStrings.ARENAS_PREFIX + mg_key + "." + arena_key + ".specloc.z")); + if (l.distance(sign) < 1) + { + return mg_key + ":" + arena_key + ":spec"; + } + } + } + } + } + return ""; + } + + @EventHandler + public void onServerPing(ServerListPingEvent evt) + { + if (this.motd != null) + { + evt.setMotd(this.motd); + } + } + + // party + + /** + * Checks if given player has a party. + * @param owner + * @return + */ + public boolean hasParty(UUID owner) + { + return this.global_party.containsKey(owner); + } + + /** + * Returns a party. + * @param owner + * @return + */ + public Party getParty(UUID owner) + { + return this.global_party.get(owner); + } + + /** + * Returns all known parties. + * @param owner + * @return + */ + public Iterable<Party> getParties() + { + return this.global_party.values(); + } + + /** + * Creates a new party + * @param owner + * @return + */ + public Party createParty(UUID owner) + { + final Party party = new Party(owner); + this.global_party.put(owner, party); + return party; + } - DataInputStream msgin = new DataInputStream(new ByteArrayInputStream(msgbytes)); - try { - final String playerData = msgin.readUTF(); - final String plugin_ = playerData.split(":")[0]; - final String arena = playerData.split(":")[1]; - final String playername = playerData.split(":")[2]; - System.out.println(plugin_ + " -> " + arena); - JavaPlugin plugin = null; - for (JavaPlugin pl : this.pinstances.keySet()) { - if (pl.getName().contains(plugin_)) { - plugin = pl; - break; - } - } - if (plugin != null) { - final Arena a = pinstances.get(plugin).getArenaByName(arena); - if (a != null) { - if (a.getArenaState() != ArenaState.INGAME && a.getArenaState() != ArenaState.RESTARTING && !a.containsPlayer(playername)) { - Bukkit.getScheduler().runTaskLater(this, new Runnable() { - public void run() { - if (!a.containsPlayer(playername)) { - a.joinPlayerLobby(playername); - } - } - }, 20L); - } - } else { - System.out.println("Arena " + arena + " couldn't be found, please fix your setup."); - } - } - } catch (IOException e) { - e.printStackTrace(); - } - } else if (subchannel.equals("MinigamesLibRequest")) { // Lobby requests sign data - short len = in.readShort(); - byte[] msgbytes = new byte[len]; - in.readFully(msgbytes); + /** + * Removes existing party from list + * @param owner + */ + public void removeParty(UUID owner) + { + this.global_party.remove(owner); + } + + /** + * Adds a party invite + * @param invitedPlayer + * @param party + */ + public void addPartyInvite(UUID invitedPlayer, Party party) + { + this.global_party_invites.computeIfAbsent(invitedPlayer, u -> new ArrayList<>()).add(party); + } - DataInputStream msgin = new DataInputStream(new ByteArrayInputStream(msgbytes)); - try { - final String requestData = msgin.readUTF(); - final String plugin_ = requestData.split(":")[0]; - final String arena = requestData.split(":")[1]; - System.out.println(plugin_ + " -> " + arena); - for (JavaPlugin pl : this.pinstances.keySet()) { - if (pl.getName().contains(plugin_)) { - Arena a = pinstances.get(pl).getArenaByName(arena); - if (a != null) { - BungeeUtil.sendSignUpdateRequest(pl, pl.getName(), a); - } else { - System.out.println("Arena " + arena + " couldn't be found, please fix your setup."); - } - break; - } - } - } catch (IOException e) { - e.printStackTrace(); - } - } - } + /** + * @param invitedPlayer + * @return + */ + public boolean hasPartyInvites(UUID invitedPlayer) + { + return this.global_party_invites.containsKey(invitedPlayer); + } - public PluginInstance getPluginInstance(JavaPlugin plugin) { - return pinstances.get(plugin); - } + /** + * @param invitedPlayer + * @return + */ + public Iterable<Party> getPartyInvites(UUID invitedPlayer) + { + return this.global_party_invites.get(invitedPlayer); + } + /** + * @param invitedPlayer + */ + public void removePartyInvites(UUID invitedPlayer) + { + this.global_party_invites.remove(invitedPlayer); + } + } diff --git a/API/src/main/java/com/comze_instancelabs/minigamesapi/Party.java b/API/src/main/java/com/comze_instancelabs/minigamesapi/Party.java index 89516a46..218e2bf3 100644 --- a/API/src/main/java/com/comze_instancelabs/minigamesapi/Party.java +++ b/API/src/main/java/com/comze_instancelabs/minigamesapi/Party.java @@ -1,71 +1,155 @@ +/* + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ package com.comze_instancelabs.minigamesapi; import java.util.ArrayList; +import java.util.UUID; import org.bukkit.Bukkit; import org.bukkit.entity.Player; -public class Party { - - String owner; - ArrayList<String> players = new ArrayList<String>(); - - public Party(String owner) { - this.owner = owner; - } - - public String getOwner() { - return owner; - } - - public ArrayList<String> getPlayers() { - return players; - } - - public void addPlayer(String p) { - if (!players.contains(p)) { - players.add(p); - } - Bukkit.getPlayer(p).sendMessage(MinigamesAPI.getAPI().partymessages.you_joined_party.replaceAll("<player>", this.getOwner())); - tellAll(MinigamesAPI.getAPI().partymessages.player_joined_party.replaceAll("<player>", p)); - } - - public boolean removePlayer(String p) { - if (players.contains(p)) { - players.remove(p); - Player p___ = Bukkit.getPlayer(p); - if (p___ != null) { - p___.sendMessage(MinigamesAPI.getAPI().partymessages.you_left_party.replaceAll("<player>", this.getOwner())); - } - tellAll(MinigamesAPI.getAPI().partymessages.player_left_party.replaceAll("<player>", p)); - return true; - } - return false; - } - - public boolean containsPlayer(String p) { - return players.contains(p); - } - - public void disband() { - tellAll(MinigamesAPI.getAPI().partymessages.party_disbanded); - if (MinigamesAPI.getAPI().global_party.containsKey(owner)) { - this.players.clear(); - MinigamesAPI.getAPI().global_party.remove(owner); - } - } - - private void tellAll(String msg) { - for (String p_ : this.getPlayers()) { - Player p__ = Bukkit.getPlayer(p_); - if (p__ != null) { - p__.sendMessage(msg); - } - } - Player p___ = Bukkit.getPlayer(this.getOwner()); - if (p___ != null) { - p___.sendMessage(msg); - } - } - +/** + * A (temporary) party for group playing with friends. + * + * @author instancelabs + */ +public class Party +{ + + /** party owner. */ + private UUID owner; + + /** party members. */ + private ArrayList<UUID> players = new ArrayList<>(); + + /** + * Constructor. + * + * @param owner + * party owner (player name) + */ + public Party(final UUID owner) + { + this.owner = owner; + } + + /** + * returns the owner player name + * + * @return player name + */ + public UUID getOwner() + { + return this.owner; + } + + /** + * Returns the party members. + * + * @return party members. + */ + public ArrayList<UUID> getPlayers() + { + return this.players; + } + + /** + * Adds a players (invite). + * + * @param p + * player to add. + */ + public void addPlayer(final UUID p) + { + if (!this.players.contains(p)) + { + this.players.add(p); + } + Bukkit.getPlayer(p).sendMessage(MinigamesAPI.getAPI().partymessages.you_joined_party.replaceAll("<player>", Bukkit.getPlayer(this.getOwner()).getName())); + this.tellAll(MinigamesAPI.getAPI().partymessages.player_joined_party.replaceAll("<player>", Bukkit.getPlayer(p).getName())); + } + + /** + * Removes a player. + * + * @param p + * player to remove + * @return {@code true} if the player was contained in the list + */ + public boolean removePlayer(final UUID p) + { + if (this.players.contains(p)) + { + this.players.remove(p); + final Player p___ = Bukkit.getPlayer(p); + if (p___ != null) + { + p___.sendMessage(MinigamesAPI.getAPI().partymessages.you_left_party.replaceAll("<player>", Bukkit.getPlayer(this.getOwner()).getName())); + this.tellAll(MinigamesAPI.getAPI().partymessages.player_left_party.replaceAll("<player>", p___.getName())); + } + return true; + } + return false; + } + + /** + * Checks if a player is present in party list. + * + * @param p + * playeer to be checked. + * @return {@code true} if the player is within the party list. + */ + public boolean containsPlayer(final UUID p) + { + return this.players.contains(p); + } + + /** + * Disband/Delete the party. + */ + public void disband() + { + this.tellAll(MinigamesAPI.getAPI().partymessages.party_disbanded); + if (MinigamesAPI.getAPI().hasParty(this.owner)) + { + this.players.clear(); + MinigamesAPI.getAPI().removeParty(this.owner); + } + } + + /** + * Internal chat message for all players within the list. + * + * @param msg + * message + */ + private void tellAll(final String msg) + { + for (final UUID p_ : this.getPlayers()) + { + final Player p__ = Bukkit.getPlayer(p_); + if (p__ != null) + { + p__.sendMessage(msg); + } + } + final Player p___ = Bukkit.getPlayer(this.getOwner()); + if (p___ != null) + { + p___.sendMessage(msg); + } + } + } diff --git a/API/src/main/java/com/comze_instancelabs/minigamesapi/PermissionStrings.java b/API/src/main/java/com/comze_instancelabs/minigamesapi/PermissionStrings.java new file mode 100644 index 00000000..2afd1aaf --- /dev/null +++ b/API/src/main/java/com/comze_instancelabs/minigamesapi/PermissionStrings.java @@ -0,0 +1,32 @@ +/* + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +package com.comze_instancelabs.minigamesapi; + +/** + * Strings for common permissions. + * + * @author mepeisen + */ +public interface PermissionStrings +{ + + /** permission prefix for minigames party. */ + String MINIGAMES_PARTY = ".party"; //$NON-NLS-1$ + + /** permission for start command. */ + String MINIGAMES_START = ".start"; //$NON-NLS-1$ + +} diff --git a/API/src/main/java/com/comze_instancelabs/minigamesapi/PluginConfigStrings.java b/API/src/main/java/com/comze_instancelabs/minigamesapi/PluginConfigStrings.java new file mode 100644 index 00000000..2ff9c380 --- /dev/null +++ b/API/src/main/java/com/comze_instancelabs/minigamesapi/PluginConfigStrings.java @@ -0,0 +1,116 @@ +/* + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +package com.comze_instancelabs.minigamesapi; + +/** + * Strings for plugins config. + * + * @author mepeisen + */ +public interface PluginConfigStrings +{ + + /** + * debug flag for minigames lib. + */ + String DEBUG = "config.debug"; //$NON-NLS-1$ + + /** + * flag to support the party command (playing with friends). + */ + String PARTY_COMMAND_ENABLED = "config.party_command_enabled"; //$NON-NLS-1$ + + /** + * the update interval for arena signs. + */ + String SIGNS_UPDATE_TIME = "signs_updating_time"; //$NON-NLS-1$ + + /** + * flag for controlling auto updates. + */ + String AUTO_UPDATING = "config.auto_updating"; //$NON-NLS-1$ + + /** + * flag for controlling metrics. + */ + String POST_METRICS = "config.post_metrics"; //$NON-NLS-1$ + + /** + * flag for enabling motd manipulation. + */ + String MOTD_ENABLED = "config.motd.enabled"; //$NON-NLS-1$ + + /** + * seconds to rotate from arena to arena. + */ + String MOTD_ROTATION_SECONDS = "config.motd.rotation"; //$NON-NLS-1$ + + /** + * string to set for motd + */ + String MOTD_TEXT = "config.motd.text"; //$NON-NLS-1$ + + /** + * string for motd state text + */ + String MOTD_STATE_JOIN = "config.motd.state.join"; //$NON-NLS-1$ + + /** + * string for motd state text + */ + String MOTD_STATE_STARTING = "config.motd.state.starting"; //$NON-NLS-1$ + + /** + * string for motd state text + */ + String MOTD_STATE_INGAME = "config.motd.state.ingame"; //$NON-NLS-1$ + + /** + * string for motd state text + */ + String MOTD_STATE_RESTARTING = "config.motd.state.restarting"; //$NON-NLS-1$ + + /** + * string for motd state text + */ + String MOTD_STATE_DISABLED = "config.motd.state.disabled"; //$NON-NLS-1$ + + /** + * Prefix for core permissions. + */ + String PERMISSION_PREFIX = "config.permissions_prefix"; //$NON-NLS-1$ + + /** + * Prefix for core permissions. + */ + String PERMISSION_KITS_PREFIX = "config.permissions_kits_prefix"; //$NON-NLS-1$ + + /** + * Prefix for gun permissions. + */ + String PERMISSION_GUN_PREFIX = "config.permissions_gun_prefix"; //$NON-NLS-1$ + + /** + * Prefix for shop-item permissions. + */ + String PERMISSION_SHOP_PREFIX = "config.permissions_shop_prefix"; //$NON-NLS-1$ + + /** + * Prefix for game permissions. + */ + String PERMISSION_GAME_PREFIX = "config.permissions_game_prefix"; //$NON-NLS-1$ + +} diff --git a/API/src/main/java/com/comze_instancelabs/minigamesapi/PluginInstance.java b/API/src/main/java/com/comze_instancelabs/minigamesapi/PluginInstance.java index 0c5a0d1d..e9539e53 100644 --- a/API/src/main/java/com/comze_instancelabs/minigamesapi/PluginInstance.java +++ b/API/src/main/java/com/comze_instancelabs/minigamesapi/PluginInstance.java @@ -1,3 +1,17 @@ +/* + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ package com.comze_instancelabs.minigamesapi; import java.util.ArrayList; @@ -25,323 +39,983 @@ import com.comze_instancelabs.minigamesapi.util.Util; import com.comze_instancelabs.minigamesapi.util.Validator; -public class PluginInstance { - - public HashMap<String, Arena> global_players = new HashMap<String, Arena>(); - public HashMap<String, Arena> global_lost = new HashMap<String, Arena>(); - public HashMap<String, Arena> global_arcade_spectator = new HashMap<String, Arena>(); - - private ArenaListener arenalistener = null; - private ArenasConfig arenasconfig = null; - private ClassesConfig classesconfig = null; - private MessagesConfig messagesconfig = null; - private StatsConfig statsconfig = null; - private GunsConfig gunsconfig = null; - private AchievementsConfig achievementsconfig = null; - private ShopConfig shopconfig = null; - private HologramsConfig hologramsconfig = null; - private JavaPlugin plugin = null; - private ArrayList<Arena> arenas = new ArrayList<Arena>(); - private HashMap<String, AClass> pclass = new HashMap<String, AClass>(); - private LinkedHashMap<String, AClass> aclasses = new LinkedHashMap<String, AClass>(); - private HashMap<String, Gun> guns = new HashMap<String, Gun>(); - private Rewards rew = null; - private MainSQL sql = null; - private Stats stats = null; - private Classes classes = null; - private Shop shop = null; - private SpectatorManager spectatormanager = null; - private ArenaAchievements achievements = null; - private Holograms holograms = null; - private boolean achievement_gui_enabled = false; - - public ArenaScoreboard scoreboardManager; - public ArenaLobbyScoreboard scoreboardLobbyManager; - public ArenaSetup arenaSetup = new ArenaSetup(); - - int lobby_countdown = 30; - int ingame_countdown = 10; - - boolean spectator_move_y_lock = true; - boolean use_xp_bar_level = true; - boolean blood_effects = true; - boolean dead_in_fake_bed_effects = true; - boolean spectator_mode_1_8 = true; - boolean damage_identifier_effects = true; - public boolean color_background_wool_of_signs; - boolean last_man_standing = true; - boolean old_reset = false; - public boolean show_classes_without_usage_permission = true; - public boolean chat_enabled = true; - - public HashMap<String, ArrayList<String>> cached_sign_states = new HashMap<String, ArrayList<String>>(); - - public PluginInstance(JavaPlugin plugin, ArenasConfig arenasconfig, MessagesConfig messagesconfig, ClassesConfig classesconfig, StatsConfig statsconfig, ArrayList<Arena> arenas) { - this.arenasconfig = arenasconfig; - this.messagesconfig = messagesconfig; - this.classesconfig = classesconfig; - this.statsconfig = statsconfig; - this.gunsconfig = new GunsConfig(plugin, false); - this.achievementsconfig = new AchievementsConfig(plugin); - this.shopconfig = new ShopConfig(plugin, false); - this.hologramsconfig = new HologramsConfig(plugin, false); - this.arenas = arenas; - this.plugin = plugin; - rew = new Rewards(plugin); - stats = new Stats(this, plugin); - sql = new MainSQL(plugin, true); - classes = new Classes(this, plugin); - shop = new Shop(this, plugin); - spectatormanager = new SpectatorManager(plugin); - achievements = new ArenaAchievements(this, plugin); - holograms = new Holograms(this); - scoreboardManager = new ArenaScoreboard(this, plugin); - scoreboardLobbyManager = new ArenaLobbyScoreboard(this, plugin); - reloadVariables(); - } - - public PluginInstance(JavaPlugin plugin, ArenasConfig arenasconfig, MessagesConfig messagesconfig, ClassesConfig classesconfig, StatsConfig statsconfig) { - this(plugin, arenasconfig, messagesconfig, classesconfig, statsconfig, new ArrayList<Arena>()); - } - - public void reloadVariables() { - lobby_countdown = plugin.getConfig().getInt("config.countdowns.lobby_countdown") + 1; - ingame_countdown = plugin.getConfig().getInt("config.countdowns.ingame_countdown") + 1; - spectator_move_y_lock = plugin.getConfig().getBoolean("config.spectator.spectator_move_y_lock"); - use_xp_bar_level = plugin.getConfig().getBoolean("config.use_xp_bar_level"); - blood_effects = plugin.getConfig().getBoolean("config.effects.blood"); - damage_identifier_effects = plugin.getConfig().getBoolean("config.effects.damage_identifier_holograms"); - dead_in_fake_bed_effects = plugin.getConfig().getBoolean("config.effects.dead_in_fake_bed"); - color_background_wool_of_signs = plugin.getConfig().getBoolean("config.color_background_wool_of_signs"); - spectator_mode_1_8 = plugin.getConfig().getBoolean("config.effects.1_8_spectator_mode"); - last_man_standing = plugin.getConfig().getBoolean("config.last_man_standing_wins"); - old_reset = plugin.getConfig().getBoolean("config.use_old_reset_method"); - show_classes_without_usage_permission = plugin.getConfig().getBoolean("config.show_classes_without_usage_permission"); - chat_enabled = plugin.getConfig().getBoolean("config.chat_enabled"); - - // Cache sign configuration - for (String state : ArenaState.getAllStateNames()) { - this.cached_sign_states.put(state, new ArrayList<String>(Arrays.asList(this.messagesconfig.getConfig().getString("signs." + state.toLowerCase() + ".0"), this.messagesconfig.getConfig().getString("signs." + state.toLowerCase() + ".1"), this.messagesconfig.getConfig().getString("signs." + state.toLowerCase() + ".2"), this.messagesconfig.getConfig().getString("signs." + state.toLowerCase() + ".3")))); - } - - } - - public JavaPlugin getPlugin() { - return plugin; - } - - public HashMap<String, AClass> getAClasses() { - return this.aclasses; - } - - public HashMap<String, AClass> getPClasses() { - return this.pclass; - } - - public void addAClass(String name, AClass a) { - this.aclasses.put(name, a); - } - - public void setPClass(String player, AClass a) { - this.pclass.put(player, a); - } - - public HashMap<String, Gun> getAllGuns() { - return this.guns; - } - - public void addGun(String name, Gun g) { - this.guns.put(name, g); - } - - public ArenasConfig getArenasConfig() { - return arenasconfig; - } - - public MessagesConfig getMessagesConfig() { - return messagesconfig; - } - - public ClassesConfig getClassesConfig() { - return classesconfig; - } - - public StatsConfig getStatsConfig() { - return statsconfig; - } - - public GunsConfig getGunsConfig() { - return gunsconfig; - } - - public AchievementsConfig getAchievementsConfig() { - return achievementsconfig; - } - - public ShopConfig getShopConfig() { - return shopconfig; - } - - public void setShopConfig(ShopConfig shopconfig) { - this.shopconfig = shopconfig; - } - - public HologramsConfig getHologramsConfig() { - return hologramsconfig; - } - - public Rewards getRewardsInstance() { - return rew; - } - - public void setRewardsInstance(Rewards r) { - rew = r; - } - - public MainSQL getSQLInstance() { - return sql; - } - - public Stats getStatsInstance() { - return stats; - } - - public ArenaListener getArenaListener() { - return this.arenalistener; - } - - public void setArenaListener(ArenaListener al) { - this.arenalistener = al; - } - - public Classes getClassesHandler() { - return this.classes; - } - - public void setClassesHandler(Classes c) { - this.classes = c; - } - - public Shop getShopHandler() { - return this.shop; - } - - public SpectatorManager getSpectatorManager() { - return this.spectatormanager; - } - - public void setSpectatorManager(SpectatorManager s) { - this.spectatormanager = s; - } - - public ArenaAchievements getArenaAchievements() { - return this.achievements; - } - - public Holograms getHologramsHandler() { - return this.holograms; - } - - public int getIngameCountdown() { - return this.ingame_countdown; - } - - public int getLobbyCountdown() { - return this.lobby_countdown; - } - - public ArrayList<Arena> getArenas() { - return arenas; - } - - public void clearArenas() { - arenas.clear(); - } - - public ArrayList<Arena> addArena(Arena arena) { - arenas.add(arena); - return getArenas(); - } - - public Arena getArenaByName(String arenaname) { - for (Arena a : getArenas()) { - if (a.getInternalName().equalsIgnoreCase(arenaname)) { - return a; - } - } - return null; - } - - public Arena removeArenaByName(String arenaname) { - Arena torem = null; - for (Arena a : getArenas()) { - if (a.getInternalName().equalsIgnoreCase(arenaname)) { - torem = a; - } - } - if (torem != null) { - removeArena(torem); - } - return null; - } - - public boolean removeArena(Arena arena) { - if (arenas.contains(arena)) { - arenas.remove(arena); - return true; - } - return false; - } - - public void addLoadedArenas(ArrayList<Arena> arenas) { - this.arenas = arenas; - } - - public boolean isAchievementGuiEnabled() { - return achievement_gui_enabled; - } - - public void setAchievementGuiEnabled(boolean achievement_gui_enabled) { - this.achievement_gui_enabled = achievement_gui_enabled; - } - - public void reloadAllArenas() { - for (Arena a : this.getArenas()) { - if (a != null) { - String arenaname = a.getInternalName(); - ArenaSetup s = this.arenaSetup; - a.init(Util.getSignLocationFromArena(plugin, arenaname), Util.getAllSpawns(plugin, arenaname), Util.getMainLobby(plugin), Util.getComponentForArena(plugin, arenaname, "lobby"), s.getPlayerCount(plugin, arenaname, true), s.getPlayerCount(plugin, arenaname, false), s.getArenaVIP(plugin, arenaname)); - if (a.isSuccessfullyInit()) { - Util.updateSign(plugin, a); - } - } - } - } - - public void reloadArena(String arenaname) { - if (Validator.isArenaValid(plugin, arenaname)) { - Arena a = this.getArenaByName(arenaname); - if (a != null) { - ArenaSetup s = this.arenaSetup; - a.init(Util.getSignLocationFromArena(plugin, arenaname), Util.getAllSpawns(plugin, arenaname), Util.getMainLobby(plugin), Util.getComponentForArena(plugin, arenaname, "lobby"), s.getPlayerCount(plugin, arenaname, true), s.getPlayerCount(plugin, arenaname, false), s.getArenaVIP(plugin, arenaname)); - } - } - } - - public boolean containsGlobalPlayer(String playername) { - return this.global_players.containsKey(playername); - } - - public boolean containsGlobalLost(String playername) { - return this.global_lost.containsKey(playername); - } - - public Arena getArenaByGlobalPlayer(String playername) { - if (containsGlobalPlayer(playername)) { - return this.global_players.get(playername); - } else { - return null; - } - } - +/** + * Internal representation of a minigames plugin. + * + * @author instancelabs + */ +public class PluginInstance +{ + + /** + * TODO describe field. + * + * @deprecated will be private in 1.5.0; replaced by new methods. + */ + @Deprecated + public HashMap<String, Arena> global_players = new HashMap<>(); + + /** + * TODO describe field. + * + * @deprecated will be private in 1.5.0; replaced by new methods. + */ + @Deprecated + public HashMap<String, Arena> global_lost = new HashMap<>(); + + /** + * TODO describe field. + * + * @deprecated will be private in 1.5.0; replaced by new methods. + */ + @Deprecated + public HashMap<String, Arena> global_arcade_spectator = new HashMap<>(); + + /** + * The arena listener for this plugin. + */ + private ArenaListener arenalistener = null; + + /** + * The arenas configuration (arenas.yml). + */ + private ArenasConfig arenasconfig = null; + + /** + * The classes configuration (classes.yml). + */ + private ClassesConfig classesconfig = null; + + /** + * The messages configuration (messages.yml). + */ + private MessagesConfig messagesconfig = null; + + /** + * The stats configuration (stats.yml). + */ + private StatsConfig statsconfig = null; + + /** + * The guns configuration (guns.yml). + */ + private GunsConfig gunsconfig = null; + + /** + * The achievements configuration (achievements.yml) + */ + private AchievementsConfig achievementsconfig = null; + + /** + * The shops config (shops.yml) + */ + private ShopConfig shopconfig = null; + + /** + * The holograms config (holograms.yml) + */ + private HologramsConfig hologramsconfig = null; + + /** + * The minigames spigot/java plugin + */ + private JavaPlugin plugin = null; + + /** + * The known/loaded arenas. + */ + private ArrayList<Arena> arenas = new ArrayList<>(); + + /** + * The classes per player. + */ + private final HashMap<String, AClass> pclass = new HashMap<>(); + + /** + * The current configured classes from classes config. + */ + private final LinkedHashMap<String, AClass> aclasses = new LinkedHashMap<>(); + + /** + * The configured guns from guns config. + */ + private final HashMap<String, Gun> guns = new HashMap<>(); + + /** + * The rewards. + */ + private Rewards rew = null; + + /** + * The main sql reference for database support. + */ + private MainSQL sql = null; + + /** + * The stats from stats config. + */ + private Stats stats = null; + + /** + * The classes gui. + */ + private Classes classes = null; + + /** + * The shop gui. + */ + private Shop shop = null; + + /** + * The spectator manager for controlling spectators. + */ + private SpectatorManager spectatormanager = null; + + /** + * The achivements manager. + */ + private ArenaAchievements achievements = null; + + /** + * The holograms manager. + */ + private Holograms holograms = null; + + /** + * Flag to enable the achivements gui. + */ + private boolean achievement_gui_enabled = false; + + /** + * TODO describe field. + * + * @deprecated will be private in 1.5.0; replaced by new methods. + */ + @Deprecated + public ArenaScoreboard scoreboardManager; + + /** + * TODO describe field. + * + * @deprecated will be private in 1.5.0; replaced by new methods. + */ + @Deprecated + public ArenaLobbyScoreboard scoreboardLobbyManager; + + /** + * TODO describe field. + * + * @deprecated will be private in 1.5.0; replaced by new methods. + */ + @Deprecated + public ArenaSetup arenaSetup = new ArenaSetup(); + + /** + * Default lobby cooldown in seconds. + * + * <p> + * TODO Allow override in arena config. + * </p> + */ + private int lobby_countdown = 30; + + /** + * Default ingame cooldown in seconds. + * + * <p> + * TODO Allow override in arena config. + * </p> + */ + private int ingame_countdown = 10; + + /** + * TODO describe field. + * + * @deprecated will be private in 1.5.0; replaced by new methods. + */ + @Deprecated + boolean spectator_move_y_lock = true; + + /** + * TODO describe field. + * + * @deprecated will be private in 1.5.0; replaced by new methods. + */ + @Deprecated + boolean use_xp_bar_level = true; + + /** + * TODO describe field. + * + * @deprecated will be private in 1.5.0; replaced by new methods. + */ + @Deprecated + boolean blood_effects = true; + + /** + * TODO describe field. + * + * @deprecated will be private in 1.5.0; replaced by new methods. + */ + @Deprecated + boolean dead_in_fake_bed_effects = true; + + /** + * TODO describe field. + * + * @deprecated will be private in 1.5.0; replaced by new methods. + */ + @Deprecated + boolean spectator_mode_1_8 = true; + + /** + * TODO describe field. + * + * @deprecated will be private in 1.5.0; replaced by new methods. + */ + @Deprecated + boolean damage_identifier_effects = true; + + /** + * TODO describe field. + * + * @deprecated will be private in 1.5.0; replaced by new methods. + */ + @Deprecated + public boolean color_background_wool_of_signs; + + /** + * TODO describe field. + * + * @deprecated will be private in 1.5.0; replaced by new methods. + */ + @Deprecated + boolean last_man_standing = true; + + /** + * {@code true} for old reset method. + * + * @deprecated will be removed in 1.4.10 + */ + @Deprecated + boolean old_reset = false; + + /** + * TODO describe field. + * + * @deprecated will be private in 1.5.0; replaced by new methods. + */ + @Deprecated + public boolean show_classes_without_usage_permission = true; + + /** + * TODO describe field. + * + * @deprecated will be private in 1.5.0; replaced by new methods. + */ + @Deprecated + public boolean chat_enabled = true; + + /** + * TODO describe field. + * + * @deprecated will be private in 1.5.0; replaced by new methods. + */ + @Deprecated + public HashMap<String, ArrayList<String>> cached_sign_states = new HashMap<>(); + + /** + * Constructor to create a new plugin instance. + * + * @param plugin + * java plugin. + * @param arenasconfig + * arenas config. + * @param messagesconfig + * messages config. + * @param classesconfig + * classes config. + * @param statsconfig + * stats config. + * @param arenas + * loaded arenas. + */ + PluginInstance(final JavaPlugin plugin, final ArenasConfig arenasconfig, final MessagesConfig messagesconfig, final ClassesConfig classesconfig, final StatsConfig statsconfig, + final ArrayList<Arena> arenas) + { + this.arenasconfig = arenasconfig; + this.messagesconfig = messagesconfig; + this.classesconfig = classesconfig; + this.statsconfig = statsconfig; + this.gunsconfig = new GunsConfig(plugin, false); + this.achievementsconfig = new AchievementsConfig(plugin); + this.shopconfig = new ShopConfig(plugin, false); + this.hologramsconfig = new HologramsConfig(plugin, false); + this.arenas = arenas; + this.plugin = plugin; + this.rew = new Rewards(plugin); + this.stats = new Stats(this, plugin); + this.sql = new MainSQL(plugin); + this.classes = new Classes(this, plugin); + this.shop = new Shop(this, plugin); + this.spectatormanager = new SpectatorManager(plugin); + this.achievements = new ArenaAchievements(this, plugin); + this.holograms = new Holograms(this); + this.scoreboardManager = new ArenaScoreboard(this, plugin); + this.scoreboardLobbyManager = new ArenaLobbyScoreboard(this, plugin); + this.reloadVariables(); + } + + /** + * Constructor to create a new plugin instance. + * + * @param plugin + * java plugin. + * @param arenasconfig + * arenas config. + * @param messagesconfig + * messages config. + * @param classesconfig + * classes config. + * @param statsconfig + * stats config. + */ + PluginInstance(final JavaPlugin plugin, final ArenasConfig arenasconfig, final MessagesConfig messagesconfig, final ClassesConfig classesconfig, final StatsConfig statsconfig) + { + this(plugin, arenasconfig, messagesconfig, classesconfig, statsconfig, new ArrayList<Arena>()); + } + + /** + * Reloads variables from plugins config.yml and caches sign states. + */ + public void reloadVariables() + { + this.lobby_countdown = this.plugin.getConfig().getInt(ArenaConfigStrings.CONFIG_LOBBY_COUNTDOWN) + 1; + this.ingame_countdown = this.plugin.getConfig().getInt(ArenaConfigStrings.CONFIG_INGAME_COUNTDOWN) + 1; + this.spectator_move_y_lock = this.plugin.getConfig().getBoolean(ArenaConfigStrings.CONFIG_SPECTATOR_MOVE_Y_LOCK); + this.use_xp_bar_level = this.plugin.getConfig().getBoolean(ArenaConfigStrings.CONFIG_USE_XP_BAR_LEVEL); + this.blood_effects = this.plugin.getConfig().getBoolean(ArenaConfigStrings.CONFIG_EFFECTS_BLOOD); + this.damage_identifier_effects = this.plugin.getConfig().getBoolean(ArenaConfigStrings.CONFIG_EFFECTS_DMG_IDENTIFIER_HOLO); + this.dead_in_fake_bed_effects = this.plugin.getConfig().getBoolean(ArenaConfigStrings.CONFIG_EFFECTS_DEAD_IN_FAKE_BED); + this.color_background_wool_of_signs = this.plugin.getConfig().getBoolean(ArenaConfigStrings.CONFIG_COLOR_BACKGROUND_WOOL); + this.spectator_mode_1_8 = this.plugin.getConfig().getBoolean(ArenaConfigStrings.CONFIG_EFFECTS_1_8_SPECTATOR_MODE); + this.last_man_standing = this.plugin.getConfig().getBoolean(ArenaConfigStrings.CONFIG_LAST_MAN_STANDING_WINS); + this.old_reset = this.plugin.getConfig().getBoolean(ArenaConfigStrings.CONFIG_USE_OLD_RESET_METHOD); + if (this.old_reset) + { + this.plugin.getLogger().severe("SEVERE! The old reset method will be removed in next version! Check if your arenas work with smart reset."); //$NON-NLS-1$ + } + this.show_classes_without_usage_permission = this.plugin.getConfig().getBoolean(ArenaConfigStrings.CONFIG_SHOW_CLASSES_WITHOUT_PERM); + this.chat_enabled = this.plugin.getConfig().getBoolean(ArenaConfigStrings.CONFIG_CHAT_ENABLED); + + // Cache sign configuration + for (final String state : ArenaState.getAllStateNames()) + { + this.cached_sign_states.put(state, + new ArrayList<>(Arrays.asList(this.messagesconfig.getConfig().getString("signs." + state.toLowerCase() + ".0"), + this.messagesconfig.getConfig().getString("signs." + state.toLowerCase() + ".1"), this.messagesconfig.getConfig().getString("signs." + state.toLowerCase() + ".2"), + this.messagesconfig.getConfig().getString("signs." + state.toLowerCase() + ".3")))); + } + this.cached_sign_states.put("spec", + new ArrayList<>(Arrays.asList(this.messagesconfig.getConfig().getString("signs.spec.0"), + this.messagesconfig.getConfig().getString("signs.spec.1"), this.messagesconfig.getConfig().getString("signs.spec.2"), + this.messagesconfig.getConfig().getString("signs.spec.3")))); + + } + + /** + * Returns the minigames java plugin. + * + * @return java plugin of this minigame. + */ + public JavaPlugin getPlugin() + { + return this.plugin; + } + + /** + * Returns the known classes. + * + * @return known classes map. + * @deprecated method signature will change to java.util.Map; will return a read-only map; manipulation is done by a new method if needed + */ + @Deprecated + public HashMap<String, AClass> getAClasses() + { + return this.aclasses; + } + + /** + * Returns the classes per player map. + * + * @return classes per players. + * @deprecated method signature will change to java.util.Map; will return a read-only map; manipulation is done by a new method if needed + */ + @Deprecated + public HashMap<String, AClass> getPClasses() + { + return this.pclass; + } + + /** + * Adds/Sets a new class. + * + * @param name + * class name + * @param a + * class + */ + public void addAClass(final String name, final AClass a) + { + this.aclasses.put(name, a); + } + + /** + * Sets a class for given player + * + * @param player + * player name + * @param a + * class + */ + public void setPClass(final String player, final AClass a) + { + this.pclass.put(player, a); + } + + /** + * Returns all guns. + * + * @return guns of this minigame. + * @deprecated method signature will change to java.util.Map; will return a read-only map; manipulation is done by a new method if needed + */ + @Deprecated + public HashMap<String, Gun> getAllGuns() + { + return this.guns; + } + + /** + * Adds/Sets a new gun. + * + * @param name + * gun name + * @param g + * gun + */ + public void addGun(final String name, final Gun g) + { + this.guns.put(name, g); + } + + /** + * Returns the arenas config. + * + * @return arenas config. + */ + public ArenasConfig getArenasConfig() + { + return this.arenasconfig; + } + + /** + * Returns the messages config. + * + * @return messages config. + */ + public MessagesConfig getMessagesConfig() + { + return this.messagesconfig; + } + + /** + * Returns the classes config. + * + * @return classes config + */ + public ClassesConfig getClassesConfig() + { + return this.classesconfig; + } + + /** + * Returns the stats config. + * + * @return stats config + */ + public StatsConfig getStatsConfig() + { + return this.statsconfig; + } + + /** + * Returns the guns config + * + * @return guns config. + */ + public GunsConfig getGunsConfig() + { + return this.gunsconfig; + } + + /** + * Returns the achievement config + * + * @return achievement config + */ + public AchievementsConfig getAchievementsConfig() + { + return this.achievementsconfig; + } + + /** + * Returns the shop config. + * + * @return shop config. + */ + public ShopConfig getShopConfig() + { + return this.shopconfig; + } + + /** + * Sets the shop config. + * + * @param shopconfig + * new shop config. + */ + public void setShopConfig(final ShopConfig shopconfig) + { + this.shopconfig = shopconfig; + } + + /** + * Returns the holograms config. + * + * @return holograms config. + */ + public HologramsConfig getHologramsConfig() + { + return this.hologramsconfig; + } + + /** + * Returns the reward instance. + * + * @return rewards. + */ + public Rewards getRewardsInstance() + { + return this.rew; + } + + /** + * Sets the reward instance. + * + * @param r + * rewards to be used. + */ + public void setRewardsInstance(final Rewards r) + { + this.rew = r; + } + + /** + * Returns the main sql instance for database support. + * + * @return database support. + */ + public MainSQL getSQLInstance() + { + return this.sql; + } + + /** + * Returns the stats instance. + * + * @return stats instance. + */ + public Stats getStatsInstance() + { + return this.stats; + } + + /** + * The arena listener. + * + * @return arena listener. + */ + public ArenaListener getArenaListener() + { + return this.arenalistener; + } + + /** + * Sets the arena listener. + * + * @param al + * new custom arena listener. + */ + public void setArenaListener(final ArenaListener al) + { + this.arenalistener = al; + } + + /** + * Returns the classes manager. + * + * @return classes manager. + */ + public Classes getClassesHandler() + { + return this.classes; + } + + /** + * Sets the classes manager. + * + * @param c + * classes manager. + */ + public void setClassesHandler(final Classes c) + { + this.classes = c; + } + + /** + * Returns the shop handler. + * + * @return shop handler. + */ + public Shop getShopHandler() + { + return this.shop; + } + + /** + * Returns the spectator manager. + * + * @return spectator manager. + */ + public SpectatorManager getSpectatorManager() + { + return this.spectatormanager; + } + + /** + * Sets the spectator manager. + * + * @param s + * spectator manager. + */ + public void setSpectatorManager(final SpectatorManager s) + { + this.spectatormanager = s; + } + + /** + * Returns the arena achievements. + * + * @return arena achievments. + */ + public ArenaAchievements getArenaAchievements() + { + return this.achievements; + } + + /** + * Returns the holograms handler. + * + * @return holograms handler. + */ + public Holograms getHologramsHandler() + { + return this.holograms; + } + + /** + * Returns the ingame cooldown + * + * @return ingame cooldown + */ + public int getIngameCountdown() + { + return this.ingame_countdown; + } + + /** + * Returns the lobby cooldown + * + * @return lobby cooldown + */ + public int getLobbyCountdown() + { + return this.lobby_countdown; + } + + /** + * Returns the arenas. + * + * @return arenas + * @deprecated will be changed in 1.5.0; returning list interface and returning a read-only copy + */ + public ArrayList<Arena> getArenas() + { + return this.arenas; + } + + /** + * Clears the arena list + */ + public void clearArenas() + { + this.arenas.clear(); + } + + /** + * Adds a new arena + * + * @param arena + * @return new arena list + * @deprecated will be changed in 1.5.0; returning list interface and returning a read-only copy + */ + @Deprecated + public ArrayList<Arena> addArena(final Arena arena) + { + this.arenas.add(arena); + return this.getArenas(); + } + + /** + * Returns arena by given name + * + * @param arenaname + * name of the arena to be searched for + * @return arena or {@code null} if the arena does not exist. + */ + public Arena getArenaByName(final String arenaname) + { + for (final Arena a : this.getArenas()) + { + if (a.getInternalName().equalsIgnoreCase(arenaname)) + { + return a; + } + } + return null; + } + + /** + * Removes arena by name. + * + * @param arenaname + * name of the arena to be removed + * @return removed arena or {@code null} if the arena does not exist. + */ + public Arena removeArenaByName(final String arenaname) + { + Arena torem = null; + for (final Arena a : this.getArenas()) + { + if (a.getInternalName().equalsIgnoreCase(arenaname)) + { + torem = a; + } + } + if (torem != null) + { + this.removeArena(torem); + } + return null; + } + + /** + * Remove arena by instance. + * + * @param arena + * arena to be removed + * @return {@code true} if the arena was caontained in the list + */ + public boolean removeArena(final Arena arena) + { + if (this.arenas.contains(arena)) + { + this.arenas.remove(arena); + return true; + } + return false; + } + + /** + * Adds given list of arenas + * + * @param arenas + * arenas to add. + * @deprecated will be removed in 1.5.0; replaced by setArenas and addArenas + */ + @Deprecated + public void addLoadedArenas(final ArrayList<Arena> arenas) + { + this.arenas = arenas; + } + + /** + * Adds given list of arenas + * + * @param arenaList + * arenas to add. + */ + public void addArenas(final Iterable<Arena> arenaList) + { + for (final Arena arena : arenaList) + { + this.arenas.add(arena); + } + } + + /** + * Adds given list of arenas + * + * @param arenaList + * arenas to add. + */ + public void addArenas(final Arena... arenaList) + { + for (final Arena arena : arenaList) + { + this.arenas.add(arena); + } + } + + /** + * Replaces the arenas with given list of arenas + * + * @param arenaList + * arenas to set. + */ + public void setArenas(final Iterable<Arena> arenaList) + { + this.clearArenas(); + this.addArenas(arenaList); + } + + /** + * Replaces the arenas with given list of arenas + * + * @param arenaList + * arenas to set. + */ + public void setArenas(final Arena... arenaList) + { + this.clearArenas(); + this.addArenas(arenaList); + } + + /** + * Returns the achievement gui flag. + * + * @return achievement gui flag. + */ + public boolean isAchievementGuiEnabled() + { + return this.achievement_gui_enabled; + } + + /** + * Sets the achievement gui flag + * + * @param achievement_gui_enabled + * achievement gui flag. + */ + public void setAchievementGuiEnabled(final boolean achievement_gui_enabled) + { + this.achievement_gui_enabled = achievement_gui_enabled; + } + + /** + * Reloads all existing arenas. + */ + public void reloadAllArenas() + { + for (final Arena a : this.getArenas()) + { + if (a != null) + { + final String arenaname = a.getInternalName(); + final ArenaSetup s = this.arenaSetup; + a.init(Util.getSignLocationFromArena(this.plugin, arenaname), Util.getAllSpawns(this.plugin, arenaname), Util.getMainLobby(this.plugin), + Util.getComponentForArena(this.plugin, arenaname, "lobby"), s.getPlayerCount(this.plugin, arenaname, true), s.getPlayerCount(this.plugin, arenaname, false), + s.getArenaVIP(this.plugin, arenaname)); + if (a.isSuccessfullyInit()) + { + Util.updateSign(this.plugin, a); + } + } + } + } + + /** + * Reload arena by name + * + * @param arenaname + * arena to be reloaded + */ + public void reloadArena(final String arenaname) + { + if (Validator.isArenaValid(this.plugin, arenaname)) + { + final Arena a = this.getArenaByName(arenaname); + if (a != null) + { + final ArenaSetup s = this.arenaSetup; + a.init(Util.getSignLocationFromArena(this.plugin, arenaname), Util.getAllSpawns(this.plugin, arenaname), Util.getMainLobby(this.plugin), + Util.getComponentForArena(this.plugin, arenaname, "lobby"), s.getPlayerCount(this.plugin, arenaname, true), s.getPlayerCount(this.plugin, arenaname, false), + s.getArenaVIP(this.plugin, arenaname)); + } + } + } + + /** + * Checks if the player is contained in given arena. + * + * @param playername + * player name. + * @return {@code true} if the player is contained in arena. + */ + public boolean containsGlobalPlayer(final String playername) + { + return this.global_players.containsKey(playername); + } + + /** + * Checks if the player already lost. + * + * @param playername + * player name + * @return {@code true} if the player already lost. + */ + public boolean containsGlobalLost(final String playername) + { + return this.global_lost.containsKey(playername); + } + + /** + * Returns the arena by player name. + * + * @param playername + * player to be searched for. + * @return arena or {@code null} if the player is not present in any arena. + */ + public Arena getArenaByGlobalPlayer(final String playername) + { + if (this.containsGlobalPlayer(playername)) + { + return this.global_players.get(playername); + } + else + { + return null; + } + } + } diff --git a/API/src/main/java/com/comze_instancelabs/minigamesapi/PrivateUtil.java b/API/src/main/java/com/comze_instancelabs/minigamesapi/PrivateUtil.java new file mode 100644 index 00000000..a3d17c25 --- /dev/null +++ b/API/src/main/java/com/comze_instancelabs/minigamesapi/PrivateUtil.java @@ -0,0 +1,172 @@ +/* + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +package com.comze_instancelabs.minigamesapi; + +import java.io.EOFException; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.nio.channels.ClosedChannelException; +import java.util.ArrayList; +import java.util.logging.Level; + +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.block.Chest; +import org.bukkit.plugin.java.JavaPlugin; +import org.bukkit.util.io.BukkitObjectInputStream; + +import com.comze_instancelabs.minigamesapi.util.ArenaBlock; +import com.comze_instancelabs.minigamesapi.util.Util; + +/** + * Helper class that is invisible in public API + * + * <p> + * NOTE: THIS IS INTERNAL API. It can change from one build to another. Do never use this Util directly. + * </p> + * + * @author mepeisen + */ +public class PrivateUtil +{ + + /** + * Old arena regeneration, developed by instancelabs + * @param plugin + * @param arena + * @deprecated will be removed in 1.4.10 + */ + @Deprecated + public static void loadArenaFromFileSYNC(final JavaPlugin plugin, final Arena arena) + { + @SuppressWarnings("unused") + int failcount = 0; + final ArrayList<ArenaBlock> failedblocks = new ArrayList<>(); + + final File f = new File(plugin.getDataFolder() + "/" + arena.getInternalName()); //$NON-NLS-1$ + if (!f.exists()) + { + plugin.getLogger().warning("Could not find arena file for " + arena.getInternalName()); //$NON-NLS-1$ + arena.setArenaState(ArenaState.JOIN); + Bukkit.getScheduler().runTask(plugin, () -> Util.updateSign(plugin, arena)); + return; + } + FileInputStream fis = null; + BukkitObjectInputStream ois = null; + try + { + fis = new FileInputStream(f); + ois = new BukkitObjectInputStream(fis); + } + catch (final IOException ex) + { + MinigamesAPI.getAPI().getLogger().log(Level.WARNING, "Something is wrong with your arena file and the reset might not be successful. Also, you're using an outdated reset method.", ex); //$NON-NLS-1$ + return; + } + + try + { + while (true) + { + Object b = null; + try + { + b = ois.readObject(); + } + catch (@SuppressWarnings("unused") final EOFException ex) + { + MinigamesAPI.getAPI().getLogger().info("Finished restoring map for " + arena.getInternalName() + " with old reset method."); //$NON-NLS-1$//$NON-NLS-2$ + + arena.setArenaState(ArenaState.JOIN); + Bukkit.getScheduler().runTask(plugin, () -> Util.updateSign(plugin, arena)); + } + catch (final ClosedChannelException ex) + { + MinigamesAPI.getAPI().getLogger().log(Level.WARNING, "Something is wrong with your arena file and the reset might not be successful. Also, you're using an outdated reset method.", ex); //$NON-NLS-1$ + } + catch (final Exception e) + { + MinigamesAPI.getAPI().getLogger().log(Level.WARNING, "exception", e); + arena.setArenaState(ArenaState.JOIN); + Bukkit.getScheduler().runTask(plugin, () -> Util.updateSign(plugin, arena)); + } + + if (b != null) + { + final ArenaBlock ablock = (ArenaBlock) b; + try + { + final Block b_ = ablock.getBlock().getWorld().getBlockAt(ablock.getBlock().getLocation()); + if (!b_.getType().toString().equalsIgnoreCase(ablock.getMaterial().toString())) + { + b_.setType(ablock.getMaterial()); + b_.setData(ablock.getData()); + } + if (b_.getType() == Material.CHEST) + { + ((Chest) b_.getState()).getInventory().setContents(ablock.getInventory()); + ((Chest) b_.getState()).update(); + } + } + catch (@SuppressWarnings("unused") final IllegalStateException ex) + { + failcount += 1; + failedblocks.add(ablock); + } + } + else + { + break; + } + } + + } + catch (final Exception e) + { + MinigamesAPI.getAPI().getLogger().log(Level.WARNING, "exception", e); + } + + try + { + ois.close(); + } + catch (final IOException e) + { + MinigamesAPI.getAPI().getLogger().log(Level.WARNING, "exception", e); + } + + Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(MinigamesAPI.getAPI(), () -> { + for (final ArenaBlock ablock : failedblocks) + { + final Block b_ = ablock.getBlock().getWorld().getBlockAt(ablock.getBlock().getLocation()); + if (!b_.getType().toString().equalsIgnoreCase(ablock.getMaterial().toString())) + { + b_.setType(ablock.getMaterial()); + b_.setData(ablock.getData()); + } + if (b_.getType() == Material.CHEST) + { + ((Chest) b_.getState()).getInventory().setContents(ablock.getInventory()); + ((Chest) b_.getState()).update(); + } + } + }, 40L); + MinigamesAPI.getAPI().getLogger().info("Successfully finished!"); //$NON-NLS-1$ + } + +} diff --git a/API/src/main/java/com/comze_instancelabs/minigamesapi/Rewards.java b/API/src/main/java/com/comze_instancelabs/minigamesapi/Rewards.java index 9578517c..647cec9b 100644 --- a/API/src/main/java/com/comze_instancelabs/minigamesapi/Rewards.java +++ b/API/src/main/java/com/comze_instancelabs/minigamesapi/Rewards.java @@ -1,6 +1,21 @@ +/* + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ package com.comze_instancelabs.minigamesapi; import java.util.ArrayList; +import java.util.logging.Level; import org.bukkit.Bukkit; import org.bukkit.entity.Player; @@ -10,250 +25,365 @@ import com.comze_instancelabs.minigamesapi.util.Util; import com.comze_instancelabs.minigamesapi.util.Validator; -public class Rewards { - - private JavaPlugin plugin = null; - - private boolean economyrewards; - private boolean itemrewards; - private boolean commandrewards; - private boolean kill_economyrewards; - private boolean kill_commandrewards; - private boolean participation_economyrewards; - private boolean participation_commandrewards; - - private int econ_reward = 0; - private int kill_econ_reward = 0; - private int participation_econ_reward = 0; - private String command = ""; - private String kill_command = ""; - private String participation_command = ""; - private ItemStack[] items = null; - - public Rewards(JavaPlugin plugin) { - this.plugin = plugin; - reloadVariables(); - - if (!MinigamesAPI.economy) { - economyrewards = false; - kill_economyrewards = false; - participation_economyrewards = false; - } - } - - public void reloadVariables() { - economyrewards = plugin.getConfig().getBoolean("config.rewards.economy"); - itemrewards = plugin.getConfig().getBoolean("config.rewards.item_reward"); - commandrewards = plugin.getConfig().getBoolean("config.rewards.command_reward"); - kill_economyrewards = plugin.getConfig().getBoolean("config.rewards.economy_for_kills"); - kill_commandrewards = plugin.getConfig().getBoolean("config.rewards.command_reward_for_kills"); - participation_economyrewards = plugin.getConfig().getBoolean("config.rewards.economy_for_participation"); - participation_commandrewards = plugin.getConfig().getBoolean("config.rewards.command_reward_for_participation"); - - econ_reward = plugin.getConfig().getInt("config.rewards.economy_reward"); - command = plugin.getConfig().getString("config.rewards.command"); - items = Util.parseItems(plugin.getConfig().getString("config.rewards.item_reward_ids")).toArray(new ItemStack[0]); - kill_econ_reward = plugin.getConfig().getInt("config.rewards.economy_reward_for_kills"); - kill_command = plugin.getConfig().getString("config.rewards.command_for_kills"); - participation_econ_reward = plugin.getConfig().getInt("config.rewards.economy_reward_for_participation"); - participation_command = plugin.getConfig().getString("config.rewards.command_for_participation"); - } - - /** - * Give all win rewards to players who won the game - * - * @param arena - * Arena - */ - public void giveRewardsToWinners(Arena arena) { - for (String p_ : arena.getAllPlayers()) { - giveWinReward(p_, arena); - } - } - - @Deprecated - public void giveReward(String p_) { - if (Validator.isPlayerOnline(p_)) { - Player p = Bukkit.getPlayer(p_); - - if (economyrewards) { - MinigamesAPI.getAPI().econ.depositPlayer(p.getName(), econ_reward); - } - - MinigamesAPI.getAPI().getPluginInstance(plugin).getStatsInstance().win(p_, 10); - } - } - - /** - * Give a player a kill reward - * - * @param p_ - * Playername - * @param reward - * Amount of statistics points the player gets - */ - public void giveKillReward(String p_) { - if (Validator.isPlayerOnline(p_)) { - PluginInstance pli = MinigamesAPI.getAPI().getPluginInstance(plugin); - Player p = Bukkit.getPlayer(p_); - - if (kill_economyrewards && MinigamesAPI.economy) { - MinigamesAPI.getAPI().econ.depositPlayer(p.getName(), kill_econ_reward); - } - if (kill_commandrewards) { - Bukkit.dispatchCommand(Bukkit.getConsoleSender(), kill_command.replaceAll("<player>", p_)); - } - - pli.getStatsInstance().addPoints(p_, pli.getStatsInstance().stats_kill_points); - pli.getStatsInstance().addKill(p_); - pli.getSQLInstance().updateWinnerStats(p, pli.getStatsInstance().stats_kill_points, false); - } - } - - @Deprecated - public void giveKillReward(String p_, int reward) { - this.giveKillReward(p_); - } - - /** - * Gives a player an achievement reward - * - * @param p_ - * Playername - * @param econ - * Whether economy rewards are enabled - * @param command - * Whether command rewards are enabled - * @param money_reward - * Amount of money to reward if economy rewards are enabled - * @param cmd - * Command to execute if command rewards are enabled - */ - public void giveAchievementReward(String p_, boolean econ, boolean command, int money_reward, String cmd) { - if (Validator.isPlayerOnline(p_)) { - Player p = Bukkit.getPlayer(p_); - - if (econ && MinigamesAPI.economy) { - MinigamesAPI.getAPI().econ.depositPlayer(p.getName(), money_reward); - } - if (command) { - Bukkit.dispatchCommand(Bukkit.getConsoleSender(), cmd.replaceAll("<player>", p_)); - } - } - } - - public void giveWinReward(String p_, Arena a) { - giveWinReward(p_, a, 1); - } - - public void giveWinReward(String p_, Arena a, int global_multiplier) { - giveWinReward(p_, a, a.getAllPlayers(), global_multiplier); - } - - /** - * Gives all rewards to a player who won and sends reward messages/win broadcasts - * - * @param p_ - * Playername - * @param a - * Arena - * @param players - * Optional array of players to send win broadcast to - * @param global_multiplier - * Money reward multiplier (default: 1) - */ - public void giveWinReward(String p_, Arena a, ArrayList<String> players, int global_multiplier) { - if (Validator.isPlayerOnline(p_)) { - PluginInstance pli = MinigamesAPI.getAPI().getPluginInstance(plugin); - final Player p = Bukkit.getPlayer(p_); - if (!pli.global_lost.containsKey(p_)) { - String received_rewards_msg = pli.getMessagesConfig().you_received_rewards; - if (economyrewards && MinigamesAPI.economy) { - int multiplier = global_multiplier; - if (pli.getShopHandler().hasItemBought(p_, "coin_boost2_solo")) { - multiplier = 2; - } - if (pli.getShopHandler().hasItemBought(p_, "coin_boost3_solo")) { - multiplier = 3; - } - MinigamesAPI.getAPI().econ.depositPlayer(p.getName(), econ_reward * multiplier); - received_rewards_msg = received_rewards_msg.replaceAll("<economyreward>", Integer.toString(econ_reward * multiplier) + " " + MinigamesAPI.econ.currencyNamePlural()); - } else { - received_rewards_msg = received_rewards_msg.replaceAll("<economyreward>", ""); - } - if (itemrewards) { - p.getInventory().addItem(items); - p.updateInventory(); - String items_str = ""; - for (ItemStack i : items) { - items_str += Integer.toString(i.getAmount()) + " " + Character.toUpperCase(i.getType().toString().charAt(0)) + i.getType().toString().toLowerCase().substring(1) + ", "; - } - if (items_str.length() > 2) { - items_str = items_str.substring(0, items_str.length() - 2); - } - if (economyrewards && MinigamesAPI.economy) { - received_rewards_msg += pli.getMessagesConfig().you_received_rewards_2; - received_rewards_msg += pli.getMessagesConfig().you_received_rewards_3.replaceAll("<itemreward>", items_str); - } else { - received_rewards_msg += pli.getMessagesConfig().you_received_rewards_3.replaceAll("<itemreward>", items_str); - } - } else { - received_rewards_msg += pli.getMessagesConfig().you_received_rewards_3.replaceAll("<itemreward>", ""); - } - if (commandrewards) { - Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command.replaceAll("<player>", p_)); - } - - pli.getStatsInstance().win(p_, pli.getStatsInstance().stats_win_points); - - try { - if (plugin.getConfig().getBoolean("config.broadcast_win")) { - String msgs[] = pli.getMessagesConfig().server_broadcast_winner.replaceAll("<player>", p_).replaceAll("<arena>", a.getInternalName()).split(";"); - for (String msg : msgs) { - Bukkit.getServer().broadcastMessage(msg); - } - } else { - String msgs[] = pli.getMessagesConfig().server_broadcast_winner.replaceAll("<player>", p_).replaceAll("<arena>", a.getInternalName()).split(";"); - for (String playername : players) { - if (Validator.isPlayerOnline(playername)) { - Bukkit.getPlayer(playername).sendMessage(msgs); - } - } - } - } catch (Exception e) { - System.out.println("Could not find arena for broadcast. " + e.getMessage()); - } - - Util.sendMessage(plugin, p, pli.getMessagesConfig().you_won); - Util.sendMessage(plugin, p, received_rewards_msg); - if (plugin.getConfig().getBoolean("config.effects.1_8_titles") && MinigamesAPI.getAPI().version.startsWith("v1_8")) { - Effects.playTitle(p, pli.getMessagesConfig().you_won, 0); - } - - // Participation Rewards - if (participation_economyrewards) { - MinigamesAPI.getAPI().econ.depositPlayer(p.getName(), participation_econ_reward); - Util.sendMessage(plugin, p, pli.getMessagesConfig().you_got_a_participation_reward.replaceAll("<economyreward>", Integer.toString(participation_econ_reward) + " " + MinigamesAPI.econ.currencyNamePlural())); - } - if (participation_commandrewards) { - Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command.replaceAll("<player>", p_)); - } - - if (plugin.getConfig().getBoolean("config.spawn_fireworks_for_winners")) { - Bukkit.getScheduler().runTaskLater(plugin, new Runnable() { - public void run() { - Util.spawnFirework(p); - } - }, 20L); - } - } else { - Util.sendMessage(plugin, p, pli.getMessagesConfig().you_lost); - if (plugin.getConfig().getBoolean("config.effects.1_8_titles") && MinigamesAPI.getAPI().version.startsWith("v1_8")) { - Effects.playTitle(p, pli.getMessagesConfig().you_lost, 0); - } - MinigamesAPI.getAPI().getPluginInstance(plugin).getStatsInstance().lose(p_); - } - } - } - +/** + * Rewards helper for minigames. + * + * @author instancelabs + */ +public class Rewards +{ + + /** minigame java plugin. */ + private JavaPlugin plugin = null; + + /** {@code true} for activated economy rewards. */ + private boolean economyrewards; + /** {@code true} for activated item rewards. */ + private boolean itemrewards; + /** {@code true} for activated command rewards. */ + private boolean commandrewards; + /** {@code true} for activated kill economy rewards. */ + private boolean kill_economyrewards; + /** {@code true} for activated kill command rewards. */ + private boolean kill_commandrewards; + /** {@code true} for activated participation economy rewards. */ + private boolean participation_economyrewards; + /** {@code true} for activated participation command rewards. */ + private boolean participation_commandrewards; + + /** money to give for winning. */ + private int econ_reward = 0; + /** money to give per kill. */ + private int kill_econ_reward = 0; + /** money to give for participation. */ + private int participation_econ_reward = 0; + /** command to execute for winning. */ + private String command = ""; //$NON-NLS-1$ + /** command to execute per kill. */ + private String kill_command = ""; //$NON-NLS-1$ + /** command to execute for participation. */ + private String participation_command = ""; //$NON-NLS-1$ + /** items to reward for winning. */ + private ItemStack[] items = null; + + /** + * Constructor to create a rewards helper. + * + * @param plugin + * minigame java plugin. + */ + public Rewards(final JavaPlugin plugin) + { + this.plugin = plugin; + this.reloadVariables(); + + if (!MinigamesAPI.getAPI().economyAvailable()) + { + this.economyrewards = false; + this.kill_economyrewards = false; + this.participation_economyrewards = false; + } + } + + /** + * Reload variables from config. + */ + public void reloadVariables() + { + this.economyrewards = this.plugin.getConfig().getBoolean(ArenaConfigStrings.CONFIG_REWARDS_ECONOMY); + this.itemrewards = this.plugin.getConfig().getBoolean(ArenaConfigStrings.CONFIG_REWARDS_ITEM_REWARD); + this.commandrewards = this.plugin.getConfig().getBoolean(ArenaConfigStrings.CONFIG_REWARDS_COMMAND_REWARD); + this.kill_economyrewards = this.plugin.getConfig().getBoolean(ArenaConfigStrings.CONFIG_REWARDS_ECONOMY_FOR_KILLS); + this.kill_commandrewards = this.plugin.getConfig().getBoolean(ArenaConfigStrings.CONFIG_REWARDS_COMMAND_REWARD_FOR_KILLS); + this.participation_economyrewards = this.plugin.getConfig().getBoolean(ArenaConfigStrings.CONFIG_REWARDS_ECONOMY_FOR_PARTICIPATION); + this.participation_commandrewards = this.plugin.getConfig().getBoolean(ArenaConfigStrings.CONFIG_REWARDS_COMMAND_REWARD_FOR_PARTICIPATION); + + this.econ_reward = this.plugin.getConfig().getInt(ArenaConfigStrings.CONFIG_REWARDS_ECONOMY_REWARD); + this.command = this.plugin.getConfig().getString(ArenaConfigStrings.CONFIG_REWARDS_COMMAND); + this.items = Util.parseItems(this.plugin.getConfig().getString(ArenaConfigStrings.CONFIG_REWARDS_ITEM_REWARD_IDS)).toArray(new ItemStack[0]); + this.kill_econ_reward = this.plugin.getConfig().getInt(ArenaConfigStrings.CONFIG_REWARDS_ECONOMY_REWARD_FOR_KILLS); + this.kill_command = this.plugin.getConfig().getString(ArenaConfigStrings.CONFIG_REWARDS_COMMAND_FOR_KILLS); + this.participation_econ_reward = this.plugin.getConfig().getInt(ArenaConfigStrings.CONFIG_REWARDS_ECONOMY_REWARD_FOR_PARTICIPATION); + this.participation_command = this.plugin.getConfig().getString(ArenaConfigStrings.CONFIG_REWARDS_COMMAND_FOR_PARTICIPATION); + } + + /** + * Give all win rewards to players who won the game + * + * @param arena + * Arena + */ + public void giveRewardsToWinners(final Arena arena) + { + for (final String p_ : arena.getAllPlayers()) + { + this.giveWinReward(p_, arena); + } + } + + /** + * Give reward for given player. + * + * @param p_ + * player name + * @deprecated will be removed in 1.5.0 + */ + @Deprecated + public void giveReward(final String p_) + { + if (Validator.isPlayerOnline(p_)) + { + final Player p = Bukkit.getPlayer(p_); + + if (this.economyrewards) + { + MinigamesAPI.getAPI(); + MinigamesAPI.econ.depositPlayer(p.getName(), this.econ_reward); + } + + MinigamesAPI.getAPI().getPluginInstance(this.plugin).getStatsInstance().win(p_, 10); + } + } + + /** + * Give a player a kill reward + * + * @param p_ + * Playername + */ + public void giveKillReward(final String p_) + { + if (Validator.isPlayerOnline(p_)) + { + final PluginInstance pli = MinigamesAPI.getAPI().getPluginInstance(this.plugin); + final Player p = Bukkit.getPlayer(p_); + + if (this.kill_economyrewards && MinigamesAPI.getAPI().economyAvailable()) + { + MinigamesAPI.getAPI(); + MinigamesAPI.econ.depositPlayer(p.getName(), this.kill_econ_reward); + } + if (this.kill_commandrewards) + { + Bukkit.dispatchCommand(Bukkit.getConsoleSender(), this.kill_command.replaceAll("<player>", p_)); + } + + pli.getStatsInstance().addPoints(p_, pli.getStatsInstance().stats_kill_points); + pli.getStatsInstance().addKill(p_); + pli.getSQLInstance().updateWinnerStats(p, pli.getStatsInstance().stats_kill_points, false); + } + } + + /** + * Give a player a kill reward + * + * @param p_ + * Playername + * @param reward + * Amount of statistics points the player gets; will be ignored + * @deprecated will be removed in 1.5.0; replaced by {@link #giveKillReward(String)} + */ + @Deprecated + public void giveKillReward(final String p_, final int reward) + { + this.giveKillReward(p_); + } + + /** + * Gives a player an achievement reward + * + * @param p_ + * Playername + * @param econ + * Whether economy rewards are enabled + * @param isCommand + * Whether command rewards are enabled + * @param money_reward + * Amount of money to reward if economy rewards are enabled + * @param cmd + * Command to execute if command rewards are enabled + */ + public void giveAchievementReward(final String p_, final boolean econ, final boolean isCommand, final int money_reward, final String cmd) + { + if (Validator.isPlayerOnline(p_)) + { + final Player p = Bukkit.getPlayer(p_); + + if (econ && MinigamesAPI.getAPI().economyAvailable()) + { + MinigamesAPI.getAPI(); + MinigamesAPI.econ.depositPlayer(p.getName(), money_reward); + } + if (isCommand) + { + Bukkit.dispatchCommand(Bukkit.getConsoleSender(), cmd.replaceAll("<player>", p_)); + } + } + } + + /** + * Give win rewards to given player + * + * @param p_ + * player name + * @param a + * Arena + */ + private void giveWinReward(final String p_, final Arena a) + { + this.giveWinReward(p_, a, 1); + } + + /** + * Give all win rewards to players who won the game + * + * @param p_ + * player name + * @param a + * Arena + * @param global_multiplier + */ + private void giveWinReward(final String p_, final Arena a, final int global_multiplier) + { + this.giveWinReward(p_, a, a.getAllPlayers(), global_multiplier); + } + + /** + * Gives all rewards to a player who won and sends reward messages/win broadcasts + * + * @param p_ + * Playername + * @param a + * Arena + * @param players + * Optional array of players to send win broadcast to + * @param global_multiplier + * Money reward multiplier (default: 1) + */ + public void giveWinReward(final String p_, final Arena a, final ArrayList<String> players, final int global_multiplier) + { + if (Validator.isPlayerOnline(p_)) + { + final PluginInstance pli = MinigamesAPI.getAPI().getPluginInstance(this.plugin); + final Player p = Bukkit.getPlayer(p_); + if (!pli.global_lost.containsKey(p_)) + { + String received_rewards_msg = pli.getMessagesConfig().you_received_rewards; + if (this.economyrewards && MinigamesAPI.getAPI().economyAvailable()) + { + int multiplier = global_multiplier; + if (pli.getShopHandler().hasItemBought(p_, "coin_boost2_solo")) + { + multiplier = 2; + } + if (pli.getShopHandler().hasItemBought(p_, "coin_boost3_solo")) + { + multiplier = 3; + } + MinigamesAPI.getAPI(); + MinigamesAPI.econ.depositPlayer(p.getName(), this.econ_reward * multiplier); + received_rewards_msg = received_rewards_msg.replaceAll("<economyreward>", Integer.toString(this.econ_reward * multiplier) + " " + MinigamesAPI.econ.currencyNamePlural()); + } + else + { + received_rewards_msg = received_rewards_msg.replaceAll("<economyreward>", ""); + } + if (this.itemrewards) + { + p.getInventory().addItem(this.items); + p.updateInventory(); + String items_str = ""; + for (final ItemStack i : this.items) + { + items_str += Integer.toString(i.getAmount()) + " " + Character.toUpperCase(i.getType().toString().charAt(0)) + i.getType().toString().toLowerCase().substring(1) + ", "; + } + if (items_str.length() > 2) + { + items_str = items_str.substring(0, items_str.length() - 2); + } + if (this.economyrewards && MinigamesAPI.getAPI().economyAvailable()) + { + received_rewards_msg += pli.getMessagesConfig().you_received_rewards_2; + received_rewards_msg += pli.getMessagesConfig().you_received_rewards_3.replaceAll("<itemreward>", items_str); + } + else + { + received_rewards_msg += pli.getMessagesConfig().you_received_rewards_3.replaceAll("<itemreward>", items_str); + } + } + else + { + received_rewards_msg += pli.getMessagesConfig().you_received_rewards_3.replaceAll("<itemreward>", ""); + } + if (this.commandrewards) + { + Bukkit.dispatchCommand(Bukkit.getConsoleSender(), this.command.replaceAll("<player>", p_)); + } + + pli.getStatsInstance().win(p_, pli.getStatsInstance().stats_win_points); + + try + { + if (this.plugin.getConfig().getBoolean(ArenaConfigStrings.CONFIG_BROADCAST_WIN)) + { + final String msgs[] = pli.getMessagesConfig().server_broadcast_winner.replaceAll("<player>", p_).replaceAll("<arena>", a.getInternalName()).split(";"); + for (final String msg : msgs) + { + Bukkit.getServer().broadcastMessage(msg); + } + } + else + { + final String msgs[] = pli.getMessagesConfig().server_broadcast_winner.replaceAll("<player>", p_).replaceAll("<arena>", a.getInternalName()).split(";"); + for (final String playername : players) + { + if (Validator.isPlayerOnline(playername)) + { + Bukkit.getPlayer(playername).sendMessage(msgs); + } + } + } + } + catch (final Exception e) + { + this.plugin.getLogger().log(Level.WARNING, "Could not find arena for broadcast. ", e); + } + + Util.sendMessage(this.plugin, p, pli.getMessagesConfig().you_won); + Util.sendMessage(this.plugin, p, received_rewards_msg); + if (this.plugin.getConfig().getBoolean(ArenaConfigStrings.CONFIG_EFFECTS_1_8_TITLES) && MinigamesAPI.SERVER_VERSION.isAfter(MinecraftVersionsType.V1_7)) + { + Effects.playTitle(p, pli.getMessagesConfig().you_won, 0); + } + + // Participation Rewards + if (this.participation_economyrewards) + { + MinigamesAPI.getAPI(); + MinigamesAPI.econ.depositPlayer(p.getName(), this.participation_econ_reward); + Util.sendMessage(this.plugin, p, pli.getMessagesConfig().you_got_a_participation_reward.replaceAll("<economyreward>", + Integer.toString(this.participation_econ_reward) + " " + MinigamesAPI.econ.currencyNamePlural())); + } + if (this.participation_commandrewards) + { + Bukkit.dispatchCommand(Bukkit.getConsoleSender(), this.participation_command.replaceAll("<player>", p_)); + } + + if (this.plugin.getConfig().getBoolean(ArenaConfigStrings.CONFIG_SPAWN_FIREWORKS_FOR_WINNERS)) + { + Bukkit.getScheduler().runTaskLater(this.plugin, () -> Util.spawnFirework(p), 20L); + } + } + else + { + Util.sendMessage(this.plugin, p, pli.getMessagesConfig().you_lost); + if (this.plugin.getConfig().getBoolean(ArenaConfigStrings.CONFIG_EFFECTS_1_8_TITLES) && MinigamesAPI.SERVER_VERSION.isAfter(MinecraftVersionsType.V1_7)) + { + Effects.playTitle(p, pli.getMessagesConfig().you_lost, 0); + } + MinigamesAPI.getAPI().getPluginInstance(this.plugin).getStatsInstance().lose(p_); + } + } + } + } diff --git a/API/src/main/java/com/comze_instancelabs/minigamesapi/Shop.java b/API/src/main/java/com/comze_instancelabs/minigamesapi/Shop.java index 3c12e8a7..68ab493e 100644 --- a/API/src/main/java/com/comze_instancelabs/minigamesapi/Shop.java +++ b/API/src/main/java/com/comze_instancelabs/minigamesapi/Shop.java @@ -1,10 +1,22 @@ +/* + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ package com.comze_instancelabs.minigamesapi; import java.util.HashMap; import java.util.LinkedHashMap; -import net.milkbowl.vault.economy.EconomyResponse; - import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.configuration.file.FileConfiguration; @@ -17,169 +29,222 @@ import com.comze_instancelabs.minigamesapi.util.ShopItem; import com.comze_instancelabs.minigamesapi.util.Util; -public class Shop { - - // Allows buying extra stuff for the games like traits, coin boosters, extra weapons - // You can change whether the particular item is persistent or just for one game - - JavaPlugin plugin; - PluginInstance pli; - public HashMap<String, IconMenu> lasticonm = new HashMap<String, IconMenu>(); - public LinkedHashMap<String, ShopItem> shopitems = new LinkedHashMap<String, ShopItem>(); - - public Shop(PluginInstance pli, JavaPlugin plugin) { - this.plugin = plugin; - this.pli = pli; - } - - public void openGUI(final String p) { - IconMenu iconm; - int mincount = pli.getAClasses().keySet().size(); - if (lasticonm.containsKey(p)) { - iconm = lasticonm.get(p); - } else { - iconm = new IconMenu(pli.getMessagesConfig().shop_item, (9 * plugin.getConfig().getInt("config.GUI.shop_gui_rows") > mincount - 1) ? 9 * plugin.getConfig().getInt("config.GUI.shop_gui_rows") : Math.round(mincount / 9) * 9 + 9, new IconMenu.OptionClickEventHandler() { - @Override - public void onOptionClick(IconMenu.OptionClickEvent event) { - if (event.getPlayer().getName().equalsIgnoreCase(p)) { - if (pli.global_players.containsKey(p)) { - if (pli.getArenas().contains(pli.global_players.get(p))) { - String d = event.getName(); - Player p = event.getPlayer(); - buy(p, d); - } - } - } - event.setWillClose(true); - } - }, plugin); - - ShopConfig shopConfig = pli.getShopConfig(); - int c = 0; - for (String ac : shopitems.keySet()) { - ShopItem ac_ = shopitems.get(ac); - if (ac_.isEnabled()) { - int slot = c; - if (pli.getShopConfig().getConfig().isSet("config.shop_items." + ac_.getInternalName() + ".slot")) { - slot = pli.getShopConfig().getConfig().getInt("config.shop_items." + ac_.getInternalName() + ".slot"); - if (slot < 0 || slot > iconm.getSize() - 1) { - slot = c; - } - } - String color = ChatColor.GREEN + ""; - if (shopConfig.getConfig().isSet("players.bought." + p + "." + ac_.getInternalName())) { - color = ChatColor.RED + ""; - } - iconm.setOption(slot, ac_.getIcon().clone(), color + ac_.getName(), pli.getShopConfig().getConfig().getString("config.shop_items." + ac_.getInternalName() + ".lore").split(";")); - c++; - } - } - } - - iconm.open(Bukkit.getPlayerExact(p)); - lasticonm.put(p, iconm); - } - - public void loadShopItems() { - Bukkit.getScheduler().runTaskLater(plugin, new Runnable() { - public void run() { - FileConfiguration config = pli.getShopConfig().getConfig(); - if (config.isSet("config.shop_items")) { - for (String aclass : config.getConfigurationSection("config.shop_items.").getKeys(false)) { - ShopItem n = new ShopItem(plugin, config.getString("config.shop_items." + aclass + ".name"), aclass, config.isSet("config.shop_items." + aclass + ".enabled") ? config.getBoolean("config.shop_items." + aclass + ".enabled") : true, Util.parseItems(config.getString("config.shop_items." + aclass + ".items")), Util.parseItems(config.getString("config.shop_items." + aclass + ".icon")).get(0)); - shopitems.put(aclass, n); - } - } - } - }, 20L); - } - - /*** - * Buy a shop item - * - * @param p - * Player who buys it - * @param item_displayname - * Displayname of the item - * @return - */ - public boolean buy(Player p, String item_displayname) { - for (String ac : shopitems.keySet()) { - ShopItem ac_ = shopitems.get(ac); - if (ac_.getName().equalsIgnoreCase(ChatColor.stripColor(item_displayname))) { - takeMoney(p, ac_.getInternalName()); - // true -> player has item already or just bought it successfully - return true; - } - } - return false; - } - - public boolean buyByInternalName(Player p, String item_name) { - for (String ac : shopitems.keySet()) { - ShopItem ac_ = shopitems.get(ac); - if (ac_.getInternalName().equalsIgnoreCase(ChatColor.stripColor(item_name))) { - takeMoney(p, ac_.getInternalName()); - // true -> player has item already or just bought it successfully - return true; - } - } - return false; - } - - public boolean hasItemBought(String p, String item) { - return pli.getShopConfig().getConfig().isSet("players.bought." + p + "." + item); - } - - public boolean requiresMoney(String item) { - return pli.getShopConfig().getConfig().getBoolean("config.shop_items." + item + ".requires_money"); - } - - public boolean takeMoney(Player p, String item) { - if (!MinigamesAPI.getAPI().economy) { - plugin.getLogger().warning("Economy is turned OFF. Turn it ON in the config."); - return false; - } - if (!requiresMoney(item)) { - return false; - } - if (MinigamesAPI.economy) { - ShopConfig shopConfig = pli.getShopConfig(); - if (!shopConfig.getConfig().isSet("players.bought." + p.getName() + "." + item)) { - int money = shopConfig.getConfig().getInt("config.shop_items." + item + ".money_amount"); - if (MinigamesAPI.getAPI().econ.getBalance(p.getName()) >= money) { - EconomyResponse r = MinigamesAPI.getAPI().econ.withdrawPlayer(p.getName(), money); - if (!r.transactionSuccess()) { - p.sendMessage(String.format("An error occured: %s", r.errorMessage)); - return false; - } - shopConfig.getConfig().set("players.bought." + p.getName() + "." + item, true); - shopConfig.saveConfig(); - p.sendMessage(pli.getMessagesConfig().successfully_bought_shopitem.replaceAll("<shopitem>", shopitems.get(item).getName()).replaceAll("<money>", Integer.toString(money))); - } else { - p.sendMessage(pli.getMessagesConfig().not_enough_money); - return false; - } - } else { - p.sendMessage(pli.getMessagesConfig().already_bought_shopitem.replaceAll("<shopitem>", shopitems.get(item).getName())); - return true; - } - return true; - } else { - return false; - } - - } - - public void giveShopItems(Player p) { - for (ShopItem ac : shopitems.values()) { - if (ac.usesItems(pli)) { - for (ItemStack i : ac.getItems()) { - p.getInventory().addItem(i); - } - p.updateInventory(); - } - } - } +import net.milkbowl.vault.economy.EconomyResponse; +/** + * The shop gui. + * + * @author instancelabs + */ +public class Shop +{ + + // Allows buying extra stuff for the games like traits, coin boosters, extra weapons + // You can change whether the particular item is persistent or just for one game + + JavaPlugin plugin; + PluginInstance pli; + public HashMap<String, IconMenu> lasticonm = new HashMap<>(); + public LinkedHashMap<String, ShopItem> shopitems = new LinkedHashMap<>(); + + public Shop(final PluginInstance pli, final JavaPlugin plugin) + { + this.plugin = plugin; + this.pli = pli; + } + + public void openGUI(final String p) + { + IconMenu iconm; + final int mincount = this.pli.getAClasses().keySet().size(); + if (this.lasticonm.containsKey(p)) + { + iconm = this.lasticonm.get(p); + } + else + { + iconm = new IconMenu(this.pli.getMessagesConfig().shop_item, + (9 * this.plugin.getConfig().getInt(ArenaConfigStrings.CONFIG_SHOP_GUI_ROWS) > mincount - 1) ? 9 * this.plugin.getConfig().getInt(ArenaConfigStrings.CONFIG_SHOP_GUI_ROWS) : Math.round(mincount / 9) * 9 + 9, + event -> { + if (event.getPlayer().getName().equalsIgnoreCase(p)) + { + if (Shop.this.pli.global_players.containsKey(p)) + { + if (Shop.this.pli.getArenas().contains(Shop.this.pli.global_players.get(p))) + { + final String d = event.getName(); + final Player p1 = event.getPlayer(); + Shop.this.buy(p1, d); + } + } + } + event.setWillClose(true); + }, this.plugin); + + final ShopConfig shopConfig = this.pli.getShopConfig(); + int c = 0; + for (final String ac : this.shopitems.keySet()) + { + final ShopItem ac_ = this.shopitems.get(ac); + if (ac_.isEnabled()) + { + int slot = c; + if (this.pli.getShopConfig().getConfig().isSet("config.shop_items." + ac_.getInternalName() + ".slot")) + { + slot = this.pli.getShopConfig().getConfig().getInt("config.shop_items." + ac_.getInternalName() + ".slot"); + if (slot < 0 || slot > iconm.getSize() - 1) + { + slot = c; + } + } + String color = ChatColor.GREEN + ""; + if (shopConfig.getConfig().isSet("players.bought." + p + "." + ac_.getInternalName())) + { + color = ChatColor.RED + ""; + } + iconm.setOption(slot, ac_.getIcon().clone(), color + ac_.getName(), + this.pli.getShopConfig().getConfig().getString("config.shop_items." + ac_.getInternalName() + ".lore").split(";")); + c++; + } + } + } + + iconm.open(Bukkit.getPlayerExact(p)); + this.lasticonm.put(p, iconm); + } + + public void loadShopItems() + { + Bukkit.getScheduler().runTaskLater(this.plugin, () -> { + final FileConfiguration config = Shop.this.pli.getShopConfig().getConfig(); + if (config.isSet("config.shop_items")) + { + for (final String aclass : config.getConfigurationSection("config.shop_items.").getKeys(false)) + { + final ShopItem n = new ShopItem(Shop.this.plugin, config.getString("config.shop_items." + aclass + ".name"), aclass, + config.isSet("config.shop_items." + aclass + ".enabled") ? config.getBoolean("config.shop_items." + aclass + ".enabled") : true, + Util.parseItems(config.getString("config.shop_items." + aclass + ".items")), Util.parseItems(config.getString("config.shop_items." + aclass + ".icon")).get(0)); + Shop.this.shopitems.put(aclass, n); + } + } + }, 20L); + } + + /*** + * Buy a shop item + * + * @param p + * Player who buys it + * @param item_displayname + * Displayname of the item + * @return + */ + public boolean buy(final Player p, final String item_displayname) + { + for (final String ac : this.shopitems.keySet()) + { + final ShopItem ac_ = this.shopitems.get(ac); + if (ac_.getName().equalsIgnoreCase(ChatColor.stripColor(item_displayname))) + { + this.takeMoney(p, ac_.getInternalName()); + // true -> player has item already or just bought it successfully + return true; + } + } + return false; + } + + public boolean buyByInternalName(final Player p, final String item_name) + { + for (final String ac : this.shopitems.keySet()) + { + final ShopItem ac_ = this.shopitems.get(ac); + if (ac_.getInternalName().equalsIgnoreCase(ChatColor.stripColor(item_name))) + { + this.takeMoney(p, ac_.getInternalName()); + // true -> player has item already or just bought it successfully + return true; + } + } + return false; + } + + public boolean hasItemBought(final String p, final String item) + { + return this.pli.getShopConfig().getConfig().isSet("players.bought." + p + "." + item); + } + + public boolean requiresMoney(final String item) + { + return this.pli.getShopConfig().getConfig().getBoolean("config.shop_items." + item + ".requires_money"); + } + + public boolean takeMoney(final Player p, final String item) + { + MinigamesAPI.getAPI(); + if (!MinigamesAPI.getAPI().economyAvailable()) + { + this.plugin.getLogger().warning("Economy is turned OFF. Turn it ON in the config."); + return false; + } + if (!this.requiresMoney(item)) + { + return false; + } + if (MinigamesAPI.getAPI().economyAvailable()) + { + final ShopConfig shopConfig = this.pli.getShopConfig(); + if (!shopConfig.getConfig().isSet("players.bought." + p.getName() + "." + item)) + { + final int money = shopConfig.getConfig().getInt("config.shop_items." + item + ".money_amount"); + MinigamesAPI.getAPI(); + if (MinigamesAPI.econ.getBalance(p.getName()) >= money) + { + MinigamesAPI.getAPI(); + final EconomyResponse r = MinigamesAPI.econ.withdrawPlayer(p.getName(), money); + if (!r.transactionSuccess()) + { + p.sendMessage(String.format("An error occured: %s", r.errorMessage)); + return false; + } + shopConfig.getConfig().set("players.bought." + p.getName() + "." + item, true); + shopConfig.saveConfig(); + p.sendMessage( + this.pli.getMessagesConfig().successfully_bought_shopitem.replaceAll("<shopitem>", this.shopitems.get(item).getName()).replaceAll("<money>", Integer.toString(money))); + } + else + { + p.sendMessage(this.pli.getMessagesConfig().not_enough_money); + return false; + } + } + else + { + p.sendMessage(this.pli.getMessagesConfig().already_bought_shopitem.replaceAll("<shopitem>", this.shopitems.get(item).getName())); + return true; + } + return true; + } + else + { + return false; + } + + } + + public void giveShopItems(final Player p) + { + for (final ShopItem ac : this.shopitems.values()) + { + if (ac.usesItems(this.pli)) + { + for (final ItemStack i : ac.getItems()) + { + p.getInventory().addItem(i); + } + p.updateInventory(); + } + } + } + } diff --git a/API/src/main/java/com/comze_instancelabs/minigamesapi/SmartReset.java b/API/src/main/java/com/comze_instancelabs/minigamesapi/SmartReset.java index 994fe086..2c6ef053 100644 --- a/API/src/main/java/com/comze_instancelabs/minigamesapi/SmartReset.java +++ b/API/src/main/java/com/comze_instancelabs/minigamesapi/SmartReset.java @@ -1,3 +1,17 @@ +/* + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ package com.comze_instancelabs.minigamesapi; import java.io.EOFException; @@ -10,13 +24,18 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; -import java.util.Map.Entry; +import java.util.Map; +import java.util.NoSuchElementException; +import java.util.TreeMap; +import java.util.logging.Level; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.SkullType; import org.bukkit.block.Block; +import org.bukkit.block.BlockState; +import org.bukkit.block.BrewingStand; import org.bukkit.block.Chest; import org.bukkit.block.Dispenser; import org.bukkit.block.DoubleChest; @@ -28,320 +47,642 @@ import org.bukkit.util.io.BukkitObjectInputStream; import org.bukkit.util.io.BukkitObjectOutputStream; -import com.comze_instancelabs.minigamesapi.util.ChangeCause; import com.comze_instancelabs.minigamesapi.util.SmartArenaBlock; import com.comze_instancelabs.minigamesapi.util.Util; -public class SmartReset implements Runnable { - - // will only reset broken/placed blocks - - HashMap<Location, SmartArenaBlock> changed = new HashMap<Location, SmartArenaBlock>(); - - Arena a; - private ArrayList<SmartArenaBlock> failedblocks = new ArrayList<SmartArenaBlock>(); - long time = 0L; - - public SmartReset(Arena a) { - this.a = a; - } - - public SmartArenaBlock addChanged(Block b) { - if (!changed.containsKey(b.getLocation())) { - SmartArenaBlock sablock = new SmartArenaBlock(b, b.getType() == Material.CHEST, b.getType() == Material.WALL_SIGN || b.getType() == Material.SIGN_POST); - changed.put(b.getLocation(), sablock); - return sablock; - } - return null; - } - - public SmartArenaBlock addChanged(Block b, boolean c) { - if (!changed.containsKey(b.getLocation())) { - SmartArenaBlock sablock = new SmartArenaBlock(b, c, b.getType() == Material.WALL_SIGN || b.getType() == Material.SIGN_POST); - changed.put(b.getLocation(), sablock); - return sablock; - } - return null; - } - - public SmartArenaBlock addChanged(Block b, boolean c, ChangeCause cause) { - if (!changed.containsKey(b.getLocation())) { - SmartArenaBlock sablock = new SmartArenaBlock(b, c, b.getType() == Material.WALL_SIGN || b.getType() == Material.SIGN_POST); - changed.put(b.getLocation(), sablock); - return sablock; - } - return null; - } - - @Deprecated - public void addChanged(Location l) { - if (!changed.containsKey(l)) { - changed.put(l, new SmartArenaBlock(l, Material.AIR, (byte) 0)); - } - } - - public void addChanged(Location l, Material m, byte data) { - if (!changed.containsKey(l)) { - changed.put(l, new SmartArenaBlock(l, m, data)); - } - } - - public void run() { - int rolledBack = 0; - - // Rollback 70 blocks at a time - Iterator<Entry<Location, SmartArenaBlock>> it = changed.entrySet().iterator(); - while (it.hasNext() && rolledBack <= 70) { - SmartArenaBlock ablock = it.next().getValue(); - - try { - resetSmartResetBlock(ablock); - it.remove(); - } catch (Exception e) { - failedblocks.add(ablock); - } - - rolledBack++; - } - - if (changed.size() != 0) { - Bukkit.getScheduler().runTaskLater(a.plugin, this, 2L); - return; - } - - a.setArenaState(ArenaState.JOIN); - Util.updateSign(a.plugin, a); - - ArenaLogger.debug(failedblocks.size() + " to redo."); - - Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(MinigamesAPI.getAPI(), new Runnable() { - public void run() { - changed.clear(); - for (SmartArenaBlock ablock : failedblocks) { - Block b_ = ablock.getBlock().getWorld().getBlockAt(ablock.getBlock().getLocation()); - if (!b_.getType().toString().equalsIgnoreCase(ablock.getMaterial().toString())) { - b_.setType(ablock.getMaterial()); - b_.setData(ablock.getData()); - } - if (b_.getType() == Material.CHEST) { - b_.setType(ablock.getMaterial()); - b_.setData(ablock.getData()); - ((Chest) b_.getState()).getInventory().setContents(ablock.getInventory()); - ((Chest) b_.getState()).update(); - } - } - } - }, 30L); - - ArenaLogger.debug("Reset time: " + (System.currentTimeMillis() - time) + "ms"); - } - - /** - * Resets all changed blocks in tasks each 70 blocks - */ - public void reset() { - time = System.currentTimeMillis(); - a.plugin.getLogger().info(changed.size() + " to reset for arena " + a.getInternalName() + "."); - Bukkit.getScheduler().runTask(a.plugin, this); - } - - /** - * Resets the raw changed blocks on the main thread - */ - public void resetRaw() { - for (final SmartArenaBlock ablock : changed.values()) { - try { - resetSmartResetBlock(ablock); - } catch (Exception e) { - a.setArenaState(ArenaState.JOIN); - Util.updateSign(a.plugin, a); - } - } - - changed.clear(); - a.setArenaState(ArenaState.JOIN); - Util.updateSign(a.plugin, a); - } - - public void resetSmartResetBlock(SmartArenaBlock ablock) { - final Block b_ = ablock.getBlock().getWorld().getBlockAt(ablock.getBlock().getLocation()); - if (b_.getType() == Material.FURNACE) { - ((Furnace) b_.getState()).getInventory().clear(); - ((Furnace) b_.getState()).update(); - } - if (b_.getType() == Material.CHEST) { - ((Chest) b_.getState()).getBlockInventory().clear(); - ((Chest) b_.getState()).update(); - } - if (b_.getType() == Material.DISPENSER) { - ((Dispenser) b_.getState()).getInventory().clear(); - ((Dispenser) b_.getState()).update(); - } - if (b_.getType() == Material.DROPPER) { - ((Dropper) b_.getState()).getInventory().clear(); - ((Dropper) b_.getState()).update(); - } - if (!b_.getType().equals(ablock.getMaterial()) || b_.getData() != ablock.getData()) { - b_.setType(ablock.getMaterial()); - b_.setData(ablock.getData()); - } - if (b_.getType() == Material.CHEST) { - if (ablock.isDoubleChest()) { - DoubleChest dc = ablock.getDoubleChest(); - HashMap<Integer, ItemStack> chestinv = ablock.getNewInventory(); - for (Integer i : chestinv.keySet()) { - ItemStack item = chestinv.get(i); - if (item != null) { - dc.getInventory().setItem(i, item); - } - } - ((Chest) b_.getState()).update(); - return; - } - ((Chest) b_.getState()).getBlockInventory().clear(); - ((Chest) b_.getState()).update(); - HashMap<Integer, ItemStack> chestinv = ablock.getNewInventory(); - for (Integer i : chestinv.keySet()) { - ItemStack item = chestinv.get(i); - if (item != null) { - if (i < 27) { - ((Chest) b_.getState()).getBlockInventory().setItem(i, item); - } - } - } - ((Chest) b_.getState()).update(); - } - if (b_.getType() == Material.DISPENSER) { - Dispenser d = (Dispenser) b_.getState(); - d.getInventory().clear(); - HashMap<Integer, ItemStack> chestinv = ablock.getNewInventory(); - for (Integer i : chestinv.keySet()) { - ItemStack item = chestinv.get(i); - if (item != null) { - if (i < 9) { - d.getInventory().setItem(i, item); - } - } - } - d.getInventory().setContents(ablock.getInventory()); - d.update(); - } - if (b_.getType() == Material.DROPPER) { - Dropper d = (Dropper) b_.getState(); - d.getInventory().clear(); - HashMap<Integer, ItemStack> chestinv = ablock.getNewInventory(); - for (Integer i : chestinv.keySet()) { - ItemStack item = chestinv.get(i); - if (item != null) { - if (i < 9) { - d.getInventory().setItem(i, item); - } - } - } - d.update(); - } - if (b_.getType() == Material.WALL_SIGN || b_.getType() == Material.SIGN_POST) { - Sign sign = (Sign) b_.getState(); - if (sign != null) { - int i = 0; - for (String line : ablock.getSignLines()) { - sign.setLine(i, line); - i++; - if (i > 3) { - break; - } - } - sign.update(); - } - } - if (b_.getType() == Material.SKULL) { - b_.setData((byte) 0x1); - b_.getState().setType(Material.SKULL); - if (b_.getState() instanceof Skull) { - Skull s = (Skull) b_.getState(); - s.setSkullType(SkullType.PLAYER); - s.setOwner(ablock.getSkullOwner()); - s.setRotation(ablock.getSkullORotation()); - s.update(); - } - } - } - - public void saveSmartBlocksToFile() { - File f = new File(a.getPlugin().getDataFolder() + "/" + a.getInternalName() + "_smart"); - - FileOutputStream fos; - ObjectOutputStream oos = null; - try { - fos = new FileOutputStream(f); - oos = new BukkitObjectOutputStream(fos); - } catch (IOException e) { - e.printStackTrace(); - } - - for (SmartArenaBlock bl : changed.values()) { - try { - oos.writeObject(bl); - } catch (IOException e) { - System.out.println(e.getMessage()); - } - } - - try { - oos.close(); - } catch (IOException e) { - e.printStackTrace(); - } - - MinigamesAPI.getAPI().getLogger().info("Saved SmartBlocks of " + a.getInternalName()); - } - - public void loadSmartBlocksFromFile() { - File f = new File(a.getPlugin().getDataFolder() + "/" + a.getInternalName() + "_smart"); - if (!f.exists()) { - return; - } - FileInputStream fis = null; - BukkitObjectInputStream ois = null; - try { - fis = new FileInputStream(f); - ois = new BukkitObjectInputStream(fis); - } catch (IOException e) { - e.printStackTrace(); - } - - try { - while (true) { - Object b = null; - try { - b = ois.readObject(); - } catch (EOFException e) { - MinigamesAPI.getAPI().getLogger().info("Finished restoring SmartReset blocks for " + a.getInternalName() + "."); - } catch (ClosedChannelException e) { - System.out.println("Something is wrong with your SmartReset file and the reset might not be successful."); - } - - if (b != null) { - SmartArenaBlock ablock = (SmartArenaBlock) b; - this.resetSmartResetBlock(ablock); - } else { - break; - } - } - } catch (IOException e) { - e.printStackTrace(); - } catch (ClassNotFoundException e) { - e.printStackTrace(); - } - - try { - ois.close(); - } catch (IOException e) { - e.printStackTrace(); - } - - if (f.exists()) { - f.delete(); - } - } +/** + * The smart reset for resetting an arena to original state. + * + * @author instancelabs + */ +public class SmartReset implements Runnable +{ + + /** the changed blocks. */ + private final SmartBlockMap changed = new SmartBlockMap(); + + /** the underlying arena. */ + private Arena a; + + /** the blocks that failed while resetting. */ + private final ArrayList<SmartArenaBlock> failedblocks = new ArrayList<>(); + + /** time for reset progress. */ + private long time = 0L; + + /** + * Constructor. + * + * @param a + * arena owner of this smart reset. + */ + public SmartReset(final Arena a) + { + this.a = a; + } + + /** + * Adds changed block. + * + * @param b + * block to be added + * @return the smart arena block or {@code null} if the block already was added before + */ + public SmartArenaBlock addChanged(final Block b) + { + if (!this.changed.hasBlock(b.getLocation())) + { + if (MinigamesAPI.debug) + { + MinigamesAPI.getAPI().getLogger().info("(1) adding changed block for location " + b.getLocation()); + } + final SmartArenaBlock sablock = new SmartArenaBlock(b, b.getType() == Material.CHEST, b.getType() == Material.WALL_SIGN || b.getType() == Material.SIGN_POST); + this.changed.putBlock(b.getLocation(), sablock); + return sablock; + } + return null; + } + + /** + * Adds changed blocks + * @param loc + */ + public void addChanged(Block[] loc) + { + if (loc != null) + { + for (final Block b : loc) + { + this.addChanged(b); + } + } + } + + /** + * Adds changed block. + * + * @param b + * block to be added + * @param blockReplacedState + * state of the block + * @return the smart arena block or {@code null} if the block already was added before + */ + public SmartArenaBlock addChanged(Block b, BlockState blockReplacedState) + { + return this.addChanged(b.getLocation(), blockReplacedState.getType(), blockReplacedState.getData().getData()); + } + + /** + * Adds changed block + * + * @param l + * location of the block. + * @param m + * original material. + * @param data + * original data value. + * @return the smart arena block or {@code null} if the block already was added before + */ + public SmartArenaBlock addChanged(final Location l, final Material m, final byte data) + { + if (!this.changed.hasBlock(l)) + { + if (MinigamesAPI.debug) + { + MinigamesAPI.getAPI().getLogger().info("(5) adding changed block for location " + l); + } + final SmartArenaBlock sab = new SmartArenaBlock(l, m, data); + if (m == Material.CHEST) + { + sab.setInventory(((Chest)l.getBlock().getState()).getInventory()); + } + this.changed.putBlock(l, sab); + return sab; + } + return null; + } + + @Override + public void run() + { + int rolledBack = 0; + + // Rollback 70 blocks at a time + final Iterator<SmartArenaBlock> it = this.changed.getBlocks().iterator(); + while (it.hasNext() && rolledBack <= 70) + { + final SmartArenaBlock ablock = it.next(); + + try + { + if (MinigamesAPI.debug) MinigamesAPI.getAPI().getLogger().info("resetting block " + ablock.getBlock().getLocation()); + this.resetSmartResetBlock(ablock); + it.remove(); + } + catch (final Exception e) + { + if (MinigamesAPI.debug) + { + MinigamesAPI.getAPI().getLogger().log(Level.INFO, "failed block " + ablock.getBlock().getLocation(), e); + } + this.failedblocks.add(ablock); + } + + rolledBack++; + } + + if (it.hasNext()) + { + Bukkit.getScheduler().runTaskLater(this.a.getPlugin(), this, 2L); + return; + } + + this.a.setArenaState(ArenaState.JOIN); + Util.updateSign(this.a.getPlugin(), this.a); + + ArenaLogger.debug(this.failedblocks.size() + " to redo."); + + Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(MinigamesAPI.getAPI(), () -> { + SmartReset.this.changed.clear(); + for (final SmartArenaBlock ablock : SmartReset.this.failedblocks) + { + MinigamesAPI.getAPI().getLogger().info("retrying failed block " + ablock.getBlock().getLocation()); + final Block b_ = ablock.getBlock().getWorld().getBlockAt(ablock.getBlock().getLocation()); + if (!b_.getType().toString().equalsIgnoreCase(ablock.getMaterial().toString())) + { + b_.setType(ablock.getMaterial()); + b_.setData(ablock.getData()); + } + if (b_.getType() == Material.CHEST) + { + b_.setType(ablock.getMaterial()); + b_.setData(ablock.getData()); + ((Chest) b_.getState()).getInventory().setContents(ablock.getInventory()); + ((Chest) b_.getState()).update(); + } + } + }, 25L); + + ArenaLogger.debug("Reset time: " + (System.currentTimeMillis() - this.time) + "ms"); + } + + /** + * Resets all changed blocks in tasks each 70 blocks + */ + public void reset() + { + this.time = System.currentTimeMillis(); + this.a.getPlugin().getLogger().info(this.changed.size() + " to reset for arena " + this.a.getInternalName() + "."); + Bukkit.getScheduler().runTask(this.a.getPlugin(), this); + } + + /** + * Resets the raw changed blocks on the main thread + */ + public void resetRaw() + { + for (final SmartArenaBlock ablock : this.changed.getBlocks()) + { + try + { + this.resetSmartResetBlock(ablock); + } + catch (final Exception e) + { + this.a.setArenaState(ArenaState.JOIN); + Util.updateSign(this.a.getPlugin(), this.a); + } + } + + this.changed.clear(); + this.a.setArenaState(ArenaState.JOIN); + Util.updateSign(this.a.getPlugin(), this.a); + } + + public void resetSmartResetBlock(final SmartArenaBlock ablock) + { + final Block b_ = ablock.getBlock().getWorld().getBlockAt(ablock.getBlock().getLocation()); + if (b_.getType() == Material.FURNACE) + { + if (MinigamesAPI.debug) + MinigamesAPI.getAPI().getLogger().info("Rolling back furnace inventory"); + ((Furnace) b_.getState()).getInventory().clear(); + ((Furnace) b_.getState()).update(); + } + if (b_.getType() == Material.CHEST) + { + if (MinigamesAPI.debug) + MinigamesAPI.getAPI().getLogger().info("Rolling back chest inventory"); + ((Chest) b_.getState()).getBlockInventory().clear(); + ((Chest) b_.getState()).update(); + } + if (b_.getType() == Material.DISPENSER) + { + if (MinigamesAPI.debug) + MinigamesAPI.getAPI().getLogger().info("Rolling back dispenser inventory"); + ((Dispenser) b_.getState()).getInventory().clear(); + ((Dispenser) b_.getState()).update(); + } + if (b_.getType() == Material.DROPPER) + { + if (MinigamesAPI.debug) + MinigamesAPI.getAPI().getLogger().info("Rolling back dropper inventory"); + ((Dropper) b_.getState()).getInventory().clear(); + ((Dropper) b_.getState()).update(); + } + if (b_.getType() == Material.BREWING_STAND) + { + if (MinigamesAPI.debug) + MinigamesAPI.getAPI().getLogger().info("Rolling back brewing stand inventory"); + ((BrewingStand) b_.getState()).getInventory().clear(); + ((BrewingStand) b_.getState()).update(); + } + if (!b_.getType().equals(ablock.getMaterial()) || b_.getData() != ablock.getData()) + { + if (MinigamesAPI.debug) + MinigamesAPI.getAPI().getLogger().info("Rolling back block material/data to " + ablock.getMaterial() + "/" + ablock.getData()); + b_.setType(ablock.getMaterial()); + b_.setData(ablock.getData()); + } + else if (MinigamesAPI.debug) + { + MinigamesAPI.getAPI().getLogger().info("Skipping block rollback from " + b_.getType() + "/" + b_.getData() + " to " + ablock.getMaterial() + "/" + ablock.getData()); + } + if (b_.getType() == Material.CHEST) + { + if (MinigamesAPI.debug) + MinigamesAPI.getAPI().getLogger().info("Rolling back chest"); + if (ablock.isDoubleChest()) + { + final DoubleChest dc = ablock.getDoubleChest(); + final HashMap<Integer, ItemStack> chestinv = ablock.getNewInventory(); + for (final Integer i : chestinv.keySet()) + { + final ItemStack item = chestinv.get(i); + if (item != null) + { + dc.getInventory().setItem(i, item); + } + } + ((Chest) b_.getState()).update(); + return; + } + ((Chest) b_.getState()).getBlockInventory().clear(); + ((Chest) b_.getState()).update(); + final HashMap<Integer, ItemStack> chestinv = ablock.getNewInventory(); + for (final Integer i : chestinv.keySet()) + { + final ItemStack item = chestinv.get(i); + if (item != null) + { + if (i < 27) + { + ((Chest) b_.getState()).getBlockInventory().setItem(i, item); + } + } + } + ((Chest) b_.getState()).update(); + } + if (b_.getType() == Material.DISPENSER) + { + if (MinigamesAPI.debug) + MinigamesAPI.getAPI().getLogger().info("Rolling back dispenser"); + final Dispenser d = (Dispenser) b_.getState(); + d.getInventory().clear(); + final HashMap<Integer, ItemStack> chestinv = ablock.getNewInventory(); + for (final Integer i : chestinv.keySet()) + { + final ItemStack item = chestinv.get(i); + if (item != null) + { + if (i < 9) + { + d.getInventory().setItem(i, item); + } + } + } + d.getInventory().setContents(ablock.getInventory()); + d.update(); + } + if (b_.getType() == Material.DROPPER) + { + if (MinigamesAPI.debug) + MinigamesAPI.getAPI().getLogger().info("Rolling back dropper"); + final Dropper d = (Dropper) b_.getState(); + d.getInventory().clear(); + final HashMap<Integer, ItemStack> chestinv = ablock.getNewInventory(); + for (final Integer i : chestinv.keySet()) + { + final ItemStack item = chestinv.get(i); + if (item != null) + { + if (i < 9) + { + d.getInventory().setItem(i, item); + } + } + } + d.update(); + } + if (b_.getType() == Material.WALL_SIGN || b_.getType() == Material.SIGN_POST) + { + if (MinigamesAPI.debug) + MinigamesAPI.getAPI().getLogger().info("Rolling back sign"); + final Sign sign = (Sign) b_.getState(); + if (sign != null) + { + int i = 0; + for (final String line : ablock.getSignLines()) + { + sign.setLine(i, line); + i++; + if (i > 3) + { + break; + } + } + sign.update(); + } + } + if (b_.getType() == Material.SKULL) + { + if (MinigamesAPI.debug) + MinigamesAPI.getAPI().getLogger().info("Rolling back skull"); + b_.setData((byte) 0x1); + b_.getState().setType(Material.SKULL); + if (b_.getState() instanceof Skull) + { + final Skull s = (Skull) b_.getState(); + s.setSkullType(SkullType.PLAYER); + s.setOwner(ablock.getSkullOwner()); + s.setRotation(ablock.getSkullORotation()); + s.update(); + } + } + } + + public void saveSmartBlocksToFile() + { + final File f = new File(this.a.getPlugin().getDataFolder() + "/" + this.a.getInternalName() + "_smart"); + + FileOutputStream fos; + ObjectOutputStream oos = null; + try + { + fos = new FileOutputStream(f); + oos = new BukkitObjectOutputStream(fos); + } + catch (final IOException e) + { + MinigamesAPI.getAPI().getLogger().log(Level.WARNING, "exception", e); + } + + for (final SmartArenaBlock bl : this.changed.getBlocks()) + { + try + { + oos.writeObject(bl); + } + catch (final IOException e) + { + MinigamesAPI.getAPI().getLogger().log(Level.WARNING, "io exception", e); + } + } + + try + { + oos.close(); + } + catch (final IOException e) + { + MinigamesAPI.getAPI().getLogger().log(Level.WARNING, "exception", e); + } + + MinigamesAPI.getAPI().getLogger().info("Saved SmartBlocks of " + this.a.getInternalName()); + } + + public void loadSmartBlocksFromFile() + { + final File f = new File(this.a.getPlugin().getDataFolder() + "/" + this.a.getInternalName() + "_smart"); + if (!f.exists()) + { + return; + } + FileInputStream fis = null; + BukkitObjectInputStream ois = null; + try + { + fis = new FileInputStream(f); + ois = new BukkitObjectInputStream(fis); + } + catch (final IOException e) + { + MinigamesAPI.getAPI().getLogger().log(Level.WARNING, "exception", e); + } + + try + { + while (true) + { + Object b = null; + try + { + b = ois.readObject(); + } + catch (final EOFException e) + { + MinigamesAPI.getAPI().getLogger().info("Finished restoring SmartReset blocks for " + this.a.getInternalName() + "."); + } + catch (final ClosedChannelException e) + { + MinigamesAPI.getAPI().getLogger().log(Level.WARNING, "Something is wrong with your SmartReset file and the reset might not be successful.", e); + } + + if (b != null) + { + final SmartArenaBlock ablock = (SmartArenaBlock) b; + this.resetSmartResetBlock(ablock); + } + else + { + break; + } + } + } + catch (final IOException e) + { + MinigamesAPI.getAPI().getLogger().log(Level.WARNING, "exception", e); + } + catch (final ClassNotFoundException e) + { + MinigamesAPI.getAPI().getLogger().log(Level.WARNING, "exception", e); + } + + try + { + ois.close(); + } + catch (final IOException e) + { + MinigamesAPI.getAPI().getLogger().log(Level.WARNING, "exception", e); + } + + if (f.exists()) + { + f.delete(); + } + } + + /** + * A map holding smart reset blocks per Y coordinate (level). + */ + private static final class SmartBlockMap extends TreeMap<Integer, Map<Location, SmartArenaBlock>> + { + + /** + * serial version uid. + */ + private static final long serialVersionUID = 8336943154139693760L; + + /** + * Puts a block into map. + * + * @param l + * location + * @param block + * smart reset block + */ + public void putBlock(Location l, SmartArenaBlock block) + { + this.computeIfAbsent(l.getBlockY(), (key) -> new HashMap<>()).put(l, block); + } + + /** + * Checks if given location is already present within map. + * + * @param l + * location to check + * @return {@code true} if location is known + */ + public boolean hasBlock(Location l) + { + final Map<Location, SmartArenaBlock> map = this.get(l.getBlockY()); + if (map != null) + { + return map.containsKey(l); + } + return false; + } + + /** + * Returns an iterable over all blocks within this map. + * + * @return iterable over all blocks. + */ + public Iterable<SmartArenaBlock> getBlocks() + { + return new Iterable<SmartArenaBlock>() { + + @Override + public Iterator<SmartArenaBlock> iterator() + { + return new NestedIterator<>(SmartBlockMap.this.values().iterator()); + } + }; + } + + } + + /** + * Helper class for nesting iterators. + * @author mepeisen + * + * @param <K> + * @param <T> + */ + public static final class NestedIterator<K, T> implements Iterator<T> + { + + /** outer iterator. */ + private Iterator<Map<K, T>> outer = null; + + /** inner iterator. */ + private Iterator<T> inner = null; + + /** prev iterator for remove. */ + private Iterator<T> prev = null; + + /** + * Constructor. + * @param iter + */ + public NestedIterator(Iterator<Map<K, T>> iter) + { + this.outer = iter; + moveNext(); + } + + @Override + public boolean hasNext() + { + // inner iterator existing and has an element? + if (this.inner != null) + { + return this.inner.hasNext(); + } + + // no more elements + return false; + } + + @Override + public T next() + { + if (this.inner == null) + { + throw new NoSuchElementException(); + } + final T result = this.inner.next(); + this.prev = this.inner; + if (!this.inner.hasNext()) + { + this.inner = null; + moveNext(); + } + return result; + } + + /** + * Moves to next element + */ + private void moveNext() + { + while (this.inner == null) + { + if (!this.outer.hasNext()) + { + // no elements found + break; + } + this.inner = this.outer.next().values().iterator(); + if (!this.inner.hasNext()) + { + this.inner = null; + } + } + } + + @Override + public void remove() + { + if (this.prev == null) + { + throw new IllegalStateException("no next called"); //$NON-NLS-1$ + } + this.prev.remove(); + } + + + } + } diff --git a/API/src/main/java/com/comze_instancelabs/minigamesapi/SpectatorManager.java b/API/src/main/java/com/comze_instancelabs/minigamesapi/SpectatorManager.java index 369c6f6d..30737199 100644 --- a/API/src/main/java/com/comze_instancelabs/minigamesapi/SpectatorManager.java +++ b/API/src/main/java/com/comze_instancelabs/minigamesapi/SpectatorManager.java @@ -1,8 +1,25 @@ +/* + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ package com.comze_instancelabs.minigamesapi; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; +import java.util.HashSet; +import java.util.Set; +import java.util.UUID; import org.bukkit.Bukkit; import org.bukkit.Location; @@ -13,150 +30,212 @@ import org.bukkit.potion.PotionEffectType; import org.bukkit.scoreboard.Team; +import com.comze_instancelabs.minigamesapi.util.ArenaScoreboard; import com.comze_instancelabs.minigamesapi.util.IconMenu; import com.comze_instancelabs.minigamesapi.util.Util; import com.comze_instancelabs.minigamesapi.util.Validator; -public class SpectatorManager { - - JavaPlugin plugin; - private HashMap<String, IconMenu> lasticonm = new HashMap<String, IconMenu>(); - - public SpectatorManager(JavaPlugin plugin) { - this.plugin = plugin; - this.setup(); - } - - public void setup() { - if (Bukkit.getScoreboardManager().getMainScoreboard().getTeam("spectators") == null) { - Bukkit.getScoreboardManager().getMainScoreboard().registerNewTeam("spectators"); - } - Bukkit.getScoreboardManager().getMainScoreboard().getTeam("spectators").setCanSeeFriendlyInvisibles(true); - clear(); - } - - public void setSpectate(Player p, boolean spectate) { - try { - if (spectate) { - p.addPotionEffect(new PotionEffect(PotionEffectType.INVISIBILITY, 9999999, 5), true); - Bukkit.getScoreboardManager().getMainScoreboard().getTeam("spectators").addPlayer(p); - } else { - p.removePotionEffect(PotionEffectType.INVISIBILITY); - if (Bukkit.getScoreboardManager().getMainScoreboard().getTeam("spectators").hasPlayer(p)) { - Bukkit.getScoreboardManager().getMainScoreboard().getTeam("spectators").removePlayer(p); - } - } - } catch (Exception e) { - } - } - - @Deprecated - public boolean isSpectating(Player p) { - return Bukkit.getScoreboardManager().getMainScoreboard().getTeam("spectators").hasPlayer(p); - } - - private void clear() { - Team t = Bukkit.getScoreboardManager().getMainScoreboard().getTeam("spectators"); - ArrayList<OfflinePlayer> offp_set = new ArrayList<OfflinePlayer>(t.getPlayers()); - for (OfflinePlayer offp : offp_set) { - t.removePlayer(offp); - } - } - - public void openSpectatorGUI(final Player p, Arena a) { - IconMenu iconm; - int mincount = a.getAllPlayers().size(); - if (lasticonm.containsKey(p.getName())) { - iconm = lasticonm.get(p.getName()); - } else { - iconm = new IconMenu(MinigamesAPI.getAPI().getPluginInstance(plugin).getMessagesConfig().spectator_item, (9 > mincount - 1) ? 9 : Math.round(mincount / 9) * 9 + 9, new IconMenu.OptionClickEventHandler() { - @Override - public void onOptionClick(IconMenu.OptionClickEvent event) { - if (event.getPlayer().getName().equalsIgnoreCase(p.getName())) { - String d = event.getName(); - Player p = event.getPlayer(); - - Player p_ = Bukkit.getPlayer(d); - if (p_ != null && p != null) { - Util.teleportPlayerFixed(p, new Location(p.getWorld(), p_.getLocation().getX(), p.getLocation().getY(), p_.getLocation().getZ())); - } - } - event.setWillClose(true); - } - }, plugin); - } - - iconm.clear(); - - PluginInstance pli = MinigamesAPI.getAPI().getPluginInstance(plugin); - int c = 0; - for (String p__ : a.getAllPlayers()) { - Player p_ = Bukkit.getPlayer(p__); - if (p_ != null) { - if (pli.global_players.containsKey(p__) && !pli.global_lost.containsKey(p__)) { - if (a.getInternalName().equalsIgnoreCase(pli.global_players.get(p__).getInternalName())) { - iconm.setOption(c, Util.getCustomHead(p__), p__, ""); - c++; - } - } - } - } - - iconm.open(p); - lasticonm.put(p.getName(), iconm); - } - - HashMap<String, ArrayList<String>> pspecs = new HashMap<String, ArrayList<String>>(); - HashMap<String, ArrayList<String>> splayers = new HashMap<String, ArrayList<String>>(); - - public void hideSpectator(Player spec, ArrayList<String> players) { - for (String p_ : players) { - if (Validator.isPlayerOnline(p_)) { - Player p = Bukkit.getPlayer(p_); - p.hidePlayer(spec); - if (pspecs.containsKey(p_)) { - ArrayList<String> t = pspecs.get(p_); - t.add(spec.getName()); - pspecs.put(p_, t); - } else { - pspecs.put(p_, new ArrayList<String>(Arrays.asList(spec.getName()))); - } - } - } - splayers.put(spec.getName(), players); - } - - public void showSpectator(Player spec) { - if (splayers.containsKey(spec.getName())) { - for (String p_ : splayers.get(spec.getName())) { - if (Validator.isPlayerOnline(p_)) { - Player p = Bukkit.getPlayer(p_); - p.showPlayer(spec); - if (pspecs.containsKey(p_)) { - ArrayList<String> t = pspecs.get(p_); - t.remove(spec.getName()); - pspecs.put(p_, t); - } - } - } - splayers.remove(spec.getName()); - } - } - - public void showSpectators(Player p) { - if (pspecs.containsKey(p.getName())) { - for (String p_ : pspecs.get(p.getName())) { - if (Validator.isPlayerOnline(p_)) { - Player spec = Bukkit.getPlayer(p_); - p.showPlayer(spec); - if (splayers.containsKey(p_)) { - ArrayList<String> t = splayers.get(p_); - t.remove(spec.getName()); - splayers.put(p_, t); - } - } - } - pspecs.remove(p.getName()); - } - } +/** + * Spectator manager. + * + * @author instancelabs + */ +public class SpectatorManager +{ + + JavaPlugin plugin; + private final HashMap<String, IconMenu> lasticonm = new HashMap<>(); + + private static final Set<UUID> spectators = new HashSet<>(); + + public SpectatorManager(final JavaPlugin plugin) + { + this.plugin = plugin; + this.setup(); + } + + public void setup() + { + final Team t = ArenaScoreboard.getMainScoreboardTeam("spectators"); + if (t != null) + { + t.setCanSeeFriendlyInvisibles(true); + } + this.clear(); + } + + public void setSpectate(final Player p, final boolean spectate) + { + try + { + boolean useScoreboard = this.plugin.getConfig().getBoolean(ArenaConfigStrings.CONFIG_USE_SPECTATOR_SCOREBOARD); + if (spectate) + { + spectators.add(p.getUniqueId()); + p.addPotionEffect(new PotionEffect(PotionEffectType.INVISIBILITY, 9999999, 5), true); + if (useScoreboard) + { + ArenaScoreboard.mainScoreboardAddPlayer("spectators", p); + } + } + else + { + if (spectators.remove(p.getUniqueId())) + { + p.removePotionEffect(PotionEffectType.INVISIBILITY); + if (useScoreboard) + { + if (ArenaScoreboard.mainScoreboardHasPlayer("spectators", p)) + { + ArenaScoreboard.mainScoreboardRemovePlayer("spectators", p); + } + } + } + } + } + catch (final Exception e) + { + // silently ignore + } + } + + @Deprecated + public static boolean isSpectating(final Player p) + { + return spectators.contains(p.getUniqueId()); + } + + private void clear() + { + spectators.clear(); + final Team t = ArenaScoreboard.getMainScoreboardTeam("spectators"); + if (t != null) + { + final ArrayList<OfflinePlayer> offp_set = new ArrayList<>(t.getPlayers()); + for (final OfflinePlayer offp : offp_set) + { + t.removePlayer(offp); + } + } + } + + public void openSpectatorGUI(final Player p, final Arena a) + { + IconMenu iconm; + final int mincount = a.getAllPlayers().size(); + if (this.lasticonm.containsKey(p.getName())) + { + iconm = this.lasticonm.get(p.getName()); + } + else + { + iconm = new IconMenu(MinigamesAPI.getAPI().getPluginInstance(this.plugin).getMessagesConfig().spectator_item, (9 > mincount - 1) ? 9 : Math.round(mincount / 9) * 9 + 9, event -> { + if (event.getPlayer().getName().equalsIgnoreCase(p.getName())) + { + final String d = event.getName(); + final Player p1 = event.getPlayer(); + + final Player p_ = Bukkit.getPlayer(d); + if (p_ != null && p1 != null) + { + Util.teleportPlayerFixed(p1, new Location(p1.getWorld(), p_.getLocation().getX(), p1.getLocation().getY(), p_.getLocation().getZ())); + } + } + event.setWillClose(true); + }, this.plugin); + } + + iconm.clear(); + + final PluginInstance pli = MinigamesAPI.getAPI().getPluginInstance(this.plugin); + int c = 0; + for (final String p__ : a.getAllPlayers()) + { + final Player p_ = Bukkit.getPlayer(p__); + if (p_ != null) + { + if (pli.global_players.containsKey(p__) && !pli.global_lost.containsKey(p__)) + { + if (a.getInternalName().equalsIgnoreCase(pli.global_players.get(p__).getInternalName())) + { + iconm.setOption(c, Util.getCustomHead(p__), p__, ""); + c++; + } + } + } + } + + iconm.open(p); + this.lasticonm.put(p.getName(), iconm); + } + + HashMap<String, ArrayList<String>> pspecs = new HashMap<>(); + HashMap<String, ArrayList<String>> splayers = new HashMap<>(); + + public void hideSpectator(final Player spec, final ArrayList<String> players) + { + for (final String p_ : players) + { + if (Validator.isPlayerOnline(p_)) + { + final Player p = Bukkit.getPlayer(p_); + spec.addPotionEffect(new PotionEffect(PotionEffectType.INVISIBILITY, 20 * 600, 1)); + if (this.pspecs.containsKey(p_)) + { + final ArrayList<String> t = this.pspecs.get(p_); + t.add(spec.getName()); + this.pspecs.put(p_, t); + } + else + { + this.pspecs.put(p_, new ArrayList<>(Arrays.asList(spec.getName()))); + } + } + } + this.splayers.put(spec.getName(), players); + } + + public void showSpectator(final Player spec) + { + if (this.splayers.containsKey(spec.getName())) + { + for (final String p_ : this.splayers.get(spec.getName())) + { + if (Validator.isPlayerOnline(p_)) + { + final Player p = Bukkit.getPlayer(p_); + if (this.pspecs.containsKey(p_)) + { + final ArrayList<String> t = this.pspecs.get(p_); + t.remove(spec.getName()); + spec.removePotionEffect(PotionEffectType.INVISIBILITY); + this.pspecs.put(p_, t); + } + } + } + this.splayers.remove(spec.getName()); + } + } + + public void showSpectators(final Player p) + { + if (this.pspecs.containsKey(p.getName())) + { + for (final String p_ : this.pspecs.get(p.getName())) + { + if (Validator.isPlayerOnline(p_)) + { + final Player spec = Bukkit.getPlayer(p_); + if (this.splayers.containsKey(p_)) + { + final ArrayList<String> t = this.splayers.get(p_); + t.remove(spec.getName()); + spec.removePotionEffect(PotionEffectType.INVISIBILITY); + this.splayers.put(p_, t); + } + } + } + this.pspecs.remove(p.getName()); + } + } } diff --git a/API/src/main/java/com/comze_instancelabs/minigamesapi/Stats.java b/API/src/main/java/com/comze_instancelabs/minigamesapi/Stats.java index b39c37bc..bf75e8e5 100644 --- a/API/src/main/java/com/comze_instancelabs/minigamesapi/Stats.java +++ b/API/src/main/java/com/comze_instancelabs/minigamesapi/Stats.java @@ -1,9 +1,24 @@ +/* + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ package com.comze_instancelabs.minigamesapi; import java.util.ArrayList; import java.util.HashMap; import java.util.TreeMap; import java.util.UUID; +import java.util.logging.Level; import org.bukkit.Bukkit; import org.bukkit.Location; @@ -21,337 +36,408 @@ import com.comze_instancelabs.minigamesapi.config.StatsConfig; import com.comze_instancelabs.minigamesapi.util.Util.ValueComparator; -public class Stats { - - // used for wins and points - // you can get points for pretty much everything in the games, - // but these points are just for top stats, nothing more - - private JavaPlugin plugin = null; - PluginInstance pli = null; - - public ArrayList<String> skullsetup = new ArrayList<String>(); - int stats_kill_points = 2; - int stats_win_points = 10; - - public Stats(PluginInstance pli, JavaPlugin plugin) { - this.plugin = plugin; - reloadVariables(); - this.pli = pli; - } - - public void reloadVariables() { - this.stats_kill_points = plugin.getConfig().getInt("config.stats.points_for_kill"); - this.stats_win_points = plugin.getConfig().getInt("config.stats.points_for_win"); - } - - public void win(String playername, int count) { - addWin(playername); - addPoints(playername, count); - Player p = Bukkit.getPlayer(playername); - if (p != null) { - pli.getSQLInstance().updateWinnerStats(p, count, true); - } else { - if (MinigamesAPI.debug) { - System.out.println("Failed updating SQL Stats as the player is not online anymore!"); - } - } - } - - public void lose(String playername) { - addLose(playername); - Player p = Bukkit.getPlayer(playername); - if (p != null) { - pli.getSQLInstance().updateLoserStats(p); - } else { - if (MinigamesAPI.debug) { - System.out.println("Failed updating SQL Stats as the player is not online anymore!"); - } - } - } - - /** - * Gets called on player join to ensure file stats are up to date (with mysql stats) - * - * @param playername - */ - public void update(String playername) { - if (plugin.getConfig().getBoolean("mysql.enabled")) { - Player p = Bukkit.getPlayer(playername); - String uuid = p.getUniqueId().toString(); - if (pli.getStatsConfig().getConfig().isSet("players." + uuid + ".wins")) { - int wins = getWins(playername); - int sqlwins = pli.getSQLInstance().getWins(p); - setWins(playername, Math.max(wins, sqlwins)); - } - if (pli.getStatsConfig().getConfig().isSet("players." + uuid + ".points")) { - int points = getPoints(playername); - int sqlpoints = pli.getSQLInstance().getPoints(p); - setPoints(playername, Math.max(points, sqlpoints)); - } - } - } - - public void updateSQLKillsDeathsAfter(Player p, Arena a) { - if (!a.getPlugin().isEnabled()) { - System.out.println("Couldn't save Death/Kill SQL stats as the server stopped/restarted."); - return; - } - // Update sql server with kills stats at the end - if (a.temp_kill_count.containsKey(p.getName())) { - if (MinigamesAPI.debug) { - System.out.println(a.temp_kill_count.get(p.getName())); - } - pli.getSQLInstance().updateKillerStats(p, a.temp_kill_count.get(p.getName())); - a.temp_kill_count.remove(p.getName()); - } - // death stats - if (a.temp_death_count.containsKey(p.getName())) { - if (MinigamesAPI.debug) { - System.out.println(a.temp_death_count.get(p.getName())); - } - pli.getSQLInstance().updateDeathStats(p, a.temp_death_count.get(p.getName())); - a.temp_death_count.remove(p.getName()); - } - } - - public void setWins(String playername, int count) { - String uuid = Bukkit.getPlayer(playername).getUniqueId().toString(); - pli.getStatsConfig().getConfig().set("players." + uuid + ".wins", count); - pli.getStatsConfig().saveConfig(); - } - - public void setPoints(String playername, int count) { - String uuid = Bukkit.getPlayer(playername).getUniqueId().toString(); - pli.getStatsConfig().getConfig().set("players." + uuid + ".points", count); - pli.getStatsConfig().saveConfig(); - } - - public void addWin(String playername) { - StatsConfig config = pli.getStatsConfig(); - int temp = 0; - String uuid = Bukkit.getPlayer(playername).getUniqueId().toString(); - if (config.getConfig().isSet("players." + uuid + ".wins")) { - temp = config.getConfig().getInt("players." + uuid + ".wins"); - } - temp++; - pli.getArenaAchievements().setAchievementDone(playername, "first_win", false); - if (temp >= 10) { - pli.getArenaAchievements().setAchievementDone(playername, "ten_wins", false); - } - config.getConfig().set("players." + uuid + ".wins", temp); - config.getConfig().set("players." + uuid + ".playername", playername); - config.saveConfig(); - } - - public void addLose(String playername) { - StatsConfig config = pli.getStatsConfig(); - int temp = 0; - String uuid = Bukkit.getPlayer(playername).getUniqueId().toString(); - if (config.getConfig().isSet("players." + uuid + ".loses")) { - temp = config.getConfig().getInt("players." + uuid + ".loses"); - } - config.getConfig().set("players." + uuid + ".loses", temp + 1); - config.getConfig().set("players." + uuid + ".playername", playername); - config.saveConfig(); - } - - public void addKill(String playername) { - StatsConfig config = pli.getStatsConfig(); - int temp = 0; - String uuid = Bukkit.getPlayer(playername).getUniqueId().toString(); - if (config.getConfig().isSet("players." + uuid + ".kills")) { - temp = config.getConfig().getInt("players." + uuid + ".kills"); - } - temp++; - config.getConfig().set("players." + uuid + ".kills", temp); - config.getConfig().set("players." + uuid + ".playername", playername); - config.saveConfig(); - pli.getArenaAchievements().setAchievementDone(playername, "first_blood", false); - if (temp >= 10 && temp < 100) { - pli.getArenaAchievements().setAchievementDone(playername, "ten_kills", false); - } else if (temp >= 100) { - pli.getArenaAchievements().setAchievementDone(playername, "hundred_kills", false); - } - // Moved to Rewards.java:257 - // pli.getSQLInstance().updateKillerStats(Bukkit.getPlayer(playername)); - } - - public void addDeath(String playername) { - StatsConfig config = pli.getStatsConfig(); - int temp = 0; - String uuid = Bukkit.getPlayer(playername).getUniqueId().toString(); - if (config.getConfig().isSet("players." + uuid + ".deaths")) { - temp = config.getConfig().getInt("players." + uuid + ".deaths"); - } - temp++; - config.getConfig().set("players." + uuid + ".deaths", temp); - config.getConfig().set("players." + uuid + ".playername", playername); - config.saveConfig(); - // Moved to Rewards.java:265 - // pli.getSQLInstance().updateDeathStats(Bukkit.getPlayer(playername)); - } - - public void addPoints(String playername, int count) { - StatsConfig config = pli.getStatsConfig(); - int temp = 0; - String uuid = Bukkit.getPlayer(playername).getUniqueId().toString(); - if (config.getConfig().isSet("players." + uuid + ".points")) { - temp = config.getConfig().getInt("players." + uuid + ".points"); - } - int temp_ = 0; - if (MinigamesAPI.getAPI().statsglobal.getConfig().isSet("players." + uuid + ".points")) { - temp_ = MinigamesAPI.getAPI().statsglobal.getConfig().getInt("players." + uuid + ".points"); - } else { - temp_ = temp; - } - MinigamesAPI.getAPI().statsglobal.getConfig().set("players." + uuid + ".points", temp_ + count); - MinigamesAPI.getAPI().statsglobal.saveConfig(); - config.getConfig().set("players." + uuid + ".points", temp + count); - config.saveConfig(); - } - - public int getPoints(String playername) { - FileConfiguration config = pli.getStatsConfig().getConfig(); - String uuid = Bukkit.getPlayer(playername).getUniqueId().toString(); - if (config.isSet("players." + uuid + ".points")) { - int points = config.getInt("players." + uuid + ".points"); - return points; - } - return 0; - } - - public int getWins(String playername) { - FileConfiguration config = pli.getStatsConfig().getConfig(); - String uuid = Bukkit.getPlayer(playername).getUniqueId().toString(); - if (config.isSet("players." + uuid + ".wins")) { - return config.getInt("players." + uuid + ".wins"); - } - return 0; - } - - public int getLoses(String playername) { - FileConfiguration config = pli.getStatsConfig().getConfig(); - String uuid = Bukkit.getPlayer(playername).getUniqueId().toString(); - if (config.isSet("players." + uuid + ".loses")) { - return config.getInt("players." + uuid + ".loses"); - } - return 0; - } - - public int getKills(String playername) { - FileConfiguration config = pli.getStatsConfig().getConfig(); - String uuid = Bukkit.getPlayer(playername).getUniqueId().toString(); - if (config.isSet("players." + uuid + ".kills")) { - return config.getInt("players." + uuid + ".kills"); - } - return 0; - } - - public int getDeaths(String playername) { - FileConfiguration config = pli.getStatsConfig().getConfig(); - String uuid = Bukkit.getPlayer(playername).getUniqueId().toString(); - if (config.isSet("players." + uuid + ".deaths")) { - return config.getInt("players." + uuid + ".deaths"); - } - return 0; - } - - public TreeMap<String, Double> getTop(int count, boolean wins) { - int c = 0; - String key = "wins"; - if (!wins) { - key = "points"; - } - FileConfiguration config = pli.getStatsConfig().getConfig(); - HashMap<String, Double> pwins = new HashMap<String, Double>(); - if (config.isSet("players.")) { - for (String p : config.getConfigurationSection("players.").getKeys(false)) { - c++; - if (c > 100) { - break; - } - pwins.put(config.getString("players." + p + ".playername"), (double) config.getInt("players." + p + "." + key)); - } - } - ValueComparator bvc = new ValueComparator(pwins); - TreeMap<String, Double> sorted_wins = new TreeMap<String, Double>(bvc); - sorted_wins.putAll(pwins); - return sorted_wins; - } - - public TreeMap<String, Double> getTop() { - FileConfiguration config = pli.getStatsConfig().getConfig(); - HashMap<String, Double> pwins = new HashMap<String, Double>(); - if (config.isSet("players.")) { - for (String p : config.getConfigurationSection("players.").getKeys(false)) { - pwins.put(config.getString("players." + p + ".playername"), (double) config.getInt("players." + p + ".wins")); - } - } - ValueComparator bvc = new ValueComparator(pwins); - TreeMap<String, Double> sorted_wins = new TreeMap<String, Double>(bvc); - sorted_wins.putAll(pwins); - return sorted_wins; - } - - public static ItemStack giveSkull(String name) { - ItemStack item = new ItemStack(Material.SKULL_ITEM, 1, (short) 3); - SkullMeta skullmeta = (SkullMeta) item.getItemMeta(); - skullmeta.setDisplayName(name); - skullmeta.setOwner(name); - item.setItemMeta(skullmeta); - return item; - } - - public void saveSkull(Location t, int count) { - FileConfiguration config = pli.getStatsConfig().getConfig(); - String base = "skulls." + UUID.randomUUID().toString() + "."; - config.set(base + "world", t.getWorld().getName()); - config.set(base + "x", t.getBlockX()); - config.set(base + "y", t.getBlockY()); - config.set(base + "z", t.getBlockZ()); - config.set(base + "pos", count); - BlockState state = t.getBlock().getState(); - if (state instanceof Skull) { - Skull skull_ = (Skull) state; - config.set(base + "dir", skull_.getRotation().toString()); - } else { - config.set(base + "dir", "SELF"); - } - - pli.getStatsConfig().saveConfig(); - } - - /* - * Since Mojangs new public API this seems to be lagging hardcore (and they're disallowing more than 1 connection per minute, gg) - */ - public void updateSkulls() { - TreeMap<String, Double> sorted_wins = getTop(); - FileConfiguration config = pli.getStatsConfig().getConfig(); - if (config.isSet("skulls.")) { - for (String skull : config.getConfigurationSection("skulls.").getKeys(false)) { - String base = "skulls." + skull; - Location t = new Location(Bukkit.getWorld(config.getString(base + ".world")), config.getDouble(base + ".x"), config.getDouble(base + ".y"), config.getDouble(base + ".z")); - t.getBlock().setData((byte) 0x1); - BlockState state = t.getBlock().getState(); - - int pos = config.getInt(base + ".pos"); - String dir = config.getString(base + ".dir"); - - if (state instanceof Skull) { - Skull skull_ = (Skull) state; - skull_.setRotation(BlockFace.valueOf(dir)); - skull_.setSkullType(SkullType.PLAYER); - System.out.println(pos + " " + sorted_wins.keySet().size()); - if (pos <= sorted_wins.keySet().size()) { - String name = (String) sorted_wins.keySet().toArray()[pos - 1]; - skull_.setOwner(name); - System.out.println(name); - } - skull_.update(); - } - } - } - } - +/** + * Statistics helper. + * + * @author instancelabs + */ +public class Stats +{ + + // used for wins and points + // you can get points for pretty much everything in the games, + // but these points are just for top stats, nothing more + + private JavaPlugin plugin = null; + PluginInstance pli = null; + + public ArrayList<String> skullsetup = new ArrayList<>(); + int stats_kill_points = 2; + int stats_win_points = 10; + + public Stats(final PluginInstance pli, final JavaPlugin plugin) + { + this.plugin = plugin; + this.reloadVariables(); + this.pli = pli; + } + + public void reloadVariables() + { + this.stats_kill_points = this.plugin.getConfig().getInt(ArenaConfigStrings.CONFIG_STATS_POINTS_FOR_KILL); + this.stats_win_points = this.plugin.getConfig().getInt(ArenaConfigStrings.CONFIG_STATS_POINTS_FOR_WIN); + } + + public void win(final String playername, final int count) + { + this.addWin(playername); + this.addPoints(playername, count); + final Player p = Bukkit.getPlayer(playername); + if (p != null) + { + this.pli.getSQLInstance().updateWinnerStats(p, count, true); + } + else + { + if (MinigamesAPI.debug) + { + this.plugin.getLogger().fine("Failed updating SQL Stats as the player is not online anymore!"); + } + } + } + + public void lose(final String playername) + { + this.addLose(playername); + final Player p = Bukkit.getPlayer(playername); + if (p != null) + { + this.pli.getSQLInstance().updateLoserStats(p); + } + else + { + if (MinigamesAPI.debug) + { + this.plugin.getLogger().fine("Failed updating SQL Stats as the player is not online anymore!"); + } + } + } + + /** + * Gets called on player join to ensure file stats are up to date (with mysql stats) + * + * @param playername + */ + public void update(final String playername) + { + final Player p = Bukkit.getPlayer(playername); + final String uuid = p.getUniqueId().toString(); + if (this.pli.getStatsConfig().getConfig().isSet("players." + uuid + ".wins")) + { + final int wins = this.getWins(playername); + final int sqlwins = this.pli.getSQLInstance().getWins(p); + this.setWins(playername, Math.max(wins, sqlwins)); + } + if (this.pli.getStatsConfig().getConfig().isSet("players." + uuid + ".points")) + { + final int points = this.getPoints(playername); + final int sqlpoints = this.pli.getSQLInstance().getPoints(p); + this.setPoints(playername, Math.max(points, sqlpoints)); + } + } + + public void updateSQLKillsDeathsAfter(final Player p, final Arena a) + { + if (!a.getPlugin().isEnabled()) + { + this.plugin.getLogger().fine("Couldn't save Death/Kill SQL stats as the server stopped/restarted."); + return; + } + // Update sql server with kills stats at the end + if (a.temp_kill_count.containsKey(p.getName())) + { + if (MinigamesAPI.debug) + { + this.plugin.getLogger().fine("" + a.temp_kill_count.get(p.getName())); //$NON-NLS-1$ + } + this.pli.getSQLInstance().updateKillerStats(p, a.temp_kill_count.get(p.getName())); + a.temp_kill_count.remove(p.getName()); + } + // death stats + if (a.temp_death_count.containsKey(p.getName())) + { + if (MinigamesAPI.debug) + { + this.plugin.getLogger().fine("" + a.temp_death_count.get(p.getName())); //$NON-NLS-1$ + } + this.pli.getSQLInstance().updateDeathStats(p, a.temp_death_count.get(p.getName())); + a.temp_death_count.remove(p.getName()); + } + } + + public void setWins(final String playername, final int count) + { + final String uuid = Bukkit.getPlayer(playername).getUniqueId().toString(); + this.pli.getStatsConfig().getConfig().set("players." + uuid + ".wins", count); + this.pli.getStatsConfig().saveConfig(); + } + + public void setPoints(final String playername, final int count) + { + final String uuid = Bukkit.getPlayer(playername).getUniqueId().toString(); + this.pli.getStatsConfig().getConfig().set("players." + uuid + ".points", count); + this.pli.getStatsConfig().saveConfig(); + } + + public void addWin(final String playername) + { + final StatsConfig config = this.pli.getStatsConfig(); + int temp = 0; + final String uuid = Bukkit.getPlayer(playername).getUniqueId().toString(); + if (config.getConfig().isSet("players." + uuid + ".wins")) + { + temp = config.getConfig().getInt("players." + uuid + ".wins"); + } + temp++; + this.pli.getArenaAchievements().setAchievementDone(playername, "first_win", false); + if (temp >= 10) + { + this.pli.getArenaAchievements().setAchievementDone(playername, "ten_wins", false); + } + config.getConfig().set("players." + uuid + ".wins", temp); + config.getConfig().set("players." + uuid + ".playername", playername); + config.saveConfig(); + } + + public void addLose(final String playername) + { + final StatsConfig config = this.pli.getStatsConfig(); + int temp = 0; + final String uuid = Bukkit.getPlayer(playername).getUniqueId().toString(); + if (config.getConfig().isSet("players." + uuid + ".loses")) + { + temp = config.getConfig().getInt("players." + uuid + ".loses"); + } + config.getConfig().set("players." + uuid + ".loses", temp + 1); + config.getConfig().set("players." + uuid + ".playername", playername); + config.saveConfig(); + } + + public void addKill(final String playername) + { + final StatsConfig config = this.pli.getStatsConfig(); + int temp = 0; + final String uuid = Bukkit.getPlayer(playername).getUniqueId().toString(); + if (config.getConfig().isSet("players." + uuid + ".kills")) + { + temp = config.getConfig().getInt("players." + uuid + ".kills"); + } + temp++; + config.getConfig().set("players." + uuid + ".kills", temp); + config.getConfig().set("players." + uuid + ".playername", playername); + config.saveConfig(); + this.pli.getArenaAchievements().setAchievementDone(playername, "first_blood", false); + if (temp >= 10 && temp < 100) + { + this.pli.getArenaAchievements().setAchievementDone(playername, "ten_kills", false); + } + else if (temp >= 100) + { + this.pli.getArenaAchievements().setAchievementDone(playername, "hundred_kills", false); + } + // Moved to Rewards.java:257 + // pli.getSQLInstance().updateKillerStats(Bukkit.getPlayer(playername)); + } + + public void addDeath(final String playername) + { + final StatsConfig config = this.pli.getStatsConfig(); + int temp = 0; + final String uuid = Bukkit.getPlayer(playername).getUniqueId().toString(); + if (config.getConfig().isSet("players." + uuid + ".deaths")) + { + temp = config.getConfig().getInt("players." + uuid + ".deaths"); + } + temp++; + config.getConfig().set("players." + uuid + ".deaths", temp); + config.getConfig().set("players." + uuid + ".playername", playername); + config.saveConfig(); + // Moved to Rewards.java:265 + // pli.getSQLInstance().updateDeathStats(Bukkit.getPlayer(playername)); + } + + public void addPoints(final String playername, final int count) + { + final StatsConfig config = this.pli.getStatsConfig(); + int temp = 0; + final String uuid = Bukkit.getPlayer(playername).getUniqueId().toString(); + if (config.getConfig().isSet("players." + uuid + ".points")) + { + temp = config.getConfig().getInt("players." + uuid + ".points"); + } + int temp_ = 0; + if (MinigamesAPI.getAPI().statsglobal.getConfig().isSet("players." + uuid + ".points")) + { + temp_ = MinigamesAPI.getAPI().statsglobal.getConfig().getInt("players." + uuid + ".points"); + } + else + { + temp_ = temp; + } + MinigamesAPI.getAPI().statsglobal.getConfig().set("players." + uuid + ".points", temp_ + count); + MinigamesAPI.getAPI().statsglobal.saveConfig(); + config.getConfig().set("players." + uuid + ".points", temp + count); + config.saveConfig(); + } + + public int getPoints(final String playername) + { + final FileConfiguration config = this.pli.getStatsConfig().getConfig(); + final String uuid = Bukkit.getPlayer(playername).getUniqueId().toString(); + if (config.isSet("players." + uuid + ".points")) + { + final int points = config.getInt("players." + uuid + ".points"); + return points; + } + return 0; + } + + public int getWins(final String playername) + { + final FileConfiguration config = this.pli.getStatsConfig().getConfig(); + final String uuid = Bukkit.getPlayer(playername).getUniqueId().toString(); + if (config.isSet("players." + uuid + ".wins")) + { + return config.getInt("players." + uuid + ".wins"); + } + return 0; + } + + public int getLoses(final String playername) + { + final FileConfiguration config = this.pli.getStatsConfig().getConfig(); + final String uuid = Bukkit.getPlayer(playername).getUniqueId().toString(); + if (config.isSet("players." + uuid + ".loses")) + { + return config.getInt("players." + uuid + ".loses"); + } + return 0; + } + + public int getKills(final String playername) + { + final FileConfiguration config = this.pli.getStatsConfig().getConfig(); + final String uuid = Bukkit.getPlayer(playername).getUniqueId().toString(); + if (config.isSet("players." + uuid + ".kills")) + { + return config.getInt("players." + uuid + ".kills"); + } + return 0; + } + + public int getDeaths(final String playername) + { + final FileConfiguration config = this.pli.getStatsConfig().getConfig(); + final String uuid = Bukkit.getPlayer(playername).getUniqueId().toString(); + if (config.isSet("players." + uuid + ".deaths")) + { + return config.getInt("players." + uuid + ".deaths"); + } + return 0; + } + + public TreeMap<String, Double> getTop(final int count, final boolean wins) + { + int c = 0; + String key = "wins"; + if (!wins) + { + key = "points"; + } + final FileConfiguration config = this.pli.getStatsConfig().getConfig(); + final HashMap<String, Double> pwins = new HashMap<>(); + if (config.isSet("players.")) + { + for (final String p : config.getConfigurationSection("players.").getKeys(false)) + { + c++; + if (c > 100) + { + break; + } + pwins.put(config.getString("players." + p + ".playername"), (double) config.getInt("players." + p + "." + key)); + } + } + final ValueComparator bvc = new ValueComparator(pwins); + final TreeMap<String, Double> sorted_wins = new TreeMap<>(bvc); + sorted_wins.putAll(pwins); + return sorted_wins; + } + + public TreeMap<String, Double> getTop() + { + final FileConfiguration config = this.pli.getStatsConfig().getConfig(); + final HashMap<String, Double> pwins = new HashMap<>(); + if (config.isSet("players.")) + { + for (final String p : config.getConfigurationSection("players.").getKeys(false)) + { + pwins.put(config.getString("players." + p + ".playername"), (double) config.getInt("players." + p + ".wins")); + } + } + final ValueComparator bvc = new ValueComparator(pwins); + final TreeMap<String, Double> sorted_wins = new TreeMap<>(bvc); + sorted_wins.putAll(pwins); + return sorted_wins; + } + + public static ItemStack giveSkull(final String name) + { + final ItemStack item = new ItemStack(Material.SKULL_ITEM, 1, (short) 3); + final SkullMeta skullmeta = (SkullMeta) item.getItemMeta(); + skullmeta.setDisplayName(name); + skullmeta.setOwner(name); + item.setItemMeta(skullmeta); + return item; + } + + public void saveSkull(final Location t, final int count) + { + final FileConfiguration config = this.pli.getStatsConfig().getConfig(); + final String base = "skulls." + UUID.randomUUID().toString() + "."; + config.set(base + "world", t.getWorld().getName()); + config.set(base + "x", t.getBlockX()); + config.set(base + "y", t.getBlockY()); + config.set(base + "z", t.getBlockZ()); + config.set(base + "pos", count); + final BlockState state = t.getBlock().getState(); + if (state instanceof Skull) + { + final Skull skull_ = (Skull) state; + config.set(base + "dir", skull_.getRotation().toString()); + } + else + { + config.set(base + "dir", "SELF"); + } + + this.pli.getStatsConfig().saveConfig(); + } + + /* + * Since Mojangs new public API this seems to be lagging hardcore (and they're disallowing more than 1 connection per minute, gg) + */ + public void updateSkulls() + { + final TreeMap<String, Double> sorted_wins = this.getTop(); + final FileConfiguration config = this.pli.getStatsConfig().getConfig(); + if (config.isSet("skulls.")) + { + for (final String skull : config.getConfigurationSection("skulls.").getKeys(false)) + { + final String base = "skulls." + skull; + final Location t = new Location(Bukkit.getWorld(config.getString(base + ".world")), config.getDouble(base + ".x"), config.getDouble(base + ".y"), config.getDouble(base + ".z")); + t.getBlock().setData((byte) 0x1); + final BlockState state = t.getBlock().getState(); + + final int pos = config.getInt(base + ".pos"); + final String dir = config.getString(base + ".dir"); + + if (state instanceof Skull) + { + final Skull skull_ = (Skull) state; + skull_.setRotation(BlockFace.valueOf(dir)); + skull_.setSkullType(SkullType.PLAYER); + this.plugin.getLogger().fine(pos + " " + sorted_wins.keySet().size()); + if (pos <= sorted_wins.keySet().size()) + { + final String name = (String) sorted_wins.keySet().toArray()[pos - 1]; + skull_.setOwner(name); + this.plugin.getLogger().fine(name); + } + skull_.update(); + } + } + } + } } diff --git a/API/src/main/java/com/comze_instancelabs/minigamesapi/achievements/AAchievement.java b/API/src/main/java/com/comze_instancelabs/minigamesapi/achievements/AAchievement.java index 7f00d857..8d1d9def 100644 --- a/API/src/main/java/com/comze_instancelabs/minigamesapi/achievements/AAchievement.java +++ b/API/src/main/java/com/comze_instancelabs/minigamesapi/achievements/AAchievement.java @@ -1,26 +1,45 @@ -package com.comze_instancelabs.minigamesapi.achievements; - -public class AAchievement { - - String name; - boolean done; - String playername; +/* + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - public AAchievement(String name, String playername, boolean done) { - this.name = name; - this.playername = playername; - this.done = done; - } + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. - public boolean isDone() { - return done; - } - - public void setDone(boolean t) { - this.done = t; - } + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ +package com.comze_instancelabs.minigamesapi.achievements; - public String getAchievementNameRaw() { - return name; - } +public class AAchievement +{ + + String name; + boolean done; + String playername; + + public AAchievement(final String name, final String playername, final boolean done) + { + this.name = name; + this.playername = playername; + this.done = done; + } + + public boolean isDone() + { + return this.done; + } + + public void setDone(final boolean t) + { + this.done = t; + } + + public String getAchievementNameRaw() + { + return this.name; + } } diff --git a/API/src/main/java/com/comze_instancelabs/minigamesapi/achievements/ArenaAchievements.java b/API/src/main/java/com/comze_instancelabs/minigamesapi/achievements/ArenaAchievements.java index c7a998da..8413b178 100644 --- a/API/src/main/java/com/comze_instancelabs/minigamesapi/achievements/ArenaAchievements.java +++ b/API/src/main/java/com/comze_instancelabs/minigamesapi/achievements/ArenaAchievements.java @@ -1,3 +1,17 @@ +/* + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ package com.comze_instancelabs.minigamesapi.achievements; import java.util.ArrayList; @@ -11,106 +25,137 @@ import com.comze_instancelabs.minigamesapi.MinigamesAPI; import com.comze_instancelabs.minigamesapi.PluginInstance; +import com.comze_instancelabs.minigamesapi.config.MessagesConfig; import com.comze_instancelabs.minigamesapi.util.IconMenu; -public class ArenaAchievements { - - JavaPlugin plugin; - PluginInstance pli; - public HashMap<String, IconMenu> lasticonm = new HashMap<String, IconMenu>(); - - public ArenaAchievements(PluginInstance pli, JavaPlugin plugin) { - this.plugin = plugin; - this.pli = pli; - } - - public void openGUI(final String p, boolean sql) { - IconMenu iconm; - ArrayList<AAchievement> alist = loadPlayerAchievements(p, sql); - int mincount = alist.size(); - if (lasticonm.containsKey(p)) { - iconm = lasticonm.get(p); - } else { - iconm = new IconMenu(MinigamesAPI.getAPI().getPluginInstance(plugin).getMessagesConfig().achievement_item, (9 > mincount - 1) ? 9 * 1 : Math.round(mincount / 9) * 9 + 9, new IconMenu.OptionClickEventHandler() { - @Override - public void onOptionClick(IconMenu.OptionClickEvent event) { - event.setWillClose(true); - } - }, plugin); - } - - int c = 0; - for (AAchievement aa : alist) { - ItemStack icon = new ItemStack(Material.STAINED_GLASS_PANE, 1, (short) 7); - if (aa.isDone()) { - icon = new ItemStack(Material.STAINED_GLASS_PANE, 1, (short) 5); - } - iconm.setOption(c, icon, ChatColor.translateAlternateColorCodes('&', pli.getAchievementsConfig().getConfig().getString("config.achievements." + aa.getAchievementNameRaw() + ".name")), "Done: " + aa.isDone()); - c++; - } - - iconm.open(Bukkit.getPlayerExact(p)); - lasticonm.put(p, iconm); - } - - public ArrayList<AAchievement> loadPlayerAchievements(String playername, boolean sql) { - ArrayList<AAchievement> ret = new ArrayList<AAchievement>(); - if (sql) { - // TODO MySQL Support - } else { - for (String achievement : pli.getAchievementsConfig().getConfig().getConfigurationSection("config.achievements").getKeys(false)) { - AAchievement ac = new AAchievement(achievement, playername, pli.getAchievementsConfig().getConfig().isSet("players." + playername + "." + achievement + ".done") ? pli.getAchievementsConfig().getConfig().getBoolean("players." + playername + "." + achievement + ".done") : false); - ret.add(ac); - } - } - return ret; - } - - public void setAchievementDone(String playername, String achievement, boolean sql) { - if (sql) { - // TODO - } else { - if (!pli.getAchievementsConfig().getConfig().isSet("players." + playername + "." + achievement + ".done")) { - pli.getAchievementsConfig().getConfig().set("players." + playername + "." + achievement + ".done", true); - pli.getAchievementsConfig().saveConfig(); - ArrayList<AAchievement> alist = loadPlayerAchievements(playername, sql); - boolean allDone = true; - AAchievement a; - for (AAchievement aac : alist) { - if (aac.getAchievementNameRaw().equalsIgnoreCase(achievement)) { - a = aac; - } - if (!aac.isDone() && !aac.getAchievementNameRaw().equalsIgnoreCase("achievement_guy")) { - allDone = false; - } - } - String base = "config.achievements." + achievement; - pli.getRewardsInstance().giveAchievementReward(playername, pli.getAchievementsConfig().getConfig().getBoolean(base + ".reward.economy_reward"), pli.getAchievementsConfig().getConfig().getBoolean(base + ".reward.command_reward"), pli.getAchievementsConfig().getConfig().getInt(base + ".reward.econ_reward_amount"), pli.getAchievementsConfig().getConfig().getString(base + ".reward.cmd")); - Bukkit.getPlayer(playername).sendMessage(pli.getMessagesConfig().you_got_the_achievement.replaceAll("<achievement>", ChatColor.translateAlternateColorCodes('&', pli.getAchievementsConfig().getConfig().getString("config.achievements." + achievement + ".name")))); - - if (allDone) { - setAchievementDone(playername, "achievement_guy", sql); - } - } - } - } - - public void addDefaultAchievement(String internalname, String name, int default_money_reward) { - pli.getAchievementsConfig().getConfig().addDefault("config.achievements." + internalname + ".enabled", true); - pli.getAchievementsConfig().getConfig().addDefault("config.achievements." + internalname + ".name", name); - pli.getAchievementsConfig().getConfig().addDefault("config.achievements." + internalname + ".reward.economy_reward", true); - pli.getAchievementsConfig().getConfig().addDefault("config.achievements." + internalname + ".reward.econ_reward_amount", default_money_reward); - pli.getAchievementsConfig().getConfig().addDefault("config.achievements." + internalname + ".reward.command_reward", false); - pli.getAchievementsConfig().getConfig().addDefault("config.achievements." + internalname + ".reward.cmd", "tell <player> Good job!"); - } - - public boolean isEnabled() { - return pli.getAchievementsConfig().getConfig().getBoolean("config.enabled"); - } - - public void setEnabled(boolean t) { - pli.getAchievementsConfig().getConfig().set("config.enabled", t); - pli.getAchievementsConfig().saveConfig(); - } - +public class ArenaAchievements +{ + + JavaPlugin plugin; + PluginInstance pli; + public HashMap<String, IconMenu> lasticonm = new HashMap<>(); + + public ArenaAchievements(final PluginInstance pli, final JavaPlugin plugin) + { + this.plugin = plugin; + this.pli = pli; + } + + public void openGUI(final String p, final boolean sql) + { + IconMenu iconm; + final ArrayList<AAchievement> alist = this.loadPlayerAchievements(p, sql); + final int mincount = alist.size(); + final MessagesConfig messagesConfig = MinigamesAPI.getAPI().getPluginInstance(this.plugin).getMessagesConfig(); + if (this.lasticonm.containsKey(p)) + { + iconm = this.lasticonm.get(p); + } + else + { + iconm = new IconMenu(messagesConfig.achievement_item, (9 > mincount - 1) ? 9 * 1 : Math.round(mincount / 9) * 9 + 9, + event -> event.setWillClose(true), this.plugin); + } + + int c = 0; + for (final AAchievement aa : alist) + { + ItemStack icon = new ItemStack(Material.STAINED_CLAY, 1, (short) 14); + if (aa.isDone()) + { + icon = new ItemStack(Material.STAINED_CLAY, 1, (short) 5); + } + iconm.setOption( + c, + icon, + ChatColor.translateAlternateColorCodes('&', this.pli.getAchievementsConfig().getConfig().getString("config.achievements." + aa.getAchievementNameRaw() + ".name")), + aa.isDone() ? messagesConfig.achievement_done_true : messagesConfig.achievement_done_false); + c++; + } + + iconm.open(Bukkit.getPlayerExact(p)); + this.lasticonm.put(p, iconm); + } + + public ArrayList<AAchievement> loadPlayerAchievements(final String playername, final boolean sql) + { + final ArrayList<AAchievement> ret = new ArrayList<>(); + if (sql) + { + // TODO MySQL Support + } + else + { + for (final String achievement : this.pli.getAchievementsConfig().getConfig().getConfigurationSection("config.achievements").getKeys(false)) + { + final AAchievement ac = new AAchievement(achievement, playername, this.pli.getAchievementsConfig().getConfig().isSet("players." + playername + "." + achievement + ".done") + ? this.pli.getAchievementsConfig().getConfig().getBoolean("players." + playername + "." + achievement + ".done") : false); + ret.add(ac); + } + } + return ret; + } + + public void setAchievementDone(final String playername, final String achievement, final boolean sql) + { + if (sql) + { + // TODO + } + else + { + if (!this.pli.getAchievementsConfig().getConfig().isSet("players." + playername + "." + achievement + ".done")) + { + this.pli.getAchievementsConfig().getConfig().set("players." + playername + "." + achievement + ".done", true); + this.pli.getAchievementsConfig().saveConfig(); + final ArrayList<AAchievement> alist = this.loadPlayerAchievements(playername, sql); + boolean allDone = true; + AAchievement a; + for (final AAchievement aac : alist) + { + if (aac.getAchievementNameRaw().equalsIgnoreCase(achievement)) + { + a = aac; + } + if (!aac.isDone() && !aac.getAchievementNameRaw().equalsIgnoreCase("achievement_guy")) + { + allDone = false; + } + } + final String base = "config.achievements." + achievement; + this.pli.getRewardsInstance().giveAchievementReward(playername, this.pli.getAchievementsConfig().getConfig().getBoolean(base + ".reward.economy_reward"), + this.pli.getAchievementsConfig().getConfig().getBoolean(base + ".reward.command_reward"), + this.pli.getAchievementsConfig().getConfig().getInt(base + ".reward.econ_reward_amount"), this.pli.getAchievementsConfig().getConfig().getString(base + ".reward.cmd")); + Bukkit.getPlayer(playername).sendMessage(this.pli.getMessagesConfig().you_got_the_achievement.replaceAll("<achievement>", + ChatColor.translateAlternateColorCodes('&', this.pli.getAchievementsConfig().getConfig().getString("config.achievements." + achievement + ".name")))); + + if (allDone) + { + this.setAchievementDone(playername, "achievement_guy", sql); + } + } + } + } + + public void addDefaultAchievement(final String internalname, final String name, final int default_money_reward) + { + this.pli.getAchievementsConfig().getConfig().addDefault("config.achievements." + internalname + ".enabled", false); + this.pli.getAchievementsConfig().getConfig().addDefault("config.achievements." + internalname + ".name", name); + this.pli.getAchievementsConfig().getConfig().addDefault("config.achievements." + internalname + ".reward.economy_reward", true); + this.pli.getAchievementsConfig().getConfig().addDefault("config.achievements." + internalname + ".reward.econ_reward_amount", default_money_reward); + this.pli.getAchievementsConfig().getConfig().addDefault("config.achievements." + internalname + ".reward.command_reward", false); + this.pli.getAchievementsConfig().getConfig().addDefault("config.achievements." + internalname + ".reward.cmd", "tell <player> Good job!"); + } + + public boolean isEnabled() + { + return this.pli.getAchievementsConfig().getConfig().getBoolean("config.enabled"); + } + + public void setEnabled(final boolean t) + { + this.pli.getAchievementsConfig().getConfig().set("config.enabled", t); + this.pli.getAchievementsConfig().saveConfig(); + } + } diff --git a/API/src/main/java/com/comze_instancelabs/minigamesapi/arcade/ArcadeInstance.java b/API/src/main/java/com/comze_instancelabs/minigamesapi/arcade/ArcadeInstance.java index 143f2667..25e2d7fa 100644 --- a/API/src/main/java/com/comze_instancelabs/minigamesapi/arcade/ArcadeInstance.java +++ b/API/src/main/java/com/comze_instancelabs/minigamesapi/arcade/ArcadeInstance.java @@ -1,3 +1,17 @@ +/* + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ package com.comze_instancelabs.minigamesapi.arcade; import java.util.ArrayList; @@ -9,311 +23,399 @@ import org.bukkit.plugin.java.JavaPlugin; import com.comze_instancelabs.minigamesapi.Arena; +import com.comze_instancelabs.minigamesapi.ArenaConfigStrings; import com.comze_instancelabs.minigamesapi.ArenaState; import com.comze_instancelabs.minigamesapi.MinigamesAPI; import com.comze_instancelabs.minigamesapi.PluginInstance; import com.comze_instancelabs.minigamesapi.util.Util; import com.comze_instancelabs.minigamesapi.util.Validator; -public class ArcadeInstance { - - public ArrayList<PluginInstance> minigames = new ArrayList<PluginInstance>(); - int currentindex = 0; - public ArrayList<String> players = new ArrayList<String>(); - Arena arena; - JavaPlugin plugin; - - boolean in_a_game = false; - Arena currentarena = null; - boolean started; - - public ArcadeInstance(JavaPlugin plugin, ArrayList<PluginInstance> minigames, Arena arena) { - this.minigames = minigames; - this.arena = arena; - this.plugin = plugin; - } - - // TODO max 16 players! - public void joinArcade(String playername) { - PluginInstance pli = MinigamesAPI.getAPI().getPluginInstance(plugin); - if (!players.contains(playername)) { - players.add(playername); - arena.addPlayer(playername); - } - Player p = Bukkit.getPlayer(playername); - if (p == null) { - return; - } - if (players.size() >= plugin.getConfig().getInt("config.arcade.min_players")) { - boolean msg = true; - if (!started) { - startArcade(); - } else { - if (currentindex < minigames.size()) { - if (in_a_game) { - if (currentarena != null) { - if (p != null) { - PluginInstance pli_ = minigames.get(currentindex); - System.out.println(pli_.getPlugin().getName() + " " + currentarena.getInternalName() + " " + p.getName()); - if (currentarena.getArenaState() != ArenaState.INGAME && currentarena.getArenaState() != ArenaState.RESTARTING) { - currentarena.joinPlayerLobby(playername, this, false, true); - } else { - msg = false; - currentarena.spectateArcade(playername); - } - - pli_.scoreboardManager.updateScoreboard(pli_.getPlugin(), currentarena); - } - } - } - } - } - if (msg) { - p.sendMessage(MinigamesAPI.getAPI().getPluginInstance(plugin).getMessagesConfig().arcade_joined_waiting.replaceAll("<count>", "0")); - } else { - p.sendMessage(MinigamesAPI.getAPI().getPluginInstance(plugin).getMessagesConfig().arcade_joined_spectator); - } - } else { - p.sendMessage(MinigamesAPI.getAPI().getPluginInstance(plugin).getMessagesConfig().arcade_joined_waiting.replaceAll("<count>", Integer.toString(plugin.getConfig().getInt("config.arcade.min_players") - players.size()))); - } - } - - public void leaveArcade(final String playername) { - this.leaveArcade(playername, true); - } - - public void leaveArcade(final String playername, boolean endOfGame) { - final PluginInstance pli = MinigamesAPI.getAPI().getPluginInstance(plugin); - if (players.contains(playername)) { - players.remove(playername); - } - if (arena.containsPlayer(playername)) { - arena.removePlayer(playername); - } - if (minigames.get(currentindex).getArenas().size() > 0) { - if (minigames.get(currentindex).getArenas().get(0).containsPlayer(playername)) { - minigames.get(currentindex).getArenas().get(0).leavePlayer(playername, false, false); - } - } - Bukkit.getScheduler().runTaskLater(MinigamesAPI.getAPI(), new Runnable() { - public void run() { - Player p = Bukkit.getPlayer(playername); - if (p != null) { - Util.teleportPlayerFixed(p, arena.getMainLobbyTemp()); - pli.getSpectatorManager().setSpectate(p, false); - if (!p.isOp()) { - p.setFlying(false); - p.setAllowFlight(false); - } - } - } - }, 20L); - clean(); - - // This shouldn't be necessary anymore except for arcade spectators - if (pli.containsGlobalPlayer(playername)) { - pli.global_players.remove(playername); - } - if (pli.containsGlobalLost(playername)) { - pli.global_lost.remove(playername); - } - if (currentarena != null) { - PluginInstance pli_ = MinigamesAPI.getAPI().pinstances.get(currentarena.getPlugin()); - if (pli_ != null) { - if (pli_.containsGlobalPlayer(playername)) { - pli_.global_players.remove(playername); - } - if (pli_.containsGlobalLost(playername)) { - pli_.global_lost.remove(playername); - } - } - } - - Util.updateSign(plugin, arena); - - if (endOfGame) { - if (players.size() < 2) { - stopArcade(false); - } - } - } - - int currentlobbycount = 31; - int currenttaskid = 0; - - public void startArcade() { - if (started) { - return; - } - started = true; - Collections.shuffle(minigames); - - currentlobbycount = plugin.getConfig().getInt("config.arcade.lobby_countdown") + 1; - final ArcadeInstance ai = this; - final PluginInstance pli = MinigamesAPI.getAPI().getPluginInstance(plugin); - - currenttaskid = Bukkit.getScheduler().runTaskTimer(MinigamesAPI.getAPI(), new Runnable() { - public void run() { - currentlobbycount--; - if (currentlobbycount == 60 || currentlobbycount == 30 || currentlobbycount == 15 || currentlobbycount == 10 || currentlobbycount < 6) { - for (String p_ : ai.players) { - if (Validator.isPlayerOnline(p_)) { - Player p = Bukkit.getPlayer(p_); - p.sendMessage(pli.getMessagesConfig().starting_in.replaceAll("<count>", Integer.toString(currentlobbycount))); - } - } - } - if (currentlobbycount < 1) { - currentindex--; - ai.nextMinigame(); - try { - Bukkit.getScheduler().cancelTask(currenttaskid); - } catch (Exception e) { - } - } - } - }, 5L, 20).getTaskId(); - } - - public void stopArcade(boolean stopOfGame) { - try { - Bukkit.getScheduler().cancelTask(currenttaskid); - } catch (Exception e) { - - } - final ArrayList<String> temp = new ArrayList<String>(players); - for (String p_ : temp) { - this.leaveArcade(p_, false); - } - players.clear(); - started = false; - in_a_game = false; - currentarena = null; - this.currentindex = 0; - - HashSet hs = new HashSet(); - hs.addAll(temp); - temp.clear(); - temp.addAll(hs); - final ArcadeInstance ai = this; - if (stopOfGame && plugin.getConfig().getBoolean("config.arcade.infinite_mode.enabled")) { - if (temp.size() > 1) { - for (String p_ : temp) { - Util.sendMessage(plugin, Bukkit.getPlayer(p_), MinigamesAPI.getAPI().getPluginInstance(plugin).getMessagesConfig().arcade_new_round.replaceAll("<count>", Integer.toString(plugin.getConfig().getInt("config.arcade.infinite_mode.seconds_to_new_round")))); - } - Bukkit.getScheduler().runTaskLater(plugin, new Runnable() { - public void run() { - for (String p_ : temp) { - if (!players.contains(p_)) { - players.add(p_); - } - } - ai.startArcade(); - } - }, Math.max(40L, 20L * plugin.getConfig().getInt("config.arcade.infinite_mode.seconds_to_new_round"))); - } - } - } - - public void stopArcade() { - this.stopArcade(false); - } - - public void stopCurrentMinigame() { - if (currentindex < minigames.size()) { - PluginInstance mg = minigames.get(currentindex); - if (mg.getArenas().size() > 0) { - if (mg.getPlugin().getConfig().getBoolean("config.arcade.arena_to_prefer.enabled")) { - String arenaname = mg.getPlugin().getConfig().getString("config.arcade.arena_to_prefer.arena"); - Arena a = mg.getArenaByName(arenaname); - if (a != null) { - a.stop(); - } - } else { - minigames.get(currentindex).getArenas().get(0).stop(); - } - } - } - } - - public void nextMinigame() { - nextMinigame(30L); - } - - public void nextMinigame(long delay) { - in_a_game = false; - - if (currentindex < minigames.size() - 1) { - currentindex++; - } else { - arena.stop(); - // stopArcade(); - return; - } - // System.out.println(delay + " " + currentindex); - final ArcadeInstance ai = this; - Bukkit.getScheduler().runTaskLater(MinigamesAPI.getAPI(), new Runnable() { - public void run() { - ArrayList<String> temp = new ArrayList<String>(players); - - PluginInstance mg = minigames.get(currentindex); - if (mg.getPlugin().getConfig().getBoolean("config.arcade.enabled")) { - Arena a = null; - if (mg.getPlugin().getConfig().getBoolean("config.arcade.arena_to_prefer.enabled")) { - String arenaname = mg.getPlugin().getConfig().getString("config.arcade.arena_to_prefer.arena"); - a = mg.getArenaByName(arenaname); - if (a == null) { - for (Arena a_ : mg.getArenas()) { - if (a_.getArenaState() == ArenaState.JOIN || a_.getArenaState() == ArenaState.STARTING) { - a = a_; - break; - } - } - } - } else { - for (Arena a_ : mg.getArenas()) { - if (a_.getArenaState() == ArenaState.JOIN || a_.getArenaState() == ArenaState.STARTING) { - a = a_; - break; - } - } - } - if (a != null) { - in_a_game = true; - currentarena = a; - PluginInstance pli = MinigamesAPI.getAPI().getPluginInstance(plugin); - for (String p_ : temp) { - if (Validator.isPlayerOnline(p_)) { - String minigame = mg.getArenaListener().getName(); - if (!a.containsPlayer(p_)) { - Bukkit.getPlayer(p_).sendMessage(mg.getMessagesConfig().arcade_next_minigame.replaceAll("<minigame>", Character.toUpperCase(minigame.charAt(0)) + minigame.substring(1))); - a.joinPlayerLobby(p_, ai, plugin.getConfig().getBoolean("config.arcade.show_each_lobby_countdown"), false); - } - pli.getSpectatorManager().setSpectate(Bukkit.getPlayer(p_), false); - } - } - } else { - nextMinigame(5L); - } - } else { - nextMinigame(5L); - } - } - }, delay); - } - - public void clean() { - ArrayList<String> rem = new ArrayList<String>(); - for (String p_ : this.players) { - if (!Validator.isPlayerOnline(p_)) { - rem.add(p_); - } - } - for (String r : rem) { - if (players.contains(r)) { - players.remove(r); - } - } - } - +public class ArcadeInstance +{ + + public ArrayList<PluginInstance> minigames = new ArrayList<>(); + int currentindex = 0; + public ArrayList<String> players = new ArrayList<>(); + Arena arena; + JavaPlugin plugin; + + boolean in_a_game = false; + Arena currentarena = null; + boolean started; + + public ArcadeInstance(final JavaPlugin plugin, final ArrayList<PluginInstance> minigames, final Arena arena) + { + this.minigames = minigames; + this.arena = arena; + this.plugin = plugin; + } + + // TODO max 16 players! + public void joinArcade(final String playername) + { + final PluginInstance pli = MinigamesAPI.getAPI().getPluginInstance(this.plugin); + if (!this.players.contains(playername)) + { + this.players.add(playername); + this.arena.addPlayer(playername); + } + final Player p = Bukkit.getPlayer(playername); + if (p == null) + { + return; + } + if (this.players.size() >= this.plugin.getConfig().getInt(ArenaConfigStrings.CONFIG_ARCADE_MIN_PLAYERS)) + { + boolean msg = true; + if (!this.started) + { + this.startArcade(); + } + else + { + if (this.currentindex < this.minigames.size()) + { + if (this.in_a_game) + { + if (this.currentarena != null) + { + if (p != null) + { + final PluginInstance pli_ = this.minigames.get(this.currentindex); + if (this.currentarena.getArenaState() != ArenaState.INGAME && this.currentarena.getArenaState() != ArenaState.RESTARTING) + { + this.currentarena.joinPlayerLobby(playername, this, false, true); + } + else + { + msg = false; + this.currentarena.spectateArcade(playername); + } + + pli_.scoreboardManager.updateScoreboard(pli_.getPlugin(), this.currentarena); + } + } + } + } + } + if (msg) + { + p.sendMessage(MinigamesAPI.getAPI().getPluginInstance(this.plugin).getMessagesConfig().arcade_joined_waiting.replaceAll("<count>", "0")); + } + else + { + p.sendMessage(MinigamesAPI.getAPI().getPluginInstance(this.plugin).getMessagesConfig().arcade_joined_spectator); + } + } + else + { + p.sendMessage(MinigamesAPI.getAPI().getPluginInstance(this.plugin).getMessagesConfig().arcade_joined_waiting.replaceAll("<count>", + Integer.toString(this.plugin.getConfig().getInt(ArenaConfigStrings.CONFIG_ARCADE_MIN_PLAYERS) - this.players.size()))); + } + } + + public void leaveArcade(final String playername) + { + this.leaveArcade(playername, true); + } + + public void leaveArcade(final String playername, final boolean endOfGame) + { + final PluginInstance pli = MinigamesAPI.getAPI().getPluginInstance(this.plugin); + if (this.players.contains(playername)) + { + this.players.remove(playername); + } + if (this.arena.containsPlayer(playername)) + { + this.arena.removePlayer(playername); + } + if (this.minigames.get(this.currentindex).getArenas().size() > 0) + { + if (this.minigames.get(this.currentindex).getArenas().get(0).containsPlayer(playername)) + { + this.minigames.get(this.currentindex).getArenas().get(0).leavePlayer(playername, false, false); + } + } + Bukkit.getScheduler().runTaskLater(MinigamesAPI.getAPI(), () -> { + final Player p = Bukkit.getPlayer(playername); + if (p != null) + { + Util.teleportPlayerFixed(p, ArcadeInstance.this.arena.getMainLobbyTemp()); + pli.getSpectatorManager().setSpectate(p, false); + if (!p.isOp()) + { + p.setFlying(false); + p.setAllowFlight(false); + } + } + }, 20L); + this.clean(); + + // This shouldn't be necessary anymore except for arcade spectators + if (pli.containsGlobalPlayer(playername)) + { + pli.global_players.remove(playername); + } + if (pli.containsGlobalLost(playername)) + { + pli.global_lost.remove(playername); + } + if (this.currentarena != null) + { + MinigamesAPI.getAPI(); + final PluginInstance pli_ = MinigamesAPI.pinstances.get(this.currentarena.getPlugin()); + if (pli_ != null) + { + if (pli_.containsGlobalPlayer(playername)) + { + pli_.global_players.remove(playername); + } + if (pli_.containsGlobalLost(playername)) + { + pli_.global_lost.remove(playername); + } + } + } + + Util.updateSign(this.plugin, this.arena); + + if (endOfGame) + { + if (this.players.size() < 2) + { + this.stopArcade(false); + } + } + } + + int currentlobbycount = 31; + int currenttaskid = 0; + + public void startArcade() + { + if (this.started) + { + return; + } + this.started = true; + Collections.shuffle(this.minigames); + + this.currentlobbycount = this.plugin.getConfig().getInt(ArenaConfigStrings.CONFIG_ARCADE_LOBBY_COUNTDOWN) + 1; + final ArcadeInstance ai = this; + final PluginInstance pli = MinigamesAPI.getAPI().getPluginInstance(this.plugin); + + this.currenttaskid = Bukkit.getScheduler().runTaskTimer(MinigamesAPI.getAPI(), () -> { + ArcadeInstance.this.currentlobbycount--; + if (ArcadeInstance.this.currentlobbycount == 60 || ArcadeInstance.this.currentlobbycount == 30 || ArcadeInstance.this.currentlobbycount == 15 || ArcadeInstance.this.currentlobbycount == 10 + || ArcadeInstance.this.currentlobbycount < 6) + { + for (final String p_ : ai.players) + { + if (Validator.isPlayerOnline(p_)) + { + final Player p = Bukkit.getPlayer(p_); + p.sendMessage(pli.getMessagesConfig().starting_in.replaceAll("<count>", Integer.toString(ArcadeInstance.this.currentlobbycount))); + } + } + } + if (ArcadeInstance.this.currentlobbycount < 1) + { + ArcadeInstance.this.currentindex--; + ai.nextMinigame(); + try + { + Bukkit.getScheduler().cancelTask(ArcadeInstance.this.currenttaskid); + } + catch (final Exception e) + { + // silently ignore + } + } + }, 5L, 20).getTaskId(); + } + + public void stopArcade(final boolean stopOfGame) + { + try + { + Bukkit.getScheduler().cancelTask(this.currenttaskid); + } + catch (final Exception e) + { + // silently ignore + } + final ArrayList<String> temp = new ArrayList<>(this.players); + for (final String p_ : temp) + { + this.leaveArcade(p_, false); + } + this.players.clear(); + this.started = false; + this.in_a_game = false; + this.currentarena = null; + this.currentindex = 0; + + final HashSet hs = new HashSet(); + hs.addAll(temp); + temp.clear(); + temp.addAll(hs); + final ArcadeInstance ai = this; + if (stopOfGame && this.plugin.getConfig().getBoolean(ArenaConfigStrings.CONFIG_ARCADE_INFINITE_ENABLED)) + { + if (temp.size() > 1) + { + for (final String p_ : temp) + { + Util.sendMessage(this.plugin, Bukkit.getPlayer(p_), MinigamesAPI.getAPI().getPluginInstance(this.plugin).getMessagesConfig().arcade_new_round.replaceAll("<count>", + Integer.toString(this.plugin.getConfig().getInt(ArenaConfigStrings.CONFIG_ARCADE_INFINITE_SECONDS_TO_NEW_ROUND)))); + } + Bukkit.getScheduler().runTaskLater(this.plugin, () -> { + for (final String p_ : temp) + { + if (!ArcadeInstance.this.players.contains(p_)) + { + ArcadeInstance.this.players.add(p_); + } + } + ai.startArcade(); + }, Math.max(40L, 20L * this.plugin.getConfig().getInt(ArenaConfigStrings.CONFIG_ARCADE_INFINITE_SECONDS_TO_NEW_ROUND))); + } + } + } + + public void stopArcade() + { + this.stopArcade(false); + } + + public void stopCurrentMinigame() + { + if (this.currentindex < this.minigames.size()) + { + final PluginInstance mg = this.minigames.get(this.currentindex); + if (mg.getArenas().size() > 0) + { + if (mg.getPlugin().getConfig().getBoolean(ArenaConfigStrings.CONFIG_ARCADE_ARENA_TO_PREFER_ENABLED)) + { + final String arenaname = mg.getPlugin().getConfig().getString(ArenaConfigStrings.CONFIG_ARCADE_ARENA_TO_PREFER_ARENA); + final Arena a = mg.getArenaByName(arenaname); + if (a != null) + { + a.stopArena(); + } + } + else + { + this.minigames.get(this.currentindex).getArenas().get(0).stopArena(); + } + } + } + } + + public void nextMinigame() + { + this.nextMinigame(30L); + } + + public void nextMinigame(final long delay) + { + this.in_a_game = false; + + if (this.currentindex < this.minigames.size() - 1) + { + this.currentindex++; + } + else + { + this.arena.stopArena(); + // stopArcade(); + return; + } + final ArcadeInstance ai = this; + Bukkit.getScheduler().runTaskLater(MinigamesAPI.getAPI(), () -> { + final ArrayList<String> temp = new ArrayList<>(ArcadeInstance.this.players); + + final PluginInstance mg = ArcadeInstance.this.minigames.get(ArcadeInstance.this.currentindex); + if (mg.getPlugin().getConfig().getBoolean(ArenaConfigStrings.CONFIG_ARCADE_ENABLED)) + { + Arena a = null; + if (mg.getPlugin().getConfig().getBoolean(ArenaConfigStrings.CONFIG_ARCADE_ARENA_TO_PREFER_ENABLED)) + { + final String arenaname = mg.getPlugin().getConfig().getString(ArenaConfigStrings.CONFIG_ARCADE_ARENA_TO_PREFER_ARENA); + a = mg.getArenaByName(arenaname); + if (a == null) + { + for (final Arena a_1 : mg.getArenas()) + { + if (a_1.getArenaState() == ArenaState.JOIN || a_1.getArenaState() == ArenaState.STARTING) + { + a = a_1; + break; + } + } + } + } + else + { + for (final Arena a_2 : mg.getArenas()) + { + if (a_2.getArenaState() == ArenaState.JOIN || a_2.getArenaState() == ArenaState.STARTING) + { + a = a_2; + break; + } + } + } + if (a != null) + { + ArcadeInstance.this.in_a_game = true; + ArcadeInstance.this.currentarena = a; + final PluginInstance pli = MinigamesAPI.getAPI().getPluginInstance(ArcadeInstance.this.plugin); + for (final String p_ : temp) + { + if (Validator.isPlayerOnline(p_)) + { + final String minigame = mg.getArenaListener().getName(); + if (!a.containsPlayer(p_)) + { + Bukkit.getPlayer(p_) + .sendMessage(mg.getMessagesConfig().arcade_next_minigame.replaceAll("<minigame>", Character.toUpperCase(minigame.charAt(0)) + minigame.substring(1))); + a.joinPlayerLobby(p_, ai, ArcadeInstance.this.plugin.getConfig().getBoolean(ArenaConfigStrings.CONFIG_ARCADE_SHOW_EACH_LOBBY_COUNTDOWN), false); + } + pli.getSpectatorManager().setSpectate(Bukkit.getPlayer(p_), false); + } + } + } + else + { + ArcadeInstance.this.nextMinigame(5L); + } + } + else + { + ArcadeInstance.this.nextMinigame(5L); + } + }, delay); + } + + public void clean() + { + final ArrayList<String> rem = new ArrayList<>(); + for (final String p_ : this.players) + { + if (!Validator.isPlayerOnline(p_)) + { + rem.add(p_); + } + } + for (final String r : rem) + { + if (this.players.contains(r)) + { + this.players.remove(r); + } + } + } + } diff --git a/API/src/main/java/com/comze_instancelabs/minigamesapi/bungee/BungeeSocket.java b/API/src/main/java/com/comze_instancelabs/minigamesapi/bungee/BungeeSocket.java deleted file mode 100644 index 1b48a417..00000000 --- a/API/src/main/java/com/comze_instancelabs/minigamesapi/bungee/BungeeSocket.java +++ /dev/null @@ -1,72 +0,0 @@ -package com.comze_instancelabs.minigamesapi.bungee; - -import java.io.BufferedReader; -import java.io.InputStreamReader; -import java.io.PrintWriter; -import java.net.ServerSocket; -import java.net.Socket; -import java.util.ArrayList; - -import com.comze_instancelabs.minigamesapi.Arena; -import com.comze_instancelabs.minigamesapi.ArenaLogger; -import com.comze_instancelabs.minigamesapi.PluginInstance; - -public class BungeeSocket { - - // Here sits the lovely MGLib server waiting for requests from our Lobby slaves >:D - // Socket server moved to lobby, dis our slave now :( - - // We're gonna send simple strings like: sign:<minigame>:<arena>:<state>:<players>/<amxplayers> - - public static String signUpdateString(PluginInstance pli, Arena a) { - if (a == null) { - return "sign:" + pli.getPlugin().getName() + ":null:JOIN:0:0"; - } - return "sign:" + pli.getPlugin().getName() + ":" + a.getInternalName() + ":" + a.getArenaState().toString() + ":" + a.getAllPlayers().size() + ":" + a.getMaxPlayers(); - } - - static ArrayList<Integer> portsUp = new ArrayList<Integer>(); - static boolean init = false; - static boolean initializing = false; - - public static void sendSignUpdate(final PluginInstance pli, final Arena a) { - try { - if (init) { - for (int i : portsUp) { - ArenaLogger.debug("Sending to port " + i); - Socket socket = new Socket("127.0.0.1", i); - PrintWriter out = new PrintWriter(socket.getOutputStream(), true); - out.println(signUpdateString(pli, a)); - socket.close(); - } - return; - } - // Of course we'll have lags at the first sign update as we check through 20 ports - if (!initializing) { - initializing = true; - new Thread(new Runnable() { - public void run() { - for (int i = 13380; i < 13400; i++) { - try { - ArenaLogger.debug("Trying port " + i); - Socket socket = new Socket("127.0.0.1", i); - if (socket.isConnected()) { - portsUp.add(i); - } - PrintWriter out = new PrintWriter(socket.getOutputStream(), true); - out.println(signUpdateString(pli, a)); - socket.close(); - } catch (Exception e) { - ArenaLogger.debug("Could not connect to port " + i); - } - } - init = true; - } - }).start(); - } - } catch (Exception e) { - e.printStackTrace(); - } - - } -} diff --git a/API/src/main/java/com/comze_instancelabs/minigamesapi/commands/CommandHandler.java b/API/src/main/java/com/comze_instancelabs/minigamesapi/commands/CommandHandler.java index 6fc11a66..4b63fa94 100644 --- a/API/src/main/java/com/comze_instancelabs/minigamesapi/commands/CommandHandler.java +++ b/API/src/main/java/com/comze_instancelabs/minigamesapi/commands/CommandHandler.java @@ -1,9 +1,25 @@ +/* + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ package com.comze_instancelabs.minigamesapi.commands; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.Map; import java.util.TreeMap; +import java.util.UUID; +import java.util.logging.Level; import org.bukkit.Bukkit; import org.bukkit.ChatColor; @@ -13,1117 +29,1628 @@ import org.bukkit.plugin.java.JavaPlugin; import com.comze_instancelabs.minigamesapi.Arena; +import com.comze_instancelabs.minigamesapi.ArenaConfigStrings; import com.comze_instancelabs.minigamesapi.ArenaPlayer; import com.comze_instancelabs.minigamesapi.ArenaState; +import com.comze_instancelabs.minigamesapi.CommandStrings; import com.comze_instancelabs.minigamesapi.MinigamesAPI; import com.comze_instancelabs.minigamesapi.Party; import com.comze_instancelabs.minigamesapi.PluginInstance; +import com.comze_instancelabs.minigamesapi.PrivateUtil; +import com.comze_instancelabs.minigamesapi.Stats; import com.comze_instancelabs.minigamesapi.config.HologramsConfig; import com.comze_instancelabs.minigamesapi.util.AClass; import com.comze_instancelabs.minigamesapi.util.Util; import com.comze_instancelabs.minigamesapi.util.Validator; -public class CommandHandler { - - /** - * Handles the default commands needed for arena management. - * - * @param uber_permission - * Main setup permission. Example: Skywars.setup - * @param cmd - * The command. Example: /sw - * @param sender - * @param args - * @return - */ - public boolean handleArgs(JavaPlugin plugin, String uber_permission, String cmd, CommandSender sender, String args[]) { - if (args.length > 0) { - if (!(sender instanceof Player)) { - sender.sendMessage("Please execute this command ingame."); - return true; - } - Player p = (Player) sender; - PluginInstance pli = MinigamesAPI.getAPI().getPluginInstance(plugin); - String action = args[0]; - if (action.equalsIgnoreCase("setspawn")) { - return this.setSpawn(pli, sender, args, uber_permission, cmd, action, plugin, p); - } else if (action.equalsIgnoreCase("setspecspawn")) { - return this.setSpecSpawn(pli, sender, args, uber_permission, cmd, action, plugin, p); - } else if (action.equalsIgnoreCase("setlobby")) { - return this.setLobby(pli, sender, args, uber_permission, cmd, action, plugin, p); - } else if (action.equalsIgnoreCase("setmainlobby")) { - return this.setMainLobby(pli, sender, args, uber_permission, cmd, action, plugin, p); - } else if (action.equalsIgnoreCase("setbounds")) { - return this.setBounds(pli, sender, args, uber_permission, cmd, action, plugin, p); - } else if (action.equalsIgnoreCase("setlobbybounds")) { - return this.setLobbyBounds(pli, sender, args, uber_permission, cmd, action, plugin, p); - } else if (action.equalsIgnoreCase("setspecbounds")) { - return this.setSpecBounds(pli, sender, args, uber_permission, cmd, action, plugin, p); - } else if (action.equalsIgnoreCase("savearena") || action.equalsIgnoreCase("save")) { - return this.saveArena(pli, sender, args, uber_permission, cmd, action, plugin, p); - } else if (action.equalsIgnoreCase("setmaxplayers")) { - return this.setMaxPlayers(pli, sender, args, uber_permission, cmd, action, plugin, p); - } else if (action.equalsIgnoreCase("setminplayers")) { - return this.setMinPlayers(pli, sender, args, uber_permission, cmd, action, plugin, p); - } else if (action.equalsIgnoreCase("setarenavip") || action.equalsIgnoreCase("setvip")) { - return this.setArenaVIP(pli, sender, args, uber_permission, cmd, action, plugin, p); - } else if (action.equalsIgnoreCase("join")) { - return this.joinArena(pli, sender, args, uber_permission, cmd, action, plugin, p); - } else if (action.equalsIgnoreCase("leave")) { - return this.leaveArena(pli, sender, args, uber_permission, cmd, action, plugin, p); - } else if (action.equalsIgnoreCase("start")) { - return this.startArena(pli, sender, args, uber_permission, cmd, action, plugin, p); - } else if (action.equalsIgnoreCase("stop")) { - return this.stopArena(pli, sender, args, uber_permission, cmd, action, plugin, p); - } else if (action.equalsIgnoreCase("stopall")) { - return this.stopAllArenas(pli, sender, args, uber_permission, cmd, action, plugin, p); - } else if (action.equalsIgnoreCase("removearena")) { - return this.removeArena(pli, sender, args, uber_permission, cmd, action, plugin, p); - } else if (action.equalsIgnoreCase("removespawn")) { - return this.removeSpawn(pli, sender, args, uber_permission, cmd, action, plugin, p); - } else if (action.equalsIgnoreCase("setskull")) { - return this.setSkull(pli, sender, args, uber_permission, cmd, action, plugin, p); - } else if (action.equalsIgnoreCase("setenabled")) { - return this.setEnabled(pli, sender, args, uber_permission, cmd, action, plugin, p); - } else if (action.equalsIgnoreCase("setshowscoreboard")) { - return this.setShowScoreboard(pli, sender, args, uber_permission, cmd, action, plugin, p); - } else if (action.equalsIgnoreCase("reset")) { - return this.resetArena(pli, sender, args, uber_permission, cmd, action, plugin, p); - } else if (action.equalsIgnoreCase("setauthor")) { - return this.setAuthor(pli, sender, args, uber_permission, cmd, action, plugin, p); - } else if (action.equalsIgnoreCase("setdescription")) { - return this.setDescription(pli, sender, args, uber_permission, cmd, action, plugin, p); - } else if (action.equalsIgnoreCase("setdisplayname")) { - return this.setArenaDisplayName(pli, sender, args, uber_permission, cmd, action, plugin, p); - } else if (action.equalsIgnoreCase("kit")) { - return this.setKit(pli, sender, args, uber_permission, cmd, action, plugin, p); - } else if (action.equalsIgnoreCase("spectate")) { - return this.spectate(pli, sender, args, uber_permission, cmd, action, plugin, p); - } else if (action.equalsIgnoreCase("shop")) { - return this.openShop(pli, sender, args, uber_permission, cmd, action, plugin, p); - } else if (action.equalsIgnoreCase("leaderboards") || action.equalsIgnoreCase("lb")) { - return this.getLeaderboards(pli, sender, args, uber_permission, cmd, action, plugin, p); - } else if (action.equalsIgnoreCase("stats")) { - return this.getStats(pli, sender, args, uber_permission, cmd, action, plugin, p); - } else if (action.equalsIgnoreCase("sethologram")) { - return this.setHologram(pli, sender, args, uber_permission, cmd, action, plugin, p); - } else if (action.equalsIgnoreCase("listholograms")) { - return this.listHolograms(pli, sender, args, uber_permission, cmd, action, plugin, p); - } else if (action.equalsIgnoreCase("removehologram")) { - return this.removeHologram(pli, sender, args, uber_permission, cmd, action, plugin, p); - } else if (action.equalsIgnoreCase("help")) { - sendHelp(cmd, sender); - } else if (action.equalsIgnoreCase("list")) { - sender.sendMessage(ChatColor.DARK_GRAY + "------- " + ChatColor.BLUE + "Arenas" + ChatColor.DARK_GRAY + " -------"); - for (Arena a : pli.getArenas()) { - if (args.length > 1) { - sender.sendMessage(ChatColor.GREEN + a.getInternalName() + "[" + a.getClass().getSimpleName().toString() + "]"); - } else { - sender.sendMessage(ChatColor.GREEN + a.getInternalName()); - } - } - } else if (action.equalsIgnoreCase("reload")) { - plugin.reloadConfig(); - pli.getMessagesConfig().reloadConfig(); - pli.getArenasConfig().reloadConfig(); - pli.getClassesConfig().reloadConfig(); - pli.getAchievementsConfig().reloadConfig(); - pli.getStatsConfig().reloadConfig(); - pli.getShopConfig().reloadConfig(); - pli.getMessagesConfig().init(); - pli.reloadVariables(); - pli.getRewardsInstance().reloadVariables(); - pli.getStatsInstance().reloadVariables(); - pli.getAClasses().clear(); - pli.getClassesHandler().loadClasses(); - try { - pli.reloadAllArenas(); - } catch (Exception e) { - System.out.println("Looks like one arena is invalid, but most arenas should be reloaded just fine. " + e.getMessage()); - } - sender.sendMessage(pli.getMessagesConfig().successfully_reloaded); - } else { - boolean cont = false; - ArrayList<String> cmds = new ArrayList<String>(); - for (String cmd_ : cmddesc.keySet()) { - if (cmd_.toLowerCase().contains(action.toLowerCase())) { - cmds.add(cmd_); - cont = true; - } - } - if (cont) { - sendHelp(cmd, sender); - for (String cmd_ : cmds) { - sender.sendMessage(ChatColor.RED + "Did you mean " + ChatColor.DARK_RED + cmd + " " + cmd_ + ChatColor.RED + "?"); - } - } - } - } else { - sendHelp(cmd, sender); - } - return true; - } - - public static LinkedHashMap<String, String> cmddesc; - static { - cmddesc = new LinkedHashMap<String, String>(); - cmddesc.put("", ""); - cmddesc.put("setspawn <arena>", "Sets the spawn point."); - cmddesc.put("setlobby <arena>", "Sets the lobby point."); - cmddesc.put("setmainlobby", "Sets the main lobby point."); - cmddesc.put("setbounds <arena> <low/high>", "Sets the low or high boundary point for later arena regeneration."); - cmddesc.put("savearena <arena>", "Saves the arena."); - cmddesc.put(" ", ""); - cmddesc.put("setmaxplayers <arena> <count>", "Sets the max players allowed to join to given count."); - cmddesc.put("setminplayers <arena> <count>", "Sets the min players needed to start to given count."); - cmddesc.put("setarenavip <arena> <true/false>", "Sets whether arena needs permission to join."); - cmddesc.put("removearena <arena>", "Deletes an arena from config."); - cmddesc.put("removespawn <arena> <count>", "Deletes a spawn from config."); - cmddesc.put("setenabled", "Enables/Disables the arena."); - cmddesc.put("join <arena>", "Joins the arena."); - cmddesc.put("leave", "Leaves the arena."); - cmddesc.put("start <arena>", "Forces the arena to start."); - cmddesc.put("stop <arena>", "Forces the arena to stop."); - cmddesc.put("list", "Lists all arenas."); - cmddesc.put("reload", "Reloads the config."); - cmddesc.put("reset <arena>", "Forces the arena to reset."); - cmddesc.put("setlobbybounds <arena> <low/high>", "Optional: Set lobby boundaries."); - cmddesc.put("setspecbounds <arena> <low/high>", "Optional: Set extra spectator boundaries."); - cmddesc.put("setauthor <arena> <author>", "Will always display the author of the map at join."); - cmddesc.put("setdescription <arena> <description>", "Will always display a description of the map at join."); - cmddesc.put("setdisplayname <arena> <displayname>", "Allows changing displayname of an arena (whitespaces and colors)."); - } - - public static void sendHelp(String cmd, CommandSender sender) { - sender.sendMessage(ChatColor.DARK_GRAY + "------- " + ChatColor.BLUE + "Help" + ChatColor.DARK_GRAY + " -------"); - for (String k : cmddesc.keySet()) { - if (k.length() < 3) { - sender.sendMessage(""); - continue; - } - String v = cmddesc.get(k); - sender.sendMessage(ChatColor.DARK_AQUA + cmd + " " + k + ChatColor.DARK_GRAY + " - " + ChatColor.GRAY + v); - } - } - - public static LinkedHashMap<String, String> cmdpartydesc; - static { - cmdpartydesc = new LinkedHashMap<String, String>(); - cmdpartydesc.put("", ""); - cmdpartydesc.put("invite <player>", "Invites a player to your party and creates one if you don't have one yet."); - cmdpartydesc.put("accept <player>", "Accepts an invitation to a party"); - cmdpartydesc.put("disband", "Disbands the party"); - cmdpartydesc.put("kick <player>", "Kicks a player from your party."); - cmdpartydesc.put("leave", "Leaves a party you're in."); - cmdpartydesc.put("list", "Lists all players and the owner of the party."); - } - - public static void sendPartyHelp(String cmd, CommandSender sender) { - sender.sendMessage(ChatColor.DARK_GRAY + "------- " + ChatColor.BLUE + "Help" + ChatColor.DARK_GRAY + " -------"); - for (String k : cmdpartydesc.keySet()) { - if (k.length() < 3) { - sender.sendMessage(""); - continue; - } - String v = cmdpartydesc.get(k); - sender.sendMessage(ChatColor.DARK_AQUA + cmd + " " + k + ChatColor.DARK_GRAY + " - " + ChatColor.GRAY + v); - } - } - - public boolean setSpawn(PluginInstance pli, CommandSender sender, String[] args, String uber_permission, String cmd, String action, JavaPlugin plugin, Player p) { - if (!sender.hasPermission(uber_permission + ".setup")) { - sender.sendMessage(pli.getMessagesConfig().no_perm); - return true; - } - if (args.length > 1) { - pli.arenaSetup.setSpawn(plugin, args[1], p.getLocation()); - sender.sendMessage(pli.getMessagesConfig().successfully_set.replaceAll("<component>", "spawn")); - } else { - sender.sendMessage(ChatColor.DARK_GRAY + "[" + ChatColor.RED + "-" + ChatColor.DARK_GRAY + "]" + ChatColor.GRAY + " Usage: " + cmd + " " + action + " <arena>"); - } - return true; - } - - public boolean setSpecSpawn(PluginInstance pli, CommandSender sender, String[] args, String uber_permission, String cmd, String action, JavaPlugin plugin, Player p) { - if (!sender.hasPermission(uber_permission + ".setup")) { - sender.sendMessage(pli.getMessagesConfig().no_perm); - return true; - } - if (args.length > 1) { - Util.saveComponentForArena(plugin, args[1], "specspawn", p.getLocation()); - sender.sendMessage(pli.getMessagesConfig().successfully_set.replaceAll("<component>", "spectator spawn")); - } else { - sender.sendMessage(ChatColor.DARK_GRAY + "[" + ChatColor.RED + "-" + ChatColor.DARK_GRAY + "]" + ChatColor.GRAY + " Usage: " + cmd + " " + action + " <arena>"); - } - return true; - } - - public boolean setLobby(PluginInstance pli, CommandSender sender, String[] args, String uber_permission, String cmd, String action, JavaPlugin plugin, Player p) { - if (!sender.hasPermission(uber_permission + ".setup")) { - sender.sendMessage(pli.getMessagesConfig().no_perm); - return true; - } - if (args.length > 1) { - pli.arenaSetup.setLobby(plugin, args[1], p.getLocation()); - sender.sendMessage(pli.getMessagesConfig().successfully_set.replaceAll("<component>", "waiting lobby")); - } else { - sender.sendMessage(ChatColor.DARK_GRAY + "[" + ChatColor.RED + "-" + ChatColor.DARK_GRAY + "]" + ChatColor.GRAY + " Usage: " + cmd + " " + action + " <arena>"); - } - return true; - } - - public boolean setMainLobby(PluginInstance pli, CommandSender sender, String[] args, String uber_permission, String cmd, String action, JavaPlugin plugin, Player p) { - if (!sender.hasPermission(uber_permission + ".setup")) { - sender.sendMessage(pli.getMessagesConfig().no_perm); - return true; - } - pli.arenaSetup.setMainLobby(plugin, p.getLocation()); - sender.sendMessage(pli.getMessagesConfig().successfully_set.replaceAll("<component>", "main lobby")); - return true; - } - - public boolean setBounds(PluginInstance pli, CommandSender sender, String[] args, String uber_permission, String cmd, String action, JavaPlugin plugin, Player p) { - if (!sender.hasPermission(uber_permission + ".setup")) { - sender.sendMessage(pli.getMessagesConfig().no_perm); - return true; - } - if (args.length > 2) { - if (args[2].equalsIgnoreCase("low")) { - pli.arenaSetup.setBoundaries(plugin, args[1], p.getLocation(), true); - } else if (args[2].equalsIgnoreCase("high")) { - pli.arenaSetup.setBoundaries(plugin, args[1], p.getLocation(), false); - } else { - sender.sendMessage(ChatColor.DARK_GRAY + "[" + ChatColor.RED + "-" + ChatColor.DARK_GRAY + "]" + ChatColor.GRAY + " Usage: " + cmd + " " + action + " <arena> <low/high>"); - return true; - } - sender.sendMessage(pli.getMessagesConfig().successfully_set.replaceAll("<component>", "boundary")); - } else { - sender.sendMessage(ChatColor.DARK_GRAY + "[" + ChatColor.RED + "-" + ChatColor.DARK_GRAY + "]" + ChatColor.GRAY + " Usage: " + cmd + " " + action + " <arena> <low/high>"); - } - return true; - } - - public boolean setLobbyBounds(PluginInstance pli, CommandSender sender, String[] args, String uber_permission, String cmd, String action, JavaPlugin plugin, Player p) { - if (!sender.hasPermission(uber_permission + ".setup")) { - sender.sendMessage(pli.getMessagesConfig().no_perm); - return true; - } - if (args.length > 2) { - if (args[2].equalsIgnoreCase("low")) { - pli.arenaSetup.setBoundaries(plugin, args[1], p.getLocation(), true, "lobbybounds"); - } else if (args[2].equalsIgnoreCase("high")) { - pli.arenaSetup.setBoundaries(plugin, args[1], p.getLocation(), false, "lobbybounds"); - } else { - sender.sendMessage(ChatColor.DARK_GRAY + "[" + ChatColor.RED + "-" + ChatColor.DARK_GRAY + "]" + ChatColor.GRAY + " Usage: " + cmd + " " + action + " <arena> <low/high>"); - return true; - } - sender.sendMessage(pli.getMessagesConfig().successfully_set.replaceAll("<component>", "lobby boundary")); - } else { - sender.sendMessage(ChatColor.DARK_GRAY + "[" + ChatColor.RED + "-" + ChatColor.DARK_GRAY + "]" + ChatColor.GRAY + " Usage: " + cmd + " " + action + " <arena> <low/high>"); - } - return true; - } - - public boolean setSpecBounds(PluginInstance pli, CommandSender sender, String[] args, String uber_permission, String cmd, String action, JavaPlugin plugin, Player p) { - if (!sender.hasPermission(uber_permission + ".setup")) { - sender.sendMessage(pli.getMessagesConfig().no_perm); - return true; - } - if (args.length > 2) { - if (args[2].equalsIgnoreCase("low")) { - pli.arenaSetup.setBoundaries(plugin, args[1], p.getLocation(), true, "specbounds"); - } else if (args[2].equalsIgnoreCase("high")) { - pli.arenaSetup.setBoundaries(plugin, args[1], p.getLocation(), false, "specbounds"); - } else { - sender.sendMessage(ChatColor.DARK_GRAY + "[" + ChatColor.RED + "-" + ChatColor.DARK_GRAY + "]" + ChatColor.GRAY + " Usage: " + cmd + " " + action + " <arena> <low/high>"); - return true; - } - sender.sendMessage(pli.getMessagesConfig().successfully_set.replaceAll("<component>", "spectator boundary")); - } else { - sender.sendMessage(ChatColor.DARK_GRAY + "[" + ChatColor.RED + "-" + ChatColor.DARK_GRAY + "]" + ChatColor.GRAY + " Usage: " + cmd + " " + action + " <arena> <low/high>"); - } - return true; - } - - public boolean saveArena(PluginInstance pli, CommandSender sender, String[] args, String uber_permission, String cmd, String action, JavaPlugin plugin, Player p) { - if (!sender.hasPermission(uber_permission + ".setup")) { - sender.sendMessage(pli.getMessagesConfig().no_perm); - return true; - } - if (args.length > 1) { - Arena temp = pli.arenaSetup.saveArena(plugin, args[1]); - if (temp != null) { - sender.sendMessage(pli.getMessagesConfig().successfully_saved_arena.replaceAll("<arena>", args[1])); - } else { - sender.sendMessage(pli.getMessagesConfig().failed_saving_arena.replaceAll("<arena>", args[1])); - sender.sendMessage(ChatColor.GRAY + "++ Debug Info ++"); - sender.sendMessage(ChatColor.GRAY + "LOBBY:" + Util.isComponentForArenaValidRaw(plugin, args[1], "lobby") + ChatColor.RED + ";" + ChatColor.GRAY + " SPAWN0:" + Util.isComponentForArenaValidRaw(plugin, args[1], "spawns.spawn0") + ChatColor.RED + ";" + ChatColor.GRAY + " BOUNDARIES(possibly needed): low:" + Util.isComponentForArenaValidRaw(plugin, args[1], "bounds.low") + ", high:" + Util.isComponentForArenaValidRaw(plugin, args[1], "bounds.high")); - } - } else { - sender.sendMessage(ChatColor.DARK_GRAY + "[" + ChatColor.RED + "-" + ChatColor.DARK_GRAY + "]" + ChatColor.GRAY + " Usage: " + cmd + " " + action + " <arena>"); - } - return true; - } - - public boolean setMaxPlayers(PluginInstance pli, CommandSender sender, String[] args, String uber_permission, String cmd, String action, JavaPlugin plugin, Player p) { - if (!sender.hasPermission(uber_permission + ".setup")) { - sender.sendMessage(pli.getMessagesConfig().no_perm); - return true; - } - if (args.length > 2) { - if (!Util.isNumeric(args[2])) { - return true; - } - pli.arenaSetup.setPlayerCount(plugin, args[1], Integer.parseInt(args[2]), true); - if (pli.getArenaByName(args[1]) != null) { - pli.getArenaByName(args[1]).setMaxPlayers(Integer.parseInt(args[2])); - } - sender.sendMessage(pli.getMessagesConfig().successfully_set.replaceAll("<component>", "max players")); - } else { - sender.sendMessage(ChatColor.DARK_GRAY + "[" + ChatColor.RED + "-" + ChatColor.DARK_GRAY + "]" + ChatColor.GRAY + " Usage: " + cmd + " " + action + " <arena> <count>"); - } - return true; - } - - public boolean setMinPlayers(PluginInstance pli, CommandSender sender, String[] args, String uber_permission, String cmd, String action, JavaPlugin plugin, Player p) { - if (!sender.hasPermission(uber_permission + ".setup")) { - sender.sendMessage(pli.getMessagesConfig().no_perm); - return true; - } - if (args.length > 2) { - if (!Util.isNumeric(args[2])) { - return true; - } - pli.arenaSetup.setPlayerCount(plugin, args[1], Integer.parseInt(args[2]), false); - if (pli.getArenaByName(args[1]) != null) { - pli.getArenaByName(args[1]).setMinPlayers(Integer.parseInt(args[2])); - } - sender.sendMessage(pli.getMessagesConfig().successfully_set.replaceAll("<component>", "min players")); - } else { - sender.sendMessage(ChatColor.DARK_GRAY + "[" + ChatColor.RED + "-" + ChatColor.DARK_GRAY + "]" + ChatColor.GRAY + " Usage: " + cmd + " " + action + " <arena> <count>"); - } - return true; - } - - public boolean setArenaVIP(PluginInstance pli, CommandSender sender, String[] args, String uber_permission, String cmd, String action, JavaPlugin plugin, Player p) { - if (!sender.hasPermission(uber_permission + ".setup")) { - sender.sendMessage(pli.getMessagesConfig().no_perm); - return true; - } - if (args.length > 2) { - if (!args[2].equalsIgnoreCase("true") && !args[2].equalsIgnoreCase("false")) { - return true; - } - pli.arenaSetup.setArenaVIP(plugin, args[1], Boolean.parseBoolean(args[2])); - if (pli.getArenaByName(args[1]) != null) { - pli.getArenaByName(args[1]).setVIPArena(Boolean.parseBoolean(args[2])); - } - sender.sendMessage(pli.getMessagesConfig().successfully_set.replaceAll("<component>", "vip value")); - } else { - sender.sendMessage(ChatColor.DARK_GRAY + "[" + ChatColor.RED + "-" + ChatColor.DARK_GRAY + "]" + ChatColor.GRAY + " Usage: " + cmd + " " + action + " <arena> <true/false>"); - } - return true; - } - - public boolean joinArena(PluginInstance pli, CommandSender sender, String[] args, String uber_permission, String cmd, String action, JavaPlugin plugin, Player p) { - if (args.length > 1) { - String playername = p.getName(); - if (args.length > 2) { - if (Validator.isPlayerOnline(args[2])) { - playername = args[2]; - } - } - Arena temp = pli.getArenaByName(args[1]); - if (temp != null) { - if (!temp.containsPlayer(playername)) { - temp.joinPlayerLobby(playername); - } else { - sender.sendMessage(pli.getMessagesConfig().you_already_are_in_arena.replaceAll("<arena>", temp.getInternalName())); - } - } else { - sender.sendMessage(pli.getMessagesConfig().arena_invalid.replaceAll("<arena>", args[1])); - } - } else { - Arena a_ = null; - for (Arena a : pli.getArenas()) { - if (a.getArenaState() != ArenaState.INGAME) { - a_ = a; - } - } - if (a_ != null) { - a_.joinPlayerLobby(p.getName()); - } else { - sender.sendMessage(pli.getMessagesConfig().arena_invalid.replaceAll("<arena>", "Arena")); - } - } - return true; - } - - public boolean leaveArena(PluginInstance pli, CommandSender sender, String[] args, String uber_permission, String cmd, String action, JavaPlugin plugin, Player p) { - if (pli.global_players.containsKey(p.getName())) { - String playername = p.getName(); - if (args.length > 1) { - if (sender.hasPermission(uber_permission + ".kickplayer")) { - if (Validator.isPlayerOnline(args[1])) { - playername = args[1]; - } - } - } - Arena a = pli.global_players.get(playername); - if (a.getArcadeInstance() != null) { - a.getArcadeInstance().leaveArcade(playername, true); - } - a.leavePlayer(playername, false, false); - } else { - sender.sendMessage(pli.getMessagesConfig().not_in_arena); - } - return true; - } - - public boolean startArena(PluginInstance pli, CommandSender sender, String[] args, String uber_permission, String cmd, String action, JavaPlugin plugin, Player p) { - if (!sender.hasPermission(uber_permission + ".start")) { - sender.sendMessage(pli.getMessagesConfig().no_perm); - return true; - } - if (args.length > 1) { - Arena temp = pli.getArenaByName(args[1]); - if (temp != null) { - temp.start(true); - sender.sendMessage(pli.getMessagesConfig().arena_action.replaceAll("<arena>", args[1]).replaceAll("<action>", "started")); - } else { - sender.sendMessage(pli.getMessagesConfig().arena_invalid.replaceAll("<arena>", args[1])); - } - } else { - sender.sendMessage(pli.getMessagesConfig().arena_invalid.replaceAll("<arena>", "Arena")); - } - return true; - } - - public boolean stopArena(PluginInstance pli, CommandSender sender, String[] args, String uber_permission, String cmd, String action, JavaPlugin plugin, Player p) { - if (!sender.hasPermission(uber_permission + ".stop")) { - sender.sendMessage(pli.getMessagesConfig().no_perm); - return true; - } - if (args.length > 1) { - Arena temp = pli.getArenaByName(args[1]); - if (temp != null) { - temp.stop(); - sender.sendMessage(pli.getMessagesConfig().arena_action.replaceAll("<arena>", args[1]).replaceAll("<action>", "stopped")); - } else { - sender.sendMessage(pli.getMessagesConfig().arena_invalid.replaceAll("<arena>", args[1])); - } - } else { - if (pli.containsGlobalPlayer(p.getName())) { - Arena a = pli.global_players.get(p.getName()); - a.stop(); - sender.sendMessage(pli.getMessagesConfig().arena_action.replaceAll("<arena>", args[1]).replaceAll("<action>", "stopped")); - return true; - } - sender.sendMessage(pli.getMessagesConfig().arena_invalid.replaceAll("<arena>", "Arena")); - } - return true; - } - - public boolean stopAllArenas(PluginInstance pli, CommandSender sender, String[] args, String uber_permission, String cmd, String action, JavaPlugin plugin, Player p) { - if (!sender.hasPermission(uber_permission + ".stop")) { - sender.sendMessage(pli.getMessagesConfig().no_perm); - return true; - } - for (Arena a : pli.getArenas()) { - a.stop(); - } - return true; - } - - public boolean removeArena(PluginInstance pli, CommandSender sender, String[] args, String uber_permission, String cmd, String action, JavaPlugin plugin, Player p) { - if (!sender.hasPermission(uber_permission + ".setup")) { - sender.sendMessage(pli.getMessagesConfig().no_perm); - return true; - } - if (args.length > 1) { - pli.getArenasConfig().getConfig().set("arenas." + args[1], null); - pli.getArenasConfig().saveConfig(); - if (pli.removeArena(pli.getArenaByName(args[1]))) { - sender.sendMessage(pli.getMessagesConfig().arena_action.replaceAll("<arena>", args[1]).replaceAll("<action>", "removed")); - } else { - sender.sendMessage(pli.getMessagesConfig().failed_removing_arena.replaceAll("<arena>", args[1])); - } - // TODO remove arena file if present - } else { - sender.sendMessage(ChatColor.DARK_GRAY + "[" + ChatColor.RED + "-" + ChatColor.DARK_GRAY + "]" + ChatColor.GRAY + " Usage: " + cmd + " " + action + " <arena>"); - } - return true; - } - - public boolean removeSpawn(PluginInstance pli, CommandSender sender, String[] args, String uber_permission, String cmd, String action, JavaPlugin plugin, Player p) { - if (!sender.hasPermission(uber_permission + ".setup")) { - sender.sendMessage(pli.getMessagesConfig().no_perm); - return true; - } - if (args.length > 2) { - if (Util.isNumeric(args[2])) { - if (pli.arenaSetup.removeSpawn(plugin, args[1], Integer.parseInt(args[2]))) { - sender.sendMessage(pli.getMessagesConfig().successfully_removed.replaceAll("<component>", "spawn " + args[2])); - } else { - sender.sendMessage(pli.getMessagesConfig().failed_removing_component.replaceAll("<component>", "spawn " + args[2]).replaceAll("<cause>", "Possibly the provided count couldn't be found: " + args[2])); - } - } else { - - } - } else { - sender.sendMessage(ChatColor.DARK_GRAY + "[" + ChatColor.RED + "-" + ChatColor.DARK_GRAY + "]" + ChatColor.GRAY + " Usage: " + cmd + " " + action + " <arena> <count>"); - } - return true; - } - - // TODO Implement skulls - public boolean setSkull(PluginInstance pli, CommandSender sender, String[] args, String uber_permission, String cmd, String action, JavaPlugin plugin, Player p) { - if (!sender.hasPermission(uber_permission + ".setup")) { - sender.sendMessage(pli.getMessagesConfig().no_perm); - return true; - } - sender.sendMessage(ChatColor.GRAY + "This feature is not implemented yet."); - if (args.length > 1) { - if (Util.isNumeric(args[1])) { - int count = Integer.parseInt(args[1]); - p.getInventory().addItem(pli.getStatsInstance().giveSkull(args[1])); - p.updateInventory(); - pli.getStatsInstance().skullsetup.add(p.getName()); - } else { - - } - } else { - sender.sendMessage(ChatColor.DARK_GRAY + "[" + ChatColor.RED + "-" + ChatColor.DARK_GRAY + "]" + ChatColor.GRAY + " Usage: " + cmd + " " + action + " <count>"); - } - return true; - } - - public boolean setEnabled(PluginInstance pli, CommandSender sender, String[] args, String uber_permission, String cmd, String action, JavaPlugin plugin, Player p) { - if (!sender.hasPermission(uber_permission + ".setup")) { - sender.sendMessage(pli.getMessagesConfig().no_perm); - return true; - } - if (args.length > 2) { - if (args[2].equalsIgnoreCase("true") || args[2].equalsIgnoreCase("false")) { - pli.arenaSetup.setArenaEnabled(plugin, args[1], Boolean.parseBoolean(args[2])); - sender.sendMessage(pli.getMessagesConfig().successfully_set.replaceAll("<component>", "enabled state")); - } else { - sender.sendMessage(ChatColor.DARK_GRAY + "[" + ChatColor.RED + "-" + ChatColor.DARK_GRAY + "]" + ChatColor.GRAY + " Usage: " + cmd + " " + action + " <arena> <true/false>"); - } - } else { - sender.sendMessage(ChatColor.DARK_GRAY + "[" + ChatColor.RED + "-" + ChatColor.DARK_GRAY + "]" + ChatColor.GRAY + " Usage: " + cmd + " " + action + " <arena> <true/false>"); - } - return true; - } - - public boolean setShowScoreboard(PluginInstance pli, CommandSender sender, String[] args, String uber_permission, String cmd, String action, JavaPlugin plugin, Player p) { - if (!sender.hasPermission(uber_permission + ".setup")) { - sender.sendMessage(pli.getMessagesConfig().no_perm); - return true; - } - if (args.length > 2) { - if (args[2].equalsIgnoreCase("true") || args[2].equalsIgnoreCase("false")) { - pli.arenaSetup.setShowScoreboard(plugin, args[1], Boolean.parseBoolean(args[2])); - sender.sendMessage(pli.getMessagesConfig().successfully_set.replaceAll("<component>", "scoreboard state")); - } else { - sender.sendMessage(ChatColor.DARK_GRAY + "[" + ChatColor.RED + "-" + ChatColor.DARK_GRAY + "]" + ChatColor.GRAY + " Usage: " + cmd + " " + action + " <arena> <true/false>"); - } - } else { - sender.sendMessage(ChatColor.DARK_GRAY + "[" + ChatColor.RED + "-" + ChatColor.DARK_GRAY + "]" + ChatColor.GRAY + " Usage: " + cmd + " " + action + " <arena> <true/false>"); - } - return true; - } - - public boolean resetArena(PluginInstance pli, CommandSender sender, String[] args, String uber_permission, String cmd, String action, final JavaPlugin plugin, Player p) { - if (!sender.hasPermission(uber_permission + ".reset")) { - sender.sendMessage(pli.getMessagesConfig().no_perm); - return true; - } - if (args.length > 1) { - final Arena a = pli.getArenaByName(args[1]); - if (a != null) { - if (Validator.isArenaValid(plugin, a)) { - Bukkit.getScheduler().runTask(plugin, new Runnable() { - public void run() { - Util.loadArenaFromFileSYNC(plugin, a); - } - }); - sender.sendMessage(pli.getMessagesConfig().arena_action.replaceAll("<arena>", args[1]).replaceAll("<action>", "reset")); - } - } - } else { - sender.sendMessage(ChatColor.DARK_GRAY + "[" + ChatColor.RED + "-" + ChatColor.DARK_GRAY + "]" + ChatColor.GRAY + " Usage: " + cmd + " " + action + " <arena>"); - } - return true; - } - - public boolean setAuthor(PluginInstance pli, CommandSender sender, String[] args, String uber_permission, String cmd, String action, final JavaPlugin plugin, Player p) { - if (!sender.hasPermission(uber_permission + ".setup")) { - sender.sendMessage(pli.getMessagesConfig().no_perm); - return true; - } - if (args.length > 2) { - String author = args[2]; - if (Validator.isArenaValid(plugin, args[1])) { - pli.getArenasConfig().getConfig().set("arenas." + args[1] + ".author", author); - pli.getArenasConfig().saveConfig(); - sender.sendMessage(pli.getMessagesConfig().successfully_set.replaceAll("<component>", "author")); - } - } else { - sender.sendMessage(ChatColor.DARK_GRAY + "[" + ChatColor.RED + "-" + ChatColor.DARK_GRAY + "]" + ChatColor.GRAY + " Usage: " + cmd + " " + action + " <arena> <author>"); - } - return true; - } - - public boolean setDescription(PluginInstance pli, CommandSender sender, String[] args, String uber_permission, String cmd, String action, final JavaPlugin plugin, Player p) { - if (!sender.hasPermission(uber_permission + ".setup")) { - sender.sendMessage(pli.getMessagesConfig().no_perm); - return true; - } - if (args.length > 2) { - String desc = args[2]; - if (Validator.isArenaValid(plugin, args[1])) { - pli.getArenasConfig().getConfig().set("arenas." + args[1] + ".description", desc); - pli.getArenasConfig().saveConfig(); - sender.sendMessage(pli.getMessagesConfig().successfully_set.replaceAll("<component>", "description")); - } - } else { - sender.sendMessage(ChatColor.DARK_GRAY + "[" + ChatColor.RED + "-" + ChatColor.DARK_GRAY + "]" + ChatColor.GRAY + " Usage: " + cmd + " " + action + " <arena> <description>"); - } - return true; - } - - public boolean setArenaDisplayName(PluginInstance pli, CommandSender sender, String[] args, String uber_permission, String cmd, String action, final JavaPlugin plugin, Player p) { - if (!sender.hasPermission(uber_permission + ".setup")) { - sender.sendMessage(pli.getMessagesConfig().no_perm); - return true; - } - if (args.length > 2) { - String displayname = args[2]; - if (Validator.isArenaValid(plugin, args[1])) { - pli.getArenasConfig().getConfig().set("arenas." + args[1] + ".displayname", displayname); - pli.getArenasConfig().saveConfig(); - pli.reloadArena(args[1]); - sender.sendMessage(pli.getMessagesConfig().successfully_set.replaceAll("<component>", "displayname")); - } - } else { - sender.sendMessage(ChatColor.DARK_GRAY + "[" + ChatColor.RED + "-" + ChatColor.DARK_GRAY + "]" + ChatColor.GRAY + " Usage: " + cmd + " " + action + " <arena> <displayname>"); - } - return true; - } - - public boolean spectate(PluginInstance pli, CommandSender sender, String[] args, String uber_permission, String cmd, String action, JavaPlugin plugin, Player p) { - if (args.length > 0) { - String playername = p.getName(); - if (args.length > 2) { - if (Validator.isPlayerOnline(args[2])) { - playername = args[2]; - } - } - Arena temp = pli.getArenaByName(args[1]); - if (temp != null) { - if (temp.getArenaState() == ArenaState.INGAME) { - if (!temp.containsPlayer(playername)) { - temp.addPlayer(playername); - ArenaPlayer ap = ArenaPlayer.getPlayerInstance(playername); - ap.setNoReward(true); - ap.setInventories(p.getInventory().getContents(), p.getInventory().getArmorContents()); - ap.setOriginalGamemode(p.getGameMode()); - ap.setOriginalXplvl(p.getLevel()); - pli.global_players.put(playername, temp); - pli.global_lost.put(playername, temp); - temp.spectateGame(playername); - } else { - sender.sendMessage(pli.getMessagesConfig().you_already_are_in_arena.replaceAll("<arena>", temp.getInternalName())); - } - } - } else { - sender.sendMessage(pli.getMessagesConfig().arena_invalid.replaceAll("<arena>", args[1])); - } - } - return true; - } - - public boolean setKit(PluginInstance pli, CommandSender sender, String[] args, String uber_permission, String cmd, String action, final JavaPlugin plugin, Player p) { - if (args.length > 1) { - if (!plugin.getConfig().getBoolean("config.classes_enabled")) { - return true; - } - if (args.length > 2) { - p = Bukkit.getPlayer(args[2]); - if (p == null) - return true; - } - if (!plugin.getConfig().getBoolean("config.allow_classes_selection_out_of_arenas")) { - if (pli.global_players.containsKey(p.getName())) { - Arena a = pli.global_players.get(p.getName()); - if (a.getArenaState() == ArenaState.INGAME) { - return true; - } - } else { - sender.sendMessage(pli.getMessagesConfig().not_in_arena); - return true; - } - } - - String kit = args[1]; - AClass ac = pli.getClassesHandler().getClassByInternalname(kit); - if (ac != null) { - if (pli.getAClasses().containsKey(ac.getName())) { - if (ac.isEnabled()) { - pli.getClassesHandler().setClass(kit, p.getName(), MinigamesAPI.economy); - return true; - } - } - } - - String all = ""; - for (AClass k : pli.getAClasses().values()) { - if (k.isEnabled()) { - if (!pli.show_classes_without_usage_permission) { - if (!pli.getClassesHandler().kitPlayerHasPermission(k.getInternalName(), p)) { - continue; - } - } - all += k.getInternalName() + ", "; - } - } - if (all.length() < 2) { - all = "No kits found! "; - } - all = all.substring(0, all.length() - 2); - sender.sendMessage(pli.getMessagesConfig().possible_kits + all); - - } else { - sender.sendMessage(ChatColor.DARK_GRAY + "[" + ChatColor.RED + "-" + ChatColor.DARK_GRAY + "]" + ChatColor.GRAY + " Usage: " + cmd + " " + action + " <kit>"); - if (!plugin.getConfig().getBoolean("config.classes_enabled")) { - return true; - } - if (pli.global_players.containsKey(p.getName())) { - pli.getClassesHandler().openGUI(p.getName()); - } else { - sender.sendMessage(pli.getMessagesConfig().not_in_arena); - } - } - return true; - } - - public boolean openShop(PluginInstance pli, CommandSender sender, String[] args, String uber_permission, String cmd, String action, final JavaPlugin plugin, Player p) { - if (args.length > 1) { - if (!plugin.getConfig().getBoolean("config.shop_enabled")) { - return true; - } - if (pli.global_players.containsKey(p.getName())) { - String shop_item = args[1]; - if (!pli.getShopHandler().buyByInternalName(p, shop_item)) { - String all = ""; - for (String ac : pli.getShopHandler().shopitems.keySet()) { - all += ac + ", "; - } - if (all.length() < 2) { - all = "No shop items found! "; - } - all = all.substring(0, all.length() - 2); - sender.sendMessage(pli.getMessagesConfig().possible_shopitems + all); - } - } else { - sender.sendMessage(pli.getMessagesConfig().not_in_arena); - } - } else { - if (!plugin.getConfig().getBoolean("config.shop_enabled")) { - return true; - } - if (pli.global_players.containsKey(p.getName())) { - pli.getShopHandler().openGUI(p.getName()); - } else { - sender.sendMessage(pli.getMessagesConfig().not_in_arena); - } - } - return true; - } - - public boolean getStats(PluginInstance pli, CommandSender sender, String[] args, String uber_permission, String cmd, String action, final JavaPlugin plugin, Player p) { - Util.sendStatsMessage(pli, p); - return true; - } - - public boolean getLeaderboards(PluginInstance pli, CommandSender sender, String[] args, String uber_permission, String cmd, String action, final JavaPlugin plugin, Player p) { - boolean wins = true; - int count = 10; - if (args.length > 2) { - if (Util.isNumeric(args[2])) { - count = Integer.parseInt(args[2]); - if (!args[1].equalsIgnoreCase("wins")) { - wins = false; - } - } else { - if (Util.isNumeric(args[1])) { - count = Integer.parseInt(args[1]); - } - if (!args[2].equalsIgnoreCase("wins")) { - wins = false; - } - } - } else if (args.length > 1 && args.length < 3) { - if (Util.isNumeric(args[1])) { - count = Integer.parseInt(args[1]); - } else { - if (!args[1].equalsIgnoreCase("wins")) { - wins = false; - } - } - } - sendLeaderboards(pli, sender, count, wins); - return true; - } - - /** - * Send the leaderboards to a player - * - * @param sender - * Player to send the leaderboards to - * @param count - * Amount of result items to show - * @param wins - * whether to check for wins or points leaderboards - */ - private void sendLeaderboards(PluginInstance pli, CommandSender sender, int count, boolean wins) { - int c = 0; - if (wins) { - sender.sendMessage(ChatColor.DARK_GREEN + "--- Leaderboards: Wins ---"); - TreeMap<String, Double> sorted_wins = pli.getStatsInstance().getTop(count, true); - for (Map.Entry<String, Double> entry : sorted_wins.entrySet()) { - c++; - if (c > count) { - break; - } - sender.sendMessage(ChatColor.GREEN + "" + Integer.toString((int) entry.getValue().doubleValue()) + ChatColor.DARK_GREEN + " - " + ChatColor.GREEN + "" + entry.getKey()); - } - } else { - sender.sendMessage(ChatColor.DARK_GREEN + "-- Leaderboards: Points --"); - TreeMap<String, Double> sorted_wins = pli.getStatsInstance().getTop(count, false); - for (Map.Entry<String, Double> entry : sorted_wins.entrySet()) { - c++; - if (c > count) { - break; - } - sender.sendMessage(ChatColor.GREEN + "" + Integer.toString((int) entry.getValue().doubleValue()) + ChatColor.DARK_GREEN + " - " + ChatColor.GREEN + "" + entry.getKey()); - } - } - } - - // Hologram commands - public boolean setHologram(PluginInstance pli, CommandSender sender, String[] args, String uber_permission, String cmd, String action, final JavaPlugin plugin, Player p) { - if (!sender.hasPermission(uber_permission + ".setup")) { - sender.sendMessage(pli.getMessagesConfig().no_perm); - return true; - } - Location l = p.getLocation(); - pli.getHologramsHandler().addHologram(l); - p.sendMessage(ChatColor.GREEN + "Successfully set hologram."); - return true; - } - - public boolean listHolograms(PluginInstance pli, CommandSender sender, String[] args, String uber_permission, String cmd, String action, final JavaPlugin plugin, Player p) { - if (!sender.hasPermission(uber_permission + ".setup")) { - sender.sendMessage(pli.getMessagesConfig().no_perm); - return true; - } - HologramsConfig config = pli.getHologramsConfig(); - int c = 0; - if (config.getConfig().isSet("holograms.")) { - for (String str : config.getConfig().getConfigurationSection("holograms.").getKeys(false)) { - String base = "holograms." + str; - Location l = new Location(Bukkit.getWorld(config.getConfig().getString(base + ".world")), config.getConfig().getDouble(base + ".location.x"), config.getConfig().getDouble(base + ".location.y"), config.getConfig().getDouble(base + ".location.z"), (float) config.getConfig().getDouble(base + ".location.yaw"), (float) config.getConfig().getDouble(base + ".location.pitch")); - p.sendMessage(ChatColor.GRAY + " ~ " + "world:" + l.getWorld().getName() + ", x:" + l.getBlockX() + ", y:" + l.getBlockY() + ", z:" + l.getBlockZ()); - c++; - } - } - if (c == 0) { - p.sendMessage(ChatColor.RED + "No holograms found!"); - } - return true; - } - - public boolean removeHologram(PluginInstance pli, CommandSender sender, String[] args, String uber_permission, String cmd, String action, final JavaPlugin plugin, Player p) { - if (!sender.hasPermission(uber_permission + ".setup")) { - sender.sendMessage(pli.getMessagesConfig().no_perm); - return true; - } - Location ploc = p.getLocation(); - boolean foundHologram = pli.getHologramsHandler().removeHologram(ploc); - if (foundHologram) { - p.sendMessage(ChatColor.GREEN + "Successfully removed hologram from config. It won't be sent anymore from now on!"); - return true; - } - // No holograms found - p.sendMessage(ChatColor.RED + "No near holograms found! Please stand in a maximum distance of 2 blocks to a hologram to remove it."); - return true; - } - - // Party commands - public boolean partyInvite(CommandSender sender, String[] args, String uber_permission, String cmd, String action, final JavaPlugin plugin, Player p) { - if (args.length > 1) { - if (p.getName().equalsIgnoreCase(args[1])) { - p.sendMessage(MinigamesAPI.getAPI().partymessages.cannot_invite_yourself); - return true; - } - boolean isInParty = false; - for (Party party : MinigamesAPI.getAPI().global_party.values()) { - if (party.containsPlayer(p.getName())) { - isInParty = true; - } - } - if (!isInParty) { - if (!Validator.isPlayerOnline(args[1])) { - p.sendMessage(MinigamesAPI.getAPI().partymessages.player_not_online.replaceAll("<player>", args[1])); - return true; - } - Party party = null; - if (!MinigamesAPI.getAPI().global_party.containsKey(p.getName())) { - party = new Party(p.getName()); - MinigamesAPI.getAPI().global_party.put(p.getName(), party); - } else { - party = MinigamesAPI.getAPI().global_party.get(p.getName()); - } - ArrayList<Party> parties = new ArrayList<Party>(); - if (MinigamesAPI.getAPI().global_party_invites.containsKey(p.getName())) { - parties.addAll(MinigamesAPI.getAPI().global_party_invites.get(p.getName())); - } - if (!parties.contains(party)) { - parties.add(party); - } - MinigamesAPI.getAPI().global_party_invites.put(args[1], parties); - p.sendMessage(MinigamesAPI.getAPI().partymessages.you_invited.replaceAll("<player>", args[1])); - Bukkit.getPlayer(args[1]).sendMessage(MinigamesAPI.getAPI().partymessages.you_were_invited.replaceAll("<player>", p.getName())); - } - } else { - sender.sendMessage(ChatColor.DARK_GRAY + "[" + ChatColor.RED + "-" + ChatColor.DARK_GRAY + "]" + ChatColor.GRAY + " Usage: " + cmd + " " + action + " <player>"); - } - return true; - } - - public boolean partyAccept(CommandSender sender, String[] args, String uber_permission, String cmd, String action, final JavaPlugin plugin, Player p) { - if (args.length > 1) { - if (!Validator.isPlayerOnline(args[1])) { - p.sendMessage(MinigamesAPI.getAPI().partymessages.player_not_online.replaceAll("<player>", args[1])); - return true; - } - if (!MinigamesAPI.getAPI().global_party_invites.containsKey(p.getName())) { - p.sendMessage(MinigamesAPI.getAPI().partymessages.not_invited_to_any_party); - return true; - } - - boolean isInParty = false; - Party party_ = null; - for (Party party : MinigamesAPI.getAPI().global_party.values()) { - if (party.containsPlayer(p.getName())) { - isInParty = true; - party_ = party; - } - } - if (isInParty) { - if (party_ != null) { - party_.removePlayer(p.getName()); - } - } - if (MinigamesAPI.getAPI().global_party.containsKey(p.getName())) { - MinigamesAPI.getAPI().global_party.get(p.getName()).disband(); - } - - Party party__ = null; - for (Party party : MinigamesAPI.getAPI().global_party_invites.get(p.getName())) { - if (party.getOwner().equalsIgnoreCase(args[1])) { - party__ = party; - break; - } - } - if (party__ != null) { - party__.addPlayer(p.getName()); - MinigamesAPI.getAPI().global_party_invites.remove(p.getName()); - } else { - p.sendMessage(MinigamesAPI.getAPI().partymessages.not_invited_to_players_party.replaceAll("<player>", args[1])); - } - } else { - sender.sendMessage(ChatColor.DARK_GRAY + "[" + ChatColor.RED + "-" + ChatColor.DARK_GRAY + "]" + ChatColor.GRAY + " Usage: " + cmd + " " + action + " <player>"); - } - return true; - } - - public boolean partyKick(CommandSender sender, String[] args, String uber_permission, String cmd, String action, final JavaPlugin plugin, Player p) { - if (args.length > 1) { - if (!Validator.isPlayerOnline(args[1])) { - p.sendMessage(MinigamesAPI.getAPI().partymessages.player_not_online.replaceAll("<player>", args[1])); - return true; - } - if (MinigamesAPI.getAPI().global_party.containsKey(p.getName())) { - Party party = MinigamesAPI.getAPI().global_party.get(p.getName()); - if (party.containsPlayer(args[1])) { - party.removePlayer(args[1]); - } else { - p.sendMessage(MinigamesAPI.getAPI().partymessages.player_not_in_party.replaceAll("<player>", args[1])); - } - } - } else { - sender.sendMessage(ChatColor.DARK_GRAY + "[" + ChatColor.RED + "-" + ChatColor.DARK_GRAY + "]" + ChatColor.GRAY + " Usage: " + cmd + " " + action + " <player>"); - } - return true; - } - - public boolean partyList(CommandSender sender, String[] args, String uber_permission, String cmd, String action, final JavaPlugin plugin, Player p) { - if (args.length > 0) { - Party party_ = null; - for (Party party : MinigamesAPI.getAPI().global_party.values()) { - if (party.containsPlayer(p.getName())) { - party_ = party; - } - } - if (MinigamesAPI.getAPI().global_party.containsKey(p.getName())) { - party_ = MinigamesAPI.getAPI().global_party.get(p.getName()); - } - if (party_ != null) { - String ret = ChatColor.DARK_GREEN + party_.getOwner(); - for (String p_ : party_.getPlayers()) { - ret += ChatColor.GREEN + ", " + p_; - } - p.sendMessage(ret); - } - } else { - sender.sendMessage(ChatColor.DARK_GRAY + "[" + ChatColor.RED + "-" + ChatColor.DARK_GRAY + "]" + ChatColor.GRAY + " Usage: " + cmd + " " + action); - } - return true; - } - - public boolean partyDisband(CommandSender sender, String[] args, String uber_permission, String cmd, String action, final JavaPlugin plugin, Player p) { - if (args.length > 0) { - if (MinigamesAPI.getAPI().global_party.containsKey(p.getName())) { - MinigamesAPI.getAPI().global_party.get(p.getName()).disband(); - } - } else { - sender.sendMessage(ChatColor.DARK_GRAY + "[" + ChatColor.RED + "-" + ChatColor.DARK_GRAY + "]" + ChatColor.GRAY + " Usage: " + cmd + " " + action); - } - return true; - } - - public boolean partyLeave(CommandSender sender, String[] args, String uber_permission, String cmd, String action, final JavaPlugin plugin, Player p) { - if (args.length > 0) { - if (MinigamesAPI.getAPI().global_party.containsKey(p.getName())) { - MinigamesAPI.getAPI().global_party.get(p.getName()).disband(); - return true; - } - Party party_ = null; - for (Party party : MinigamesAPI.getAPI().global_party.values()) { - if (party.containsPlayer(p.getName())) { - party_ = party; - } - } - if (party_ != null) { - party_.removePlayer(p.getName()); - } - } else { - sender.sendMessage(ChatColor.DARK_GRAY + "[" + ChatColor.RED + "-" + ChatColor.DARK_GRAY + "]" + ChatColor.GRAY + " Usage: " + cmd + " " + action); - } - return true; - } - +public class CommandHandler +{ + + /** + * Constructor. + */ + public CommandHandler() + { + this.initCmdDesc(); + } + + /** + * Handles the default commands needed for arena management. + * + * @param uber_permission + * Main setup permission. Example: Skywars.setup + * @param cmd + * The command. Example: /sw + * @param sender + * @param args + * @return + */ + public boolean handleArgs(final JavaPlugin plugin, final String uber_permission, final String cmd, final CommandSender sender, final String args[]) + { + if (args.length > 0) + { + if (!(sender instanceof Player)) + { + sender.sendMessage("Please execute this command ingame."); + return true; + } + final Player p = (Player) sender; + final PluginInstance pli = MinigamesAPI.getAPI().getPluginInstance(plugin); + final String action = args[0]; + if (action.equalsIgnoreCase(CommandStrings.GAME_SET_SPAWN)) + { + return this.setSpawn(pli, sender, args, uber_permission, cmd, action, plugin, p); + } + else if (action.equalsIgnoreCase(CommandStrings.GAME_SET_SPEC_SPAWN)) + { + return this.setSpecSpawn(pli, sender, args, uber_permission, cmd, action, plugin, p); + } + else if (action.equalsIgnoreCase(CommandStrings.GAME_SET_LOBBY)) + { + return this.setLobby(pli, sender, args, uber_permission, cmd, action, plugin, p); + } + else if (action.equalsIgnoreCase(CommandStrings.GAME_SET_MAINLOBBY)) + { + return this.setMainLobby(pli, sender, args, uber_permission, cmd, action, plugin, p); + } + else if (action.equalsIgnoreCase(CommandStrings.GAME_SET_BOUNDS)) + { + return this.setBounds(pli, sender, args, uber_permission, cmd, action, plugin, p); + } + else if (action.equalsIgnoreCase(CommandStrings.GAME_SET_LOBBY_BOUNDS)) + { + return this.setLobbyBounds(pli, sender, args, uber_permission, cmd, action, plugin, p); + } + else if (action.equalsIgnoreCase(CommandStrings.GAME_SET_SPEC_BOUNDS)) + { + return this.setSpecBounds(pli, sender, args, uber_permission, cmd, action, plugin, p); + } + else if (action.equalsIgnoreCase(CommandStrings.GAME_SAVE_ARENA) || action.equalsIgnoreCase(CommandStrings.GAME_SAVE)) + { + return this.saveArena(pli, sender, args, uber_permission, cmd, action, plugin, p); + } + else if (action.equalsIgnoreCase(CommandStrings.GAME_SET_MAX_PLAYERS)) + { + return this.setMaxPlayers(pli, sender, args, uber_permission, cmd, action, plugin, p); + } + else if (action.equalsIgnoreCase(CommandStrings.GAME_SET_MIN_PLAYERS)) + { + return this.setMinPlayers(pli, sender, args, uber_permission, cmd, action, plugin, p); + } + else if (action.equalsIgnoreCase(CommandStrings.GAME_SET_ARENA_VIP) || action.equalsIgnoreCase(CommandStrings.GAME_SET_VIP)) + { + return this.setArenaVIP(pli, sender, args, uber_permission, cmd, action, plugin, p); + } + else if (action.equalsIgnoreCase(CommandStrings.GAME_JOIN)) + { + return this.joinArena(pli, sender, args, uber_permission, cmd, action, plugin, p); + } + else if (action.equalsIgnoreCase(CommandStrings.GAME_LEAVE)) + { + return this.leaveArena(pli, sender, args, uber_permission, cmd, action, plugin, p); + } + else if (action.equalsIgnoreCase(CommandStrings.GAME_START)) + { + return this.startArena(pli, sender, args, uber_permission, cmd, action, plugin, p); + } + else if (action.equalsIgnoreCase(CommandStrings.GAME_STOP)) + { + return this.stopArena(pli, sender, args, uber_permission, cmd, action, plugin, p); + } + else if (action.equalsIgnoreCase(CommandStrings.GAME_STOP_ALL)) + { + return this.stopAllArenas(pli, sender, args, uber_permission, cmd, action, plugin, p); + } + else if (action.equalsIgnoreCase(CommandStrings.GAME_REMOVE_ARENA)) + { + return this.removeArena(pli, sender, args, uber_permission, cmd, action, plugin, p); + } + else if (action.equalsIgnoreCase(CommandStrings.GAME_REMOVE_SPAWN)) + { + return this.removeSpawn(pli, sender, args, uber_permission, cmd, action, plugin, p); + } + else if (action.equalsIgnoreCase(CommandStrings.GAME_SET_SKULL)) + { + return this.setSkull(pli, sender, args, uber_permission, cmd, action, plugin, p); + } + else if (action.equalsIgnoreCase(CommandStrings.GAME_SET_ENABLED)) + { + return this.setEnabled(pli, sender, args, uber_permission, cmd, action, plugin, p); + } + else if (action.equalsIgnoreCase(CommandStrings.GAME_SET_SHOW_SCOREBOARD)) + { + return this.setShowScoreboard(pli, sender, args, uber_permission, cmd, action, plugin, p); + } + else if (action.equalsIgnoreCase(CommandStrings.GAME_RESET)) + { + return this.resetArena(pli, sender, args, uber_permission, cmd, action, plugin, p); + } + else if (action.equalsIgnoreCase(CommandStrings.GAME_SET_AUTHOR)) + { + return this.setAuthor(pli, sender, args, uber_permission, cmd, action, plugin, p); + } + else if (action.equalsIgnoreCase(CommandStrings.GAME_SET_DESCRIPTION)) + { + return this.setDescription(pli, sender, args, uber_permission, cmd, action, plugin, p); + } + else if (action.equalsIgnoreCase(CommandStrings.GAME_SET_DISPLAYNAME)) + { + return this.setArenaDisplayName(pli, sender, args, uber_permission, cmd, action, plugin, p); + } + else if (action.equalsIgnoreCase(CommandStrings.GAME_KIT)) + { + return this.setKit(pli, sender, args, uber_permission, cmd, action, plugin, p); + } + else if (action.equalsIgnoreCase(CommandStrings.GAME_SPECTATE)) + { + return this.spectate(pli, sender, args, uber_permission, cmd, action, plugin, p); + } + else if (action.equalsIgnoreCase(CommandStrings.GAME_SHOP)) + { + return this.openShop(pli, sender, args, uber_permission, cmd, action, plugin, p); + } + else if (action.equalsIgnoreCase(CommandStrings.GAME_LEADER_BOARDS) || action.equalsIgnoreCase(CommandStrings.GAME_LB) || action.equalsIgnoreCase(CommandStrings.GAME_TOP)) + { + return this.getLeaderboards(pli, sender, args, uber_permission, cmd, action, plugin, p); + } + else if (action.equalsIgnoreCase(CommandStrings.GAME_STATS)) + { + return this.getStats(pli, sender, args, uber_permission, cmd, action, plugin, p); + } + else if (action.equalsIgnoreCase(CommandStrings.GAME_SET_HOLOGRAM)) + { + return this.setHologram(pli, sender, args, uber_permission, cmd, action, plugin, p); + } + else if (action.equalsIgnoreCase(CommandStrings.GAME_LIST_HOLOGRAMS)) + { + return this.listHolograms(pli, sender, args, uber_permission, cmd, action, plugin, p); + } + else if (action.equalsIgnoreCase(CommandStrings.GAME_REMOVE_HOLOGRAM)) + { + return this.removeHologram(pli, sender, args, uber_permission, cmd, action, plugin, p); + } + else if (action.equalsIgnoreCase(CommandStrings.GAME_HELP)) + { + return this.sendHelp(cmd, sender); + } + else if (action.equalsIgnoreCase(CommandStrings.GAME_LIST)) + { + sender.sendMessage(ChatColor.DARK_GRAY + "------- " + ChatColor.BLUE + "Arenas" + ChatColor.DARK_GRAY + " -------"); + for (final Arena a : pli.getArenas()) + { + sender.sendMessage(ChatColor.GREEN + a.getInternalName()); + } + } + else if (action.equalsIgnoreCase(CommandStrings.GAME_RELOAD)) + { + if (!sender.hasPermission(uber_permission + ".reload")) + { + sender.sendMessage(pli.getMessagesConfig().no_perm); + return true; + } + plugin.reloadConfig(); + pli.getMessagesConfig().reloadConfig(); + pli.getArenasConfig().reloadConfig(); + pli.getClassesConfig().reloadConfig(); + pli.getAchievementsConfig().reloadConfig(); + pli.getStatsConfig().reloadConfig(); + pli.getShopConfig().reloadConfig(); + pli.getMessagesConfig().init(); + pli.reloadVariables(); + pli.getRewardsInstance().reloadVariables(); + pli.getStatsInstance().reloadVariables(); + pli.getAClasses().clear(); + pli.getClassesHandler().loadClasses(); + try + { + pli.reloadAllArenas(); + } + catch (final Exception e) + { + pli.getPlugin().getLogger().log(Level.WARNING, "Looks like one arena is invalid, but most arenas should be reloaded just fine.", e); + } + sender.sendMessage(pli.getMessagesConfig().successfully_reloaded); + } + else + { + boolean cont = false; + final ArrayList<String> cmds = new ArrayList<>(); + for (final String cmd_ : this.cmddesc.keySet()) + { + if (cmd_.toLowerCase().contains(action.toLowerCase())) + { + cmds.add(cmd_); + cont = true; + } + } + if (cont) + { + this.sendHelp(cmd, sender); + for (final String cmd_ : cmds) + { + sender.sendMessage(ChatColor.RED + "Did you mean " + ChatColor.DARK_RED + cmd + " " + cmd_ + ChatColor.RED + "?"); + } + } + } + } + else + { + return this.sendHelp(cmd, sender); + } + return true; + } + + protected final LinkedHashMap<String, String> cmddesc = new LinkedHashMap<>(); + + protected void initCmdDesc() + { + this.cmddesc.put("", null); + this.cmddesc.put("setspawn <arena>", "Sets the spawn point."); + this.cmddesc.put("setlobby <arena>", "Sets the lobby point."); + this.cmddesc.put("setmainlobby", "Sets the main lobby point."); + this.cmddesc.put("setbounds <arena> <low/high>", "Sets the low or high boundary point for later arena regeneration."); + this.cmddesc.put("savearena <arena>", "Saves the arena."); + this.cmddesc.put("", null); + this.cmddesc.put("setmaxplayers <arena> <count>", "Sets the max players allowed to join to given count."); + this.cmddesc.put("setminplayers <arena> <count>", "Sets the min players needed to start to given count."); + this.cmddesc.put("setarenavip <arena> <true/false>", "Sets whether arena needs permission to join."); + this.cmddesc.put("removearena <arena>", "Deletes an arena from config."); + this.cmddesc.put("removespawn <arena> <count>", "Deletes a spawn from config."); + this.cmddesc.put("setenabled", "Enables/Disables the arena."); + this.cmddesc.put("", null); + this.cmddesc.put("join <arena>", "Joins the arena."); + this.cmddesc.put("leave", "Leaves the arena."); + this.cmddesc.put("", ""); + this.cmddesc.put("start <arena>", "Forces the arena to start."); + this.cmddesc.put("stop <arena>", "Forces the arena to stop."); + this.cmddesc.put("list", "Lists all arenas."); + this.cmddesc.put("reload", "Reloads the config."); + this.cmddesc.put("reset <arena>", "Forces the arena to reset."); + this.cmddesc.put("", null); + this.cmddesc.put("setlobbybounds <arena> <low/high>", "Optional: Set lobby boundaries."); + this.cmddesc.put("setspecbounds <arena> <low/high>", "Optional: Set extra spectator boundaries."); + this.cmddesc.put("setauthor <arena> <author>", "Will always display the author of the map at join."); + this.cmddesc.put("setdescription <arena> <description>", "Will always display a description of the map at join."); + this.cmddesc.put("setdisplayname <arena> <displayname>", "Allows changing displayname of an arena (whitespaces and colors)."); + this.cmddesc.put("", null); + } + + public boolean sendHelp(final String cmd, final CommandSender sender) + { + sender.sendMessage(ChatColor.DARK_GRAY + "------- " + ChatColor.BLUE + "Help" + ChatColor.DARK_GRAY + " -------"); + for (final String k : this.cmddesc.keySet()) + { + if (k.length() < 3) + { + sender.sendMessage(""); + continue; + } + final String v = this.cmddesc.get(k); + sender.sendMessage(ChatColor.YELLOW + cmd + " " + k + ChatColor.DARK_GRAY + " - " + ChatColor.GRAY + v); + } + return true; + } + + public static LinkedHashMap<String, String> cmdpartydesc; + static + { + CommandHandler.cmdpartydesc = new LinkedHashMap<>(); + CommandHandler.cmdpartydesc.put("", ""); + CommandHandler.cmdpartydesc.put("invite <player>", "Invites a player to your party and creates one if you don't have one yet."); + CommandHandler.cmdpartydesc.put("accept <player>", "Accepts an invitation to a party"); + CommandHandler.cmdpartydesc.put("disband", "Disbands the party"); + CommandHandler.cmdpartydesc.put("kick <player>", "Kicks a player from your party."); + CommandHandler.cmdpartydesc.put("leave", "Leaves a party you're in."); + CommandHandler.cmdpartydesc.put("list", "Lists all players and the owner of the party."); + } + + public static void sendPartyHelp(final String cmd, final CommandSender sender) + { + sender.sendMessage(ChatColor.DARK_GRAY + "------- " + ChatColor.BLUE + "Help" + ChatColor.DARK_GRAY + " -------"); + for (final String k : CommandHandler.cmdpartydesc.keySet()) + { + if (k.length() < 3) + { + sender.sendMessage(""); + continue; + } + final String v = CommandHandler.cmdpartydesc.get(k); + sender.sendMessage(ChatColor.YELLOW + cmd + " " + k + ChatColor.DARK_GRAY + " - " + ChatColor.GRAY + v); + } + } + + public boolean setSpawn(final PluginInstance pli, final CommandSender sender, final String[] args, final String uber_permission, final String cmd, final String action, final JavaPlugin plugin, + final Player p) + { + if (!sender.hasPermission(uber_permission + ".setup")) + { + sender.sendMessage(pli.getMessagesConfig().no_perm); + return true; + } + if (args.length > 1) + { + pli.arenaSetup.setSpawn(plugin, args[1], p.getLocation()); + sender.sendMessage(pli.getMessagesConfig().successfully_set.replaceAll("<component>", "spawn")); + } + else + { + sender.sendMessage(ChatColor.DARK_GRAY + "[" + ChatColor.RED + "-" + ChatColor.DARK_GRAY + "]" + ChatColor.GRAY + " Usage: " + cmd + " " + action + " <arena>"); + } + return true; + } + + public boolean setSpecSpawn(final PluginInstance pli, final CommandSender sender, final String[] args, final String uber_permission, final String cmd, final String action, final JavaPlugin plugin, + final Player p) + { + if (!sender.hasPermission(uber_permission + ".setup")) + { + sender.sendMessage(pli.getMessagesConfig().no_perm); + return true; + } + if (args.length > 1) + { + Util.saveComponentForArena(plugin, args[1], ArenaConfigStrings.SPEC_SPAWN, p.getLocation()); + sender.sendMessage(pli.getMessagesConfig().successfully_set.replaceAll("<component>", "spectator spawn")); + } + else + { + sender.sendMessage(ChatColor.DARK_GRAY + "[" + ChatColor.RED + "-" + ChatColor.DARK_GRAY + "]" + ChatColor.GRAY + " Usage: " + cmd + " " + action + " <arena>"); + } + return true; + } + + public boolean setLobby(final PluginInstance pli, final CommandSender sender, final String[] args, final String uber_permission, final String cmd, final String action, final JavaPlugin plugin, + final Player p) + { + if (!sender.hasPermission(uber_permission + ".setup")) + { + sender.sendMessage(pli.getMessagesConfig().no_perm); + return true; + } + if (args.length > 1) + { + pli.arenaSetup.setLobby(plugin, args[1], p.getLocation()); + sender.sendMessage(pli.getMessagesConfig().successfully_set.replaceAll("<component>", "waiting lobby")); + } + else + { + sender.sendMessage(ChatColor.DARK_GRAY + "[" + ChatColor.RED + "-" + ChatColor.DARK_GRAY + "]" + ChatColor.GRAY + " Usage: " + cmd + " " + action + " <arena>"); + } + return true; + } + + public boolean setMainLobby(final PluginInstance pli, final CommandSender sender, final String[] args, final String uber_permission, final String cmd, final String action, final JavaPlugin plugin, + final Player p) + { + if (!sender.hasPermission(uber_permission + ".setup")) + { + sender.sendMessage(pli.getMessagesConfig().no_perm); + return true; + } + pli.arenaSetup.setMainLobby(plugin, p.getLocation()); + sender.sendMessage(pli.getMessagesConfig().successfully_set.replaceAll("<component>", "main lobby")); + return true; + } + + public boolean setBounds(final PluginInstance pli, final CommandSender sender, final String[] args, final String uber_permission, final String cmd, final String action, final JavaPlugin plugin, + final Player p) + { + if (!sender.hasPermission(uber_permission + ".setup")) + { + sender.sendMessage(pli.getMessagesConfig().no_perm); + return true; + } + if (args.length > 2) + { + if (args[2].equalsIgnoreCase("low")) + { + pli.arenaSetup.setBoundaries(plugin, args[1], p.getLocation(), true); + } + else if (args[2].equalsIgnoreCase("high")) + { + pli.arenaSetup.setBoundaries(plugin, args[1], p.getLocation(), false); + } + else + { + sender.sendMessage(ChatColor.DARK_GRAY + "[" + ChatColor.RED + "-" + ChatColor.DARK_GRAY + "]" + ChatColor.GRAY + " Usage: " + cmd + " " + action + " <arena> <low/high>"); + return true; + } + sender.sendMessage(pli.getMessagesConfig().successfully_set.replaceAll("<component>", "boundary")); + } + else + { + sender.sendMessage(ChatColor.DARK_GRAY + "[" + ChatColor.RED + "-" + ChatColor.DARK_GRAY + "]" + ChatColor.GRAY + " Usage: " + cmd + " " + action + " <arena> <low/high>"); + } + return true; + } + + public boolean setLobbyBounds(final PluginInstance pli, final CommandSender sender, final String[] args, final String uber_permission, final String cmd, final String action, + final JavaPlugin plugin, final Player p) + { + if (!sender.hasPermission(uber_permission + ".setup")) + { + sender.sendMessage(pli.getMessagesConfig().no_perm); + return true; + } + if (args.length > 2) + { + if (args[2].equalsIgnoreCase("low")) + { + pli.arenaSetup.setBoundaries(plugin, args[1], p.getLocation(), true, "lobbybounds"); + } + else if (args[2].equalsIgnoreCase("high")) + { + pli.arenaSetup.setBoundaries(plugin, args[1], p.getLocation(), false, "lobbybounds"); + } + else + { + sender.sendMessage(ChatColor.DARK_GRAY + "[" + ChatColor.RED + "-" + ChatColor.DARK_GRAY + "]" + ChatColor.GRAY + " Usage: " + cmd + " " + action + " <arena> <low/high>"); + return true; + } + sender.sendMessage(pli.getMessagesConfig().successfully_set.replaceAll("<component>", "lobby boundary")); + } + else + { + sender.sendMessage(ChatColor.DARK_GRAY + "[" + ChatColor.RED + "-" + ChatColor.DARK_GRAY + "]" + ChatColor.GRAY + " Usage: " + cmd + " " + action + " <arena> <low/high>"); + } + return true; + } + + public boolean setSpecBounds(final PluginInstance pli, final CommandSender sender, final String[] args, final String uber_permission, final String cmd, final String action, + final JavaPlugin plugin, final Player p) + { + if (!sender.hasPermission(uber_permission + ".setup")) + { + sender.sendMessage(pli.getMessagesConfig().no_perm); + return true; + } + if (args.length > 2) + { + if (args[2].equalsIgnoreCase("low")) + { + pli.arenaSetup.setBoundaries(plugin, args[1], p.getLocation(), true, "specbounds"); + } + else if (args[2].equalsIgnoreCase("high")) + { + pli.arenaSetup.setBoundaries(plugin, args[1], p.getLocation(), false, "specbounds"); + } + else + { + sender.sendMessage(ChatColor.DARK_GRAY + "[" + ChatColor.RED + "-" + ChatColor.DARK_GRAY + "]" + ChatColor.GRAY + " Usage: " + cmd + " " + action + " <arena> <low/high>"); + return true; + } + sender.sendMessage(pli.getMessagesConfig().successfully_set.replaceAll("<component>", "spectator boundary")); + } + else + { + sender.sendMessage(ChatColor.DARK_GRAY + "[" + ChatColor.RED + "-" + ChatColor.DARK_GRAY + "]" + ChatColor.GRAY + " Usage: " + cmd + " " + action + " <arena> <low/high>"); + } + return true; + } + + public boolean saveArena(final PluginInstance pli, final CommandSender sender, final String[] args, final String uber_permission, final String cmd, final String action, final JavaPlugin plugin, + final Player p) + { + if (!sender.hasPermission(uber_permission + ".setup")) + { + sender.sendMessage(pli.getMessagesConfig().no_perm); + return true; + } + if (args.length > 1) + { + if (Util.getMainLobby(plugin) == null) + { + sender.sendMessage(pli.getMessagesConfig().failed_saving_arena.replaceAll("<arena>", args[1])); + sender.sendMessage(ChatColor.GRAY + "++ Debug Info ++"); + sender.sendMessage(ChatColor.GRAY + "MAIN LOBBY MISSING"); + } + else + { + final Arena temp = pli.arenaSetup.saveArena(plugin, args[1]); + if (temp != null) + { + sender.sendMessage(pli.getMessagesConfig().successfully_saved_arena.replaceAll("<arena>", args[1])); + } + else + { + sender.sendMessage(pli.getMessagesConfig().failed_saving_arena.replaceAll("<arena>", args[1])); + sender.sendMessage(ChatColor.GRAY + "++ Debug Info ++"); + sender.sendMessage(ChatColor.GRAY + "LOBBY:" + Util.isComponentForArenaValidRaw(plugin, args[1], "lobby") + ChatColor.RED + ";" + ChatColor.GRAY + " SPAWN0:" + + Util.isComponentForArenaValidRaw(plugin, args[1], "spawns.spawn0") + ChatColor.RED + ";" + ChatColor.GRAY + " BOUNDARIES(possibly needed): low:" + + Util.isComponentForArenaValidRaw(plugin, args[1], ArenaConfigStrings.BOUNDS_LOW) + ", high:" + Util.isComponentForArenaValidRaw(plugin, args[1], ArenaConfigStrings.BOUNDS_HIGH)); + } + } + } + else + { + sender.sendMessage(ChatColor.DARK_GRAY + "[" + ChatColor.RED + "-" + ChatColor.DARK_GRAY + "]" + ChatColor.GRAY + " Usage: " + cmd + " " + action + " <arena>"); + } + return true; + } + + public boolean setMaxPlayers(final PluginInstance pli, final CommandSender sender, final String[] args, final String uber_permission, final String cmd, final String action, + final JavaPlugin plugin, final Player p) + { + if (!sender.hasPermission(uber_permission + ".setup")) + { + sender.sendMessage(pli.getMessagesConfig().no_perm); + return true; + } + if (args.length > 2) + { + if (!Util.isNumeric(args[2])) + { + return true; + } + pli.arenaSetup.setPlayerCount(plugin, args[1], Integer.parseInt(args[2]), true); + if (pli.getArenaByName(args[1]) != null) + { + pli.getArenaByName(args[1]).setMaxPlayers(Integer.parseInt(args[2])); + } + sender.sendMessage(pli.getMessagesConfig().successfully_set.replaceAll("<component>", "max players")); + } + else + { + sender.sendMessage(ChatColor.DARK_GRAY + "[" + ChatColor.RED + "-" + ChatColor.DARK_GRAY + "]" + ChatColor.GRAY + " Usage: " + cmd + " " + action + " <arena> <count>"); + } + return true; + } + + public boolean setMinPlayers(final PluginInstance pli, final CommandSender sender, final String[] args, final String uber_permission, final String cmd, final String action, + final JavaPlugin plugin, final Player p) + { + if (!sender.hasPermission(uber_permission + ".setup")) + { + sender.sendMessage(pli.getMessagesConfig().no_perm); + return true; + } + if (args.length > 2) + { + if (!Util.isNumeric(args[2])) + { + return true; + } + pli.arenaSetup.setPlayerCount(plugin, args[1], Integer.parseInt(args[2]), false); + if (pli.getArenaByName(args[1]) != null) + { + pli.getArenaByName(args[1]).setMinPlayers(Integer.parseInt(args[2])); + } + sender.sendMessage(pli.getMessagesConfig().successfully_set.replaceAll("<component>", "min players")); + } + else + { + sender.sendMessage(ChatColor.DARK_GRAY + "[" + ChatColor.RED + "-" + ChatColor.DARK_GRAY + "]" + ChatColor.GRAY + " Usage: " + cmd + " " + action + " <arena> <count>"); + } + return true; + } + + public boolean setArenaVIP(final PluginInstance pli, final CommandSender sender, final String[] args, final String uber_permission, final String cmd, final String action, final JavaPlugin plugin, + final Player p) + { + if (!sender.hasPermission(uber_permission + ".setup")) + { + sender.sendMessage(pli.getMessagesConfig().no_perm); + return true; + } + if (args.length > 2) + { + if (!args[2].equalsIgnoreCase("true") && !args[2].equalsIgnoreCase("false")) + { + return true; + } + pli.arenaSetup.setArenaVIP(plugin, args[1], Boolean.parseBoolean(args[2])); + if (pli.getArenaByName(args[1]) != null) + { + pli.getArenaByName(args[1]).setVIPArena(Boolean.parseBoolean(args[2])); + } + sender.sendMessage(pli.getMessagesConfig().successfully_set.replaceAll("<component>", "vip value")); + } + else + { + sender.sendMessage(ChatColor.DARK_GRAY + "[" + ChatColor.RED + "-" + ChatColor.DARK_GRAY + "]" + ChatColor.GRAY + " Usage: " + cmd + " " + action + " <arena> <true/false>"); + } + return true; + } + + public boolean joinArena(final PluginInstance pli, final CommandSender sender, final String[] args, final String uber_permission, final String cmd, final String action, final JavaPlugin plugin, + final Player p) + { + if (args.length > 1) + { + String playername = p.getName(); + if (args.length > 2) + { + if (!sender.hasPermission(uber_permission + ".adminjoin")) + { + sender.sendMessage(pli.getMessagesConfig().no_perm); + return true; + } + if (Validator.isPlayerOnline(args[2])) + { + playername = args[2]; + } + } + final Arena temp = pli.getArenaByName(args[1]); + if (temp != null) + { + if (!temp.containsPlayer(playername)) + { + temp.joinPlayerLobby(playername); + } + else + { + sender.sendMessage(pli.getMessagesConfig().you_already_are_in_arena.replaceAll("<arena>", temp.getInternalName())); + } + } + else + { + sender.sendMessage(pli.getMessagesConfig().arena_invalid.replaceAll("<arena>", args[1])); + } + } + else + { + Arena a_ = null; + for (final Arena a : pli.getArenas()) + { + if (a.getArenaState() != ArenaState.INGAME) + { + a_ = a; + } + } + if (a_ != null) + { + a_.joinPlayerLobby(p.getName()); + } + else + { + sender.sendMessage(pli.getMessagesConfig().arena_invalid.replaceAll("<arena>", "Arena")); + } + } + return true; + } + + public boolean leaveArena(final PluginInstance pli, final CommandSender sender, final String[] args, final String uber_permission, final String cmd, final String action, final JavaPlugin plugin, + final Player p) + { + if (pli.global_players.containsKey(p.getName())) + { + String playername = p.getName(); + if (args.length > 1) + { + if (sender.hasPermission(uber_permission + ".kickplayer")) + { + if (Validator.isPlayerOnline(args[1])) + { + playername = args[1]; + } + } + } + final Arena a = pli.global_players.get(playername); + if (a.getArcadeInstance() != null) + { + a.getArcadeInstance().leaveArcade(playername, true); + } + a.leavePlayer(playername, false, false); + } + else + { + sender.sendMessage(pli.getMessagesConfig().not_in_arena); + } + return true; + } + + public boolean startArena(final PluginInstance pli, final CommandSender sender, final String[] args, final String uber_permission, final String cmd, final String action, final JavaPlugin plugin, + final Player p) + { + if (!sender.hasPermission(uber_permission + ".start")) + { + sender.sendMessage(pli.getMessagesConfig().no_perm); + return true; + } + if (args.length > 1) + { + final Arena temp = pli.getArenaByName(args[1]); + if (temp != null) + { + temp.start(true); + sender.sendMessage(pli.getMessagesConfig().arena_action.replaceAll("<arena>", args[1]).replaceAll("<action>", "started")); + } + else + { + sender.sendMessage(pli.getMessagesConfig().arena_invalid.replaceAll("<arena>", args[1])); + } + } + else + { + sender.sendMessage(pli.getMessagesConfig().arena_invalid.replaceAll("<arena>", "Arena")); + } + return true; + } + + public boolean stopArena(final PluginInstance pli, final CommandSender sender, final String[] args, final String uber_permission, final String cmd, final String action, final JavaPlugin plugin, + final Player p) + { + if (!sender.hasPermission(uber_permission + ".stop")) + { + sender.sendMessage(pli.getMessagesConfig().no_perm); + return true; + } + if (args.length > 1) + { + final Arena temp = pli.getArenaByName(args[1]); + if (temp != null) + { + temp.stopArena(); + sender.sendMessage(pli.getMessagesConfig().arena_action.replaceAll("<arena>", args[1]).replaceAll("<action>", "stopped")); + } + else + { + sender.sendMessage(pli.getMessagesConfig().arena_invalid.replaceAll("<arena>", args[1])); + } + } + else + { + if (pli.containsGlobalPlayer(p.getName())) + { + final Arena a = pli.global_players.get(p.getName()); + a.stopArena(); + sender.sendMessage(pli.getMessagesConfig().arena_action.replaceAll("<arena>", a.getInternalName()).replaceAll("<action>", "stopped")); + return true; + } + sender.sendMessage(pli.getMessagesConfig().arena_invalid.replaceAll("<arena>", "Arena")); + } + return true; + } + + public boolean stopAllArenas(final PluginInstance pli, final CommandSender sender, final String[] args, final String uber_permission, final String cmd, final String action, + final JavaPlugin plugin, final Player p) + { + if (!sender.hasPermission(uber_permission + ".stop")) + { + sender.sendMessage(pli.getMessagesConfig().no_perm); + return true; + } + for (final Arena a : pli.getArenas()) + { + a.stopArena(); + } + return true; + } + + public boolean removeArena(final PluginInstance pli, final CommandSender sender, final String[] args, final String uber_permission, final String cmd, final String action, final JavaPlugin plugin, + final Player p) + { + if (!sender.hasPermission(uber_permission + ".setup")) + { + sender.sendMessage(pli.getMessagesConfig().no_perm); + return true; + } + if (args.length > 1) + { + pli.getArenasConfig().getConfig().set(ArenaConfigStrings.ARENAS_PREFIX + args[1], null); + pli.getArenasConfig().saveConfig(); + if (pli.removeArena(pli.getArenaByName(args[1]))) + { + sender.sendMessage(pli.getMessagesConfig().arena_action.replaceAll("<arena>", args[1]).replaceAll("<action>", "removed")); + } + else + { + sender.sendMessage(pli.getMessagesConfig().failed_removing_arena.replaceAll("<arena>", args[1])); + } + // TODO remove arena file if present + } + else + { + sender.sendMessage(ChatColor.DARK_GRAY + "[" + ChatColor.RED + "-" + ChatColor.DARK_GRAY + "]" + ChatColor.GRAY + " Usage: " + cmd + " " + action + " <arena>"); + } + return true; + } + + public boolean removeSpawn(final PluginInstance pli, final CommandSender sender, final String[] args, final String uber_permission, final String cmd, final String action, final JavaPlugin plugin, + final Player p) + { + if (!sender.hasPermission(uber_permission + ".setup")) + { + sender.sendMessage(pli.getMessagesConfig().no_perm); + return true; + } + if (args.length > 2) + { + if (Util.isNumeric(args[2])) + { + if (pli.arenaSetup.removeSpawn(plugin, args[1], Integer.parseInt(args[2]))) + { + sender.sendMessage(pli.getMessagesConfig().successfully_removed.replaceAll("<component>", "spawn " + args[2])); + } + else + { + sender.sendMessage(pli.getMessagesConfig().failed_removing_component.replaceAll("<component>", "spawn " + args[2]).replaceAll("<cause>", + "Possibly the provided count couldn't be found: " + args[2])); + } + } + } + else + { + sender.sendMessage(ChatColor.DARK_GRAY + "[" + ChatColor.RED + "-" + ChatColor.DARK_GRAY + "]" + ChatColor.GRAY + " Usage: " + cmd + " " + action + " <arena> <count>"); + } + return true; + } + + // TODO Implement skulls + public boolean setSkull(final PluginInstance pli, final CommandSender sender, final String[] args, final String uber_permission, final String cmd, final String action, final JavaPlugin plugin, + final Player p) + { + if (!sender.hasPermission(uber_permission + ".setup")) + { + sender.sendMessage(pli.getMessagesConfig().no_perm); + return true; + } + sender.sendMessage(ChatColor.GRAY + "This feature is not implemented yet."); + if (true) return true; // TODO will be reimplemented in future versions, work is under progress + if (args.length > 1) + { + if (Util.isNumeric(args[1])) + { + final int count = Integer.parseInt(args[1]); + pli.getStatsInstance(); + p.getInventory().addItem(Stats.giveSkull(args[1])); + p.updateInventory(); + pli.getStatsInstance().skullsetup.add(p.getName()); + } + } + else + { + sender.sendMessage(ChatColor.DARK_GRAY + "[" + ChatColor.RED + "-" + ChatColor.DARK_GRAY + "]" + ChatColor.GRAY + " Usage: " + cmd + " " + action + " <count>"); + } + return true; + } + + public boolean setEnabled(final PluginInstance pli, final CommandSender sender, final String[] args, final String uber_permission, final String cmd, final String action, final JavaPlugin plugin, + final Player p) + { + if (!sender.hasPermission(uber_permission + ".setup")) + { + sender.sendMessage(pli.getMessagesConfig().no_perm); + return true; + } + if (args.length > 2) + { + if (args[2].equalsIgnoreCase("true") || args[2].equalsIgnoreCase("false")) + { + pli.arenaSetup.setArenaEnabled(plugin, args[1], Boolean.parseBoolean(args[2])); + sender.sendMessage(pli.getMessagesConfig().successfully_set.replaceAll("<component>", "enabled state")); + } + else + { + sender.sendMessage(ChatColor.DARK_GRAY + "[" + ChatColor.RED + "-" + ChatColor.DARK_GRAY + "]" + ChatColor.GRAY + " Usage: " + cmd + " " + action + " <arena> <true/false>"); + } + } + else + { + sender.sendMessage(ChatColor.DARK_GRAY + "[" + ChatColor.RED + "-" + ChatColor.DARK_GRAY + "]" + ChatColor.GRAY + " Usage: " + cmd + " " + action + " <arena> <true/false>"); + } + return true; + } + + public boolean setShowScoreboard(final PluginInstance pli, final CommandSender sender, final String[] args, final String uber_permission, final String cmd, final String action, + final JavaPlugin plugin, final Player p) + { + if (!sender.hasPermission(uber_permission + ".setup")) + { + sender.sendMessage(pli.getMessagesConfig().no_perm); + return true; + } + if (args.length > 2) + { + if (args[2].equalsIgnoreCase("true") || args[2].equalsIgnoreCase("false")) + { + pli.arenaSetup.setShowScoreboard(plugin, args[1], Boolean.parseBoolean(args[2])); + sender.sendMessage(pli.getMessagesConfig().successfully_set.replaceAll("<component>", "scoreboard state")); + } + else + { + sender.sendMessage(ChatColor.DARK_GRAY + "[" + ChatColor.RED + "-" + ChatColor.DARK_GRAY + "]" + ChatColor.GRAY + " Usage: " + cmd + " " + action + " <arena> <true/false>"); + } + } + else + { + sender.sendMessage(ChatColor.DARK_GRAY + "[" + ChatColor.RED + "-" + ChatColor.DARK_GRAY + "]" + ChatColor.GRAY + " Usage: " + cmd + " " + action + " <arena> <true/false>"); + } + return true; + } + + public boolean resetArena(final PluginInstance pli, final CommandSender sender, final String[] args, final String uber_permission, final String cmd, final String action, final JavaPlugin plugin, + final Player p) + { + if (!sender.hasPermission(uber_permission + ".reset")) + { + sender.sendMessage(pli.getMessagesConfig().no_perm); + return true; + } + if (args.length > 1) + { + final Arena a = pli.getArenaByName(args[1]); + if (a != null) + { + if (Validator.isArenaValid(plugin, a)) + { + Bukkit.getScheduler().runTask(plugin, () -> PrivateUtil.loadArenaFromFileSYNC(plugin, a)); + sender.sendMessage(pli.getMessagesConfig().arena_action.replaceAll("<arena>", args[1]).replaceAll("<action>", "reset")); + } + } + } + else + { + sender.sendMessage(ChatColor.DARK_GRAY + "[" + ChatColor.RED + "-" + ChatColor.DARK_GRAY + "]" + ChatColor.GRAY + " Usage: " + cmd + " " + action + " <arena>"); + } + return true; + } + + public boolean setAuthor(final PluginInstance pli, final CommandSender sender, final String[] args, final String uber_permission, final String cmd, final String action, final JavaPlugin plugin, + final Player p) + { + if (!sender.hasPermission(uber_permission + ".setup")) + { + sender.sendMessage(pli.getMessagesConfig().no_perm); + return true; + } + if (args.length > 2) + { + final String author = args[2]; + if (Validator.isArenaValid(plugin, args[1])) + { + pli.getArenasConfig().getConfig().set(ArenaConfigStrings.ARENAS_PREFIX + args[1] + ArenaConfigStrings.AUTHOR_SUFFIX, author); + pli.getArenasConfig().saveConfig(); + sender.sendMessage(pli.getMessagesConfig().successfully_set.replaceAll("<component>", "author")); + } + } + else + { + sender.sendMessage(ChatColor.DARK_GRAY + "[" + ChatColor.RED + "-" + ChatColor.DARK_GRAY + "]" + ChatColor.GRAY + " Usage: " + cmd + " " + action + " <arena> <author>"); + } + return true; + } + + public boolean setDescription(final PluginInstance pli, final CommandSender sender, final String[] args, final String uber_permission, final String cmd, final String action, + final JavaPlugin plugin, final Player p) + { + if (!sender.hasPermission(uber_permission + ".setup")) + { + sender.sendMessage(pli.getMessagesConfig().no_perm); + return true; + } + if (args.length > 2) + { + final String desc = args[2]; + if (Validator.isArenaValid(plugin, args[1])) + { + pli.getArenasConfig().getConfig().set(ArenaConfigStrings.ARENAS_PREFIX + args[1] + ArenaConfigStrings.DESCRIPTION_SUFFIX, desc); + pli.getArenasConfig().saveConfig(); + sender.sendMessage(pli.getMessagesConfig().successfully_set.replaceAll("<component>", "description")); + } + } + else + { + sender.sendMessage(ChatColor.DARK_GRAY + "[" + ChatColor.RED + "-" + ChatColor.DARK_GRAY + "]" + ChatColor.GRAY + " Usage: " + cmd + " " + action + " <arena> <description>"); + } + return true; + } + + public boolean setArenaDisplayName(final PluginInstance pli, final CommandSender sender, final String[] args, final String uber_permission, final String cmd, final String action, + final JavaPlugin plugin, final Player p) + { + if (!sender.hasPermission(uber_permission + ".setup")) + { + sender.sendMessage(pli.getMessagesConfig().no_perm); + return true; + } + if (args.length > 2) + { + final String displayname = args[2]; + if (Validator.isArenaValid(plugin, args[1])) + { + pli.getArenasConfig().getConfig().set(ArenaConfigStrings.ARENAS_PREFIX + args[1] + ArenaConfigStrings.DISPLAYNAME_SUFFIX, displayname); + pli.getArenasConfig().saveConfig(); + pli.reloadArena(args[1]); + sender.sendMessage(pli.getMessagesConfig().successfully_set.replaceAll("<component>", "displayname")); + } + } + else + { + sender.sendMessage(ChatColor.DARK_GRAY + "[" + ChatColor.RED + "-" + ChatColor.DARK_GRAY + "]" + ChatColor.GRAY + " Usage: " + cmd + " " + action + " <arena> <displayname>"); + } + return true; + } + + public boolean spectate(final PluginInstance pli, final CommandSender sender, final String[] args, final String uber_permission, final String cmd, final String action, final JavaPlugin plugin, + final Player p) + { + // TODO args > 1 and else leave current player arena + if (args.length > 0) + { + String playername = p.getName(); + if (args.length > 2) + { + if (!sender.hasPermission(uber_permission + ".adminspectate")) + { + sender.sendMessage(pli.getMessagesConfig().no_perm); + return true; + } + if (Validator.isPlayerOnline(args[2])) + { + playername = args[2]; + } + } + else if (args.length > 1) + { + final Arena temp = pli.getArenaByName(args[1]); + if (temp != null) + { + if (temp.getArenaState() == ArenaState.INGAME) + { + if (!temp.containsPlayer(playername)) + { + if (!sender.hasPermission(uber_permission + ".spectate")) + { + sender.sendMessage(pli.getMessagesConfig().no_perm); + } + else + { + temp.joinSpectate(p); + } + } + else + { + sender.sendMessage(pli.getMessagesConfig().you_already_are_in_arena.replaceAll("<arena>", temp.getInternalName())); + } + } + else + { + sender.sendMessage(pli.getMessagesConfig().no_game_started.replaceAll("<arena>", args[1])); + } + } + else + { + sender.sendMessage(pli.getMessagesConfig().arena_invalid.replaceAll("<arena>", args[1])); + } + } + else + { + sender.sendMessage(pli.getMessagesConfig().arena_invalid.replaceAll("<arena>", "Arena")); + } + } + return true; + } + + public boolean setKit(final PluginInstance pli, final CommandSender sender, final String[] args, final String uber_permission, final String cmd, final String action, final JavaPlugin plugin, + Player player) + { + Player p = player; + if (args.length > 1) + { + if (!plugin.getConfig().getBoolean(ArenaConfigStrings.CONFIG_CLASSES_ENABLED)) + { + return true; + } + if (args.length > 2) + { + if (!sender.hasPermission(uber_permission + ".adminkit")) + { + sender.sendMessage(pli.getMessagesConfig().no_perm); + return true; + } + p = Bukkit.getPlayer(args[2]); + if (p == null) + { + return true; + } + } + if (!plugin.getConfig().getBoolean(ArenaConfigStrings.CONFIG_ALLOW_CLASSES_SELECTION_OUT_OF_ARENAS)) + { + if (pli.global_players.containsKey(p.getName())) + { + final Arena a = pli.global_players.get(p.getName()); + if (a.getArenaState() == ArenaState.INGAME) + { + return true; + } + } + else + { + sender.sendMessage(pli.getMessagesConfig().not_in_arena); + return true; + } + } + + final String kit = args[1]; + final AClass ac = pli.getClassesHandler().getClassByInternalname(kit); + if (ac != null) + { + if (pli.getAClasses().containsKey(ac.getName())) + { + if (ac.isEnabled()) + { + pli.getClassesHandler().setClass(kit, p.getName(), MinigamesAPI.getAPI().economyAvailable()); + return true; + } + } + } + + String all = ""; + for (final AClass k : pli.getAClasses().values()) + { + if (k.isEnabled()) + { + if (!pli.show_classes_without_usage_permission) + { + if (!pli.getClassesHandler().kitPlayerHasPermission(k.getInternalName(), p)) + { + continue; + } + } + all += k.getInternalName() + ", "; + } + } + if (all.length() < 2) + { + all = "No kits found! "; + } + all = all.substring(0, all.length() - 2); + sender.sendMessage(pli.getMessagesConfig().possible_kits + all); + + } + else + { + sender.sendMessage(ChatColor.DARK_GRAY + "[" + ChatColor.RED + "-" + ChatColor.DARK_GRAY + "]" + ChatColor.GRAY + " Usage: " + cmd + " " + action + " <kit>"); + if (!plugin.getConfig().getBoolean(ArenaConfigStrings.CONFIG_CLASSES_ENABLED)) + { + return true; + } + if (pli.global_players.containsKey(p.getName())) + { + pli.getClassesHandler().openGUI(p.getName()); + } + else + { + sender.sendMessage(pli.getMessagesConfig().not_in_arena); + } + } + return true; + } + + public boolean openShop(final PluginInstance pli, final CommandSender sender, final String[] args, final String uber_permission, final String cmd, final String action, final JavaPlugin plugin, + final Player p) + { + if (args.length > 1) + { + if (!plugin.getConfig().getBoolean(ArenaConfigStrings.CONFIG_SHOP_ENABLED)) + { + return true; + } + if (pli.global_players.containsKey(p.getName())) + { + final String shop_item = args[1]; + if (!pli.getShopHandler().buyByInternalName(p, shop_item)) + { + String all = ""; + for (final String ac : pli.getShopHandler().shopitems.keySet()) + { + all += ac + ", "; + } + if (all.length() < 2) + { + all = "No shop items found! "; + } + all = all.substring(0, all.length() - 2); + sender.sendMessage(pli.getMessagesConfig().possible_shopitems + all); + } + } + else + { + sender.sendMessage(pli.getMessagesConfig().not_in_arena); + } + } + else + { + if (!plugin.getConfig().getBoolean(ArenaConfigStrings.CONFIG_SHOP_ENABLED)) + { + return true; + } + if (pli.global_players.containsKey(p.getName())) + { + pli.getShopHandler().openGUI(p.getName()); + } + else + { + sender.sendMessage(pli.getMessagesConfig().not_in_arena); + } + } + return true; + } + + public boolean getStats(final PluginInstance pli, final CommandSender sender, final String[] args, final String uber_permission, final String cmd, final String action, final JavaPlugin plugin, + final Player p) + { + Util.sendStatsMessage(pli, p); + return true; + } + + public boolean getLeaderboards(final PluginInstance pli, final CommandSender sender, final String[] args, final String uber_permission, final String cmd, final String action, + final JavaPlugin plugin, final Player p) + { + boolean wins = true; + int count = 10; + if (args.length > 2) + { + if (Util.isNumeric(args[2])) + { + count = Integer.parseInt(args[2]); + if (!args[1].equalsIgnoreCase("wins")) + { + wins = false; + } + } + else + { + if (Util.isNumeric(args[1])) + { + count = Integer.parseInt(args[1]); + } + if (!args[2].equalsIgnoreCase("wins")) + { + wins = false; + } + } + } + else if (args.length > 1 && args.length < 3) + { + if (Util.isNumeric(args[1])) + { + count = Integer.parseInt(args[1]); + } + else + { + if (!args[1].equalsIgnoreCase("wins")) + { + wins = false; + } + } + } + this.sendLeaderboards(pli, sender, count, wins); + return true; + } + + /** + * Send the leaderboards to a player + * + * @param sender + * Player to send the leaderboards to + * @param count + * Amount of result items to show + * @param wins + * whether to check for wins or points leaderboards + */ + private void sendLeaderboards(final PluginInstance pli, final CommandSender sender, final int count, final boolean wins) + { + int c = 0; + if (wins) + { + sender.sendMessage(ChatColor.DARK_GREEN + "--- TOP WINS ---"); + final TreeMap<String, Double> sorted_wins = pli.getStatsInstance().getTop(count, true); + for (final Map.Entry<String, Double> entry : sorted_wins.entrySet()) + { + c++; + if (c > count) + { + break; + } + sender.sendMessage(ChatColor.GREEN + "" + Integer.toString((int) entry.getValue().doubleValue()) + ChatColor.DARK_GREEN + " - " + ChatColor.GREEN + "" + entry.getKey()); + } + } + else + { + sender.sendMessage(ChatColor.DARK_GREEN + "-- TOP POINTS --"); + final TreeMap<String, Double> sorted_wins = pli.getStatsInstance().getTop(count, false); + for (final Map.Entry<String, Double> entry : sorted_wins.entrySet()) + { + c++; + if (c > count) + { + break; + } + sender.sendMessage(ChatColor.GREEN + "" + Integer.toString((int) entry.getValue().doubleValue()) + ChatColor.DARK_GREEN + " - " + ChatColor.GREEN + "" + entry.getKey()); + } + } + } + + // Hologram commands + public boolean setHologram(final PluginInstance pli, final CommandSender sender, final String[] args, final String uber_permission, final String cmd, final String action, final JavaPlugin plugin, + final Player p) + { + if (!sender.hasPermission(uber_permission + ".setup")) + { + sender.sendMessage(pli.getMessagesConfig().no_perm); + return true; + } + final Location l = p.getLocation(); + pli.getHologramsHandler().addHologram(l); + p.sendMessage(ChatColor.GREEN + "Successfully set hologram."); + return true; + } + + public boolean listHolograms(final PluginInstance pli, final CommandSender sender, final String[] args, final String uber_permission, final String cmd, final String action, + final JavaPlugin plugin, final Player p) + { + if (!sender.hasPermission(uber_permission + ".setup")) + { + sender.sendMessage(pli.getMessagesConfig().no_perm); + return true; + } + final HologramsConfig config = pli.getHologramsConfig(); + int c = 0; + if (config.getConfig().isSet("holograms.")) + { + for (final String str : config.getConfig().getConfigurationSection("holograms.").getKeys(false)) + { + final String base = "holograms." + str; + final Location l = new Location(Bukkit.getWorld(config.getConfig().getString(base + ".world")), config.getConfig().getDouble(base + ".location.x"), + config.getConfig().getDouble(base + ".location.y"), config.getConfig().getDouble(base + ".location.z"), (float) config.getConfig().getDouble(base + ".location.yaw"), + (float) config.getConfig().getDouble(base + ".location.pitch")); + p.sendMessage(ChatColor.GRAY + " ~ " + "world:" + l.getWorld().getName() + ", x:" + l.getBlockX() + ", y:" + l.getBlockY() + ", z:" + l.getBlockZ()); + c++; + } + } + if (c == 0) + { + p.sendMessage(ChatColor.RED + "No holograms found!"); + } + return true; + } + + public boolean removeHologram(final PluginInstance pli, final CommandSender sender, final String[] args, final String uber_permission, final String cmd, final String action, + final JavaPlugin plugin, final Player p) + { + if (!sender.hasPermission(uber_permission + ".setup")) + { + sender.sendMessage(pli.getMessagesConfig().no_perm); + return true; + } + final Location ploc = p.getLocation(); + final boolean foundHologram = pli.getHologramsHandler().removeHologram(ploc); + if (foundHologram) + { + p.sendMessage(ChatColor.GREEN + "Successfully removed hologram from config. It won't be sent anymore from now on!"); + return true; + } + // No holograms found + p.sendMessage(ChatColor.RED + "No near holograms found! Please stand in a maximum distance of 2 blocks to a hologram to remove it."); + return true; + } + + // Party commands + public boolean partyInvite(final CommandSender sender, final String[] args, final String uber_permission, final String cmd, final String action, final JavaPlugin plugin, final Player p) + { + if (args.length > 1) + { + final Player target = Bukkit.getPlayer(args[1]); + if (target == null) + { + p.sendMessage(MinigamesAPI.getAPI().partymessages.player_not_online.replaceAll("<player>", args[1])); + return true; + } + + if (p.getUniqueId().equals(target.getUniqueId())) + { + p.sendMessage(MinigamesAPI.getAPI().partymessages.cannot_invite_yourself); + return true; + } + + boolean isInParty = false; + for (final Party party : MinigamesAPI.getAPI().getParties()) + { + if (party.containsPlayer(p.getUniqueId())) + { + isInParty = true; + } + } + if (!isInParty) + { + if (!Validator.isPlayerOnline(args[1])) + { + p.sendMessage(MinigamesAPI.getAPI().partymessages.player_not_online.replaceAll("<player>", args[1])); + return true; + } + Party party = null; + if (!MinigamesAPI.getAPI().hasParty(p.getUniqueId())) + { + party = MinigamesAPI.getAPI().createParty(p.getUniqueId()); + } + else + { + party = MinigamesAPI.getAPI().getParty(p.getUniqueId()); + } + final Player invited = Bukkit.getPlayer(args[1]); + MinigamesAPI.getAPI().addPartyInvite(invited.getUniqueId(), party); + p.sendMessage(MinigamesAPI.getAPI().partymessages.you_invited.replaceAll("<player>", args[1])); + invited.sendMessage(MinigamesAPI.getAPI().partymessages.you_were_invited.replaceAll("<player>", p.getName())); + } + } + else + { + sender.sendMessage(ChatColor.DARK_GRAY + "[" + ChatColor.RED + "-" + ChatColor.DARK_GRAY + "]" + ChatColor.GRAY + " Usage: " + cmd + " " + action + " <player>"); + } + return true; + } + + public boolean partyAccept(final CommandSender sender, final String[] args, final String uber_permission, final String cmd, final String action, final JavaPlugin plugin, final Player p) + { + if (args.length > 1) + { + if (!Validator.isPlayerOnline(args[1])) + { + p.sendMessage(MinigamesAPI.getAPI().partymessages.player_not_online.replaceAll("<player>", args[1])); + return true; + } + if (!MinigamesAPI.getAPI().hasPartyInvites(p.getUniqueId())) + { + p.sendMessage(MinigamesAPI.getAPI().partymessages.not_invited_to_any_party); + return true; + } + + boolean isInParty = false; + Party party_ = null; + for (final Party party : MinigamesAPI.getAPI().getParties()) + { + if (party.containsPlayer(p.getUniqueId())) + { + isInParty = true; + party_ = party; + } + } + if (isInParty) + { + if (party_ != null) + { + party_.removePlayer(p.getUniqueId()); + } + } + if (MinigamesAPI.getAPI().hasParty(p.getUniqueId())) + { + MinigamesAPI.getAPI().getParty(p.getUniqueId()).disband(); + } + + Party party__ = null; + for (final Party party : MinigamesAPI.getAPI().getPartyInvites(p.getUniqueId())) + { + if (party.getOwner().equals(Bukkit.getPlayer(args[1]).getUniqueId())) + { + party__ = party; + break; + } + } + if (party__ != null) + { + party__.addPlayer(p.getUniqueId()); + MinigamesAPI.getAPI().removePartyInvites(p.getUniqueId()); + } + else + { + p.sendMessage(MinigamesAPI.getAPI().partymessages.not_invited_to_players_party.replaceAll("<player>", args[1])); + } + } + else + { + sender.sendMessage(ChatColor.DARK_GRAY + "[" + ChatColor.RED + "-" + ChatColor.DARK_GRAY + "]" + ChatColor.GRAY + " Usage: " + cmd + " " + action + " <player>"); + } + return true; + } + + public boolean partyKick(final CommandSender sender, final String[] args, final String uber_permission, final String cmd, final String action, final JavaPlugin plugin, final Player p) + { + if (args.length > 1) + { + if (!Validator.isPlayerOnline(args[1])) + { + p.sendMessage(MinigamesAPI.getAPI().partymessages.player_not_online.replaceAll("<player>", args[1])); + return true; + } + if (MinigamesAPI.getAPI().hasParty(p.getUniqueId())) + { + final Party party = MinigamesAPI.getAPI().getParty(p.getUniqueId()); + final Player target = Bukkit.getPlayer(args[1]); + if (party.containsPlayer(target.getUniqueId())) + { + party.removePlayer(target.getUniqueId()); + } + else + { + p.sendMessage(MinigamesAPI.getAPI().partymessages.player_not_in_party.replaceAll("<player>", args[1])); + } + } + } + else + { + sender.sendMessage(ChatColor.DARK_GRAY + "[" + ChatColor.RED + "-" + ChatColor.DARK_GRAY + "]" + ChatColor.GRAY + " Usage: " + cmd + " " + action + " <player>"); + } + return true; + } + + public boolean partyList(final CommandSender sender, final String[] args, final String uber_permission, final String cmd, final String action, final JavaPlugin plugin, final Player p) + { + if (args.length > 0) + { + Party party_ = null; + for (final Party party : MinigamesAPI.getAPI().getParties()) + { + if (party.containsPlayer(p.getUniqueId())) + { + party_ = party; + } + } + if (MinigamesAPI.getAPI().hasParty(p.getUniqueId())) + { + party_ = MinigamesAPI.getAPI().getParty(p.getUniqueId()); + } + if (party_ != null) + { + String ret = ChatColor.DARK_GREEN + Bukkit.getPlayer(party_.getOwner()).getName(); + for (final UUID p_ : party_.getPlayers()) + { + ret += ChatColor.GREEN + ", " + Bukkit.getPlayer(p_).getName(); + } + p.sendMessage(ret); + } + } + else + { + sender.sendMessage(ChatColor.DARK_GRAY + "[" + ChatColor.RED + "-" + ChatColor.DARK_GRAY + "]" + ChatColor.GRAY + " Usage: " + cmd + " " + action); + } + return true; + } + + public boolean partyDisband(final CommandSender sender, final String[] args, final String uber_permission, final String cmd, final String action, final JavaPlugin plugin, final Player p) + { + if (args.length > 0) + { + if (MinigamesAPI.getAPI().hasParty(p.getUniqueId())) + { + MinigamesAPI.getAPI().getParty(p.getUniqueId()).disband(); + } + } + else + { + sender.sendMessage(ChatColor.DARK_GRAY + "[" + ChatColor.RED + "-" + ChatColor.DARK_GRAY + "]" + ChatColor.GRAY + " Usage: " + cmd + " " + action); + } + return true; + } + + public boolean partyLeave(final CommandSender sender, final String[] args, final String uber_permission, final String cmd, final String action, final JavaPlugin plugin, final Player p) + { + if (args.length > 0) + { + if (MinigamesAPI.getAPI().hasParty(p.getUniqueId())) + { + MinigamesAPI.getAPI().getParty(p.getUniqueId()).disband(); + return true; + } + Party party_ = null; + for (final Party party : MinigamesAPI.getAPI().getParties()) + { + if (party.containsPlayer(p.getUniqueId())) + { + party_ = party; + } + } + if (party_ != null) + { + party_.removePlayer(p.getUniqueId()); + } + } + else + { + sender.sendMessage(ChatColor.DARK_GRAY + "[" + ChatColor.RED + "-" + ChatColor.DARK_GRAY + "]" + ChatColor.GRAY + " Usage: " + cmd + " " + action); + } + return true; + } + } diff --git a/API/src/main/java/com/comze_instancelabs/minigamesapi/config/AchievementsConfig.java b/API/src/main/java/com/comze_instancelabs/minigamesapi/config/AchievementsConfig.java index 40a96e17..4904da0e 100644 --- a/API/src/main/java/com/comze_instancelabs/minigamesapi/config/AchievementsConfig.java +++ b/API/src/main/java/com/comze_instancelabs/minigamesapi/config/AchievementsConfig.java @@ -1,100 +1,127 @@ +/* + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ package com.comze_instancelabs.minigamesapi.config; -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.configuration.file.YamlConfiguration; -import org.bukkit.plugin.java.JavaPlugin; - import java.io.File; import java.io.IOException; import java.io.InputStream; +import java.io.InputStreamReader; -public class AchievementsConfig { - - private FileConfiguration arenaConfig = null; - private File arenaFile = null; - private JavaPlugin plugin = null; - - public AchievementsConfig(JavaPlugin plugin) { - this.plugin = plugin; - this.getConfig().options().header("Used for saving achievements details."); - - this.getConfig().addDefault("config.enabled", true); - - this.getConfig().addDefault("config.achievements.first_blood.enabled", true); - this.getConfig().addDefault("config.achievements.first_blood.name", "First Blood!"); - this.getConfig().addDefault("config.achievements.first_blood.reward.economy_reward", true); - this.getConfig().addDefault("config.achievements.first_blood.reward.econ_reward_amount", 20); - this.getConfig().addDefault("config.achievements.first_blood.reward.command_reward", false); - this.getConfig().addDefault("config.achievements.first_blood.reward.cmd", "tell <player> Good job!"); - - this.getConfig().addDefault("config.achievements.ten_kills.enabled", true); - this.getConfig().addDefault("config.achievements.ten_kills.name", "Ten Kills!"); - this.getConfig().addDefault("config.achievements.ten_kills.reward.economy_reward", true); - this.getConfig().addDefault("config.achievements.ten_kills.reward.econ_reward_amount", 50); - this.getConfig().addDefault("config.achievements.ten_kills.reward.command_reward", false); - this.getConfig().addDefault("config.achievements.ten_kills.reward.cmd", "tell <player> Good job!"); - - this.getConfig().addDefault("config.achievements.hundred_kills.enabled", true); - this.getConfig().addDefault("config.achievements.hundred_kills.name", "Hundred Kills!"); - this.getConfig().addDefault("config.achievements.hundred_kills.reward.economy_reward", true); - this.getConfig().addDefault("config.achievements.hundred_kills.reward.econ_reward_amount", 1000); - this.getConfig().addDefault("config.achievements.hundred_kills.reward.command_reward", false); - this.getConfig().addDefault("config.achievements.hundred_kills.reward.cmd", "tell <player> Good job!"); - - this.getConfig().addDefault("config.achievements.first_win.enabled", true); - this.getConfig().addDefault("config.achievements.first_win.name", "Your first win!"); - this.getConfig().addDefault("config.achievements.first_win.reward.economy_reward", true); - this.getConfig().addDefault("config.achievements.first_win.reward.econ_reward_amount", 30); - this.getConfig().addDefault("config.achievements.first_win.reward.command_reward", false); - this.getConfig().addDefault("config.achievements.first_win.reward.cmd", "tell <player> Good job!"); - - this.getConfig().addDefault("config.achievements.ten_wins.enabled", true); - this.getConfig().addDefault("config.achievements.ten_wins.name", "Ten wins!"); - this.getConfig().addDefault("config.achievements.ten_wins.reward.economy_reward", true); - this.getConfig().addDefault("config.achievements.ten_wins.reward.econ_reward_amount", 30); - this.getConfig().addDefault("config.achievements.ten_wins.reward.command_reward", false); - this.getConfig().addDefault("config.achievements.ten_wins.reward.cmd", "tell <player> Good job!"); - - this.getConfig().addDefault("config.achievements.achievement_guy.enabled", true); - this.getConfig().addDefault("config.achievements.achievement_guy.name", "All achievement guy!"); - this.getConfig().addDefault("config.achievements.achievement_guy.reward.economy_reward", true); - this.getConfig().addDefault("config.achievements.achievement_guy.reward.econ_reward_amount", 30); - this.getConfig().addDefault("config.achievements.achievement_guy.reward.command_reward", false); - this.getConfig().addDefault("config.achievements.achievement_guy.reward.cmd", "tell <player> Good job!"); - - this.getConfig().options().copyDefaults(true); - this.saveConfig(); - } - - public FileConfiguration getConfig() { - if (arenaConfig == null) { - reloadConfig(); - } - return arenaConfig; - } - - public void saveConfig() { - if (arenaConfig == null || arenaFile == null) { - return; - } - try { - getConfig().save(arenaFile); - } catch (IOException ex) { - - } - } - - public void reloadConfig() { - if (arenaFile == null) { - arenaFile = new File(plugin.getDataFolder(), "achievements.yml"); - } - arenaConfig = YamlConfiguration.loadConfiguration(arenaFile); - - InputStream defConfigStream = plugin.getResource("achievements.yml"); - if (defConfigStream != null) { - YamlConfiguration defConfig = YamlConfiguration.loadConfiguration(defConfigStream); - arenaConfig.setDefaults(defConfig); - } - } +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.plugin.java.JavaPlugin; +public class AchievementsConfig +{ + + private FileConfiguration arenaConfig = null; + private File arenaFile = null; + private JavaPlugin plugin = null; + + public AchievementsConfig(final JavaPlugin plugin) + { + this.plugin = plugin; + this.getConfig().options().header("Used for saving achievements details."); + + this.getConfig().addDefault("config.enabled", true); + + this.getConfig().addDefault("config.achievements.first_blood.enabled", true); + this.getConfig().addDefault("config.achievements.first_blood.name", "First Blood!"); + this.getConfig().addDefault("config.achievements.first_blood.reward.economy_reward", true); + this.getConfig().addDefault("config.achievements.first_blood.reward.econ_reward_amount", 20); + this.getConfig().addDefault("config.achievements.first_blood.reward.command_reward", false); + this.getConfig().addDefault("config.achievements.first_blood.reward.cmd", "tell <player> Good job!"); + + this.getConfig().addDefault("config.achievements.ten_kills.enabled", true); + this.getConfig().addDefault("config.achievements.ten_kills.name", "Ten Kills!"); + this.getConfig().addDefault("config.achievements.ten_kills.reward.economy_reward", true); + this.getConfig().addDefault("config.achievements.ten_kills.reward.econ_reward_amount", 50); + this.getConfig().addDefault("config.achievements.ten_kills.reward.command_reward", false); + this.getConfig().addDefault("config.achievements.ten_kills.reward.cmd", "tell <player> Good job!"); + + this.getConfig().addDefault("config.achievements.hundred_kills.enabled", true); + this.getConfig().addDefault("config.achievements.hundred_kills.name", "Hundred Kills!"); + this.getConfig().addDefault("config.achievements.hundred_kills.reward.economy_reward", true); + this.getConfig().addDefault("config.achievements.hundred_kills.reward.econ_reward_amount", 1000); + this.getConfig().addDefault("config.achievements.hundred_kills.reward.command_reward", false); + this.getConfig().addDefault("config.achievements.hundred_kills.reward.cmd", "tell <player> Good job!"); + + this.getConfig().addDefault("config.achievements.first_win.enabled", true); + this.getConfig().addDefault("config.achievements.first_win.name", "Your first win!"); + this.getConfig().addDefault("config.achievements.first_win.reward.economy_reward", true); + this.getConfig().addDefault("config.achievements.first_win.reward.econ_reward_amount", 30); + this.getConfig().addDefault("config.achievements.first_win.reward.command_reward", false); + this.getConfig().addDefault("config.achievements.first_win.reward.cmd", "tell <player> Good job!"); + + this.getConfig().addDefault("config.achievements.ten_wins.enabled", true); + this.getConfig().addDefault("config.achievements.ten_wins.name", "Ten wins!"); + this.getConfig().addDefault("config.achievements.ten_wins.reward.economy_reward", true); + this.getConfig().addDefault("config.achievements.ten_wins.reward.econ_reward_amount", 30); + this.getConfig().addDefault("config.achievements.ten_wins.reward.command_reward", false); + this.getConfig().addDefault("config.achievements.ten_wins.reward.cmd", "tell <player> Good job!"); + + this.getConfig().addDefault("config.achievements.achievement_guy.enabled", true); + this.getConfig().addDefault("config.achievements.achievement_guy.name", "All achievement guy!"); + this.getConfig().addDefault("config.achievements.achievement_guy.reward.economy_reward", true); + this.getConfig().addDefault("config.achievements.achievement_guy.reward.econ_reward_amount", 30); + this.getConfig().addDefault("config.achievements.achievement_guy.reward.command_reward", false); + this.getConfig().addDefault("config.achievements.achievement_guy.reward.cmd", "tell <player> Good job!"); + + this.getConfig().options().copyDefaults(true); + this.saveConfig(); + } + + public FileConfiguration getConfig() + { + if (this.arenaConfig == null) + { + this.reloadConfig(); + } + return this.arenaConfig; + } + + public void saveConfig() + { + if (this.arenaConfig == null || this.arenaFile == null) + { + return; + } + try + { + this.getConfig().save(this.arenaFile); + } + catch (final IOException ex) + { + // silently ignore + } + } + + public void reloadConfig() + { + if (this.arenaFile == null) + { + this.arenaFile = new File(this.plugin.getDataFolder(), "achievements.yml"); + } + this.arenaConfig = YamlConfiguration.loadConfiguration(this.arenaFile); + + final InputStream defConfigStream = this.plugin.getResource("achievements.yml"); + if (defConfigStream != null) + { + final YamlConfiguration defConfig = YamlConfiguration.loadConfiguration(new InputStreamReader(defConfigStream)); + this.arenaConfig.setDefaults(defConfig); + } + } + } diff --git a/API/src/main/java/com/comze_instancelabs/minigamesapi/config/ArenasConfig.java b/API/src/main/java/com/comze_instancelabs/minigamesapi/config/ArenasConfig.java index 1b4928a6..18ade8d0 100644 --- a/API/src/main/java/com/comze_instancelabs/minigamesapi/config/ArenasConfig.java +++ b/API/src/main/java/com/comze_instancelabs/minigamesapi/config/ArenasConfig.java @@ -1,55 +1,82 @@ -package com.comze_instancelabs.minigamesapi.config; +/* + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.configuration.file.YamlConfiguration; -import org.bukkit.plugin.java.JavaPlugin; + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ +package com.comze_instancelabs.minigamesapi.config; import java.io.File; import java.io.IOException; import java.io.InputStream; +import java.io.InputStreamReader; -public class ArenasConfig { - - private FileConfiguration arenaConfig = null; - private File arenaFile = null; - private JavaPlugin plugin = null; - - public ArenasConfig(JavaPlugin plugin) { - this.plugin = plugin; - this.getConfig().options().header("Used for saving arena details."); - // this.getConfig().options().copyDefaults(true); - this.saveConfig(); - } - - public FileConfiguration getConfig() { - if (arenaConfig == null) { - reloadConfig(); - } - return arenaConfig; - } - - public void saveConfig() { - if (arenaConfig == null || arenaFile == null) { - return; - } - try { - getConfig().save(arenaFile); - } catch (IOException ex) { - - } - } - - public void reloadConfig() { - if (arenaFile == null) { - arenaFile = new File(plugin.getDataFolder(), "arenas.yml"); - } - arenaConfig = YamlConfiguration.loadConfiguration(arenaFile); - - InputStream defConfigStream = plugin.getResource("arenas.yml"); - if (defConfigStream != null) { - YamlConfiguration defConfig = YamlConfiguration.loadConfiguration(defConfigStream); - arenaConfig.setDefaults(defConfig); - } - } +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.plugin.java.JavaPlugin; +public class ArenasConfig +{ + + private FileConfiguration arenaConfig = null; + private File arenaFile = null; + private JavaPlugin plugin = null; + + public ArenasConfig(final JavaPlugin plugin) + { + this.plugin = plugin; + this.getConfig().options().header("Used for saving arena details."); + // this.getConfig().options().copyDefaults(true); + this.saveConfig(); + } + + public FileConfiguration getConfig() + { + if (this.arenaConfig == null) + { + this.reloadConfig(); + } + return this.arenaConfig; + } + + public void saveConfig() + { + if (this.arenaConfig == null || this.arenaFile == null) + { + return; + } + try + { + this.getConfig().save(this.arenaFile); + } + catch (final IOException ex) + { + // silently ignore + } + } + + public void reloadConfig() + { + if (this.arenaFile == null) + { + this.arenaFile = new File(this.plugin.getDataFolder(), "arenas.yml"); + } + this.arenaConfig = YamlConfiguration.loadConfiguration(this.arenaFile); + + final InputStream defConfigStream = this.plugin.getResource("arenas.yml"); + if (defConfigStream != null) + { + final YamlConfiguration defConfig = YamlConfiguration.loadConfiguration(new InputStreamReader(defConfigStream)); + this.arenaConfig.setDefaults(defConfig); + } + } + } diff --git a/API/src/main/java/com/comze_instancelabs/minigamesapi/config/ClassesConfig.java b/API/src/main/java/com/comze_instancelabs/minigamesapi/config/ClassesConfig.java index d5d830c5..e15443d0 100644 --- a/API/src/main/java/com/comze_instancelabs/minigamesapi/config/ClassesConfig.java +++ b/API/src/main/java/com/comze_instancelabs/minigamesapi/config/ClassesConfig.java @@ -1,66 +1,96 @@ -package com.comze_instancelabs.minigamesapi.config; +/* + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.configuration.file.YamlConfiguration; -import org.bukkit.plugin.java.JavaPlugin; + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ +package com.comze_instancelabs.minigamesapi.config; import java.io.File; import java.io.IOException; import java.io.InputStream; +import java.io.InputStreamReader; -public class ClassesConfig { - - private FileConfiguration classesConfig = null; - private File classesFile = null; - private JavaPlugin plugin = null; - - public ClassesConfig(JavaPlugin plugin, boolean custom) { - this.plugin = plugin; - if (!custom) { - this.getConfig().options().header("Used for saving classes. Default class:"); - this.getConfig().addDefault("config.kits.default.name", "default"); - this.getConfig().addDefault("config.kits.default.enabled", true); - this.getConfig().addDefault("config.kits.default.items", "351:5#DAMAGE_ALL:1#KNOCKBACK*1"); - this.getConfig().addDefault("config.kits.default.icon", "351:5#DAMAGE_ALL:1#KNOCKBACK*1"); - this.getConfig().addDefault("config.kits.default.lore", "The default class.;Second line"); - this.getConfig().addDefault("config.kits.default.requires_money", false); - this.getConfig().addDefault("config.kits.default.requires_permission", false); - this.getConfig().addDefault("config.kits.default.money_amount", 100); - this.getConfig().addDefault("config.kits.default.permission_node", "minigames.kits.default"); - } - this.getConfig().options().copyDefaults(true); - this.saveConfig(); - } - - public FileConfiguration getConfig() { - if (classesConfig == null) { - reloadConfig(); - } - return classesConfig; - } - - public void saveConfig() { - if (classesConfig == null || classesFile == null) { - return; - } - try { - getConfig().save(classesFile); - } catch (IOException ex) { - - } - } - - public void reloadConfig() { - if (classesFile == null) { - classesFile = new File(plugin.getDataFolder(), "classes.yml"); - } - classesConfig = YamlConfiguration.loadConfiguration(classesFile); +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.plugin.java.JavaPlugin; - InputStream defConfigStream = plugin.getResource("classes.yml"); - if (defConfigStream != null) { - YamlConfiguration defConfig = YamlConfiguration.loadConfiguration(defConfigStream); - classesConfig.setDefaults(defConfig); - } - } +import com.comze_instancelabs.minigamesapi.MinigamesAPI; +public class ClassesConfig +{ + + private FileConfiguration classesConfig = null; + private File classesFile = null; + private JavaPlugin plugin = null; + + public ClassesConfig(final JavaPlugin plugin, final boolean custom) + { + this.plugin = plugin; + if (!custom) + { + this.getConfig().options().header("Used for saving classes. Default class:"); + this.getConfig().addDefault("config.kits.default.name", "default"); + this.getConfig().addDefault("config.kits.default.enabled", true); + this.getConfig().addDefault("config.kits.default.items", "351:5#DAMAGE_ALL:1#KNOCKBACK*1"); + this.getConfig().addDefault("config.kits.default.icon", "351:5#DAMAGE_ALL:1#KNOCKBACK*1"); + this.getConfig().addDefault("config.kits.default.lore", "The default class.;Second line"); + this.getConfig().addDefault("config.kits.default.requires_money", false); + this.getConfig().addDefault("config.kits.default.requires_permission", false); + this.getConfig().addDefault("config.kits.default.money_amount", 100); + this.getConfig().addDefault("config.kits.default.permission_node", MinigamesAPI.getAPI().getPermissionKitPrefix() + ".default"); + } + this.getConfig().options().copyDefaults(true); + this.saveConfig(); + } + + public FileConfiguration getConfig() + { + if (this.classesConfig == null) + { + this.reloadConfig(); + } + return this.classesConfig; + } + + public void saveConfig() + { + if (this.classesConfig == null || this.classesFile == null) + { + return; + } + try + { + this.getConfig().save(this.classesFile); + } + catch (final IOException ex) + { + // silently ignore + } + } + + public void reloadConfig() + { + if (this.classesFile == null) + { + this.classesFile = new File(this.plugin.getDataFolder(), "classes.yml"); + } + this.classesConfig = YamlConfiguration.loadConfiguration(this.classesFile); + + final InputStream defConfigStream = this.plugin.getResource("classes.yml"); + if (defConfigStream != null) + { + final YamlConfiguration defConfig = YamlConfiguration.loadConfiguration(new InputStreamReader(defConfigStream)); + this.classesConfig.setDefaults(defConfig); + } + } + } diff --git a/API/src/main/java/com/comze_instancelabs/minigamesapi/config/DefaultConfig.java b/API/src/main/java/com/comze_instancelabs/minigamesapi/config/DefaultConfig.java index 840cb9cb..ba76e115 100644 --- a/API/src/main/java/com/comze_instancelabs/minigamesapi/config/DefaultConfig.java +++ b/API/src/main/java/com/comze_instancelabs/minigamesapi/config/DefaultConfig.java @@ -1,3 +1,17 @@ +/* + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ package com.comze_instancelabs.minigamesapi.config; import java.io.IOException; @@ -5,172 +19,196 @@ import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.plugin.java.JavaPlugin; -public class DefaultConfig { - - JavaPlugin plugin; - - public DefaultConfig(JavaPlugin plugin, boolean custom) { - this.plugin = plugin; - DefaultConfig.init(plugin, custom); - } - - public static void init(JavaPlugin plugin, boolean custom) { - FileConfiguration config = plugin.getConfig(); - config.options().header("The default config. Check http://dev.bukkit.org/bukkit-plugins/instances-minigamesapi/#w-tutorials \n" + "or https://github.com/instance01/MinigamesAPI/wiki/Default-Config-and-Item-Markup \n" + "for more information if you don't understand a config entry. \n" + "You can find classes (kits) in classes.yml, all saved arenas in arenas.yml, all messages in messages.yml. \n" + "You can edit/disable achievements in achievements.yml."); - if (!custom) { - config.addDefault("config.selection_items.classes_selection_item", 399); - config.addDefault("config.selection_items.exit_item", 152); - config.addDefault("config.selection_items.achievement_item", 160); - config.addDefault("config.selection_items.spectator_item", 345); - config.addDefault("config.selection_items.shop_selection_item", 388); - config.addDefault("config.GUI.classes_gui_rows", 3); - config.addDefault("config.GUI.shop_gui_rows", 3); - config.addDefault("config.spectator.spectator_after_fall_or_death", true); - config.addDefault("config.spectator.spectator_move_y_lock", true); - config.addDefault("config.defaults.default_max_players", 4); - config.addDefault("config.defaults.default_min_players", 2); - config.addDefault("config.defaults.default_max_game_time_in_minutes", 30); - config.addDefault("config.countdowns.lobby_countdown", 30); - config.addDefault("config.countdowns.ingame_countdown", 10); - config.addDefault("config.countdowns.ingame_countdown_enabled", true); - config.addDefault("config.countdowns.skip_lobby", false); - config.addDefault("config.countdowns.clearinv_while_ingamecountdown", false); - - config.addDefault("config.classes_enabled", true); - config.addDefault("config.shop_enabled", true); - config.addDefault("config.use_credits_instead_of_money_for_kits", false); - config.addDefault("config.reset_inventory_when_players_leave_server", true); - config.addDefault("config.color_background_wool_of_signs", false); - config.addDefault("config.show_classes_without_usage_permission", true); - - config.addDefault("config.rewards.economy", true); - config.addDefault("config.rewards.economy_reward", 10); - config.addDefault("config.rewards.item_reward", false); - config.addDefault("config.rewards.item_reward_ids", "264*1;11*1"); - config.addDefault("config.rewards.command_reward", false); - config.addDefault("config.rewards.command", "pex user <player> add SKILLZ.*"); - config.addDefault("config.rewards.economy_for_kills", true); - config.addDefault("config.rewards.economy_reward_for_kills", 5); - config.addDefault("config.rewards.command_reward_for_kills", false); - config.addDefault("config.rewards.command_for_kills", "pex user <player> add SKILLZ.*"); - config.addDefault("config.rewards.economy_for_participation", false); - config.addDefault("config.rewards.economy_reward_for_participation", 5); - config.addDefault("config.rewards.command_reward_for_participation", false); - config.addDefault("config.rewards.command_for_participation", "pex user <player> add SKILLZ.*"); - - config.addDefault("config.stats.points_for_kill", 2); - config.addDefault("config.stats.points_for_win", 10); - - config.addDefault("config.arcade.enabled", true); - config.addDefault("config.arcade.min_players", 1); - config.addDefault("config.arcade.max_players", 16); - config.addDefault("config.arcade.arena_to_prefer.enabled", false); - config.addDefault("config.arcade.arena_to_prefer.arena", "arena1"); - config.addDefault("config.arcade.lobby_countdown", 20); - config.addDefault("config.arcade.show_each_lobby_countdown", false); - config.addDefault("config.arcade.infinite_mode.enabled", false); - config.addDefault("config.arcade.infinite_mode.seconds_to_new_round", 10); - config.addDefault("config.bungee.game_on_join", false); - config.addDefault("config.bungee.teleport_all_to_server_on_stop.tp", false); - config.addDefault("config.bungee.teleport_all_to_server_on_stop.server", "lobby"); - config.addDefault("config.bungee.whitelist_while_game_running", false); - config.addDefault("config.execute_cmds_on_stop", false); - config.addDefault("config.cmds", ""); - config.addDefault("config.cmds_after", "say SERVER STOPPING;stop"); - config.addDefault("config.map_rotation", false); - config.addDefault("config.broadcast_win", true); - config.addDefault("config.buy_classes_forever", true); - config.addDefault("config.disable_commands_in_arena", true); - config.addDefault("config.command_whitelist", "/msg,/pm,/help"); - config.addDefault("config.leave_command", "/leave"); - config.addDefault("config.spawn_fireworks_for_winners", true); - config.addDefault("config.powerup_spawning.broadcast", false); - config.addDefault("config.powerup_spawning.spawn_firework", false); - config.addDefault("config.use_custom_scoreboard", false); - config.addDefault("config.delay.enabled", false); - config.addDefault("config.delay.amount_seconds", 5); - config.addDefault("config.send_game_started_msg", false); - config.addDefault("config.auto_add_default_kit", true); - config.addDefault("config.last_man_standing_wins", true); - config.addDefault("config.effects.blood", true); - config.addDefault("config.effects.damage_identifier_holograms", true); - config.addDefault("config.effects.dead_in_fake_bed", true); - config.addDefault("config.effects.1_8_titles", true); - config.addDefault("config.effects.1_8_spectator_mode", false); - config.addDefault("config.sounds.lobby_countdown", "none"); - config.addDefault("config.sounds.ingame_countdown", "SUCCESSFUL_HIT"); - config.addDefault("config.chat_per_arena_only", false); - config.addDefault("config.chat_show_score_in_arena", false); - config.addDefault("config.compass_tracking_enabled", true); - config.addDefault("config.allow_classes_selection_out_of_arenas", false); - config.addDefault("config.send_stats_on_stop", true); - config.addDefault("config.use_xp_bar_level", true); - config.addDefault("config.use_old_reset_method", false); - config.addDefault("config.chat_enabled", true); - - config.addDefault("config.extra_lobby_item.item0.enabled", false); - config.addDefault("config.extra_lobby_item.item0.item", 9); - config.addDefault("config.extra_lobby_item.item0.name", "Custom Item"); - config.addDefault("config.extra_lobby_item.item0.command", "say This is a custom extra lobby item."); - - config.addDefault("mysql.enabled", false); - config.addDefault("mysql.host", "127.0.0.1"); - config.addDefault("mysql.user", "root"); - config.addDefault("mysql.pw", "root"); - config.addDefault("mysql.database", "mcminigames"); - } - config.options().copyDefaults(true); - plugin.saveConfig(); - - try { - convert(plugin); - } catch (Exception e) { - - } - } - - public static void convert(JavaPlugin plugin) throws IOException { - FileConfiguration config = plugin.getConfig(); - if (!config.isSet("config.version")) { - // TODO new config - config.set("config.selection_items.classes_selection_item", config.get("config.classes_selection_item")); - config.set("config.selection_items.exit_item", config.get("config.exit_item")); - config.set("config.selection_items.achievement_item", config.get("config.achievement_item")); - config.set("config.selection_items.spectator_item", config.get("config.exit_item")); - config.set("config.selection_items.shop_selection_item", config.get("config.shop_selection_item")); - config.set("config.GUI.classes_gui_rows", config.get("config.classes_gui_rows")); - config.set("config.GUI.shop_gui_rows", config.get("config.shop_gui_rows")); - config.set("config.spectator.spectator_after_fall_or_death", config.get("config.spectator_after_fall_or_death")); - config.set("config.spectator.spectator_move_y_lock", config.get("config.spectator_move_y_lock")); - config.set("config.defaults.default_max_players", config.get("config.default_max_players")); - config.set("config.defaults.default_min_players", config.get("config.default_min_players")); - config.set("config.defaults.default_max_game_time_in_minutes", config.get("config.default_max_game_time_in_minutes")); - config.set("config.countdowns.lobby_countdown", config.get("config.lobby_countdown")); - config.set("config.countdowns.ingame_countdown", config.get("config.ingame_countdown")); - config.set("config.countdowns.ingame_countdown_enabled", config.get("config.ingame_countdown_enabled")); - config.set("config.countdowns.skip_lobby", config.get("config.skip_lobby")); - config.set("config.countdowns.clearinv_while_ingamecountdown", config.get("config.clearinv_while_ingamecountdown")); - - config.set("config.classes_selection_item", null); - config.set("config.exit_item", null); - config.set("config.achievement_item", null); - config.set("config.shop_selection_item", null); - config.set("config.classes_gui_rows", null); - config.set("config.shop_gui_rows", null); - config.set("config.clearinv_while_ingamecountdown", null); - config.set("config.spectator_after_fall_or_death", null); - config.set("config.spectator_move_y_lock", null); - config.set("config.default_max_players", null); - config.set("config.default_min_players", null); - config.set("config.default_max_game_time_in_minutes", null); - config.set("config.lobby_countdown", null); - config.set("config.ingame_countdown", null); - config.set("config.ingame_countdown_enabled", null); - config.set("config.skip_lobby", null); - - config.set("config.version", 1); - plugin.saveConfig(); - } - } - +import com.comze_instancelabs.minigamesapi.ArenaConfigStrings; + +public class DefaultConfig +{ + + JavaPlugin plugin; + + public DefaultConfig(final JavaPlugin plugin, final boolean custom) + { + this.plugin = plugin; + DefaultConfig.init(plugin, custom); + } + + public static void init(final JavaPlugin plugin, final boolean custom) + { + final FileConfiguration config = plugin.getConfig(); + config.options() + .header("The default config. Check http://dev.bukkit.org/bukkit-plugins/instances-minigamesapi/#w-tutorials \n" + + "or https://github.com/instance01/MinigamesAPI/wiki/Default-Config-and-Item-Markup \n" + "for more information if you don't understand a config entry. \n" + + "You can find classes (kits) in classes.yml, all saved arenas in arenas.yml, all messages in messages.yml. \n" + "You can edit/disable achievements in achievements.yml."); + if (!custom) + { + config.addDefault(ArenaConfigStrings.CONFIG_CLASS_SELECTION_ITEM, 399); + config.addDefault(ArenaConfigStrings.CONFIG_EXIT_ITEM, 152); + config.addDefault(ArenaConfigStrings.CONFIG_ACHIEVEMENT_ITEMS, 160); + config.addDefault(ArenaConfigStrings.CONFIG_SPECTATOR_ITEM, 345); + config.addDefault(ArenaConfigStrings.CONFIG_SHOP_SELECTION_ITEM, 388); + config.addDefault(ArenaConfigStrings.CONFIG_CLASSES_GUI_ROWS, 3); + config.addDefault(ArenaConfigStrings.CONFIG_SHOP_GUI_ROWS, 3); + config.addDefault(ArenaConfigStrings.CONFIG_SPECTATOR_AFTER_FALL_OR_DEATH, true); + config.addDefault(ArenaConfigStrings.CONFIG_SPECTATOR_MOVE_Y_LOCK, true); + config.addDefault(ArenaConfigStrings.CONFIG_DEFAULT_MAX_PLAYERS, 4); + config.addDefault(ArenaConfigStrings.CONFIG_DEFAULT_MIN_PLAYERS, 2); + config.addDefault(ArenaConfigStrings.CONFIG_DEFAULT_MAX_GAME_TIME_IN_MINUTES, 30); + config.addDefault(ArenaConfigStrings.CONFIG_LOBBY_COUNTDOWN, 30); + config.addDefault(ArenaConfigStrings.CONFIG_INGAME_COUNTDOWN, 10); + config.addDefault(ArenaConfigStrings.CONFIG_INGAME_COUNTDOWN_ENABLED, true); + config.addDefault(ArenaConfigStrings.CONFIG_SKIP_LOBBY, false); + config.addDefault(ArenaConfigStrings.CONFIG_CLEANINV_WHILE_INGAMECOUNTDOWN, false); + + config.addDefault(ArenaConfigStrings.CONFIG_CLASSES_ENABLED, true); + config.addDefault(ArenaConfigStrings.CONFIG_SHOP_ENABLED, true); + config.addDefault(ArenaConfigStrings.CONFIG_USE_CREADITS_INSTEAD_MONEY_FOR_KITS, false); + config.addDefault(ArenaConfigStrings.CONFIG_RESET_INV_WHEN_LEAVING_SERVER, true); + config.addDefault(ArenaConfigStrings.CONFIG_COLOR_BACKGROUND_WOOL, false); + config.addDefault(ArenaConfigStrings.CONFIG_SHOW_CLASSES_WITHOUT_PERM, true); + + config.addDefault(ArenaConfigStrings.CONFIG_REWARDS_ECONOMY, true); + config.addDefault(ArenaConfigStrings.CONFIG_REWARDS_ECONOMY_REWARD, 10); + config.addDefault(ArenaConfigStrings.CONFIG_REWARDS_ITEM_REWARD, false); + config.addDefault(ArenaConfigStrings.CONFIG_REWARDS_ITEM_REWARD_IDS, "264*1;11*1"); + config.addDefault(ArenaConfigStrings.CONFIG_REWARDS_COMMAND_REWARD, false); + config.addDefault(ArenaConfigStrings.CONFIG_REWARDS_COMMAND, "pex user <player> add SKILLZ.*"); + config.addDefault(ArenaConfigStrings.CONFIG_REWARDS_ECONOMY_FOR_KILLS, true); + config.addDefault(ArenaConfigStrings.CONFIG_REWARDS_ECONOMY_REWARD_FOR_KILLS, 5); + config.addDefault(ArenaConfigStrings.CONFIG_REWARDS_COMMAND_REWARD_FOR_KILLS, false); + config.addDefault(ArenaConfigStrings.CONFIG_REWARDS_COMMAND_FOR_KILLS, "pex user <player> add SKILLZ.*"); + config.addDefault(ArenaConfigStrings.CONFIG_REWARDS_ECONOMY_FOR_PARTICIPATION, false); + config.addDefault(ArenaConfigStrings.CONFIG_REWARDS_ECONOMY_REWARD_FOR_PARTICIPATION, 5); + config.addDefault(ArenaConfigStrings.CONFIG_REWARDS_COMMAND_REWARD_FOR_PARTICIPATION, false); + config.addDefault(ArenaConfigStrings.CONFIG_REWARDS_COMMAND_FOR_PARTICIPATION, "pex user <player> add SKILLZ.*"); + + config.addDefault(ArenaConfigStrings.CONFIG_STATS_POINTS_FOR_KILL, 2); + config.addDefault(ArenaConfigStrings.CONFIG_STATS_POINTS_FOR_WIN, 10); + + config.addDefault(ArenaConfigStrings.CONFIG_ARCADE_ENABLED, true); + config.addDefault(ArenaConfigStrings.CONFIG_ARCADE_MIN_PLAYERS, 1); + config.addDefault(ArenaConfigStrings.CONFIG_ARCADE_MAX_PLAYERS, 16); + config.addDefault(ArenaConfigStrings.CONFIG_ARCADE_ARENA_TO_PREFER_ENABLED, false); + config.addDefault(ArenaConfigStrings.CONFIG_ARCADE_ARENA_TO_PREFER_ARENA, "arena1"); + config.addDefault(ArenaConfigStrings.CONFIG_ARCADE_LOBBY_COUNTDOWN, 20); + config.addDefault(ArenaConfigStrings.CONFIG_ARCADE_SHOW_EACH_LOBBY_COUNTDOWN, false); + config.addDefault(ArenaConfigStrings.CONFIG_ARCADE_INFINITE_ENABLED, false); + config.addDefault(ArenaConfigStrings.CONFIG_ARCADE_INFINITE_SECONDS_TO_NEW_ROUND, 10); + config.addDefault(ArenaConfigStrings.CONFIG_BUNGEE_GAME_ON_JOIN, false); + config.addDefault(ArenaConfigStrings.CONFIG_BUNGEE_TELEPORT_ALL_TO_SERVER_ON_STOP_TP, false); + config.addDefault(ArenaConfigStrings.CONFIG_BUNGEE_TELEPORT_ALL_TO_SERVER_ON_STOP_SERVER, "lobby"); + config.addDefault(ArenaConfigStrings.CONFIG_BUNGEE_WHITELIST_WHILE_GAME_RUNNING, false); + config.addDefault(ArenaConfigStrings.CONFIG_EXECUTE_CMDS_ON_STOP, false); + config.addDefault(ArenaConfigStrings.CONFIG_CMDS, ""); + config.addDefault(ArenaConfigStrings.CONFIG_CMDS_AFTER, "say SERVER STOPPING;stop"); + config.addDefault(ArenaConfigStrings.CONFIG_MAP_ROTATION, false); + config.addDefault(ArenaConfigStrings.CONFIG_BROADCAST_WIN, true); + config.addDefault(ArenaConfigStrings.CONFIG_BUY_CLASSES_FOREVER, true); + config.addDefault(ArenaConfigStrings.CONFIG_DISABLE_COMMANDS_IN_ARENA, true); + config.addDefault(ArenaConfigStrings.CONFIG_COMMAND_WHITELIST, "/msg,/pm,/help"); + config.addDefault(ArenaConfigStrings.CONFIG_LEAVE_COMMAND, "/leave"); + config.addDefault(ArenaConfigStrings.CONFIG_SPAWN_FIREWORKS_FOR_WINNERS, true); + config.addDefault(ArenaConfigStrings.CONFIG_POWERUP_BROADCAST, false); + config.addDefault(ArenaConfigStrings.CONFIG_POWERUP_FIREWORKS, false); + config.addDefault(ArenaConfigStrings.CONFIG_USE_CUSTOM_SCOREBOARD, false); + config.addDefault(ArenaConfigStrings.CONFIG_USE_SPECTATOR_SCOREBOARD, true); + config.addDefault(ArenaConfigStrings.CONFIG_DELAY_ENABLED, false); + config.addDefault(ArenaConfigStrings.CONFIG_DELAY_AMOUNT_SECONDS, 5); + config.addDefault(ArenaConfigStrings.CONFIG_SEND_GAME_STARTED_MSG, false); + config.addDefault(ArenaConfigStrings.CONFIG_AUTO_ADD_DEFAULT_KIT, true); + config.addDefault(ArenaConfigStrings.CONFIG_LAST_MAN_STANDING_WINS, true); + config.addDefault(ArenaConfigStrings.CONFIG_EFFECTS_BLOOD, true); + config.addDefault(ArenaConfigStrings.CONFIG_EFFECTS_DMG_IDENTIFIER_HOLO, true); + config.addDefault(ArenaConfigStrings.CONFIG_EFFECTS_DEAD_IN_FAKE_BED, true); + config.addDefault(ArenaConfigStrings.CONFIG_EFFECTS_1_8_TITLES, true); + config.addDefault(ArenaConfigStrings.CONFIG_EFFECTS_1_8_SPECTATOR_MODE, false); + config.addDefault(ArenaConfigStrings.CONFIG_SOUNDS_LOBBY_COUNTDOWN, "none"); + config.addDefault(ArenaConfigStrings.CONFIG_SOUNDS_INGAME_COUNTDOWN, "SUCCESSFUL_HIT"); + config.addDefault(ArenaConfigStrings.CONFIG_CHAT_PER_ARENA_ONLY, false); + config.addDefault(ArenaConfigStrings.CONFIG_CHAT_SHOW_SCORE_IN_ARENA, false); + config.addDefault(ArenaConfigStrings.CONFIG_COMPASS_TRACKING_ENABLED, true); + config.addDefault(ArenaConfigStrings.CONFIG_ALLOW_CLASSES_SELECTION_OUT_OF_ARENAS, false); + config.addDefault(ArenaConfigStrings.CONFIG_SEND_STATS_ON_STOP, true); + config.addDefault(ArenaConfigStrings.CONFIG_USE_XP_BAR_LEVEL, true); + config.addDefault(ArenaConfigStrings.CONFIG_USE_OLD_RESET_METHOD, false); + config.addDefault(ArenaConfigStrings.CONFIG_CHAT_ENABLED, true); + + config.addDefault(ArenaConfigStrings.CONFIG_EXTRA_LOBBY_ITEM_PREFIX + "item0" + ArenaConfigStrings.CONFIG_EXTRA_LOBBY_ITEM_ENABLED_SUFFIX, false); + config.addDefault(ArenaConfigStrings.CONFIG_EXTRA_LOBBY_ITEM_PREFIX + "item0" + ArenaConfigStrings.CONFIG_EXTRA_LOBBY_ITEM_ITEM_SUFFIX, 9); + config.addDefault(ArenaConfigStrings.CONFIG_EXTRA_LOBBY_ITEM_PREFIX + "item0" + ArenaConfigStrings.CONFIG_EXTRA_LOBBY_ITEM_NAME_SUFFIX, "Custom Name".replace("&", "§")); + config.addDefault(ArenaConfigStrings.CONFIG_EXTRA_LOBBY_ITEM_PREFIX + "item0" + ArenaConfigStrings.CONFIG_EXTRA_LOBBY_ITEM_COMMAND_SUFFIX, "say This is a custom extra lobby item."); + + config.addDefault(ArenaConfigStrings.CONFIG_MYSQL_ENABLED, false); + config.addDefault(ArenaConfigStrings.CONFIG_MYSQL_HOST, "127.0.0.1"); + config.addDefault(ArenaConfigStrings.CONFIG_MYSQL_USER, "root"); + config.addDefault(ArenaConfigStrings.CONFIG_MYSQL_PW, "root"); + config.addDefault(ArenaConfigStrings.CONFIG_MYSQL_DATABASE, "mcminigames"); + + config.addDefault(ArenaConfigStrings.CONFIG_SQLITE_ENABLED, false); + config.addDefault(ArenaConfigStrings.CONFIG_SQLITE_USER, "root"); + config.addDefault(ArenaConfigStrings.CONFIG_SQLITE_PW, "root"); + config.addDefault(ArenaConfigStrings.CONFIG_SQLITE_DATABASE, "mcminigames.sqlite"); + + config.addDefault(ArenaConfigStrings.RESET_GAMEMMODE, true); + config.addDefault(ArenaConfigStrings.RESET_INVENTORY, true); + config.addDefault(ArenaConfigStrings.RESET_XP, true); + } + config.options().copyDefaults(true); + plugin.saveConfig(); + + try + { + DefaultConfig.convert(plugin); + } + catch (final Exception e) + { + // silently ignore + } + } + + public static void convert(final JavaPlugin plugin) throws IOException + { + final FileConfiguration config = plugin.getConfig(); + if (!config.isSet("config.version")) + { + // TODO new config + config.set(ArenaConfigStrings.CONFIG_CLASS_SELECTION_ITEM, config.get("config.classes_selection_item")); + config.set(ArenaConfigStrings.CONFIG_EXIT_ITEM, config.get("config.exit_item")); + config.set(ArenaConfigStrings.CONFIG_ACHIEVEMENT_ITEMS, config.get("config.achievement_item")); + config.set(ArenaConfigStrings.CONFIG_SPECTATOR_ITEM, config.get("config.exit_item")); + config.set(ArenaConfigStrings.CONFIG_SHOP_SELECTION_ITEM, config.get("config.shop_selection_item")); + config.set(ArenaConfigStrings.CONFIG_CLASSES_GUI_ROWS, config.get("config.classes_gui_rows")); + config.set(ArenaConfigStrings.CONFIG_SHOP_GUI_ROWS, config.get("config.shop_gui_rows")); + config.set(ArenaConfigStrings.CONFIG_SPECTATOR_AFTER_FALL_OR_DEATH, config.get("config.spectator_after_fall_or_death")); + config.set(ArenaConfigStrings.CONFIG_SPECTATOR_MOVE_Y_LOCK, config.get("config.spectator_move_y_lock")); + config.set(ArenaConfigStrings.CONFIG_DEFAULT_MAX_PLAYERS, config.get("config.default_max_players")); + config.set(ArenaConfigStrings.CONFIG_DEFAULT_MIN_PLAYERS, config.get("config.default_min_players")); + config.set(ArenaConfigStrings.CONFIG_DEFAULT_MAX_GAME_TIME_IN_MINUTES, config.get("config.default_max_game_time_in_minutes")); + config.set(ArenaConfigStrings.CONFIG_LOBBY_COUNTDOWN, config.get("config.lobby_countdown")); + config.set(ArenaConfigStrings.CONFIG_INGAME_COUNTDOWN, config.get("config.ingame_countdown")); + config.set(ArenaConfigStrings.CONFIG_INGAME_COUNTDOWN_ENABLED, config.get("config.ingame_countdown_enabled")); + config.set(ArenaConfigStrings.CONFIG_SKIP_LOBBY, config.get("config.skip_lobby")); + config.set(ArenaConfigStrings.CONFIG_CLEANINV_WHILE_INGAMECOUNTDOWN, config.get("config.clearinv_while_ingamecountdown")); + + config.set("config.classes_selection_item", null); + config.set("config.exit_item", null); + config.set("config.achievement_item", null); + config.set("config.shop_selection_item", null); + config.set("config.classes_gui_rows", null); + config.set("config.shop_gui_rows", null); + config.set("config.clearinv_while_ingamecountdown", null); + config.set("config.spectator_after_fall_or_death", null); + config.set("config.spectator_move_y_lock", null); + config.set("config.default_max_players", null); + config.set("config.default_min_players", null); + config.set("config.default_max_game_time_in_minutes", null); + config.set("config.lobby_countdown", null); + config.set("config.ingame_countdown", null); + config.set("config.ingame_countdown_enabled", null); + config.set("config.skip_lobby", null); + + config.set("config.version", 1); + plugin.saveConfig(); + } + } + } diff --git a/API/src/main/java/com/comze_instancelabs/minigamesapi/config/GunsConfig.java b/API/src/main/java/com/comze_instancelabs/minigamesapi/config/GunsConfig.java index 8d6f5923..4c97530f 100644 --- a/API/src/main/java/com/comze_instancelabs/minigamesapi/config/GunsConfig.java +++ b/API/src/main/java/com/comze_instancelabs/minigamesapi/config/GunsConfig.java @@ -1,98 +1,128 @@ -package com.comze_instancelabs.minigamesapi.config; +/* + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.configuration.file.YamlConfiguration; -import org.bukkit.plugin.java.JavaPlugin; + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ +package com.comze_instancelabs.minigamesapi.config; import java.io.File; import java.io.IOException; import java.io.InputStream; +import java.io.InputStreamReader; -public class GunsConfig { - - private FileConfiguration arenaConfig = null; - private File arenaFile = null; - private JavaPlugin plugin = null; - - // TODO add bullet option - - public GunsConfig(JavaPlugin plugin, boolean custom) { - this.plugin = plugin; - if (!custom) { - this.getConfig().options().header("Be aware that this config is barely used in any minigame. \nUsed for saving gun classes. Default:"); - this.getConfig().addDefault("config.guns.pistol.name", "Pistol"); - this.getConfig().addDefault("config.guns.pistol.items", "256#DAMAGE_ALL:1#KNOCKBACK*1"); - this.getConfig().addDefault("config.guns.pistol.icon", "256#DAMAGE_ALL:1#KNOCKBACK*1"); - this.getConfig().addDefault("config.guns.pistol.lore", "The Pistol."); - this.getConfig().addDefault("config.guns.pistol.speed", 1D); - this.getConfig().addDefault("config.guns.pistol.durability", 50); - this.getConfig().addDefault("config.guns.pistol.shoot_amount", 1); - this.getConfig().addDefault("config.guns.pistol.knockback_multiplier", 1.1D); - this.getConfig().addDefault("config.guns.pistol.permission_node", "minigames.guns.pistol"); - - this.getConfig().addDefault("config.guns.sniper.name", "Sniper"); - this.getConfig().addDefault("config.guns.sniper.items", "292#DAMAGE_ALL:1#KNOCKBACK*1"); - this.getConfig().addDefault("config.guns.sniper.icon", "292#DAMAGE_ALL:1#KNOCKBACK*1"); - this.getConfig().addDefault("config.guns.sniper.lore", "The Sniper."); - this.getConfig().addDefault("config.guns.sniper.speed", 0.5D); - this.getConfig().addDefault("config.guns.sniper.durability", 10); - this.getConfig().addDefault("config.guns.sniper.shoot_amount", 1); - this.getConfig().addDefault("config.guns.sniper.knockback_multiplier", 3D); - this.getConfig().addDefault("config.guns.sniper.permission_node", "minigames.guns.sniper"); - - this.getConfig().addDefault("config.guns.grenade.name", "Grenade Launcher"); - this.getConfig().addDefault("config.guns.grenade.items", "257#DAMAGE_ALL:1#KNOCKBACK*1"); - this.getConfig().addDefault("config.guns.grenade.icon", "257#DAMAGE_ALL:1#KNOCKBACK*1"); - this.getConfig().addDefault("config.guns.grenade.lore", "The Grenade Launcher."); - this.getConfig().addDefault("config.guns.grenade.speed", 0.1D); - this.getConfig().addDefault("config.guns.grenade.durability", 10); - this.getConfig().addDefault("config.guns.grenade.shoot_amount", 1); - this.getConfig().addDefault("config.guns.grenade.knockback_multiplier", 2.5D); - this.getConfig().addDefault("config.guns.grenade.permission_node", "minigames.guns.grenade"); - - this.getConfig().addDefault("config.guns.freeze.name", "Freeze Gun"); - this.getConfig().addDefault("config.guns.freeze.items", "258#DAMAGE_ALL:1#KNOCKBACK*1"); - this.getConfig().addDefault("config.guns.freeze.icon", "258#DAMAGE_ALL:1#KNOCKBACK*1"); - this.getConfig().addDefault("config.guns.freeze.lore", "The Freeze Gun."); - this.getConfig().addDefault("config.guns.freeze.speed", 0.8D); - this.getConfig().addDefault("config.guns.freeze.durability", 5); - this.getConfig().addDefault("config.guns.freeze.shoot_amount", 1); - this.getConfig().addDefault("config.guns.freeze.knockback_multiplier", 0.5D); - this.getConfig().addDefault("config.guns.freeze.permission_node", "minigames.guns.freeze"); - } - this.getConfig().options().copyDefaults(true); - this.saveConfig(); - } - - public FileConfiguration getConfig() { - if (arenaConfig == null) { - reloadConfig(); - } - return arenaConfig; - } - - public void saveConfig() { - if (arenaConfig == null || arenaFile == null) { - return; - } - try { - getConfig().save(arenaFile); - } catch (IOException ex) { - - } - } - - public void reloadConfig() { - if (arenaFile == null) { - arenaFile = new File(plugin.getDataFolder(), "guns.yml"); - } - arenaConfig = YamlConfiguration.loadConfiguration(arenaFile); +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.plugin.java.JavaPlugin; - InputStream defConfigStream = plugin.getResource("guns.yml"); - if (defConfigStream != null) { - YamlConfiguration defConfig = YamlConfiguration.loadConfiguration(defConfigStream); - arenaConfig.setDefaults(defConfig); - } - } +import com.comze_instancelabs.minigamesapi.MinigamesAPI; +public class GunsConfig +{ + + private FileConfiguration arenaConfig = null; + private File arenaFile = null; + private JavaPlugin plugin = null; + + // TODO add bullet option + + public GunsConfig(final JavaPlugin plugin, final boolean custom) + { + this.plugin = plugin; + if (!custom) + { + this.getConfig().options().header("Be aware that this config is barely used in any minigame. \nUsed for saving gun classes. Default:"); + this.getConfig().addDefault("config.guns.pistol.name", "Pistol"); + this.getConfig().addDefault("config.guns.pistol.items", "256#DAMAGE_ALL:1#KNOCKBACK*1"); + this.getConfig().addDefault("config.guns.pistol.icon", "256#DAMAGE_ALL:1#KNOCKBACK*1"); + this.getConfig().addDefault("config.guns.pistol.lore", "The Pistol."); + this.getConfig().addDefault("config.guns.pistol.speed", 1D); + this.getConfig().addDefault("config.guns.pistol.durability", 50); + this.getConfig().addDefault("config.guns.pistol.shoot_amount", 1); + this.getConfig().addDefault("config.guns.pistol.knockback_multiplier", 1.1D); + this.getConfig().addDefault("config.guns.pistol.permission_node", MinigamesAPI.getAPI().getPermissionGunPrefix() + ".pistol"); + + this.getConfig().addDefault("config.guns.sniper.name", "Sniper"); + this.getConfig().addDefault("config.guns.sniper.items", "292#DAMAGE_ALL:1#KNOCKBACK*1"); + this.getConfig().addDefault("config.guns.sniper.icon", "292#DAMAGE_ALL:1#KNOCKBACK*1"); + this.getConfig().addDefault("config.guns.sniper.lore", "The Sniper."); + this.getConfig().addDefault("config.guns.sniper.speed", 0.5D); + this.getConfig().addDefault("config.guns.sniper.durability", 10); + this.getConfig().addDefault("config.guns.sniper.shoot_amount", 1); + this.getConfig().addDefault("config.guns.sniper.knockback_multiplier", 3D); + this.getConfig().addDefault("config.guns.sniper.permission_node", MinigamesAPI.getAPI().getPermissionGunPrefix() + ".sniper"); + + this.getConfig().addDefault("config.guns.grenade.name", "Grenade Launcher"); + this.getConfig().addDefault("config.guns.grenade.items", "257#DAMAGE_ALL:1#KNOCKBACK*1"); + this.getConfig().addDefault("config.guns.grenade.icon", "257#DAMAGE_ALL:1#KNOCKBACK*1"); + this.getConfig().addDefault("config.guns.grenade.lore", "The Grenade Launcher."); + this.getConfig().addDefault("config.guns.grenade.speed", 0.1D); + this.getConfig().addDefault("config.guns.grenade.durability", 10); + this.getConfig().addDefault("config.guns.grenade.shoot_amount", 1); + this.getConfig().addDefault("config.guns.grenade.knockback_multiplier", 2.5D); + this.getConfig().addDefault("config.guns.grenade.permission_node", MinigamesAPI.getAPI().getPermissionGunPrefix() + ".grenade"); + + this.getConfig().addDefault("config.guns.freeze.name", "Freeze Gun"); + this.getConfig().addDefault("config.guns.freeze.items", "258#DAMAGE_ALL:1#KNOCKBACK*1"); + this.getConfig().addDefault("config.guns.freeze.icon", "258#DAMAGE_ALL:1#KNOCKBACK*1"); + this.getConfig().addDefault("config.guns.freeze.lore", "The Freeze Gun."); + this.getConfig().addDefault("config.guns.freeze.speed", 0.8D); + this.getConfig().addDefault("config.guns.freeze.durability", 5); + this.getConfig().addDefault("config.guns.freeze.shoot_amount", 1); + this.getConfig().addDefault("config.guns.freeze.knockback_multiplier", 0.5D); + this.getConfig().addDefault("config.guns.freeze.permission_node", MinigamesAPI.getAPI().getPermissionGunPrefix() + ".freeze"); + } + this.getConfig().options().copyDefaults(true); + this.saveConfig(); + } + + public FileConfiguration getConfig() + { + if (this.arenaConfig == null) + { + this.reloadConfig(); + } + return this.arenaConfig; + } + + public void saveConfig() + { + if (this.arenaConfig == null || this.arenaFile == null) + { + return; + } + try + { + this.getConfig().save(this.arenaFile); + } + catch (final IOException ex) + { + // silently ignore + } + } + + public void reloadConfig() + { + if (this.arenaFile == null) + { + this.arenaFile = new File(this.plugin.getDataFolder(), "guns.yml"); + } + this.arenaConfig = YamlConfiguration.loadConfiguration(this.arenaFile); + + final InputStream defConfigStream = this.plugin.getResource("guns.yml"); + if (defConfigStream != null) + { + final YamlConfiguration defConfig = YamlConfiguration.loadConfiguration(new InputStreamReader(defConfigStream)); + this.arenaConfig.setDefaults(defConfig); + } + } + } diff --git a/API/src/main/java/com/comze_instancelabs/minigamesapi/config/HologramsConfig.java b/API/src/main/java/com/comze_instancelabs/minigamesapi/config/HologramsConfig.java index 78d6fef2..cc26cedf 100644 --- a/API/src/main/java/com/comze_instancelabs/minigamesapi/config/HologramsConfig.java +++ b/API/src/main/java/com/comze_instancelabs/minigamesapi/config/HologramsConfig.java @@ -1,57 +1,85 @@ -package com.comze_instancelabs.minigamesapi.config; +/* + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.configuration.file.YamlConfiguration; -import org.bukkit.plugin.java.JavaPlugin; + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ +package com.comze_instancelabs.minigamesapi.config; import java.io.File; import java.io.IOException; import java.io.InputStream; +import java.io.InputStreamReader; -public class HologramsConfig { - - private FileConfiguration holoConfig = null; - private File holoFile = null; - private JavaPlugin plugin = null; - - public HologramsConfig(JavaPlugin plugin, boolean custom) { - this.plugin = plugin; - if (!custom) { - this.getConfig().options().header("Used for saving stats holograms."); - } - this.getConfig().options().copyDefaults(true); - this.saveConfig(); - } - - public FileConfiguration getConfig() { - if (holoConfig == null) { - reloadConfig(); - } - return holoConfig; - } - - public void saveConfig() { - if (holoConfig == null || holoFile == null) { - return; - } - try { - getConfig().save(holoFile); - } catch (IOException ex) { - - } - } - - public void reloadConfig() { - if (holoFile == null) { - holoFile = new File(plugin.getDataFolder(), "holograms.yml"); - } - holoConfig = YamlConfiguration.loadConfiguration(holoFile); - - InputStream defConfigStream = plugin.getResource("holograms.yml"); - if (defConfigStream != null) { - YamlConfiguration defConfig = YamlConfiguration.loadConfiguration(defConfigStream); - holoConfig.setDefaults(defConfig); - } - } +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.plugin.java.JavaPlugin; +public class HologramsConfig +{ + + private FileConfiguration holoConfig = null; + private File holoFile = null; + private JavaPlugin plugin = null; + + public HologramsConfig(final JavaPlugin plugin, final boolean custom) + { + this.plugin = plugin; + if (!custom) + { + this.getConfig().options().header("Used for saving stats holograms."); + } + this.getConfig().options().copyDefaults(true); + this.saveConfig(); + } + + public FileConfiguration getConfig() + { + if (this.holoConfig == null) + { + this.reloadConfig(); + } + return this.holoConfig; + } + + public void saveConfig() + { + if (this.holoConfig == null || this.holoFile == null) + { + return; + } + try + { + this.getConfig().save(this.holoFile); + } + catch (final IOException ex) + { + // silently ignore + } + } + + public void reloadConfig() + { + if (this.holoFile == null) + { + this.holoFile = new File(this.plugin.getDataFolder(), "holograms.yml"); + } + this.holoConfig = YamlConfiguration.loadConfiguration(this.holoFile); + + final InputStream defConfigStream = this.plugin.getResource("holograms.yml"); + if (defConfigStream != null) + { + final YamlConfiguration defConfig = YamlConfiguration.loadConfiguration(new InputStreamReader(defConfigStream)); + this.holoConfig.setDefaults(defConfig); + } + } + } diff --git a/API/src/main/java/com/comze_instancelabs/minigamesapi/config/MessagesConfig.java b/API/src/main/java/com/comze_instancelabs/minigamesapi/config/MessagesConfig.java index 4000d7a5..71b08abe 100644 --- a/API/src/main/java/com/comze_instancelabs/minigamesapi/config/MessagesConfig.java +++ b/API/src/main/java/com/comze_instancelabs/minigamesapi/config/MessagesConfig.java @@ -1,10 +1,25 @@ +/* + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ package com.comze_instancelabs.minigamesapi.config; import java.io.File; import java.io.IOException; import java.io.InputStream; +import java.io.InputStreamReader; import java.util.Arrays; -import java.util.HashMap; +import java.util.Map; import org.bukkit.ChatColor; import org.bukkit.configuration.file.FileConfiguration; @@ -13,329 +28,347 @@ import com.comze_instancelabs.minigamesapi.ArenaState; -public class MessagesConfig { - - private FileConfiguration messagesConfig = null; - private File messagesFile = null; - private JavaPlugin plugin = null; - - public MessagesConfig(JavaPlugin plugin) { - this.plugin = plugin; - Arrays.fill(squares_mid, (char) 0x25A0); - Arrays.fill(squares_full, (char) 0x2588); - Arrays.fill(squares_medium, (char) 0x2592); - Arrays.fill(squares_light, (char) 0x2591); - for (int i = 0; i < 10; i++) { - squares += Character.toString((char) 0x25A0); - } - this.init(); - } - - public static String squares = Character.toString((char) 0x25A0); - - public static char[] squares_mid = new char[10]; - public static char[] squares_full = new char[10]; - public static char[] squares_medium = new char[10]; - public static char[] squares_light = new char[10]; - - public void init() { - // all signs - this.getConfig().options().header("Contains all messages for easy translation. You can remove a mesage by setting it to nothing, like so: ''"); - HashMap<String, String> namecol = ArenaState.getAllStateNameColors(); - for (String state : namecol.keySet()) { - String color = namecol.get(state); - this.getConfig().addDefault("signs." + state.toLowerCase() + ".0", color + "[]"); - this.getConfig().addDefault("signs." + state.toLowerCase() + ".1", color + "<arena>"); - this.getConfig().addDefault("signs." + state.toLowerCase() + ".2", color + "<count>/<maxcount>"); - this.getConfig().addDefault("signs." + state.toLowerCase() + ".3", color + "[]"); - } - - // Arcade sign (I think that one is unused) - this.getConfig().addDefault("signs.arcade.0", "[]"); - this.getConfig().addDefault("signs.arcade.1", "&cArcade"); - this.getConfig().addDefault("signs.arcade.2", "<count>/<maxcount>"); - this.getConfig().addDefault("signs.arcade.3", "[]"); - - // Leave sign - this.getConfig().addDefault("signs.leave.0", ""); - this.getConfig().addDefault("signs.leave.1", "&4Leave"); - this.getConfig().addDefault("signs.leave.2", ""); - this.getConfig().addDefault("signs.leave.3", ""); - - // Random arena sign - this.getConfig().addDefault("signs.random.0", "&a[]"); - this.getConfig().addDefault("signs.random.1", "&2Random"); - this.getConfig().addDefault("signs.random.2", ""); - this.getConfig().addDefault("signs.random.3", "&a[]"); - - this.getConfig().addDefault("messages.no_perm", no_perm); - this.getConfig().addDefault("messages.successfully_reloaded", successfully_reloaded); - this.getConfig().addDefault("messages.successfully_set", successfully_set); - this.getConfig().addDefault("messages.successfully_saved_arena", successfully_saved_arena); - this.getConfig().addDefault("messages.arena_invalid", arena_invalid); - this.getConfig().addDefault("messages.failed_saving_arena", failed_saving_arena); - this.getConfig().addDefault("messages.broadcast_players_left", broadcast_players_left); - this.getConfig().addDefault("messages.broadcast_player_joined", broadcast_player_joined); - this.getConfig().addDefault("messages.player_died", player_died); - this.getConfig().addDefault("messages.arena_action", arena_action); - this.getConfig().addDefault("messages.you_already_are_in_arena", you_already_are_in_arena); - this.getConfig().addDefault("messages.you_joined_arena", you_joined_arena); - this.getConfig().addDefault("messages.not_in_arena", not_in_arena); - this.getConfig().addDefault("messages.teleporting_to_arena_in", teleporting_to_arena_in); - this.getConfig().addDefault("messages.starting_in", starting_in); - this.getConfig().addDefault("messages.failed_removing_arena", failed_removing_arena); - this.getConfig().addDefault("messages.successfully_removed", successfully_removed); - this.getConfig().addDefault("messages.failed_removing_component", failed_removing_component); - this.getConfig().addDefault("messages.joined_arena", joined_arena); - this.getConfig().addDefault("messages.you_won", you_won); - this.getConfig().addDefault("messages.you_lost", you_lost); - this.getConfig().addDefault("messages.you_got_a_kill", you_got_a_kill); - this.getConfig().addDefault("messages.player_was_killed_by", player_was_killed_by); - this.getConfig().addDefault("messages.arena_not_initialized", arena_not_initialized); - this.getConfig().addDefault("messages.guns.attributelevel_increased", attributelevel_increased); - this.getConfig().addDefault("messages.guns.not_enough_credits", not_enough_credits); - this.getConfig().addDefault("messages.guns.too_many_main_guns", too_many_main_guns); - this.getConfig().addDefault("messages.guns.successfully_set_main_gun", successfully_set_main_gun); - this.getConfig().addDefault("messages.guns.all_guns", all_guns); - this.getConfig().addDefault("messages.arcade_next_minigame", arcade_next_minigame); - this.getConfig().addDefault("messages.arcade_joined_waiting", arcade_joined_waiting); - this.getConfig().addDefault("messages.arcade_joined_spectator", arcade_joined_spectator); - this.getConfig().addDefault("messages.arcade_new_round", arcade_new_round); - this.getConfig().addDefault("messages.arena_disabled", arena_disabled); - this.getConfig().addDefault("messages.you_can_leave_with", you_can_leave_with); - this.getConfig().addDefault("messages.no_perm_to_join_arena", no_perm_to_join_arena); - this.getConfig().addDefault("messages.set_kit", set_kit); - this.getConfig().addDefault("messages.classes_item", classes_item); - this.getConfig().addDefault("messages.achievement_item", achievement_item); - this.getConfig().addDefault("messages.shop_item", shop_item); - this.getConfig().addDefault("messages.spectator_item", spectator_item); - this.getConfig().addDefault("messages.server_broadcast_winner", server_broadcast_winner); - this.getConfig().addDefault("messages.exit_item", exit_item); - this.getConfig().addDefault("messages.successfully_bought_kit", successfully_bought_kit); - this.getConfig().addDefault("messages.scoreboard.title", scoreboard_title); - this.getConfig().addDefault("messages.scoreboard.lobby_title", scoreboard_lobby_title); - this.getConfig().addDefault("messages.you_got_kicked_because_vip_joined", you_got_kicked_because_vip_joined); - this.getConfig().addDefault("messages.powerup_spawned", powerup_spawned); - if (!this.getConfig().isSet("config.generatedv182")) { - this.getConfig().addDefault("messages.custom_scoreboard.line0", "Players:<playercount>"); - this.getConfig().addDefault("messages.custom_scoreboard.line1", "Spectators:<lostplayercount>"); - this.getConfig().addDefault("messages.custom_scoreboard.line2", "Alive:<playeralivecount>"); - this.getConfig().addDefault("messages.custom_scoreboard.line3", "Your Credits:<points>"); - this.getConfig().addDefault("messages.custom_scoreboard.line4", "Your Wins:<wins>"); - this.getConfig().addDefault("messages.custom_lobby_scoreboard.line0", "Players:<playercount>"); - this.getConfig().addDefault("messages.custom_lobby_scoreboard.line1", "Max Players:<maxplayercount>"); - this.getConfig().addDefault("messages.custom_lobby_scoreboard.line2", "Your Credits:<points>"); - this.getConfig().addDefault("messages.custom_lobby_scoreboard.line3", "Your Wins:<wins>"); - } - this.getConfig().addDefault("messages.you_got_the_achievement", you_got_the_achievement); - this.getConfig().addDefault("messages.game_started", game_started); - this.getConfig().addDefault("messages.author_of_the_map", author_of_the_map); - this.getConfig().addDefault("messages.description_of_the_map", description_of_the_map); - this.getConfig().addDefault("messages.not_enough_money", not_enough_money); - this.getConfig().addDefault("messages.possible_kits", possible_kits); - this.getConfig().addDefault("messages.possible_shopitems", possible_shopitems); - this.getConfig().addDefault("messages.cancelled_starting", cancelled_starting); - this.getConfig().addDefault("messages.minigame_description", minigame_description); - this.getConfig().addDefault("messages.successfully_bought_shopitem", successfully_bought_shopitem); - this.getConfig().addDefault("messages.already_bought_shopitem", already_bought_shopitem); - this.getConfig().addDefault("messages.you_received_rewards", you_received_rewards); - this.getConfig().addDefault("messages.you_received_rewards_2", you_received_rewards_2); - this.getConfig().addDefault("messages.you_received_rewards_3", you_received_rewards_3); - this.getConfig().addDefault("messages.already_in_arena", already_in_arena); - this.getConfig().addDefault("messages.stop_cause_maximum_game_time", stop_cause_maximum_game_time); - this.getConfig().addDefault("messages.compass.no_player_found", compass_no_player_found); - this.getConfig().addDefault("messages.compass.found_player", compass_player_found); - this.getConfig().addDefault("messages.you_got_a_participation_reward", you_got_a_participation_reward); - this.getConfig().addDefault("messages.kit_warning", kit_warning); - if (!this.getConfig().isSet("config.generatedv1102")) { - this.getConfig().addDefault("messages.stats.line0", "&7----- &a&lStats &7-----; "); - this.getConfig().addDefault("messages.stats.line1", "&7Wins: &a<wins>"); - this.getConfig().addDefault("messages.stats.line2", "&7Loses: &c<loses>"); - this.getConfig().addDefault("messages.stats.line3", "&7Alltime Kills: &a<alltime_kills>"); - this.getConfig().addDefault("messages.stats.line4", "&7Alltime Deaths: &c<alltime_deaths>"); - this.getConfig().addDefault("messages.stats.line5", "&7KDR: &e<kdr>"); - this.getConfig().addDefault("messages.stats.line6", "&7Points: &e<points>"); - this.getConfig().addDefault("messages.stats.line7", " ;&7-----------------"); - } - - // save - this.getConfig().options().copyDefaults(true); - this.saveConfig(); - - // load - this.no_perm = ChatColor.translateAlternateColorCodes('&', getConfig().getString("messages.no_perm")); - this.successfully_reloaded = ChatColor.translateAlternateColorCodes('&', getConfig().getString("messages.successfully_reloaded")); - this.successfully_set = ChatColor.translateAlternateColorCodes('&', getConfig().getString("messages.successfully_set")); - this.successfully_saved_arena = ChatColor.translateAlternateColorCodes('&', getConfig().getString("messages.successfully_saved_arena")); - this.failed_saving_arena = ChatColor.translateAlternateColorCodes('&', getConfig().getString("messages.failed_saving_arena")); - this.arena_invalid = ChatColor.translateAlternateColorCodes('&', getConfig().getString("messages.arena_invalid")); - this.player_died = ChatColor.translateAlternateColorCodes('&', getConfig().getString("messages.player_died")); - this.broadcast_players_left = ChatColor.translateAlternateColorCodes('&', getConfig().getString("messages.broadcast_players_left")); - this.broadcast_player_joined = ChatColor.translateAlternateColorCodes('&', getConfig().getString("messages.broadcast_player_joined")); - this.arena_action = ChatColor.translateAlternateColorCodes('&', getConfig().getString("messages.arena_action")); - this.you_already_are_in_arena = ChatColor.translateAlternateColorCodes('&', getConfig().getString("messages.you_already_are_in_arena")); - this.you_joined_arena = ChatColor.translateAlternateColorCodes('&', getConfig().getString("messages.you_joined_arena")); - this.not_in_arena = ChatColor.translateAlternateColorCodes('&', getConfig().getString("messages.not_in_arena")); - this.teleporting_to_arena_in = ChatColor.translateAlternateColorCodes('&', getConfig().getString("messages.teleporting_to_arena_in")); - this.starting_in = ChatColor.translateAlternateColorCodes('&', getConfig().getString("messages.starting_in")); - this.failed_removing_arena = ChatColor.translateAlternateColorCodes('&', getConfig().getString("messages.failed_removing_arena")); - this.successfully_removed = ChatColor.translateAlternateColorCodes('&', getConfig().getString("messages.successfully_removed")); - this.failed_removing_component = ChatColor.translateAlternateColorCodes('&', getConfig().getString("messages.failed_removing_component")); - this.joined_arena = ChatColor.translateAlternateColorCodes('&', getConfig().getString("messages.joined_arena")); - this.you_won = ChatColor.translateAlternateColorCodes('&', getConfig().getString("messages.you_won")); - this.you_lost = ChatColor.translateAlternateColorCodes('&', getConfig().getString("messages.you_lost")); - this.you_got_a_kill = ChatColor.translateAlternateColorCodes('&', getConfig().getString("messages.you_got_a_kill")); - this.player_was_killed_by = ChatColor.translateAlternateColorCodes('&', getConfig().getString("messages.player_was_killed_by")); - this.arena_not_initialized = ChatColor.translateAlternateColorCodes('&', getConfig().getString("messages.arena_not_initialized")); - this.arcade_next_minigame = ChatColor.translateAlternateColorCodes('&', getConfig().getString("messages.arcade_next_minigame")); - this.arcade_new_round = ChatColor.translateAlternateColorCodes('&', getConfig().getString("messages.arcade_new_round")); - this.arena_disabled = ChatColor.translateAlternateColorCodes('&', getConfig().getString("messages.arena_disabled")); - this.you_can_leave_with = ChatColor.translateAlternateColorCodes('&', getConfig().getString("messages.you_can_leave_with")); - this.arcade_joined_waiting = ChatColor.translateAlternateColorCodes('&', getConfig().getString("messages.arcade_joined_waiting")); - this.arcade_joined_spectator = ChatColor.translateAlternateColorCodes('&', getConfig().getString("messages.arcade_joined_spectator")); - this.no_perm_to_join_arena = ChatColor.translateAlternateColorCodes('&', getConfig().getString("messages.no_perm_to_join_arena")); - this.set_kit = ChatColor.translateAlternateColorCodes('&', getConfig().getString("messages.set_kit")); - this.classes_item = ChatColor.translateAlternateColorCodes('&', getConfig().getString("messages.classes_item")); - this.achievement_item = ChatColor.translateAlternateColorCodes('&', getConfig().getString("messages.achievement_item")); - this.shop_item = ChatColor.translateAlternateColorCodes('&', getConfig().getString("messages.shop_item")); - this.spectator_item = ChatColor.translateAlternateColorCodes('&', getConfig().getString("messages.spectator_item")); - this.server_broadcast_winner = ChatColor.translateAlternateColorCodes('&', getConfig().getString("messages.server_broadcast_winner")); - this.exit_item = ChatColor.translateAlternateColorCodes('&', getConfig().getString("messages.exit_item")); - this.successfully_bought_kit = ChatColor.translateAlternateColorCodes('&', getConfig().getString("messages.successfully_bought_kit")); - this.scoreboard_title = ChatColor.translateAlternateColorCodes('&', getConfig().getString("messages.scoreboard.title")); - this.scoreboard_lobby_title = ChatColor.translateAlternateColorCodes('&', getConfig().getString("messages.scoreboard.lobby_title")); - this.you_got_kicked_because_vip_joined = ChatColor.translateAlternateColorCodes('&', getConfig().getString("messages.you_got_kicked_because_vip_joined")); - this.powerup_spawned = ChatColor.translateAlternateColorCodes('&', getConfig().getString("messages.powerup_spawned")); - this.you_got_the_achievement = ChatColor.translateAlternateColorCodes('&', getConfig().getString("messages.you_got_the_achievement")); - this.game_started = ChatColor.translateAlternateColorCodes('&', getConfig().getString("messages.game_started")); - this.author_of_the_map = ChatColor.translateAlternateColorCodes('&', getConfig().getString("messages.author_of_the_map")); - this.description_of_the_map = ChatColor.translateAlternateColorCodes('&', getConfig().getString("messages.description_of_the_map")); - this.not_enough_money = ChatColor.translateAlternateColorCodes('&', getConfig().getString("messages.not_enough_money")); - this.possible_kits = ChatColor.translateAlternateColorCodes('&', getConfig().getString("messages.possible_kits")); - this.possible_shopitems = ChatColor.translateAlternateColorCodes('&', getConfig().getString("messages.possible_shopitems")); - this.cancelled_starting = ChatColor.translateAlternateColorCodes('&', getConfig().getString("messages.cancelled_starting")); - this.minigame_description = ChatColor.translateAlternateColorCodes('&', getConfig().getString("messages.minigame_description")); - this.successfully_bought_shopitem = ChatColor.translateAlternateColorCodes('&', getConfig().getString("messages.successfully_bought_shopitem")); - this.already_bought_shopitem = ChatColor.translateAlternateColorCodes('&', getConfig().getString("messages.already_bought_shopitem")); - this.you_received_rewards = ChatColor.translateAlternateColorCodes('&', getConfig().getString("messages.you_received_rewards")); - this.you_received_rewards_2 = ChatColor.translateAlternateColorCodes('&', getConfig().getString("messages.you_received_rewards_2")); - this.you_received_rewards_3 = ChatColor.translateAlternateColorCodes('&', getConfig().getString("messages.you_received_rewards_3")); - this.already_in_arena = ChatColor.translateAlternateColorCodes('&', getConfig().getString("messages.already_in_arena")); - this.stop_cause_maximum_game_time = ChatColor.translateAlternateColorCodes('&', getConfig().getString("messages.stop_cause_maximum_game_time")); - this.compass_no_player_found = ChatColor.translateAlternateColorCodes('&', getConfig().getString("messages.compass.no_player_found")); - this.compass_player_found = ChatColor.translateAlternateColorCodes('&', getConfig().getString("messages.compass.found_player")); - this.you_got_a_participation_reward = ChatColor.translateAlternateColorCodes('&', getConfig().getString("messages.you_got_a_participation_reward")); - this.kit_warning = ChatColor.translateAlternateColorCodes('&', getConfig().getString("messages.kit_warning")); - - this.attributelevel_increased = ChatColor.translateAlternateColorCodes('&', getConfig().getString("messages.guns.attributelevel_increased")); - this.not_enough_credits = ChatColor.translateAlternateColorCodes('&', getConfig().getString("messages.guns.not_enough_credits")); - this.too_many_main_guns = ChatColor.translateAlternateColorCodes('&', getConfig().getString("messages.guns.too_many_main_guns")); - this.successfully_set_main_gun = ChatColor.translateAlternateColorCodes('&', getConfig().getString("messages.guns.successfully_set_main_gun")); - this.all_guns = ChatColor.translateAlternateColorCodes('&', getConfig().getString("messages.guns.all_guns")); - - this.getConfig().set("config.generatedv182", true); - this.getConfig().set("config.generatedv1102", true); - this.saveConfig(); - } - - public String no_perm = "&cYou don't have permission."; - public String successfully_reloaded = "&aSuccessfully reloaded all configs."; - public String successfully_set = "&aSuccessfully set &3<component>&a."; - public String successfully_saved_arena = "&aSuccessfully saved &3<arena>&a."; - public String failed_saving_arena = "&cFailed to save &3<arena>&c."; - public String failed_removing_arena = "&cFailed to remove &3<arena>&c."; - public String arena_invalid = "&3<arena> &cappears to be invalid."; - public String broadcast_players_left = "&eThere are &4<count> &eplayers left!"; - public String broadcast_player_joined = "&2<player> &ajoined the arena! (<count>/<maxcount>)"; - public String player_died = "&c<player> died."; - public String arena_action = "&aYou <action> arena &3<arena>&a!"; - public String you_joined_arena = "&aYou joined arena &3<arena>&a!"; - public String you_already_are_in_arena = "&aYou already seem to be in arena &3<arena>&a!"; - public String arena_not_initialized = "&cThe arena appears to be not initialized, did you save the arena?"; - public String not_in_arena = "&cYou don't seem to be in an arena right now."; - public String teleporting_to_arena_in = "&7Teleporting to arena in <count>."; - public String starting_in = "&aStarting in <count>!"; - public String successfully_removed = "&cSuccessfully removed &3<component>&c!"; - public String failed_removing_component = "&cFailed removing &3<component>&c. <cause>."; - public String joined_arena = "&aYou joined &3<arena>&a."; - public String you_won = "&aYou &2won &athe game!"; - public String you_lost = "&cYou &4lost &cthe game."; - public String you_got_a_kill = "&aYou killed &2<player>!"; - public String player_was_killed_by = "&4<player> &cwas killed by &4<killer>&c!"; - public String attributelevel_increased = "&aThe <attribute> level was increased successfully!"; - public String not_enough_credits = "&cThe max level of 3 was reached or you don't have enough credits. Needed: <credits>"; - public String too_many_main_guns = "&cYou already have 2 main guns, remove one first."; - public String successfully_set_main_gun = "&aSuccessfully set a main gun (of a maximum of two)."; - public String arcade_next_minigame = "&6Next Arcade game: &4<minigame>&6!"; - public String arena_disabled = "&cThe arena is disabled thus you can't join."; - public String all_guns = "&aYour current main guns: &2<guns>"; - public String you_can_leave_with = "&cYou can leave with <cmd> or /l!"; - public String arcade_joined_spectator = "&6You joined Arcade as a spectator! You'll be able to play in the next minigame."; - public String arcade_joined_waiting = "&6You joined Arcade! Waiting for <count> more players to start."; - public String arcade_new_round = "&6Next Arcade round in <count>!"; - public String no_perm_to_join_arena = "&cYou don't have permission (arenas.<arena>) to join this arena as it's vip!"; - public String set_kit = "&aSuccessfully set &2<kit>&a!"; - public String classes_item = "&4Classes"; - public String achievement_item = "&4Achievements"; - public String shop_item = "&4Shop"; - public String spectator_item = "&4Players"; - public String server_broadcast_winner = "&2<player> &awon the game on &2<arena>&a!"; - public String exit_item = "&4Leave the game"; - public String successfully_bought_kit = "&aSuccessfully bought &2<kit> &afor &2<money>&a."; - public String scoreboard_title = "&4<arena>"; - public String scoreboard_lobby_title = "&4[<arena>]"; - public String you_got_kicked_because_vip_joined = "&cYou got kicked out of the game because a vip joined!"; - public String powerup_spawned = "&2A Powerup spawned!"; - public String you_got_the_achievement = "&3You got the achievement &b<achievement>&3!"; - public String game_started = "&2The game has started!"; - public String author_of_the_map = "&3You are playing on the map &b<arena> &3by &b<author>&3!"; - public String description_of_the_map = "<description>"; - public String not_enough_money = "&cYou don't have enough money."; - public String possible_kits = "&aPossible kits: &2"; - public String possible_shopitems = "&aPossible shop items: &2"; - public String cancelled_starting = "&cThe starting countdown was cancelled because there's only one player left in the arena."; - public String minigame_description = ""; - public String successfully_bought_shopitem = "&aSuccessfully bought &2<shopitem> &afor &2<money>&a."; - public String already_bought_shopitem = "&aYou already had &2<shopitem>&a."; - public String you_received_rewards = "&aYou received a reward of &2<economyreward>"; - public String you_received_rewards_2 = " &aand "; - public String you_received_rewards_3 = "&2<itemreward>&a!"; - public String already_in_arena = "&cYou are already in an arena."; - public String stop_cause_maximum_game_time = "&cThe game is stopping in 5 seconds because the maximum game time was reached."; - public String compass_no_player_found = "&cNo near players found!"; - public String compass_player_found = "&aThe compass is tracking &3<player> &anow. Distance: <distance>"; - public String you_got_a_participation_reward = "&aYou received &2<economyreward> &afor participating!"; - public String kit_warning = "&7Be aware that you'll only get the &8last &7kit you bought even if you buy all of them."; - - public FileConfiguration getConfig() { - if (messagesConfig == null) { - reloadConfig(); - } - return messagesConfig; - } - - public void saveConfig() { - if (messagesConfig == null || messagesFile == null) { - return; - } - try { - getConfig().save(messagesFile); - } catch (IOException ex) { - - } - } - - public void reloadConfig() { - if (messagesFile == null) { - messagesFile = new File(plugin.getDataFolder(), "messages.yml"); - } - messagesConfig = YamlConfiguration.loadConfiguration(messagesFile); - - InputStream defConfigStream = plugin.getResource("messages.yml"); - if (defConfigStream != null) { - YamlConfiguration defConfig = YamlConfiguration.loadConfiguration(defConfigStream); - messagesConfig.setDefaults(defConfig); - } - } - +public class MessagesConfig +{ + + private FileConfiguration messagesConfig = null; + private File messagesFile = null; + private JavaPlugin plugin = null; + + public MessagesConfig(final JavaPlugin plugin) + { + this.plugin = plugin; + this.init(); + } + + public void init() + { + // all signs + this.getConfig().options().header("Contains all messages for easy translation. You can remove a mesage by setting it to nothing, like so: ''"); + final Map<String, String> namecol = ArenaState.getAllStateNameColors(); + for (final String state : namecol.keySet()) + { + final String color = namecol.get(state); + this.getConfig().addDefault("signs." + state.toLowerCase() + ".0", color + "[]"); + this.getConfig().addDefault("signs." + state.toLowerCase() + ".1", color + "<arena>"); + this.getConfig().addDefault("signs." + state.toLowerCase() + ".2", color + "<count>/<maxcount>"); + this.getConfig().addDefault("signs." + state.toLowerCase() + ".3", color + "[]"); + } + this.getConfig().addDefault("signs.spec.0", "&cSPECTATE"); + this.getConfig().addDefault("signs.spec.1", "&c<arena>"); + this.getConfig().addDefault("signs.spec.2", "<count>/<maxcount>"); + this.getConfig().addDefault("signs.spec.3", "[]"); + + // Arcade sign (I think that one is unused) + this.getConfig().addDefault("signs.arcade.0", "[]"); + this.getConfig().addDefault("signs.arcade.1", "&cArcade"); + this.getConfig().addDefault("signs.arcade.2", "<count>/<maxcount>"); + this.getConfig().addDefault("signs.arcade.3", "[]"); + + // Leave sign + this.getConfig().addDefault("signs.leave.0", ""); + this.getConfig().addDefault("signs.leave.1", "&4Leave"); + this.getConfig().addDefault("signs.leave.2", ""); + this.getConfig().addDefault("signs.leave.3", ""); + + // Random arena sign + this.getConfig().addDefault("signs.random.0", "&a[]"); + this.getConfig().addDefault("signs.random.1", "&2Random"); + this.getConfig().addDefault("signs.random.2", ""); + this.getConfig().addDefault("signs.random.3", "&a[]"); + + this.getConfig().addDefault("messages.no_perm", this.no_perm); + this.getConfig().addDefault("messages.successfully_reloaded", this.successfully_reloaded); + this.getConfig().addDefault("messages.successfully_set", this.successfully_set); + this.getConfig().addDefault("messages.successfully_saved_arena", this.successfully_saved_arena); + this.getConfig().addDefault("messages.arena_invalid", this.arena_invalid); + this.getConfig().addDefault("messages.failed_saving_arena", this.failed_saving_arena); + this.getConfig().addDefault("messages.broadcast_players_left", this.broadcast_players_left); + this.getConfig().addDefault("messages.broadcast_player_joined", this.broadcast_player_joined); + this.getConfig().addDefault("messages.player_died", this.player_died); + this.getConfig().addDefault("messages.arena_action", this.arena_action); + this.getConfig().addDefault("messages.you_already_are_in_arena", this.you_already_are_in_arena); + this.getConfig().addDefault("messages.you_joined_arena", this.you_joined_arena); + this.getConfig().addDefault("messages.not_in_arena", this.not_in_arena); + this.getConfig().addDefault("messages.teleporting_to_arena_in", this.teleporting_to_arena_in); + this.getConfig().addDefault("messages.starting_in", this.starting_in); + this.getConfig().addDefault("messages.failed_removing_arena", this.failed_removing_arena); + this.getConfig().addDefault("messages.successfully_removed", this.successfully_removed); + this.getConfig().addDefault("messages.failed_removing_component", this.failed_removing_component); + this.getConfig().addDefault("messages.joined_arena", this.joined_arena); + this.getConfig().addDefault("messages.you_won", this.you_won); + this.getConfig().addDefault("messages.you_lost", this.you_lost); + this.getConfig().addDefault("messages.you_got_a_kill", this.you_got_a_kill); + this.getConfig().addDefault("messages.player_was_killed_by", this.player_was_killed_by); + this.getConfig().addDefault("messages.arena_not_initialized", this.arena_not_initialized); + this.getConfig().addDefault("messages.guns.attributelevel_increased", this.attributelevel_increased); + this.getConfig().addDefault("messages.guns.not_enough_credits", this.not_enough_credits); + this.getConfig().addDefault("messages.guns.too_many_main_guns", this.too_many_main_guns); + this.getConfig().addDefault("messages.guns.successfully_set_main_gun", this.successfully_set_main_gun); + this.getConfig().addDefault("messages.guns.all_guns", this.all_guns); + this.getConfig().addDefault("messages.arcade_next_minigame", this.arcade_next_minigame); + this.getConfig().addDefault("messages.arcade_joined_waiting", this.arcade_joined_waiting); + this.getConfig().addDefault("messages.arcade_joined_spectator", this.arcade_joined_spectator); + this.getConfig().addDefault("messages.arcade_new_round", this.arcade_new_round); + this.getConfig().addDefault("messages.arena_disabled", this.arena_disabled); + this.getConfig().addDefault("messages.you_can_leave_with", this.you_can_leave_with); + this.getConfig().addDefault("messages.no_perm_to_join_arena", this.no_perm_to_join_arena); + this.getConfig().addDefault("messages.set_kit", this.set_kit); + this.getConfig().addDefault("messages.classes_item", this.classes_item); + this.getConfig().addDefault("messages.achievement_item", this.achievement_item); + this.getConfig().addDefault("messages.achievement_done_true", this.achievement_done_true); + this.getConfig().addDefault("messages.achievement_done_false", this.achievement_done_false); + this.getConfig().addDefault("messages.shop_item", this.shop_item); + this.getConfig().addDefault("messages.spectator_item", this.spectator_item); + this.getConfig().addDefault("messages.server_broadcast_winner", this.server_broadcast_winner); + this.getConfig().addDefault("messages.exit_item", this.exit_item); + this.getConfig().addDefault("messages.successfully_bought_kit", this.successfully_bought_kit); + this.getConfig().addDefault("messages.scoreboard.title", this.scoreboard_title); + this.getConfig().addDefault("messages.scoreboard.lobby_title", this.scoreboard_lobby_title); + this.getConfig().addDefault("messages.you_got_kicked_because_vip_joined", this.you_got_kicked_because_vip_joined); + this.getConfig().addDefault("messages.powerup_spawned", this.powerup_spawned); + if (!this.getConfig().isSet("config.generatedv182")) + { + this.getConfig().addDefault("messages.custom_scoreboard.line0", "Players:<playercount>"); + this.getConfig().addDefault("messages.custom_scoreboard.line1", "Spectators:<lostplayercount>"); + this.getConfig().addDefault("messages.custom_scoreboard.line2", "Alive:<playeralivecount>"); + this.getConfig().addDefault("messages.custom_scoreboard.line3", "Your Credits:<points>"); + this.getConfig().addDefault("messages.custom_scoreboard.line4", "Your Wins:<wins>"); + this.getConfig().addDefault("messages.custom_lobby_scoreboard.line0", "Players:<playercount>"); + this.getConfig().addDefault("messages.custom_lobby_scoreboard.line1", "Max Players:<maxplayercount>"); + this.getConfig().addDefault("messages.custom_lobby_scoreboard.line2", "Your Credits:<points>"); + this.getConfig().addDefault("messages.custom_lobby_scoreboard.line3", "Your Wins:<wins>"); + } + this.getConfig().addDefault("messages.you_got_the_achievement", this.you_got_the_achievement); + this.getConfig().addDefault("messages.game_started", this.game_started); + this.getConfig().addDefault("messages.no_game_started", this.no_game_started); + this.getConfig().addDefault("messages.author_of_the_map", this.author_of_the_map); + this.getConfig().addDefault("messages.description_of_the_map", this.description_of_the_map); + this.getConfig().addDefault("messages.not_enough_money", this.not_enough_money); + this.getConfig().addDefault("messages.possible_kits", this.possible_kits); + this.getConfig().addDefault("messages.possible_shopitems", this.possible_shopitems); + this.getConfig().addDefault("messages.cancelled_starting", this.cancelled_starting); + this.getConfig().addDefault("messages.minigame_description", this.minigame_description); + this.getConfig().addDefault("messages.successfully_bought_shopitem", this.successfully_bought_shopitem); + this.getConfig().addDefault("messages.already_bought_shopitem", this.already_bought_shopitem); + this.getConfig().addDefault("messages.you_received_rewards", this.you_received_rewards); + this.getConfig().addDefault("messages.you_received_rewards_2", this.you_received_rewards_2); + this.getConfig().addDefault("messages.you_received_rewards_3", this.you_received_rewards_3); + this.getConfig().addDefault("messages.already_in_arena", this.already_in_arena); + this.getConfig().addDefault("messages.stop_cause_maximum_game_time_sec", this.stop_cause_maximum_game_time_sec); + this.getConfig().addDefault("messages.stop_cause_maximum_game_time_now", this.stop_cause_maximum_game_time_now); + this.getConfig().addDefault("messages.compass.no_player_found", this.compass_no_player_found); + this.getConfig().addDefault("messages.compass.found_player", this.compass_player_found); + this.getConfig().addDefault("messages.you_got_a_participation_reward", this.you_got_a_participation_reward); + this.getConfig().addDefault("messages.kit_warning", this.kit_warning); + if (!this.getConfig().isSet("config.generatedv1102")) + { + this.getConfig().addDefault("messages.stats.line0", "&7----- &a&lStats &7-----; "); + this.getConfig().addDefault("messages.stats.line1", "&7Wins: &a<wins>"); + this.getConfig().addDefault("messages.stats.line2", "&7Loses: &c<loses>"); + this.getConfig().addDefault("messages.stats.line3", "&7Alltime Kills: &a<alltime_kills>"); + this.getConfig().addDefault("messages.stats.line4", "&7Alltime Deaths: &c<alltime_deaths>"); + this.getConfig().addDefault("messages.stats.line5", "&7KDR: &e<kdr>"); + this.getConfig().addDefault("messages.stats.line6", "&7Points: &e<points>"); + this.getConfig().addDefault("messages.stats.line7", " ;&7-----------------"); + } + + // save + this.getConfig().options().copyDefaults(true); + this.saveConfig(); + + // load + this.no_perm = ChatColor.translateAlternateColorCodes('&', this.getConfig().getString("messages.no_perm")); + this.successfully_reloaded = ChatColor.translateAlternateColorCodes('&', this.getConfig().getString("messages.successfully_reloaded")); + this.successfully_set = ChatColor.translateAlternateColorCodes('&', this.getConfig().getString("messages.successfully_set")); + this.successfully_saved_arena = ChatColor.translateAlternateColorCodes('&', this.getConfig().getString("messages.successfully_saved_arena")); + this.failed_saving_arena = ChatColor.translateAlternateColorCodes('&', this.getConfig().getString("messages.failed_saving_arena")); + this.arena_invalid = ChatColor.translateAlternateColorCodes('&', this.getConfig().getString("messages.arena_invalid")); + this.player_died = ChatColor.translateAlternateColorCodes('&', this.getConfig().getString("messages.player_died")); + this.broadcast_players_left = ChatColor.translateAlternateColorCodes('&', this.getConfig().getString("messages.broadcast_players_left")); + this.broadcast_player_joined = ChatColor.translateAlternateColorCodes('&', this.getConfig().getString("messages.broadcast_player_joined")); + this.arena_action = ChatColor.translateAlternateColorCodes('&', this.getConfig().getString("messages.arena_action")); + this.you_already_are_in_arena = ChatColor.translateAlternateColorCodes('&', this.getConfig().getString("messages.you_already_are_in_arena")); + this.you_joined_arena = ChatColor.translateAlternateColorCodes('&', this.getConfig().getString("messages.you_joined_arena")); + this.not_in_arena = ChatColor.translateAlternateColorCodes('&', this.getConfig().getString("messages.not_in_arena")); + this.teleporting_to_arena_in = ChatColor.translateAlternateColorCodes('&', this.getConfig().getString("messages.teleporting_to_arena_in")); + this.starting_in = ChatColor.translateAlternateColorCodes('&', this.getConfig().getString("messages.starting_in")); + this.failed_removing_arena = ChatColor.translateAlternateColorCodes('&', this.getConfig().getString("messages.failed_removing_arena")); + this.successfully_removed = ChatColor.translateAlternateColorCodes('&', this.getConfig().getString("messages.successfully_removed")); + this.failed_removing_component = ChatColor.translateAlternateColorCodes('&', this.getConfig().getString("messages.failed_removing_component")); + this.joined_arena = ChatColor.translateAlternateColorCodes('&', this.getConfig().getString("messages.joined_arena")); + this.you_won = ChatColor.translateAlternateColorCodes('&', this.getConfig().getString("messages.you_won")); + this.you_lost = ChatColor.translateAlternateColorCodes('&', this.getConfig().getString("messages.you_lost")); + this.you_got_a_kill = ChatColor.translateAlternateColorCodes('&', this.getConfig().getString("messages.you_got_a_kill")); + this.player_was_killed_by = ChatColor.translateAlternateColorCodes('&', this.getConfig().getString("messages.player_was_killed_by")); + this.arena_not_initialized = ChatColor.translateAlternateColorCodes('&', this.getConfig().getString("messages.arena_not_initialized")); + this.arcade_next_minigame = ChatColor.translateAlternateColorCodes('&', this.getConfig().getString("messages.arcade_next_minigame")); + this.arcade_new_round = ChatColor.translateAlternateColorCodes('&', this.getConfig().getString("messages.arcade_new_round")); + this.arena_disabled = ChatColor.translateAlternateColorCodes('&', this.getConfig().getString("messages.arena_disabled")); + this.you_can_leave_with = ChatColor.translateAlternateColorCodes('&', this.getConfig().getString("messages.you_can_leave_with")); + this.arcade_joined_waiting = ChatColor.translateAlternateColorCodes('&', this.getConfig().getString("messages.arcade_joined_waiting")); + this.arcade_joined_spectator = ChatColor.translateAlternateColorCodes('&', this.getConfig().getString("messages.arcade_joined_spectator")); + this.no_perm_to_join_arena = ChatColor.translateAlternateColorCodes('&', this.getConfig().getString("messages.no_perm_to_join_arena")); + this.set_kit = ChatColor.translateAlternateColorCodes('&', this.getConfig().getString("messages.set_kit")); + this.classes_item = ChatColor.translateAlternateColorCodes('&', this.getConfig().getString("messages.classes_item")); + this.achievement_item = ChatColor.translateAlternateColorCodes('&', this.getConfig().getString("messages.achievement_item")); + this.achievement_done_true = ChatColor.translateAlternateColorCodes('&', this.getConfig().getString("messages.achievement_done_true")); + this.achievement_done_false = ChatColor.translateAlternateColorCodes('&', this.getConfig().getString("messages.achievement_done_false")); + this.shop_item = ChatColor.translateAlternateColorCodes('&', this.getConfig().getString("messages.shop_item")); + this.spectator_item = ChatColor.translateAlternateColorCodes('&', this.getConfig().getString("messages.spectator_item")); + this.server_broadcast_winner = ChatColor.translateAlternateColorCodes('&', this.getConfig().getString("messages.server_broadcast_winner")); + this.exit_item = ChatColor.translateAlternateColorCodes('&', this.getConfig().getString("messages.exit_item")); + this.successfully_bought_kit = ChatColor.translateAlternateColorCodes('&', this.getConfig().getString("messages.successfully_bought_kit")); + this.scoreboard_title = ChatColor.translateAlternateColorCodes('&', this.getConfig().getString("messages.scoreboard.title")); + this.scoreboard_lobby_title = ChatColor.translateAlternateColorCodes('&', this.getConfig().getString("messages.scoreboard.lobby_title")); + this.you_got_kicked_because_vip_joined = ChatColor.translateAlternateColorCodes('&', this.getConfig().getString("messages.you_got_kicked_because_vip_joined")); + this.powerup_spawned = ChatColor.translateAlternateColorCodes('&', this.getConfig().getString("messages.powerup_spawned")); + this.you_got_the_achievement = ChatColor.translateAlternateColorCodes('&', this.getConfig().getString("messages.you_got_the_achievement")); + this.game_started = ChatColor.translateAlternateColorCodes('&', this.getConfig().getString("messages.game_started")); + this.no_game_started = ChatColor.translateAlternateColorCodes('&', this.getConfig().getString("messages.no_game_started")); + this.author_of_the_map = ChatColor.translateAlternateColorCodes('&', this.getConfig().getString("messages.author_of_the_map")); + this.description_of_the_map = ChatColor.translateAlternateColorCodes('&', this.getConfig().getString("messages.description_of_the_map")); + this.not_enough_money = ChatColor.translateAlternateColorCodes('&', this.getConfig().getString("messages.not_enough_money")); + this.possible_kits = ChatColor.translateAlternateColorCodes('&', this.getConfig().getString("messages.possible_kits")); + this.possible_shopitems = ChatColor.translateAlternateColorCodes('&', this.getConfig().getString("messages.possible_shopitems")); + this.cancelled_starting = ChatColor.translateAlternateColorCodes('&', this.getConfig().getString("messages.cancelled_starting")); + this.minigame_description = ChatColor.translateAlternateColorCodes('&', this.getConfig().getString("messages.minigame_description")); + this.successfully_bought_shopitem = ChatColor.translateAlternateColorCodes('&', this.getConfig().getString("messages.successfully_bought_shopitem")); + this.already_bought_shopitem = ChatColor.translateAlternateColorCodes('&', this.getConfig().getString("messages.already_bought_shopitem")); + this.you_received_rewards = ChatColor.translateAlternateColorCodes('&', this.getConfig().getString("messages.you_received_rewards")); + this.you_received_rewards_2 = ChatColor.translateAlternateColorCodes('&', this.getConfig().getString("messages.you_received_rewards_2")); + this.you_received_rewards_3 = ChatColor.translateAlternateColorCodes('&', this.getConfig().getString("messages.you_received_rewards_3")); + this.already_in_arena = ChatColor.translateAlternateColorCodes('&', this.getConfig().getString("messages.already_in_arena")); + this.stop_cause_maximum_game_time_sec = ChatColor.translateAlternateColorCodes('&', this.getConfig().getString("messages.stop_cause_maximum_game_time_sec")); + this.stop_cause_maximum_game_time_now = ChatColor.translateAlternateColorCodes('&', this.getConfig().getString("messages.stop_cause_maximum_game_time_now")); + this.compass_no_player_found = ChatColor.translateAlternateColorCodes('&', this.getConfig().getString("messages.compass.no_player_found")); + this.compass_player_found = ChatColor.translateAlternateColorCodes('&', this.getConfig().getString("messages.compass.found_player")); + this.you_got_a_participation_reward = ChatColor.translateAlternateColorCodes('&', this.getConfig().getString("messages.you_got_a_participation_reward")); + this.kit_warning = ChatColor.translateAlternateColorCodes('&', this.getConfig().getString("messages.kit_warning")); + + this.attributelevel_increased = ChatColor.translateAlternateColorCodes('&', this.getConfig().getString("messages.guns.attributelevel_increased")); + this.not_enough_credits = ChatColor.translateAlternateColorCodes('&', this.getConfig().getString("messages.guns.not_enough_credits")); + this.too_many_main_guns = ChatColor.translateAlternateColorCodes('&', this.getConfig().getString("messages.guns.too_many_main_guns")); + this.successfully_set_main_gun = ChatColor.translateAlternateColorCodes('&', this.getConfig().getString("messages.guns.successfully_set_main_gun")); + this.all_guns = ChatColor.translateAlternateColorCodes('&', this.getConfig().getString("messages.guns.all_guns")); + + this.getConfig().set("config.generatedv182", true); + this.getConfig().set("config.generatedv1102", true); + this.saveConfig(); + } + + public String no_perm = "&cYou don't have permission."; + public String successfully_reloaded = "&aSuccessfully reloaded all configs."; + public String successfully_set = "&aSuccessfully set &3<component>&a."; + public String successfully_saved_arena = "&aSuccessfully saved &3<arena>&a."; + public String failed_saving_arena = "&cFailed to save &3<arena>&c."; + public String failed_removing_arena = "&cFailed to remove &3<arena>&c."; + public String arena_invalid = "&3<arena> &cappears to be invalid."; + public String broadcast_players_left = "&eThere are &4<count> &eplayers left!"; + public String broadcast_player_joined = "&2<player> &ajoined the arena! (<count>/<maxcount>)"; + public String player_died = "&c<player> died."; + public String arena_action = "&aYou <action> arena &3<arena>&a!"; + public String you_joined_arena = "&aYou joined arena &3<arena>&a!"; + public String you_already_are_in_arena = "&aYou already seem to be in arena &3<arena>&a!"; + public String arena_not_initialized = "&cThe arena appears to be not initialized, did you save the arena?"; + public String not_in_arena = "&cYou don't seem to be in an arena right now."; + public String teleporting_to_arena_in = "&7Teleporting to arena in <count>."; + public String starting_in = "&aStarting in <count>!"; + public String successfully_removed = "&cSuccessfully removed &3<component>&c!"; + public String failed_removing_component = "&cFailed removing &3<component>&c. <cause>."; + public String joined_arena = "&aYou joined &3<arena>&a."; + public String you_won = "&aYou &2won &athe game!"; + public String you_lost = "&cYou &4lost &cthe game."; + public String you_got_a_kill = "&aYou killed &2<player>!"; + public String player_was_killed_by = "&4<player> &cwas killed by &4<killer>&c!"; + public String attributelevel_increased = "&aThe <attribute> level was increased successfully!"; + public String not_enough_credits = "&cThe max level of 3 was reached or you don't have enough credits. Needed: <credits>"; + public String too_many_main_guns = "&cYou already have 2 main guns, remove one first."; + public String successfully_set_main_gun = "&aSuccessfully set a main gun (of a maximum of two)."; + public String arcade_next_minigame = "&6Next Arcade game: &4<minigame>&6!"; + public String arena_disabled = "&cThe arena is disabled thus you can't join."; + public String all_guns = "&aYour current main guns: &2<guns>"; + public String you_can_leave_with = "&cYou can leave with <cmd> or /l!"; + public String arcade_joined_spectator = "&6You joined Arcade as a spectator! You'll be able to play in the next minigame."; + public String arcade_joined_waiting = "&6You joined Arcade! Waiting for <count> more players to start."; + public String arcade_new_round = "&6Next Arcade round in <count>!"; + public String no_perm_to_join_arena = "&cYou don't have permission (arenas.<arena>) to join this arena as it's vip!"; + public String set_kit = "&aSuccessfully set &2<kit>&a!"; + public String classes_item = "&4Classes"; + public String achievement_item = "&4Achievements"; + public String achievement_done_true = "Done: true"; + public String achievement_done_false = "Done: false"; + public String shop_item = "&4Shop"; + public String spectator_item = "&4Players"; + public String server_broadcast_winner = "&2<player> &awon the game on &2<arena>&a!"; + public String exit_item = "&4Leave the game"; + public String successfully_bought_kit = "&aSuccessfully bought &2<kit> &afor &2<money>&a."; + public String scoreboard_title = "&4<arena>"; + public String scoreboard_lobby_title = "&4[<arena>]"; + public String you_got_kicked_because_vip_joined = "&cYou got kicked out of the game because a vip joined!"; + public String powerup_spawned = "&2A Powerup spawned!"; + public String you_got_the_achievement = "&3You got the achievement &b<achievement>&3!"; + public String game_started = "&2The game has started!"; + public String no_game_started = "&cThere is no started game!"; + public String author_of_the_map = "&3You are playing on the map &b<arena> &3by &b<author>&3!"; + public String description_of_the_map = "<description>"; + public String not_enough_money = "&cYou don't have enough money."; + public String possible_kits = "&aPossible kits: &2"; + public String possible_shopitems = "&aPossible shop items: &2"; + public String cancelled_starting = "&cThe starting countdown was cancelled because there's only one player left in the arena."; + public String minigame_description = ""; + public String successfully_bought_shopitem = "&aSuccessfully bought &2<shopitem> &afor &2<money>&a."; + public String already_bought_shopitem = "&aYou already had &2<shopitem>&a."; + public String you_received_rewards = "&aYou received a reward of &2<economyreward>"; + public String you_received_rewards_2 = " &aand "; + public String you_received_rewards_3 = "&2<itemreward>&a!"; + public String already_in_arena = "&cYou are already in an arena."; + public String stop_cause_maximum_game_time_now = "&cThe game is stopping now because the maximum game time was reached."; + public String stop_cause_maximum_game_time_sec = "&cThe game is stopping in <sec> seconds because the maximum game time was reached."; + public String compass_no_player_found = "&cNo near players found!"; + public String compass_player_found = "&aThe compass is tracking &3<player> &anow. Distance: <distance>"; + public String you_got_a_participation_reward = "&aYou received &2<economyreward> &afor participating!"; + public String kit_warning = "&7Be aware that you'll only get the &8last &7kit you bought even if you buy all of them."; + + public FileConfiguration getConfig() + { + if (this.messagesConfig == null) + { + this.reloadConfig(); + } + return this.messagesConfig; + } + + public void saveConfig() + { + if (this.messagesConfig == null || this.messagesFile == null) + { + return; + } + try + { + this.getConfig().save(this.messagesFile); + } + catch (final IOException ex) + { + // silently ignore + } + } + + public void reloadConfig() + { + if (this.messagesFile == null) + { + this.messagesFile = new File(this.plugin.getDataFolder(), "messages.yml"); + } + this.messagesConfig = YamlConfiguration.loadConfiguration(this.messagesFile); + + final InputStream defConfigStream = this.plugin.getResource("messages.yml"); + if (defConfigStream != null) + { + final YamlConfiguration defConfig = YamlConfiguration.loadConfiguration(new InputStreamReader(defConfigStream)); + this.messagesConfig.setDefaults(defConfig); + } + } + } diff --git a/API/src/main/java/com/comze_instancelabs/minigamesapi/config/PartyMessagesConfig.java b/API/src/main/java/com/comze_instancelabs/minigamesapi/config/PartyMessagesConfig.java index 0b17ed7c..ea630d8c 100644 --- a/API/src/main/java/com/comze_instancelabs/minigamesapi/config/PartyMessagesConfig.java +++ b/API/src/main/java/com/comze_instancelabs/minigamesapi/config/PartyMessagesConfig.java @@ -1,107 +1,132 @@ +/* + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ package com.comze_instancelabs.minigamesapi.config; import java.io.File; import java.io.IOException; import java.io.InputStream; -import java.util.HashMap; +import java.io.InputStreamReader; import org.bukkit.ChatColor; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.plugin.java.JavaPlugin; -import com.comze_instancelabs.minigamesapi.ArenaState; - -public class PartyMessagesConfig { - - private FileConfiguration messagesConfig = null; - private File messagesFile = null; - private JavaPlugin plugin = null; - - public PartyMessagesConfig(JavaPlugin plugin) { - this.plugin = plugin; - this.init(); - } - - public void init() { - this.getConfig().addDefault("messages.cannot_invite_yourself", cannot_invite_yourself); - this.getConfig().addDefault("messages.player_not_online", player_not_online); - this.getConfig().addDefault("messages.you_invited", you_invited); - this.getConfig().addDefault("messages.you_were_invited", you_were_invited); - this.getConfig().addDefault("messages.not_invited_to_any_party", not_invited_to_any_party); - this.getConfig().addDefault("messages.not_invited_to_players_party", not_invited_to_players_party); - this.getConfig().addDefault("messages.player_not_in_party", player_not_in_party); - this.getConfig().addDefault("messages.you_joined_party", you_joined_party); - this.getConfig().addDefault("messages.player_joined_party", player_joined_party); - this.getConfig().addDefault("messages.you_left_party", you_left_party); - this.getConfig().addDefault("messages.player_left_party", player_left_party); - this.getConfig().addDefault("messages.party_disbanded", party_disbanded); - this.getConfig().addDefault("messages.party_too_big_to_join", party_too_big_to_join); - - // save - this.getConfig().options().copyDefaults(true); - this.saveConfig(); - - // load - this.cannot_invite_yourself = ChatColor.translateAlternateColorCodes('&', getConfig().getString("messages.cannot_invite_yourself")); - this.player_not_online = ChatColor.translateAlternateColorCodes('&', getConfig().getString("messages.player_not_online")); - this.you_invited = ChatColor.translateAlternateColorCodes('&', getConfig().getString("messages.you_invited")); - this.you_were_invited = ChatColor.translateAlternateColorCodes('&', getConfig().getString("messages.you_were_invited")); - this.not_invited_to_any_party = ChatColor.translateAlternateColorCodes('&', getConfig().getString("messages.not_invited_to_any_party")); - this.not_invited_to_players_party = ChatColor.translateAlternateColorCodes('&', getConfig().getString("messages.not_invited_to_players_party")); - this.player_not_in_party = ChatColor.translateAlternateColorCodes('&', getConfig().getString("messages.player_not_in_party")); - this.you_joined_party = ChatColor.translateAlternateColorCodes('&', getConfig().getString("messages.you_joined_party")); - this.player_joined_party = ChatColor.translateAlternateColorCodes('&', getConfig().getString("messages.player_joined_party")); - this.you_left_party = ChatColor.translateAlternateColorCodes('&', getConfig().getString("messages.you_left_party")); - this.player_left_party = ChatColor.translateAlternateColorCodes('&', getConfig().getString("messages.player_left_party")); - this.party_disbanded = ChatColor.translateAlternateColorCodes('&', getConfig().getString("messages.party_disbanded")); - this.party_too_big_to_join = ChatColor.translateAlternateColorCodes('&', getConfig().getString("messages.party_too_big_to_join")); - - } - - public String cannot_invite_yourself = "&cYou cannot invite yourself!"; - public String player_not_online = "&4<player> &cis not online!"; - public String you_invited = "&aYou invited &2<player>&a!"; - public String you_were_invited = "&2<player> &ainvited you to join his/her party! Type &2/party accept <player> &ato accept."; - public String not_invited_to_any_party = "&cYou are not invited to any party."; - public String not_invited_to_players_party = "&cYou are not invited to the party of &4<player>&c."; - public String player_not_in_party = "&4<player> &cis not in your party."; - public String you_joined_party = "&7You joined the party of &8<player>&7."; - public String player_joined_party = "&2<player> &ajoined the party."; - public String you_left_party = "&7You left the party of &8<player>&7."; - public String player_left_party = "&4<player> &cleft the party."; - public String party_disbanded = "&cThe party was disbanded."; - public String party_too_big_to_join = "&cYour party is too big to join this arena."; - - public FileConfiguration getConfig() { - if (messagesConfig == null) { - reloadConfig(); - } - return messagesConfig; - } - - public void saveConfig() { - if (messagesConfig == null || messagesFile == null) { - return; - } - try { - getConfig().save(messagesFile); - } catch (IOException ex) { - - } - } - - public void reloadConfig() { - if (messagesFile == null) { - messagesFile = new File(plugin.getDataFolder(), "partymessages.yml"); - } - messagesConfig = YamlConfiguration.loadConfiguration(messagesFile); - - InputStream defConfigStream = plugin.getResource("partymessages.yml"); - if (defConfigStream != null) { - YamlConfiguration defConfig = YamlConfiguration.loadConfiguration(defConfigStream); - messagesConfig.setDefaults(defConfig); - } - } - +public class PartyMessagesConfig +{ + + private FileConfiguration messagesConfig = null; + private File messagesFile = null; + private JavaPlugin plugin = null; + + public PartyMessagesConfig(final JavaPlugin plugin) + { + this.plugin = plugin; + this.init(); + } + + public void init() + { + this.getConfig().addDefault("messages.cannot_invite_yourself", this.cannot_invite_yourself); + this.getConfig().addDefault("messages.player_not_online", this.player_not_online); + this.getConfig().addDefault("messages.you_invited", this.you_invited); + this.getConfig().addDefault("messages.you_were_invited", this.you_were_invited); + this.getConfig().addDefault("messages.not_invited_to_any_party", this.not_invited_to_any_party); + this.getConfig().addDefault("messages.not_invited_to_players_party", this.not_invited_to_players_party); + this.getConfig().addDefault("messages.player_not_in_party", this.player_not_in_party); + this.getConfig().addDefault("messages.you_joined_party", this.you_joined_party); + this.getConfig().addDefault("messages.player_joined_party", this.player_joined_party); + this.getConfig().addDefault("messages.you_left_party", this.you_left_party); + this.getConfig().addDefault("messages.player_left_party", this.player_left_party); + this.getConfig().addDefault("messages.party_disbanded", this.party_disbanded); + this.getConfig().addDefault("messages.party_too_big_to_join", this.party_too_big_to_join); + + // save + this.getConfig().options().copyDefaults(true); + this.saveConfig(); + + // load + this.cannot_invite_yourself = ChatColor.translateAlternateColorCodes('&', this.getConfig().getString("messages.cannot_invite_yourself")); + this.player_not_online = ChatColor.translateAlternateColorCodes('&', this.getConfig().getString("messages.player_not_online")); + this.you_invited = ChatColor.translateAlternateColorCodes('&', this.getConfig().getString("messages.you_invited")); + this.you_were_invited = ChatColor.translateAlternateColorCodes('&', this.getConfig().getString("messages.you_were_invited")); + this.not_invited_to_any_party = ChatColor.translateAlternateColorCodes('&', this.getConfig().getString("messages.not_invited_to_any_party")); + this.not_invited_to_players_party = ChatColor.translateAlternateColorCodes('&', this.getConfig().getString("messages.not_invited_to_players_party")); + this.player_not_in_party = ChatColor.translateAlternateColorCodes('&', this.getConfig().getString("messages.player_not_in_party")); + this.you_joined_party = ChatColor.translateAlternateColorCodes('&', this.getConfig().getString("messages.you_joined_party")); + this.player_joined_party = ChatColor.translateAlternateColorCodes('&', this.getConfig().getString("messages.player_joined_party")); + this.you_left_party = ChatColor.translateAlternateColorCodes('&', this.getConfig().getString("messages.you_left_party")); + this.player_left_party = ChatColor.translateAlternateColorCodes('&', this.getConfig().getString("messages.player_left_party")); + this.party_disbanded = ChatColor.translateAlternateColorCodes('&', this.getConfig().getString("messages.party_disbanded")); + this.party_too_big_to_join = ChatColor.translateAlternateColorCodes('&', this.getConfig().getString("messages.party_too_big_to_join")); + + } + + public String cannot_invite_yourself = "&cYou cannot invite yourself!"; + public String player_not_online = "&4<player> &cis not online!"; + public String you_invited = "&aYou invited &2<player>&a!"; + public String you_were_invited = "&2<player> &ainvited you to join his/her party! Type &2/party accept <player> &ato accept."; + public String not_invited_to_any_party = "&cYou are not invited to any party."; + public String not_invited_to_players_party = "&cYou are not invited to the party of &4<player>&c."; + public String player_not_in_party = "&4<player> &cis not in your party."; + public String you_joined_party = "&7You joined the party of &8<player>&7."; + public String player_joined_party = "&2<player> &ajoined the party."; + public String you_left_party = "&7You left the party of &8<player>&7."; + public String player_left_party = "&4<player> &cleft the party."; + public String party_disbanded = "&cThe party was disbanded."; + public String party_too_big_to_join = "&cYour party is too big to join this arena."; + + public FileConfiguration getConfig() + { + if (this.messagesConfig == null) + { + this.reloadConfig(); + } + return this.messagesConfig; + } + + public void saveConfig() + { + if (this.messagesConfig == null || this.messagesFile == null) + { + return; + } + try + { + this.getConfig().save(this.messagesFile); + } + catch (final IOException ex) + { + // silently ignore + } + } + + public void reloadConfig() + { + if (this.messagesFile == null) + { + this.messagesFile = new File(this.plugin.getDataFolder(), "partymessages.yml"); + } + this.messagesConfig = YamlConfiguration.loadConfiguration(this.messagesFile); + + final InputStream defConfigStream = this.plugin.getResource("partymessages.yml"); + if (defConfigStream != null) + { + final YamlConfiguration defConfig = YamlConfiguration.loadConfiguration(new InputStreamReader(defConfigStream)); + this.messagesConfig.setDefaults(defConfig); + } + } + } diff --git a/API/src/main/java/com/comze_instancelabs/minigamesapi/config/ShopConfig.java b/API/src/main/java/com/comze_instancelabs/minigamesapi/config/ShopConfig.java index f1d7595d..3d7ec534 100644 --- a/API/src/main/java/com/comze_instancelabs/minigamesapi/config/ShopConfig.java +++ b/API/src/main/java/com/comze_instancelabs/minigamesapi/config/ShopConfig.java @@ -1,100 +1,130 @@ -package com.comze_instancelabs.minigamesapi.config; +/* + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.configuration.file.YamlConfiguration; -import org.bukkit.plugin.java.JavaPlugin; + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ +package com.comze_instancelabs.minigamesapi.config; import java.io.File; import java.io.IOException; import java.io.InputStream; +import java.io.InputStreamReader; -public class ShopConfig { - - private FileConfiguration shopConfig = null; - private File shopFile = null; - private JavaPlugin plugin = null; - - public ShopConfig(JavaPlugin plugin, boolean custom) { - this.plugin = plugin; - if (!custom) { - this.getConfig().options().header("Used for saving shop items. Default shop items:"); - this.getConfig().addDefault("config.shop_items.coin_boost2.name", "Coin boost * 2"); - this.getConfig().addDefault("config.shop_items.coin_boost2.enabled", true); - this.getConfig().addDefault("config.shop_items.coin_boost2.uses_items", false); - this.getConfig().addDefault("config.shop_items.coin_boost2.items", "388*1"); - this.getConfig().addDefault("config.shop_items.coin_boost2.icon", "388*1"); - this.getConfig().addDefault("config.shop_items.coin_boost2.lore", "Will give all winners a double money reward boost."); - this.getConfig().addDefault("config.shop_items.coin_boost2.requires_money", true); - this.getConfig().addDefault("config.shop_items.coin_boost2.requires_permission", false); - this.getConfig().addDefault("config.shop_items.coin_boost2.money_amount", 1500); - this.getConfig().addDefault("config.shop_items.coin_boost2.permission_node", "minigames.shop_item.coin_boost2"); - - this.getConfig().addDefault("config.shop_items.coin_boost3.name", "Coin boost * 3"); - this.getConfig().addDefault("config.shop_items.coin_boost3.enabled", true); - this.getConfig().addDefault("config.shop_items.coin_boost3.uses_items", false); - this.getConfig().addDefault("config.shop_items.coin_boost3.items", "388*2"); - this.getConfig().addDefault("config.shop_items.coin_boost3.icon", "388*2"); - this.getConfig().addDefault("config.shop_items.coin_boost3.lore", "Will give all winners a triple money reward boost."); - this.getConfig().addDefault("config.shop_items.coin_boost3.requires_money", true); - this.getConfig().addDefault("config.shop_items.coin_boost3.requires_permission", false); - this.getConfig().addDefault("config.shop_items.coin_boost3.money_amount", 3000); - this.getConfig().addDefault("config.shop_items.coin_boost3.permission_node", "minigames.shop_item.coin_boost3"); - - this.getConfig().addDefault("config.shop_items.coin_boost2_solo.name", "Coin boost * 2 Solo"); - this.getConfig().addDefault("config.shop_items.coin_boost2_solo.enabled", true); - this.getConfig().addDefault("config.shop_items.coin_boost2_solo.uses_items", false); - this.getConfig().addDefault("config.shop_items.coin_boost2_solo.items", "264*1"); - this.getConfig().addDefault("config.shop_items.coin_boost2_solo.icon", "264*1"); - this.getConfig().addDefault("config.shop_items.coin_boost2_solo.lore", "Will give you a double money reward boost."); - this.getConfig().addDefault("config.shop_items.coin_boost2_solo.requires_money", true); - this.getConfig().addDefault("config.shop_items.coin_boost2_solo.requires_permission", false); - this.getConfig().addDefault("config.shop_items.coin_boost2_solo.money_amount", 1000); - this.getConfig().addDefault("config.shop_items.coin_boost2_solo.permission_node", "minigames.shop_item.coin_boost2_solo"); - - this.getConfig().addDefault("config.shop_items.coin_boost3_solo.name", "Coin boost * 3 Solo"); - this.getConfig().addDefault("config.shop_items.coin_boost3_solo.enabled", true); - this.getConfig().addDefault("config.shop_items.coin_boost3_solo.uses_items", false); - this.getConfig().addDefault("config.shop_items.coin_boost3_solo.items", "264*2"); - this.getConfig().addDefault("config.shop_items.coin_boost3_solo.icon", "264*2"); - this.getConfig().addDefault("config.shop_items.coin_boost3_solo.lore", "Will give you a triple money reward boost."); - this.getConfig().addDefault("config.shop_items.coin_boost3_solo.requires_money", true); - this.getConfig().addDefault("config.shop_items.coin_boost3_solo.requires_permission", false); - this.getConfig().addDefault("config.shop_items.coin_boost3_solo.money_amount", 2000); - this.getConfig().addDefault("config.shop_items.coin_boost3_solo.permission_node", "minigames.shop_item.coin_boost3_solo"); - } - this.getConfig().options().copyDefaults(true); - this.saveConfig(); - } - - public FileConfiguration getConfig() { - if (shopConfig == null) { - reloadConfig(); - } - return shopConfig; - } - - public void saveConfig() { - if (shopConfig == null || shopFile == null) { - return; - } - try { - getConfig().save(shopFile); - } catch (IOException ex) { - - } - } - - public void reloadConfig() { - if (shopFile == null) { - shopFile = new File(plugin.getDataFolder(), "shop.yml"); - } - shopConfig = YamlConfiguration.loadConfiguration(shopFile); +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.plugin.java.JavaPlugin; - InputStream defConfigStream = plugin.getResource("shop.yml"); - if (defConfigStream != null) { - YamlConfiguration defConfig = YamlConfiguration.loadConfiguration(defConfigStream); - shopConfig.setDefaults(defConfig); - } - } +import com.comze_instancelabs.minigamesapi.MinigamesAPI; +public class ShopConfig +{ + + private FileConfiguration shopConfig = null; + private File shopFile = null; + private JavaPlugin plugin = null; + + public ShopConfig(final JavaPlugin plugin, final boolean custom) + { + this.plugin = plugin; + if (!custom) + { + this.getConfig().options().header("Used for saving shop items. Default shop items:"); + this.getConfig().addDefault("config.shop_items.coin_boost2.name", "Coin boost * 2"); + this.getConfig().addDefault("config.shop_items.coin_boost2.enabled", true); + this.getConfig().addDefault("config.shop_items.coin_boost2.uses_items", false); + this.getConfig().addDefault("config.shop_items.coin_boost2.items", "388*1"); + this.getConfig().addDefault("config.shop_items.coin_boost2.icon", "388*1"); + this.getConfig().addDefault("config.shop_items.coin_boost2.lore", "Will give all winners a double money reward boost."); + this.getConfig().addDefault("config.shop_items.coin_boost2.requires_money", true); + this.getConfig().addDefault("config.shop_items.coin_boost2.requires_permission", false); + this.getConfig().addDefault("config.shop_items.coin_boost2.money_amount", 1500); + this.getConfig().addDefault("config.shop_items.coin_boost2.permission_node", MinigamesAPI.getAPI().getPermissionShopPrefix() + ".coin_boost2"); + + this.getConfig().addDefault("config.shop_items.coin_boost3.name", "Coin boost * 3"); + this.getConfig().addDefault("config.shop_items.coin_boost3.enabled", true); + this.getConfig().addDefault("config.shop_items.coin_boost3.uses_items", false); + this.getConfig().addDefault("config.shop_items.coin_boost3.items", "388*2"); + this.getConfig().addDefault("config.shop_items.coin_boost3.icon", "388*2"); + this.getConfig().addDefault("config.shop_items.coin_boost3.lore", "Will give all winners a triple money reward boost."); + this.getConfig().addDefault("config.shop_items.coin_boost3.requires_money", true); + this.getConfig().addDefault("config.shop_items.coin_boost3.requires_permission", false); + this.getConfig().addDefault("config.shop_items.coin_boost3.money_amount", 3000); + this.getConfig().addDefault("config.shop_items.coin_boost3.permission_node", MinigamesAPI.getAPI().getPermissionShopPrefix() + ".coin_boost3"); + + this.getConfig().addDefault("config.shop_items.coin_boost2_solo.name", "Coin boost * 2 Solo"); + this.getConfig().addDefault("config.shop_items.coin_boost2_solo.enabled", true); + this.getConfig().addDefault("config.shop_items.coin_boost2_solo.uses_items", false); + this.getConfig().addDefault("config.shop_items.coin_boost2_solo.items", "264*1"); + this.getConfig().addDefault("config.shop_items.coin_boost2_solo.icon", "264*1"); + this.getConfig().addDefault("config.shop_items.coin_boost2_solo.lore", "Will give you a double money reward boost."); + this.getConfig().addDefault("config.shop_items.coin_boost2_solo.requires_money", true); + this.getConfig().addDefault("config.shop_items.coin_boost2_solo.requires_permission", false); + this.getConfig().addDefault("config.shop_items.coin_boost2_solo.money_amount", 1000); + this.getConfig().addDefault("config.shop_items.coin_boost2_solo.permission_node", MinigamesAPI.getAPI().getPermissionShopPrefix() + ".coin_boost2_solo"); + + this.getConfig().addDefault("config.shop_items.coin_boost3_solo.name", "Coin boost * 3 Solo"); + this.getConfig().addDefault("config.shop_items.coin_boost3_solo.enabled", true); + this.getConfig().addDefault("config.shop_items.coin_boost3_solo.uses_items", false); + this.getConfig().addDefault("config.shop_items.coin_boost3_solo.items", "264*2"); + this.getConfig().addDefault("config.shop_items.coin_boost3_solo.icon", "264*2"); + this.getConfig().addDefault("config.shop_items.coin_boost3_solo.lore", "Will give you a triple money reward boost."); + this.getConfig().addDefault("config.shop_items.coin_boost3_solo.requires_money", true); + this.getConfig().addDefault("config.shop_items.coin_boost3_solo.requires_permission", false); + this.getConfig().addDefault("config.shop_items.coin_boost3_solo.money_amount", 2000); + this.getConfig().addDefault("config.shop_items.coin_boost3_solo.permission_node", MinigamesAPI.getAPI().getPermissionShopPrefix() + ".coin_boost3_solo"); + } + this.getConfig().options().copyDefaults(true); + this.saveConfig(); + } + + public FileConfiguration getConfig() + { + if (this.shopConfig == null) + { + this.reloadConfig(); + } + return this.shopConfig; + } + + public void saveConfig() + { + if (this.shopConfig == null || this.shopFile == null) + { + return; + } + try + { + this.getConfig().save(this.shopFile); + } + catch (final IOException ex) + { + // silently ignore + } + } + + public void reloadConfig() + { + if (this.shopFile == null) + { + this.shopFile = new File(this.plugin.getDataFolder(), "shop.yml"); + } + this.shopConfig = YamlConfiguration.loadConfiguration(this.shopFile); + + final InputStream defConfigStream = this.plugin.getResource("shop.yml"); + if (defConfigStream != null) + { + final YamlConfiguration defConfig = YamlConfiguration.loadConfiguration(new InputStreamReader(defConfigStream)); + this.shopConfig.setDefaults(defConfig); + } + } + } diff --git a/API/src/main/java/com/comze_instancelabs/minigamesapi/config/StatsConfig.java b/API/src/main/java/com/comze_instancelabs/minigamesapi/config/StatsConfig.java index 73e924a9..cce15a5b 100644 --- a/API/src/main/java/com/comze_instancelabs/minigamesapi/config/StatsConfig.java +++ b/API/src/main/java/com/comze_instancelabs/minigamesapi/config/StatsConfig.java @@ -1,61 +1,89 @@ -package com.comze_instancelabs.minigamesapi.config; +/* + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.configuration.file.YamlConfiguration; -import org.bukkit.plugin.java.JavaPlugin; + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ +package com.comze_instancelabs.minigamesapi.config; import java.io.File; import java.io.IOException; import java.io.InputStream; +import java.io.InputStreamReader; -public class StatsConfig { +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.plugin.java.JavaPlugin; - private FileConfiguration statsConfig = null; - private File statsFile = null; - private JavaPlugin plugin = null; +public class StatsConfig +{ - public StatsConfig(JavaPlugin plugin, boolean custom){ - this.plugin = plugin; - if(!custom){ - this.getConfig().options().header("Used for saving user statistics. Example user stats:"); - this.getConfig().addDefault("players.3c8c41ff-51f5-4b7a-8c2b-44df0beba03b.wins", 1); - this.getConfig().addDefault("players.3c8c41ff-51f5-4b7a-8c2b-44df0beba03b.loses", 1); - this.getConfig().addDefault("players.3c8c41ff-51f5-4b7a-8c2b-44df0beba03b.points", 10); - this.getConfig().addDefault("players.3c8c41ff-51f5-4b7a-8c2b-44df0beba03b.playername", "InstanceLabs"); - } - this.getConfig().options().copyDefaults(true); - this.saveConfig(); + private FileConfiguration statsConfig = null; + private File statsFile = null; + private JavaPlugin plugin = null; + + public StatsConfig(final JavaPlugin plugin, final boolean custom) + { + this.plugin = plugin; + if (!custom) + { + this.getConfig().options().header("Used for saving user statistics. Example user stats:"); + this.getConfig().addDefault("players.3c8c41ff-51f5-4b7a-8c2b-44df0beba03b.wins", 1); + this.getConfig().addDefault("players.3c8c41ff-51f5-4b7a-8c2b-44df0beba03b.loses", 1); + this.getConfig().addDefault("players.3c8c41ff-51f5-4b7a-8c2b-44df0beba03b.points", 10); + this.getConfig().addDefault("players.3c8c41ff-51f5-4b7a-8c2b-44df0beba03b.playername", "TheMrQuake"); + } + this.getConfig().options().copyDefaults(true); + this.saveConfig(); } - - public FileConfiguration getConfig() { - if (statsConfig == null) { - reloadConfig(); + + public FileConfiguration getConfig() + { + if (this.statsConfig == null) + { + this.reloadConfig(); } - return statsConfig; + return this.statsConfig; } - - public void saveConfig() { - if (statsConfig == null || statsFile == null) { + + public void saveConfig() + { + if (this.statsConfig == null || this.statsFile == null) + { return; } - try { - getConfig().save(statsFile); - } catch (IOException ex) { - + try + { + this.getConfig().save(this.statsFile); } - } - - public void reloadConfig() { - if (statsFile == null) { - statsFile = new File(plugin.getDataFolder(), "stats.yml"); + catch (final IOException ex) + { + // silently ignore } - statsConfig = YamlConfiguration.loadConfiguration(statsFile); + } - InputStream defConfigStream = plugin.getResource("stats.yml"); - if (defConfigStream != null) { - YamlConfiguration defConfig = YamlConfiguration.loadConfiguration(defConfigStream); - statsConfig.setDefaults(defConfig); + public void reloadConfig() + { + if (this.statsFile == null) + { + this.statsFile = new File(this.plugin.getDataFolder(), "stats.yml"); + } + this.statsConfig = YamlConfiguration.loadConfiguration(this.statsFile); + + final InputStream defConfigStream = this.plugin.getResource("stats.yml"); + if (defConfigStream != null) + { + final YamlConfiguration defConfig = YamlConfiguration.loadConfiguration(new InputStreamReader(defConfigStream)); + this.statsConfig.setDefaults(defConfig); } } - + } diff --git a/API/src/main/java/com/comze_instancelabs/minigamesapi/config/StatsGlobalConfig.java b/API/src/main/java/com/comze_instancelabs/minigamesapi/config/StatsGlobalConfig.java index dc3a03c0..edc441e9 100644 --- a/API/src/main/java/com/comze_instancelabs/minigamesapi/config/StatsGlobalConfig.java +++ b/API/src/main/java/com/comze_instancelabs/minigamesapi/config/StatsGlobalConfig.java @@ -1,61 +1,89 @@ -package com.comze_instancelabs.minigamesapi.config; +/* + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.configuration.file.YamlConfiguration; -import org.bukkit.plugin.java.JavaPlugin; + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ +package com.comze_instancelabs.minigamesapi.config; import java.io.File; import java.io.IOException; import java.io.InputStream; +import java.io.InputStreamReader; -public class StatsGlobalConfig { +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.plugin.java.JavaPlugin; - private FileConfiguration statsConfig = null; - private File statsFile = null; - private JavaPlugin plugin = null; +public class StatsGlobalConfig +{ - public StatsGlobalConfig(JavaPlugin plugin, boolean custom){ - this.plugin = plugin; - if(!custom){ - this.getConfig().options().header("Used for saving user statistics. Example user stats:"); - this.getConfig().addDefault("players.3c8c41ff-51f5-4b7a-8c2b-44df0beba03b.wins", 1); - this.getConfig().addDefault("players.3c8c41ff-51f5-4b7a-8c2b-44df0beba03b.loses", 1); - this.getConfig().addDefault("players.3c8c41ff-51f5-4b7a-8c2b-44df0beba03b.points", 10); - this.getConfig().addDefault("players.3c8c41ff-51f5-4b7a-8c2b-44df0beba03b.playername", "InstanceLabs"); - } - this.getConfig().options().copyDefaults(true); - this.saveConfig(); + private FileConfiguration statsConfig = null; + private File statsFile = null; + private JavaPlugin plugin = null; + + public StatsGlobalConfig(final JavaPlugin plugin, final boolean custom) + { + this.plugin = plugin; + if (!custom) + { + this.getConfig().options().header("Used for saving user statistics. Example user stats:"); + this.getConfig().addDefault("players.3c8c41ff-51f5-4b7a-8c2b-44df0beba03b.wins", 1); + this.getConfig().addDefault("players.3c8c41ff-51f5-4b7a-8c2b-44df0beba03b.loses", 1); + this.getConfig().addDefault("players.3c8c41ff-51f5-4b7a-8c2b-44df0beba03b.points", 10); + this.getConfig().addDefault("players.3c8c41ff-51f5-4b7a-8c2b-44df0beba03b.playername", "TheMrQuake"); + } + this.getConfig().options().copyDefaults(true); + this.saveConfig(); } - - public FileConfiguration getConfig() { - if (statsConfig == null) { - reloadConfig(); + + public FileConfiguration getConfig() + { + if (this.statsConfig == null) + { + this.reloadConfig(); } - return statsConfig; + return this.statsConfig; } - - public void saveConfig() { - if (statsConfig == null || statsFile == null) { + + public void saveConfig() + { + if (this.statsConfig == null || this.statsFile == null) + { return; } - try { - getConfig().save(statsFile); - } catch (IOException ex) { - + try + { + this.getConfig().save(this.statsFile); } - } - - public void reloadConfig() { - if (statsFile == null) { - statsFile = new File(plugin.getDataFolder(), "global_stats.yml"); + catch (final IOException ex) + { + // silently ignore } - statsConfig = YamlConfiguration.loadConfiguration(statsFile); + } - InputStream defConfigStream = plugin.getResource("global_stats.yml"); - if (defConfigStream != null) { - YamlConfiguration defConfig = YamlConfiguration.loadConfiguration(defConfigStream); - statsConfig.setDefaults(defConfig); + public void reloadConfig() + { + if (this.statsFile == null) + { + this.statsFile = new File(this.plugin.getDataFolder(), "global_stats.yml"); + } + this.statsConfig = YamlConfiguration.loadConfiguration(this.statsFile); + + final InputStream defConfigStream = this.plugin.getResource("global_stats.yml"); + if (defConfigStream != null) + { + final YamlConfiguration defConfig = YamlConfiguration.loadConfiguration(new InputStreamReader(defConfigStream)); + this.statsConfig.setDefaults(defConfig); } } - + } diff --git a/API/src/main/java/com/comze_instancelabs/minigamesapi/events/ArenaEvent.java b/API/src/main/java/com/comze_instancelabs/minigamesapi/events/ArenaEvent.java index 6960c2c0..9e62f34b 100644 --- a/API/src/main/java/com/comze_instancelabs/minigamesapi/events/ArenaEvent.java +++ b/API/src/main/java/com/comze_instancelabs/minigamesapi/events/ArenaEvent.java @@ -1,34 +1,42 @@ +/* + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ package com.comze_instancelabs.minigamesapi.events; import org.bukkit.event.Event; -import org.bukkit.event.HandlerList; import org.bukkit.plugin.java.JavaPlugin; import com.comze_instancelabs.minigamesapi.Arena; -public class ArenaEvent extends Event { - private static final HandlerList handlers = new HandlerList(); - private Arena arena; - private JavaPlugin plugin; - - public ArenaEvent(JavaPlugin plugin, Arena a) { - this.arena = a; - this.plugin = plugin; - } - - public Arena getArena() { - return arena; - } - - public JavaPlugin getPlugin() { - return plugin; - } - - public HandlerList getHandlers() { - return handlers; - } - - public static HandlerList getHandlerList() { - return handlers; - } +public abstract class ArenaEvent extends Event +{ + private final Arena arena; + private final JavaPlugin plugin; + + public ArenaEvent(final JavaPlugin plugin, final Arena a) + { + this.arena = a; + this.plugin = plugin; + } + + public Arena getArena() + { + return this.arena; + } + + public JavaPlugin getPlugin() + { + return this.plugin; + } } diff --git a/API/src/main/java/com/comze_instancelabs/minigamesapi/events/ArenaStartEvent.java b/API/src/main/java/com/comze_instancelabs/minigamesapi/events/ArenaStartEvent.java index 036b66e5..dc0ffdaa 100644 --- a/API/src/main/java/com/comze_instancelabs/minigamesapi/events/ArenaStartEvent.java +++ b/API/src/main/java/com/comze_instancelabs/minigamesapi/events/ArenaStartEvent.java @@ -1,15 +1,41 @@ +/* + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ package com.comze_instancelabs.minigamesapi.events; -import org.bukkit.event.Event; import org.bukkit.event.HandlerList; import org.bukkit.plugin.java.JavaPlugin; import com.comze_instancelabs.minigamesapi.Arena; -public class ArenaStartEvent extends ArenaEvent { +public class ArenaStartEvent extends ArenaEvent +{ + + public ArenaStartEvent(final JavaPlugin plugin, final Arena a) + { + super(plugin, a); + } - public ArenaStartEvent(JavaPlugin plugin, Arena a) { - super(plugin, a); - } + private static final HandlerList handlers = new HandlerList(); + @Override + public HandlerList getHandlers() + { + return handlers; + } + public static HandlerList getHandlerList() + { + return handlers; + } } diff --git a/API/src/main/java/com/comze_instancelabs/minigamesapi/events/ArenaStartedEvent.java b/API/src/main/java/com/comze_instancelabs/minigamesapi/events/ArenaStartedEvent.java index 9f892624..76a613ea 100644 --- a/API/src/main/java/com/comze_instancelabs/minigamesapi/events/ArenaStartedEvent.java +++ b/API/src/main/java/com/comze_instancelabs/minigamesapi/events/ArenaStartedEvent.java @@ -1,13 +1,40 @@ +/* + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ package com.comze_instancelabs.minigamesapi.events; +import org.bukkit.event.HandlerList; import org.bukkit.plugin.java.JavaPlugin; import com.comze_instancelabs.minigamesapi.Arena; -public class ArenaStartedEvent extends ArenaEvent { +public class ArenaStartedEvent extends ArenaEvent +{ + public ArenaStartedEvent(final JavaPlugin plugin, final Arena a) + { + super(plugin, a); + } - public ArenaStartedEvent(JavaPlugin plugin, Arena a) { - super(plugin, a); - } + private static final HandlerList handlers = new HandlerList(); + @Override + public HandlerList getHandlers() + { + return handlers; + } + public static HandlerList getHandlerList() + { + return handlers; + } } diff --git a/API/src/main/java/com/comze_instancelabs/minigamesapi/events/ArenaStopEvent.java b/API/src/main/java/com/comze_instancelabs/minigamesapi/events/ArenaStopEvent.java index fafb4d8c..042e47d9 100644 --- a/API/src/main/java/com/comze_instancelabs/minigamesapi/events/ArenaStopEvent.java +++ b/API/src/main/java/com/comze_instancelabs/minigamesapi/events/ArenaStopEvent.java @@ -1,13 +1,41 @@ +/* + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ package com.comze_instancelabs.minigamesapi.events; +import org.bukkit.event.HandlerList; import org.bukkit.plugin.java.JavaPlugin; import com.comze_instancelabs.minigamesapi.Arena; -public class ArenaStopEvent extends ArenaEvent { +public class ArenaStopEvent extends ArenaEvent +{ + + public ArenaStopEvent(final JavaPlugin plugin, final Arena a) + { + super(plugin, a); + } - public ArenaStopEvent(JavaPlugin plugin, Arena a) { - super(plugin, a); - } + private static final HandlerList handlers = new HandlerList(); + @Override + public HandlerList getHandlers() + { + return handlers; + } + public static HandlerList getHandlerList() + { + return handlers; + } } diff --git a/API/src/main/java/com/comze_instancelabs/minigamesapi/events/PlayerEvent.java b/API/src/main/java/com/comze_instancelabs/minigamesapi/events/PlayerEvent.java index d08b370e..4c6e4093 100644 --- a/API/src/main/java/com/comze_instancelabs/minigamesapi/events/PlayerEvent.java +++ b/API/src/main/java/com/comze_instancelabs/minigamesapi/events/PlayerEvent.java @@ -1,41 +1,50 @@ +/* + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ package com.comze_instancelabs.minigamesapi.events; import org.bukkit.entity.Player; import org.bukkit.event.Event; -import org.bukkit.event.HandlerList; import org.bukkit.plugin.java.JavaPlugin; import com.comze_instancelabs.minigamesapi.Arena; -public class PlayerEvent extends Event { - private static final HandlerList handlers = new HandlerList(); - private Arena arena; - private JavaPlugin plugin; - private Player player; - - public PlayerEvent(Player p, JavaPlugin plugin, Arena a) { - this.arena = a; - this.plugin = plugin; - this.player = p; - } - - public Arena getArena() { - return arena; - } - - public Player getPlayer() { - return player; - } - - public JavaPlugin getPlugin() { - return plugin; - } - - public HandlerList getHandlers() { - return handlers; - } - - public static HandlerList getHandlerList() { - return handlers; - } +public abstract class PlayerEvent extends Event +{ + private final Arena arena; + private final JavaPlugin plugin; + private final Player player; + + public PlayerEvent(final Player p, final JavaPlugin plugin, final Arena a) + { + this.arena = a; + this.plugin = plugin; + this.player = p; + } + + public Arena getArena() + { + return this.arena; + } + + public Player getPlayer() + { + return this.player; + } + + public JavaPlugin getPlugin() + { + return this.plugin; + } } diff --git a/API/src/main/java/com/comze_instancelabs/minigamesapi/events/PlayerJoinLobbyEvent.java b/API/src/main/java/com/comze_instancelabs/minigamesapi/events/PlayerJoinLobbyEvent.java index b0d63230..48f0fd78 100644 --- a/API/src/main/java/com/comze_instancelabs/minigamesapi/events/PlayerJoinLobbyEvent.java +++ b/API/src/main/java/com/comze_instancelabs/minigamesapi/events/PlayerJoinLobbyEvent.java @@ -1,14 +1,42 @@ +/* + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ package com.comze_instancelabs.minigamesapi.events; import org.bukkit.entity.Player; +import org.bukkit.event.HandlerList; import org.bukkit.plugin.java.JavaPlugin; import com.comze_instancelabs.minigamesapi.Arena; -public class PlayerJoinLobbyEvent extends PlayerEvent { +public class PlayerJoinLobbyEvent extends PlayerEvent +{ + + public PlayerJoinLobbyEvent(final Player p, final JavaPlugin plugin, final Arena a) + { + super(p, plugin, a); + } - public PlayerJoinLobbyEvent(Player p, JavaPlugin plugin, Arena a) { - super(p, plugin, a); - } + private static final HandlerList handlers = new HandlerList(); + @Override + public HandlerList getHandlers() + { + return handlers; + } + public static HandlerList getHandlerList() + { + return handlers; + } } diff --git a/API/src/main/java/com/comze_instancelabs/minigamesapi/events/PlayerLeaveArenaEvent.java b/API/src/main/java/com/comze_instancelabs/minigamesapi/events/PlayerLeaveArenaEvent.java index c7b05384..be76b8ef 100644 --- a/API/src/main/java/com/comze_instancelabs/minigamesapi/events/PlayerLeaveArenaEvent.java +++ b/API/src/main/java/com/comze_instancelabs/minigamesapi/events/PlayerLeaveArenaEvent.java @@ -1,14 +1,42 @@ +/* + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ package com.comze_instancelabs.minigamesapi.events; import org.bukkit.entity.Player; +import org.bukkit.event.HandlerList; import org.bukkit.plugin.java.JavaPlugin; import com.comze_instancelabs.minigamesapi.Arena; -public class PlayerLeaveArenaEvent extends PlayerEvent { +public class PlayerLeaveArenaEvent extends PlayerEvent +{ + + public PlayerLeaveArenaEvent(final Player p, final JavaPlugin plugin, final Arena a) + { + super(p, plugin, a); + } - public PlayerLeaveArenaEvent(Player p, JavaPlugin plugin, Arena a) { - super(p, plugin, a); - } + private static final HandlerList handlers = new HandlerList(); + @Override + public HandlerList getHandlers() + { + return handlers; + } + public static HandlerList getHandlerList() + { + return handlers; + } } diff --git a/API/src/main/java/com/comze_instancelabs/minigamesapi/guns/Gun.java b/API/src/main/java/com/comze_instancelabs/minigamesapi/guns/Gun.java index 8bf78920..4303eb56 100644 --- a/API/src/main/java/com/comze_instancelabs/minigamesapi/guns/Gun.java +++ b/API/src/main/java/com/comze_instancelabs/minigamesapi/guns/Gun.java @@ -1,3 +1,17 @@ +/* + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ package com.comze_instancelabs.minigamesapi.guns; import java.util.ArrayList; @@ -11,95 +25,99 @@ import org.bukkit.entity.Snowball; import org.bukkit.inventory.ItemStack; import org.bukkit.plugin.java.JavaPlugin; -import org.bukkit.util.Vector; - -public class Gun { - - public double speed = 1D; // the higher the faster - public int shoot_amount = 1; - public int max_durability = 50; - public int durability = 50; - public Class<? extends Projectile> bullet = Egg.class; - public JavaPlugin plugin; - public double knockback_multiplier = 1.1D; - public String name = "Gun"; - - boolean canshoot = true; - public HashMap<String, Boolean> canshoot_ = new HashMap<String, Boolean>(); - - ArrayList<ItemStack> items; - ArrayList<ItemStack> icon; - - public Gun(JavaPlugin plugin, String name, double speed, int shoot_amount, int durability, double knockback_multiplier, Class<? extends Projectile> bullet, ArrayList<ItemStack> items, ArrayList<ItemStack> icon) { - this.plugin = plugin; - this.name = name; - this.speed = speed; - this.shoot_amount = shoot_amount; - this.durability = durability; - this.max_durability = durability; - this.bullet = bullet; - this.knockback_multiplier = knockback_multiplier; - this.items = items; - this.icon = icon; - if(name.equalsIgnoreCase("grenade")){ - this.bullet = Snowball.class; - } - } - - public Gun(JavaPlugin plugin, ArrayList<ItemStack> items, ArrayList<ItemStack> icon) { - this(plugin, "Gun", 1D, 1, 50, 1.1D, Egg.class, items, icon); - } - - public void shoot(Player p) { - if(canshoot){ - for (int i = 0; i < shoot_amount; i++) { - p.launchProjectile(bullet); - this.durability -= 1; - } - canshoot = false; - Bukkit.getScheduler().runTaskLater(plugin, new Runnable(){ - public void run(){ - canshoot = true; - } - }, (long) (20D / speed)); - } - } - - public void shoot(final Player p, int shoot_amount, int durability, int speed) { - if(!canshoot_.containsKey(p.getName())){ - canshoot_.put(p.getName(), true); - } - if(canshoot_.get(p.getName())){ - for (int i = 0; i < shoot_amount + 1; i++) { - p.launchProjectile(bullet); - this.durability -= (int) (10D / durability); - } - canshoot_.put(p.getName(), false); - Bukkit.getScheduler().runTaskLater(plugin, new Runnable(){ - public void run(){ - canshoot_.put(p.getName(), true); - } - }, (long) (60D / speed)); - } - } - - public void onHit(Entity ent, int knockback_multiplier) { - if(this.name.equalsIgnoreCase("freeze")){ - final Player p = (Player) ent; - p.setWalkSpeed(0.0F); - Bukkit.getScheduler().runTaskLater(plugin, new Runnable(){ - public void run(){ - p.setWalkSpeed(0.2F); - } - }, 20L + 20L * knockback_multiplier); - }else{ - ent.setVelocity(ent.getLocation().getDirection().multiply((-1D) * knockback_multiplier)); - } - } - public void reloadGun(){ - this.durability = this.max_durability; - this.canshoot = true; - } - +public class Gun +{ + + public double speed = 1D; // the higher the faster + public int shoot_amount = 1; + public int max_durability = 50; + public int durability = 50; + public Class<? extends Projectile> bullet = Egg.class; + public JavaPlugin plugin; + public double knockback_multiplier = 1.1D; + public String name = "Gun"; + + boolean canshoot = true; + public HashMap<String, Boolean> canshoot_ = new HashMap<>(); + + ArrayList<ItemStack> items; + ArrayList<ItemStack> icon; + + public Gun(final JavaPlugin plugin, final String name, final double speed, final int shoot_amount, final int durability, final double knockback_multiplier, + final Class<? extends Projectile> bullet, final ArrayList<ItemStack> items, final ArrayList<ItemStack> icon) + { + this.plugin = plugin; + this.name = name; + this.speed = speed; + this.shoot_amount = shoot_amount; + this.durability = durability; + this.max_durability = durability; + this.bullet = bullet; + this.knockback_multiplier = knockback_multiplier; + this.items = items; + this.icon = icon; + if (name.equalsIgnoreCase("grenade")) + { + this.bullet = Snowball.class; + } + } + + public Gun(final JavaPlugin plugin, final ArrayList<ItemStack> items, final ArrayList<ItemStack> icon) + { + this(plugin, "Gun", 1D, 1, 50, 1.1D, Egg.class, items, icon); + } + + public void shoot(final Player p) + { + if (this.canshoot) + { + for (int i = 0; i < this.shoot_amount; i++) + { + p.launchProjectile(this.bullet); + this.durability -= 1; + } + this.canshoot = false; + Bukkit.getScheduler().runTaskLater(this.plugin, () -> Gun.this.canshoot = true, (long) (20D / this.speed)); + } + } + + public void shoot(final Player p, final int shoot_amount, final int durability, final int speed) + { + if (!this.canshoot_.containsKey(p.getName())) + { + this.canshoot_.put(p.getName(), true); + } + if (this.canshoot_.get(p.getName())) + { + for (int i = 0; i < shoot_amount + 1; i++) + { + p.launchProjectile(this.bullet); + this.durability -= (int) (10D / durability); + } + this.canshoot_.put(p.getName(), false); + Bukkit.getScheduler().runTaskLater(this.plugin, () -> Gun.this.canshoot_.put(p.getName(), true), (long) (60D / speed)); + } + } + + public void onHit(final Entity ent, final int knockback_multiplier) + { + if (this.name.equalsIgnoreCase("freeze")) + { + final Player p = (Player) ent; + p.setWalkSpeed(0.0F); + Bukkit.getScheduler().runTaskLater(this.plugin, () -> p.setWalkSpeed(0.2F), 20L + 20L * knockback_multiplier); + } + else + { + ent.setVelocity(ent.getLocation().getDirection().multiply((-1D) * knockback_multiplier)); + } + } + + public void reloadGun() + { + this.durability = this.max_durability; + this.canshoot = true; + } + } diff --git a/API/src/main/java/com/comze_instancelabs/minigamesapi/guns/Guns.java b/API/src/main/java/com/comze_instancelabs/minigamesapi/guns/Guns.java index 67158b56..4fbd7508 100644 --- a/API/src/main/java/com/comze_instancelabs/minigamesapi/guns/Guns.java +++ b/API/src/main/java/com/comze_instancelabs/minigamesapi/guns/Guns.java @@ -1,3 +1,17 @@ +/* + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ package com.comze_instancelabs.minigamesapi.guns; import java.util.ArrayList; @@ -15,331 +29,391 @@ import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.plugin.java.JavaPlugin; -import com.comze_instancelabs.minigamesapi.guns.Gun; import com.comze_instancelabs.minigamesapi.MinigamesAPI; import com.comze_instancelabs.minigamesapi.util.IconMenu; import com.comze_instancelabs.minigamesapi.util.Util; -public class Guns { - - // Four gun types: - // - default pistol - // - sniper - // - freeze gun - // - grenade launcher - - // Four upgradable attributes: - // - speed - // - durability - // - shoot_amount - // - knockback_multiplier - - // each attribute has 3 levels - // that gives us 4*4*3 = 48 levels - - // how much more the next level of an attribute will cost - public double level_multiplier = 3D; - - // attribute base costs - public int speed_cost = 40; - public int durability_cost = 30; - public int shoot_amount_cost = 70; - public int knockback_multiplier_cost = 100; - - public HashMap<String, IconMenu> lastmainiconm = new HashMap<String, IconMenu>(); - public HashMap<String, IconMenu> lastmainediticonm = new HashMap<String, IconMenu>(); - public HashMap<String, IconMenu> lastupgradeiconm = new HashMap<String, IconMenu>(); - - // TODO this means only for one plugin for now - public HashMap<String, HashMap<Gun, int[]>> pgunattributes = new HashMap<String, HashMap<Gun, int[]>>(); - - public JavaPlugin plugin; - - public Guns(JavaPlugin plugin) { - this.plugin = plugin; - } - - public void openGUI(String p) { - final int credits = MinigamesAPI.getAPI().getPluginInstance(plugin).getStatsInstance().getPoints(p); - IconMenu iconm; - if (lastmainiconm.containsKey(p)) { - iconm = lastmainiconm.get(p); - } else { - iconm = new IconMenu("Gun Upgrades (Credits: " + credits + ")", 36, new IconMenu.OptionClickEventHandler() { - @Override - public void onOptionClick(IconMenu.OptionClickEvent event) { - String d = event.getName(); - Player p = event.getPlayer(); - if (MinigamesAPI.getAPI().getPluginInstance(plugin).getAllGuns().containsKey(d)) { - openGunMainEditGUI(p.getName(), d); - } else { - String raw = event.getItem().getItemMeta().getLore().get(0); - String gun = raw.substring(0, raw.indexOf(" ")); - Gun g = MinigamesAPI.getAPI().getPluginInstance(plugin).getAllGuns().get(gun); - if (g != null) { - int[] pattributes = getPlayerGunAttributeLevels(plugin, p.getName(), g); - HashMap<Gun, int[]> t; - if (pgunattributes.containsKey(p.getName())) { - t = pgunattributes.get(p.getName()); - t.put(g, pattributes); - } else { - t = new HashMap<Gun, int[]>(); - t.put(g, pattributes); - } - pgunattributes.put(p.getName(), t); - boolean done = false; - double cost = 0.0D; - if (d.startsWith("Speed")) { - int i = pattributes[0]; - cost = Math.pow(level_multiplier, i) * speed_cost; - if (i < 3 && credits >= cost) { - openUpgradeGUI(p.getName(), gun, "speed", pattributes[0] + 1, cost); - done = true; - // setPlayerGunLevel(plugin, p.getName(), gun, "speed", pattributes[0] + 1); - } - } else if (d.startsWith("Durability")) { - int i = pattributes[1]; - cost = Math.pow(level_multiplier, i) * durability_cost; - if (i < 3 && credits >= cost) { - openUpgradeGUI(p.getName(), gun, "durability", pattributes[1] + 1, cost); - done = true; - } - } else if (d.startsWith("Shoot")) { - int i = pattributes[2]; - cost = Math.pow(level_multiplier, i) * shoot_amount_cost; - if (i < 3 && credits >= cost) { - openUpgradeGUI(p.getName(), gun, "shoot", pattributes[2] + 1, cost); - done = true; - } - } else if (d.startsWith("Knockback")) { - int i = pattributes[3]; - cost = Math.pow(level_multiplier, i) * knockback_multiplier_cost; - if (i < 3 && credits >= cost) { - openUpgradeGUI(p.getName(), gun, "knockback", pattributes[3] + 1, cost); - done = true; - } - } - if (!done) { - p.sendMessage(MinigamesAPI.getAPI().getPluginInstance(plugin).getMessagesConfig().not_enough_credits.replaceAll("<credits>", Double.toString(cost))); - } - } - } - event.setWillClose(false); - } - }, plugin); - lastmainiconm.put(p, iconm); - } - - int c = 0; - for (String ac : MinigamesAPI.getAPI().getPluginInstance(plugin).getAllGuns().keySet()) { - Gun ac_ = MinigamesAPI.getAPI().getPluginInstance(plugin).getAllGuns().get(ac); - int[] pattributes = getPlayerGunAttributeLevels(plugin, p, ac_); - iconm.setOption(c, ac_.icon.get(0), ac, MinigamesAPI.getAPI().getPluginInstance(plugin).getGunsConfig().getConfig().getString("config.guns." + ac + ".lore")); - iconm.setOption(c + 2, new ItemStack(Material.SUGAR), "Speed Lv " + ChatColor.DARK_RED + pattributes[0], ac + " Speed Upgrade"); - iconm.setOption(c + 3, new ItemStack(Material.DIAMOND), "Durability Lv " + ChatColor.DARK_RED + pattributes[1], ac + " Durability Upgrade"); - iconm.setOption(c + 4, new ItemStack(Material.EGG), "Shoot Lv " + ChatColor.DARK_RED + pattributes[2], ac + " Shoot amount Upgrade"); - iconm.setOption(c + 5, new ItemStack(Material.STICK), "Knockback Lv " + ChatColor.DARK_RED + pattributes[3], ac + " Knockback Upgrade"); - c += 9; - } - - iconm.open(Bukkit.getPlayerExact(p)); - } - - public int[] getPlayerGunAttributeLevels(JavaPlugin plugin, String p, Gun g) { - int[] ret = new int[4]; - FileConfiguration config = MinigamesAPI.getAPI().getPluginInstance(plugin).getGunsConfig().getConfig(); - String path = "players." + p + "." + g.name + "."; - ret[0] = config.isSet(path + "speed") ? config.getInt(path + "speed") : 0; - ret[1] = config.isSet(path + "durability") ? config.getInt(path + "durability") : 0; - ret[2] = config.isSet(path + "shoot") ? config.getInt(path + "shoot") : 0; - ret[3] = config.isSet(path + "knockback") ? config.getInt(path + "knockback") : 0; - HashMap<Gun, int[]> t; - if (pgunattributes.containsKey(p)) { - t = pgunattributes.get(p); - t.put(g, ret); - } else { - t = new HashMap<Gun, int[]>(); - t.put(g, ret); - } - pgunattributes.put(p, t); - return ret; - } - - public void setPlayerGunLevel(JavaPlugin plugin, String p, String g, String attribute, int level, double cost) { - int credits = MinigamesAPI.getAPI().getPluginInstance(plugin).getStatsInstance().getPoints(p); - FileConfiguration config = MinigamesAPI.getAPI().getPluginInstance(plugin).getGunsConfig().getConfig(); - String path = "players." + p + "." + g + "."; - config.set(path + attribute, level); - MinigamesAPI.getAPI().getPluginInstance(plugin).getGunsConfig().saveConfig(); - MinigamesAPI.getAPI().getPluginInstance(plugin).getStatsInstance().setPoints(p, (int) (credits - cost)); - } - - public void setPlayerGunMain(JavaPlugin plugin, String p, String g, boolean val) { - FileConfiguration config = MinigamesAPI.getAPI().getPluginInstance(plugin).getGunsConfig().getConfig(); - String path = "players." + p + "." + g + ".main"; - if (getPlayerAllMainGunsCount(plugin, p) > 1 && val) { - Bukkit.getPlayer(p).sendMessage(MinigamesAPI.getAPI().getPluginInstance(plugin).getMessagesConfig().too_many_main_guns); - return; - } - config.set(path, val); - MinigamesAPI.getAPI().getPluginInstance(plugin).getGunsConfig().saveConfig(); - } - - public int getPlayerAllMainGunsCount(JavaPlugin plugin, String p) { - FileConfiguration config = MinigamesAPI.getAPI().getPluginInstance(plugin).getGunsConfig().getConfig(); - String path = "players." + p + "."; - int ret = 0; - if (config.isSet(path)) { - for (String g : config.getConfigurationSection(path).getKeys(false)) { - if (config.isSet(path + g + ".main")) { - if (config.getBoolean(path + g + ".main")) { - ret++; - } - } - } - } - return ret; - } - - public void openGunMainEditGUI(String p, final String g) { - IconMenu iconm; - Player p_ = Bukkit.getPlayer(p); - String guns = ""; - for (String gun : getAllMainGuns(p_)) { - guns += gun + ", "; - } - if(guns.equalsIgnoreCase("")){ - guns = "--"; - } - guns = guns.substring(0, guns.length() - 2); - p_.sendMessage(MinigamesAPI.getAPI().getPluginInstance(plugin).getMessagesConfig().all_guns.replaceAll("<guns>", guns)); - - if (lastmainediticonm.containsKey(p)) { - iconm = lastmainediticonm.get(p); - } else { - iconm = new IconMenu("Set Main Gun", 9, new IconMenu.OptionClickEventHandler() { - @Override - public void onOptionClick(IconMenu.OptionClickEvent event) { - String d = event.getName(); - Player p = event.getPlayer(); - if (d.startsWith("Set")) { - setPlayerGunMain(plugin, p.getName(), g, true); - } else if (d.startsWith("Remove")) { - setPlayerGunMain(plugin, p.getName(), g, false); - } - openGUI(p.getName()); - event.setWillClose(false); - event.setWillDestroy(true); - } - }, plugin); - } - - iconm.setOption(0, new ItemStack(Material.WOOL, 1, (short) 5), "Set " + g + " as Main/Secondary Gun", ""); - iconm.setOption(8, new ItemStack(Material.WOOL, 1, (short) 14), "Remove " + g + " as Main/Secondary Gun", ""); - - iconm.open(Bukkit.getPlayerExact(p)); - } - - public void openUpgradeGUI(String p, final String g, final String attribute, final int level, final double cost) { - IconMenu iconm; - if (lastupgradeiconm.containsKey(p)) { - iconm = lastupgradeiconm.get(p); - } else { - iconm = new IconMenu("Upgrade?", 9, new IconMenu.OptionClickEventHandler() { - @Override - public void onOptionClick(IconMenu.OptionClickEvent event) { - String d = event.getName(); - Player p = event.getPlayer(); - if (d.startsWith("Buy")) { - setPlayerGunLevel(plugin, p.getName(), g, attribute, level, cost); - p.sendMessage(MinigamesAPI.getAPI().getPluginInstance(plugin).getMessagesConfig().attributelevel_increased.replaceAll("<attribute>", attribute)); - } - openGUI(p.getName()); - event.setWillClose(false); - event.setWillDestroy(true); - } - }, plugin); - } - - iconm.setOption(0, new ItemStack(Material.WOOL, 1, (short) 5), "Buy " + attribute + " Upgrade", ""); - iconm.setOption(8, new ItemStack(Material.WOOL, 1, (short) 14), "DON'T buy " + attribute + " Upgrade", ""); - - iconm.open(Bukkit.getPlayerExact(p)); - } - - public static void loadGuns(JavaPlugin plugin) { - FileConfiguration config = MinigamesAPI.getAPI().getPluginInstance(plugin).getGunsConfig().getConfig(); - if (config.isSet("config.guns")) { - for (String gun : config.getConfigurationSection("config.guns.").getKeys(false)) { - String path = "config.guns." + gun + "."; - Gun n = new Gun(plugin, gun, config.getDouble(path + "speed"), config.getInt(path + "durability"), config.getInt(path + "shoot_amount"), config.getDouble(path + "knockback_multiplier"), Egg.class, Util.parseItems(config.getString(path + "items")), Util.parseItems(config.getString(path + "icon"))); - MinigamesAPI.getAPI().getPluginInstance(plugin).addGun(gun, n); - } - } - } - - public ArrayList<String> getAllMainGuns(Player p) { - FileConfiguration config = MinigamesAPI.getAPI().getPluginInstance(plugin).getGunsConfig().getConfig(); - ArrayList<String> ret = new ArrayList<String>(); - if(config.isSet("players." + p.getName())){ - for (String gun : config.getConfigurationSection("players." + p.getName() + ".").getKeys(false)) { - String path = "players." + p.getName() + "." + gun + ".main"; - if (config.isSet(path)) { - if(config.getBoolean(path)){ - ret.add(gun); - } - } - } - } - return ret; - } - - public void giveMainGuns(Player p) { - FileConfiguration config = MinigamesAPI.getAPI().getPluginInstance(plugin).getGunsConfig().getConfig(); - if (config.isSet("players." + p.getName() + ".")) { - int count = 0; - for (String gun : config.getConfigurationSection("players." + p.getName() + ".").getKeys(false)) { - String path = "players." + p.getName() + "." + gun + ".main"; - if (config.isSet(path)) { - if (config.getBoolean(path)) { - // main gun - Gun g = MinigamesAPI.getAPI().getPluginInstance(plugin).getAllGuns().get(gun); - if (g != null) { - p.updateInventory(); - for (ItemStack i : g.items) { - ItemStack temp = i; - ItemMeta itemm = temp.getItemMeta(); - itemm.setDisplayName(gun); - //System.out.println(itemm.getDisplayName()); - temp.setItemMeta(itemm); - p.getInventory().addItem(temp); - } - p.updateInventory(); - count++; - } - } - } - } - if (count < 1) { - // player doesn't have any main, give random gun - HashMap<String, Gun> guns = MinigamesAPI.getAPI().getPluginInstance(plugin).getAllGuns(); - List<String> t = new ArrayList<String>(guns.keySet()); - String gun = t.get((new Random()).nextInt(t.size())); - Gun g = guns.get(gun); - if (g != null) { - p.updateInventory(); - for (ItemStack i : g.items) { - ItemStack temp = i; - ItemMeta itemm = temp.getItemMeta(); - itemm.setDisplayName(gun); - temp.setItemMeta(itemm); - p.getInventory().addItem(temp); - } - p.updateInventory(); - count++; - } - } - } - } - +public class Guns +{ + + // Four gun types: + // - default pistol + // - sniper + // - freeze gun + // - grenade launcher + + // Four upgradable attributes: + // - speed + // - durability + // - shoot_amount + // - knockback_multiplier + + // each attribute has 3 levels + // that gives us 4*4*3 = 48 levels + + // how much more the next level of an attribute will cost + public double level_multiplier = 3D; + + // attribute base costs + public int speed_cost = 40; + public int durability_cost = 30; + public int shoot_amount_cost = 70; + public int knockback_multiplier_cost = 100; + + public HashMap<String, IconMenu> lastmainiconm = new HashMap<>(); + public HashMap<String, IconMenu> lastmainediticonm = new HashMap<>(); + public HashMap<String, IconMenu> lastupgradeiconm = new HashMap<>(); + + // TODO this means only for one plugin for now + public HashMap<String, HashMap<Gun, int[]>> pgunattributes = new HashMap<>(); + + public JavaPlugin plugin; + + public Guns(final JavaPlugin plugin) + { + this.plugin = plugin; + } + + public void openGUI(final String p) + { + final int credits = MinigamesAPI.getAPI().getPluginInstance(this.plugin).getStatsInstance().getPoints(p); + IconMenu iconm; + if (this.lastmainiconm.containsKey(p)) + { + iconm = this.lastmainiconm.get(p); + } + else + { + iconm = new IconMenu("Gun Upgrades (Credits: " + credits + ")", 36, event -> { + final String d = event.getName(); + final Player p1 = event.getPlayer(); + if (MinigamesAPI.getAPI().getPluginInstance(Guns.this.plugin).getAllGuns().containsKey(d)) + { + Guns.this.openGunMainEditGUI(p1.getName(), d); + } + else + { + final String raw = event.getItem().getItemMeta().getLore().get(0); + final String gun = raw.substring(0, raw.indexOf(" ")); + final Gun g = MinigamesAPI.getAPI().getPluginInstance(Guns.this.plugin).getAllGuns().get(gun); + if (g != null) + { + final int[] pattributes = Guns.this.getPlayerGunAttributeLevels(Guns.this.plugin, p1.getName(), g); + HashMap<Gun, int[]> t; + if (Guns.this.pgunattributes.containsKey(p1.getName())) + { + t = Guns.this.pgunattributes.get(p1.getName()); + t.put(g, pattributes); + } + else + { + t = new HashMap<>(); + t.put(g, pattributes); + } + Guns.this.pgunattributes.put(p1.getName(), t); + boolean done = false; + double cost = 0.0D; + if (d.startsWith("Speed")) + { + final int i1 = pattributes[0]; + cost = Math.pow(Guns.this.level_multiplier, i1) * Guns.this.speed_cost; + if (i1 < 3 && credits >= cost) + { + Guns.this.openUpgradeGUI(p1.getName(), gun, "speed", pattributes[0] + 1, cost); + done = true; + // setPlayerGunLevel(plugin, p.getName(), gun, "speed", pattributes[0] + 1); + } + } + else if (d.startsWith("Durability")) + { + final int i2 = pattributes[1]; + cost = Math.pow(Guns.this.level_multiplier, i2) * Guns.this.durability_cost; + if (i2 < 3 && credits >= cost) + { + Guns.this.openUpgradeGUI(p1.getName(), gun, "durability", pattributes[1] + 1, cost); + done = true; + } + } + else if (d.startsWith("Shoot")) + { + final int i3 = pattributes[2]; + cost = Math.pow(Guns.this.level_multiplier, i3) * Guns.this.shoot_amount_cost; + if (i3 < 3 && credits >= cost) + { + Guns.this.openUpgradeGUI(p1.getName(), gun, "shoot", pattributes[2] + 1, cost); + done = true; + } + } + else if (d.startsWith("Knockback")) + { + final int i4 = pattributes[3]; + cost = Math.pow(Guns.this.level_multiplier, i4) * Guns.this.knockback_multiplier_cost; + if (i4 < 3 && credits >= cost) + { + Guns.this.openUpgradeGUI(p1.getName(), gun, "knockback", pattributes[3] + 1, cost); + done = true; + } + } + if (!done) + { + p1.sendMessage(MinigamesAPI.getAPI().getPluginInstance(Guns.this.plugin).getMessagesConfig().not_enough_credits.replaceAll("<credits>", Double.toString(cost))); + } + } + } + event.setWillClose(false); + }, this.plugin); + this.lastmainiconm.put(p, iconm); + } + + int c = 0; + for (final String ac : MinigamesAPI.getAPI().getPluginInstance(this.plugin).getAllGuns().keySet()) + { + final Gun ac_ = MinigamesAPI.getAPI().getPluginInstance(this.plugin).getAllGuns().get(ac); + final int[] pattributes = this.getPlayerGunAttributeLevels(this.plugin, p, ac_); + iconm.setOption(c, ac_.icon.get(0), ac, MinigamesAPI.getAPI().getPluginInstance(this.plugin).getGunsConfig().getConfig().getString("config.guns." + ac + ".lore")); + iconm.setOption(c + 2, new ItemStack(Material.SUGAR), "Speed Lv " + ChatColor.DARK_RED + pattributes[0], ac + " Speed Upgrade"); + iconm.setOption(c + 3, new ItemStack(Material.DIAMOND), "Durability Lv " + ChatColor.DARK_RED + pattributes[1], ac + " Durability Upgrade"); + iconm.setOption(c + 4, new ItemStack(Material.EGG), "Shoot Lv " + ChatColor.DARK_RED + pattributes[2], ac + " Shoot amount Upgrade"); + iconm.setOption(c + 5, new ItemStack(Material.STICK), "Knockback Lv " + ChatColor.DARK_RED + pattributes[3], ac + " Knockback Upgrade"); + c += 9; + } + + iconm.open(Bukkit.getPlayerExact(p)); + } + + public int[] getPlayerGunAttributeLevels(final JavaPlugin plugin, final String p, final Gun g) + { + final int[] ret = new int[4]; + final FileConfiguration config = MinigamesAPI.getAPI().getPluginInstance(plugin).getGunsConfig().getConfig(); + final String path = "players." + p + "." + g.name + "."; + ret[0] = config.isSet(path + "speed") ? config.getInt(path + "speed") : 0; + ret[1] = config.isSet(path + "durability") ? config.getInt(path + "durability") : 0; + ret[2] = config.isSet(path + "shoot") ? config.getInt(path + "shoot") : 0; + ret[3] = config.isSet(path + "knockback") ? config.getInt(path + "knockback") : 0; + HashMap<Gun, int[]> t; + if (this.pgunattributes.containsKey(p)) + { + t = this.pgunattributes.get(p); + t.put(g, ret); + } + else + { + t = new HashMap<>(); + t.put(g, ret); + } + this.pgunattributes.put(p, t); + return ret; + } + + public void setPlayerGunLevel(final JavaPlugin plugin, final String p, final String g, final String attribute, final int level, final double cost) + { + final int credits = MinigamesAPI.getAPI().getPluginInstance(plugin).getStatsInstance().getPoints(p); + final FileConfiguration config = MinigamesAPI.getAPI().getPluginInstance(plugin).getGunsConfig().getConfig(); + final String path = "players." + p + "." + g + "."; + config.set(path + attribute, level); + MinigamesAPI.getAPI().getPluginInstance(plugin).getGunsConfig().saveConfig(); + MinigamesAPI.getAPI().getPluginInstance(plugin).getStatsInstance().setPoints(p, (int) (credits - cost)); + } + + public void setPlayerGunMain(final JavaPlugin plugin, final String p, final String g, final boolean val) + { + final FileConfiguration config = MinigamesAPI.getAPI().getPluginInstance(plugin).getGunsConfig().getConfig(); + final String path = "players." + p + "." + g + ".main"; + if (this.getPlayerAllMainGunsCount(plugin, p) > 1 && val) + { + Bukkit.getPlayer(p).sendMessage(MinigamesAPI.getAPI().getPluginInstance(plugin).getMessagesConfig().too_many_main_guns); + return; + } + config.set(path, val); + MinigamesAPI.getAPI().getPluginInstance(plugin).getGunsConfig().saveConfig(); + } + + public int getPlayerAllMainGunsCount(final JavaPlugin plugin, final String p) + { + final FileConfiguration config = MinigamesAPI.getAPI().getPluginInstance(plugin).getGunsConfig().getConfig(); + final String path = "players." + p + "."; + int ret = 0; + if (config.isSet(path)) + { + for (final String g : config.getConfigurationSection(path).getKeys(false)) + { + if (config.isSet(path + g + ".main")) + { + if (config.getBoolean(path + g + ".main")) + { + ret++; + } + } + } + } + return ret; + } + + public void openGunMainEditGUI(final String p, final String g) + { + IconMenu iconm; + final Player p_ = Bukkit.getPlayer(p); + String guns = ""; + for (final String gun : this.getAllMainGuns(p_)) + { + guns += gun + ", "; + } + if (guns.equalsIgnoreCase("")) + { + guns = "--"; + } + guns = guns.substring(0, guns.length() - 2); + p_.sendMessage(MinigamesAPI.getAPI().getPluginInstance(this.plugin).getMessagesConfig().all_guns.replaceAll("<guns>", guns)); + + if (this.lastmainediticonm.containsKey(p)) + { + iconm = this.lastmainediticonm.get(p); + } + else + { + iconm = new IconMenu("Set Main Gun", 9, event -> { + final String d = event.getName(); + final Player p1 = event.getPlayer(); + if (d.startsWith("Set")) + { + Guns.this.setPlayerGunMain(Guns.this.plugin, p1.getName(), g, true); + } + else if (d.startsWith("Remove")) + { + Guns.this.setPlayerGunMain(Guns.this.plugin, p1.getName(), g, false); + } + Guns.this.openGUI(p1.getName()); + event.setWillClose(false); + event.setWillDestroy(true); + }, this.plugin); + } + + iconm.setOption(0, new ItemStack(Material.WOOL, 1, (short) 5), "Set " + g + " as Main/Secondary Gun", ""); + iconm.setOption(8, new ItemStack(Material.WOOL, 1, (short) 14), "Remove " + g + " as Main/Secondary Gun", ""); + + iconm.open(Bukkit.getPlayerExact(p)); + } + + public void openUpgradeGUI(final String p, final String g, final String attribute, final int level, final double cost) + { + IconMenu iconm; + if (this.lastupgradeiconm.containsKey(p)) + { + iconm = this.lastupgradeiconm.get(p); + } + else + { + iconm = new IconMenu("Upgrade?", 9, event -> { + final String d = event.getName(); + final Player p1 = event.getPlayer(); + if (d.startsWith("Buy")) + { + Guns.this.setPlayerGunLevel(Guns.this.plugin, p1.getName(), g, attribute, level, cost); + p1.sendMessage(MinigamesAPI.getAPI().getPluginInstance(Guns.this.plugin).getMessagesConfig().attributelevel_increased.replaceAll("<attribute>", attribute)); + } + Guns.this.openGUI(p1.getName()); + event.setWillClose(false); + event.setWillDestroy(true); + }, this.plugin); + } + + iconm.setOption(0, new ItemStack(Material.WOOL, 1, (short) 5), "Buy " + attribute + " Upgrade", ""); + iconm.setOption(8, new ItemStack(Material.WOOL, 1, (short) 14), "DON'T buy " + attribute + " Upgrade", ""); + + iconm.open(Bukkit.getPlayerExact(p)); + } + + public static void loadGuns(final JavaPlugin plugin) + { + final FileConfiguration config = MinigamesAPI.getAPI().getPluginInstance(plugin).getGunsConfig().getConfig(); + if (config.isSet("config.guns")) + { + for (final String gun : config.getConfigurationSection("config.guns.").getKeys(false)) + { + final String path = "config.guns." + gun + "."; + final Gun n = new Gun(plugin, gun, config.getDouble(path + "speed"), config.getInt(path + "durability"), config.getInt(path + "shoot_amount"), + config.getDouble(path + "knockback_multiplier"), Egg.class, Util.parseItems(config.getString(path + "items")), Util.parseItems(config.getString(path + "icon"))); + MinigamesAPI.getAPI().getPluginInstance(plugin).addGun(gun, n); + } + } + } + + public ArrayList<String> getAllMainGuns(final Player p) + { + final FileConfiguration config = MinigamesAPI.getAPI().getPluginInstance(this.plugin).getGunsConfig().getConfig(); + final ArrayList<String> ret = new ArrayList<>(); + if (config.isSet("players." + p.getName())) + { + for (final String gun : config.getConfigurationSection("players." + p.getName() + ".").getKeys(false)) + { + final String path = "players." + p.getName() + "." + gun + ".main"; + if (config.isSet(path)) + { + if (config.getBoolean(path)) + { + ret.add(gun); + } + } + } + } + return ret; + } + + public void giveMainGuns(final Player p) + { + final FileConfiguration config = MinigamesAPI.getAPI().getPluginInstance(this.plugin).getGunsConfig().getConfig(); + if (config.isSet("players." + p.getName() + ".")) + { + int count = 0; + for (final String gun : config.getConfigurationSection("players." + p.getName() + ".").getKeys(false)) + { + final String path = "players." + p.getName() + "." + gun + ".main"; + if (config.isSet(path)) + { + if (config.getBoolean(path)) + { + // main gun + final Gun g = MinigamesAPI.getAPI().getPluginInstance(this.plugin).getAllGuns().get(gun); + if (g != null) + { + p.updateInventory(); + for (final ItemStack i : g.items) + { + final ItemStack temp = i; + final ItemMeta itemm = temp.getItemMeta(); + itemm.setDisplayName(gun); + temp.setItemMeta(itemm); + p.getInventory().addItem(temp); + } + p.updateInventory(); + count++; + } + } + } + } + if (count < 1) + { + // player doesn't have any main, give random gun + final HashMap<String, Gun> guns = MinigamesAPI.getAPI().getPluginInstance(this.plugin).getAllGuns(); + final List<String> t = new ArrayList<>(guns.keySet()); + final String gun = t.get((new Random()).nextInt(t.size())); + final Gun g = guns.get(gun); + if (g != null) + { + p.updateInventory(); + for (final ItemStack i : g.items) + { + final ItemStack temp = i; + final ItemMeta itemm = temp.getItemMeta(); + itemm.setDisplayName(gun); + temp.setItemMeta(itemm); + p.getInventory().addItem(temp); + } + p.updateInventory(); + count++; + } + } + } + } + } diff --git a/API/src/main/java/com/comze_instancelabs/minigamesapi/messages.properties b/API/src/main/java/com/comze_instancelabs/minigamesapi/messages.properties new file mode 100644 index 00000000..58ab066f --- /dev/null +++ b/API/src/main/java/com/comze_instancelabs/minigamesapi/messages.properties @@ -0,0 +1,40 @@ +Arena.BoundariesInvalid=&cThe boundaries of an arena appear to be invalid (missing world?), please fix\! Arena: %0$s +Arena.SaveFailedBoundaries=&cFailed to save arenas as you forgot to set boundaries or they could not be found. This will lead to errors later, please fix your setup. %0$s +MinigamesAPI.AllSignsUpdated=�aAll signs updated\! +MinigamesAPI.CannotFindParticleEffect=�cCouldn't find particle effect. +MinigamesAPI.DebugAllPlayers=~ All players for %0$s: +MinigamesAPI.DebugAllPlayersLine=�7 %0$s %1$s %2$s +MinigamesAPI.DebugArenas=~ Arenas: +MinigamesAPI.DebugArenasLine=\ %0$s - %1$s +MinigamesAPI.DebugGlobalLost=~ global_lost: +MinigamesAPI.DebugGlobalLostLine=\ %0$s +MinigamesAPI.DebugGlobalPlayers=~ global_players: +MinigamesAPI.DebugGlobalPlayersLine=\ %0$s +MinigamesAPI.DebugInfoHeader=Debug info about +MinigamesAPI.DebugSpectatorManager=~ SpectatorManager: +MinigamesAPI.DebugSpectatorManagerLine=\ %0$s +MinigamesAPI.ExecuteIngame=Please execute this command ingame. +MinigamesAPI.ListArenasLine=~ %0$s: %1$d Arenas +MinigamesAPI.MgApiSubcommandDebug=/mapi debug +MinigamesAPI.MgApiSubcommandHologram=/mapi hologram +MinigamesAPI.MgApiSubcommandInfo=/mapi info <player> +MinigamesAPI.MgApiSubcommandList=/mapi list +MinigamesAPI.MgApiSubcommandPotionEffect=/mapi <potioneffect> +MinigamesAPI.MgApiSubcommands=�6Subcommands: +MinigamesAPI.MgApiSubcommandSigns=/mapi signs - Update all signs +MinigamesAPI.MgApiSubcommandStatsHologram=/mapi setstatshologram +MinigamesAPI.MgApiSubcommandSubtitle=/mapi subtitle <subtitle> +MinigamesAPI.MgApiSubcommandTitle=/mapi title <title> +MinigamesAPI.MinigamesLibHeader=�6�lMinigamesLib <3 %0$s +MinigamesAPI.NoMinigamesFound=~ No installed minigames found\! Download/Install some from the project page. +MinigamesAPI.NoPermissionForStart=�c�lYou are not allowed to use command /start. +MinigamesAPI.PlayingHologram=Playing hologram. +MinigamesAPI.PlayingStatsHologram=Playing statistics hologram. +MinigamesAPI.PluginArenaCount=~ �7 %0$s: �f%1$d Arenas +MinigamesAPI.SetDebugMode=�6Debug mode is now: %0$s +MinigamesAPI.Started=started +MinigamesAPI.StartNotWithinArena=�c�lYou are not within any arena. Nothing found to start. +MinigamesAPI.StatsDeaths=Deaths: +MinigamesAPI.StatsKills=Kills: +MinigamesAPI.StatsPotions=Potions: +MinigamesAPI.StatsWins=Wins: diff --git a/API/src/main/java/com/comze_instancelabs/minigamesapi/sql/Database.java b/API/src/main/java/com/comze_instancelabs/minigamesapi/sql/Database.java deleted file mode 100644 index 33120b15..00000000 --- a/API/src/main/java/com/comze_instancelabs/minigamesapi/sql/Database.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.comze_instancelabs.minigamesapi.sql; // replace this with yours - - -import java.sql.Connection; - - -public abstract class Database -{ - protected boolean connected; - protected Connection connection; - public int lastUpdate; - - - public Database() - { - this.connected = false; - this.connection = null; - } - - - protected Statements getStatement(String query) { - String trimmedQuery = query.trim(); - if (trimmedQuery.substring(0, 6).equalsIgnoreCase("SELECT")) - return Statements.SELECT; - if (trimmedQuery.substring(0, 6).equalsIgnoreCase("INSERT")) - return Statements.INSERT; - if (trimmedQuery.substring(0, 6).equalsIgnoreCase("UPDATE")) - return Statements.UPDATE; - if (trimmedQuery.substring(0, 6).equalsIgnoreCase("DELETE")) - return Statements.DELETE; - if (trimmedQuery.substring(0, 6).equalsIgnoreCase("CREATE")) - return Statements.CREATE; - if (trimmedQuery.substring(0, 5).equalsIgnoreCase("ALTER")) - return Statements.ALTER; - if (trimmedQuery.substring(0, 4).equalsIgnoreCase("DROP")) - return Statements.DROP; - if (trimmedQuery.substring(0, 8).equalsIgnoreCase("TRUNCATE")) - return Statements.TRUNCATE; - if (trimmedQuery.substring(0, 6).equalsIgnoreCase("RENAME")) - return Statements.RENAME; - if (trimmedQuery.substring(0, 2).equalsIgnoreCase("DO")) - return Statements.DO; - if (trimmedQuery.substring(0, 7).equalsIgnoreCase("REPLACE")) - return Statements.REPLACE; - if (trimmedQuery.substring(0, 4).equalsIgnoreCase("LOAD")) - return Statements.LOAD; - if (trimmedQuery.substring(0, 7).equalsIgnoreCase("HANDLER")) - return Statements.HANDLER; - if (trimmedQuery.substring(0, 4).equalsIgnoreCase("CALL")) { - return Statements.CALL; - } - return Statements.SELECT; - } - - - protected static enum Statements - { - SELECT, INSERT, UPDATE, DELETE, DO, REPLACE, LOAD, HANDLER, CALL, - CREATE, ALTER, DROP, TRUNCATE, RENAME, START, COMMIT, ROLLBACK, - SAVEPOINT, LOCK, UNLOCK, PREPARE, EXECUTE, DEALLOCATE, SET, SHOW, - DESCRIBE, EXPLAIN, HELP, USE, ANALYZE, ATTACH, BEGIN, DETACH, - END, INDEXED, ON, PRAGMA, REINDEX, RELEASE, VACUUM; - } -} \ No newline at end of file diff --git a/API/src/main/java/com/comze_instancelabs/minigamesapi/sql/MainSQL.java b/API/src/main/java/com/comze_instancelabs/minigamesapi/sql/MainSQL.java index a11fd440..18ebab2d 100644 --- a/API/src/main/java/com/comze_instancelabs/minigamesapi/sql/MainSQL.java +++ b/API/src/main/java/com/comze_instancelabs/minigamesapi/sql/MainSQL.java @@ -1,264 +1,747 @@ +/* + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ package com.comze_instancelabs.minigamesapi.sql; -import org.bukkit.entity.Player; -import org.bukkit.plugin.java.JavaPlugin; - -import com.comze_instancelabs.minigamesapi.sql.MySQL; -import com.comze_instancelabs.minigamesapi.sql.SQLite; - import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; +import java.sql.Statement; +import java.util.logging.Level; -public class MainSQL { - - // used for rewards and stats - - JavaPlugin plugin = null; - private boolean mysql = true; // false for sqlite - MySQL MySQL; - SQLite SQLite; - - // Set to true if tables don't contain UUIDs - boolean oldFormat = false; - - public MainSQL(JavaPlugin plugin, boolean mysql) { - this.plugin = plugin; - this.mysql = mysql; - - if (mysql) { - MySQL = new MySQL(plugin.getConfig().getString("mysql.host"), "3306", plugin.getConfig().getString("mysql.database"), plugin.getConfig().getString("mysql.user"), plugin.getConfig().getString("mysql.pw")); - } else { - SQLite = new SQLite(plugin.getConfig().getString("mysql.database"), plugin.getConfig().getString("mysql.user"), plugin.getConfig().getString("mysql.pw")); - } - - if (plugin.getConfig().getBoolean("mysql.enabled") && MySQL != null) { - try { - this.createTables(); - } catch (Exception e) { - System.out.println("Failed initializing MySQL. Disabling!"); - plugin.getConfig().set("mysql.enabled", false); - plugin.saveConfig(); - } - } else if (plugin.getConfig().getBoolean("mysql.enabled") && MySQL == null) { - System.out.println("Failed initializing MySQL. Disabling!"); - plugin.getConfig().set("mysql.enabled", false); - plugin.saveConfig(); - } - } - - public void createTables() { - if (!plugin.getConfig().getBoolean("mysql.enabled")) { - return; - } - if (!mysql) { - // TODO SQLite - } - Connection c = MySQL.open(); - - try { - c.createStatement().execute("CREATE DATABASE IF NOT EXISTS `" + plugin.getConfig().getString("mysql.database") + "`"); - c.createStatement().execute("CREATE TABLE IF NOT EXISTS " + plugin.getName() + " (id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, player VARCHAR(100), points INT, wins INT, loses INT, kills INT)"); - ResultSet res = c.createStatement().executeQuery("SHOW COLUMNS FROM `" + plugin.getName() + "` LIKE 'kills'"); - if (!res.isBeforeFirst()) { - // old table format without kills column -> add kills column - c.createStatement().execute("ALTER TABLE " + plugin.getName() + " ADD kills INT"); - } - ResultSet res2 = c.createStatement().executeQuery("SHOW COLUMNS FROM `" + plugin.getName() + "` LIKE 'deaths'"); - if (!res2.isBeforeFirst()) { - // old table format without deaths column -> add deaths column - c.createStatement().execute("ALTER TABLE " + plugin.getName() + " ADD deaths INT"); - } - ResultSet res3 = c.createStatement().executeQuery("SHOW COLUMNS FROM `" + plugin.getName() + "` LIKE 'uuid'"); - if (!res3.isBeforeFirst()) { - // old table format without uuid column -> add uuid column - c.createStatement().execute("ALTER TABLE " + plugin.getName() + " ADD uuid VARCHAR(100)"); - oldFormat = true; - } - } catch (SQLException e) { - e.printStackTrace(); - } - } - - public void updateWinnerStats(Player p, int reward, boolean addwin) { - if (!plugin.getConfig().getBoolean("mysql.enabled")) { - return; - } - if (!mysql) { - // TODO SQLite - } - String uuid = p.getUniqueId().toString(); - Connection c = MySQL.open(); - - int wincount = addwin ? 1 : 0; - - try { - if (oldFormat) { - c.createStatement().executeUpdate("UPDATE " + plugin.getName() + " SET uuid='" + uuid + "' WHERE player='" + p.getName() + "'"); - } - ResultSet res3 = c.createStatement().executeQuery("SELECT * FROM " + plugin.getName() + " WHERE uuid='" + uuid + "'"); - if (!res3.isBeforeFirst()) { - // there's no such user - c.createStatement().executeUpdate("INSERT INTO " + plugin.getName() + " VALUES('0', '" + p.getName() + "', '" + Integer.toString(reward) + "', '" + Integer.toString(wincount) + "', '0', '0', '0', '" + uuid + "')"); - return; - } - res3.next(); - int points = res3.getInt("points") + reward; - int wins = res3.getInt("wins") + wincount; - - c.createStatement().executeUpdate("UPDATE " + plugin.getName() + " SET points='" + Integer.toString(points) + "', wins='" + Integer.toString(wins) + "' WHERE uuid='" + uuid + "'"); - - } catch (SQLException e) { - e.printStackTrace(); - } - } - - public void updateLoserStats(Player p) { - if (!plugin.getConfig().getBoolean("mysql.enabled")) { - return; - } - if (!mysql) { - // TODO SQLite - } - String uuid = p.getUniqueId().toString(); - Connection c = MySQL.open(); - - try { - if (oldFormat) { - c.createStatement().executeUpdate("UPDATE " + plugin.getName() + " SET uuid='" + uuid + "' WHERE player='" + p.getName() + "'"); - } - ResultSet res3 = c.createStatement().executeQuery("SELECT * FROM " + plugin.getName() + " WHERE uuid='" + uuid + "'"); - if (!res3.isBeforeFirst()) { - // there's no such user - c.createStatement().executeUpdate("INSERT INTO " + plugin.getName() + " VALUES('0', '" + p.getName() + "', '0', '0', '1', '0', '0', '" + uuid + "')"); - return; - } - res3.next(); - int loses = res3.getInt("loses") + 1; - - c.createStatement().executeUpdate("UPDATE " + plugin.getName() + " SET loses='" + Integer.toString(loses) + "' WHERE uuid='" + uuid + "'"); - - } catch (SQLException e) { - e.printStackTrace(); - } - } - - public void updateKillerStats(Player p, int kills_) { - if (!plugin.getConfig().getBoolean("mysql.enabled")) { - return; - } - if (!mysql) { - // TODO SQLite - } - String uuid = p.getUniqueId().toString(); - Connection c = MySQL.open(); - - try { - if (oldFormat) { - c.createStatement().executeUpdate("UPDATE " + plugin.getName() + " SET uuid='" + uuid + "' WHERE player='" + p.getName() + "'"); - } - ResultSet res3 = c.createStatement().executeQuery("SELECT * FROM " + plugin.getName() + " WHERE uuid='" + uuid + "'"); - if (!res3.isBeforeFirst()) { - // there's no such user - c.createStatement().executeUpdate("INSERT INTO " + plugin.getName() + " VALUES('0', '" + p.getName() + "', '0', '0', '0', '1', '0', '" + uuid + "')"); - return; - } - res3.next(); - int kills = res3.getInt("kills") + kills_; - - c.createStatement().executeUpdate("UPDATE " + plugin.getName() + " SET kills='" + Integer.toString(kills) + "' WHERE uuid='" + uuid + "'"); - - } catch (SQLException e) { - e.printStackTrace(); - } - } - - public void updateDeathStats(Player p, int deaths_) { - if (!plugin.getConfig().getBoolean("mysql.enabled")) { - return; - } - if (!mysql) { - // TODO SQLite - } - String uuid = p.getUniqueId().toString(); - Connection c = MySQL.open(); - - try { - if (oldFormat) { - c.createStatement().executeUpdate("UPDATE " + plugin.getName() + " SET uuid='" + uuid + "' WHERE player='" + p.getName() + "'"); - } - ResultSet res3 = c.createStatement().executeQuery("SELECT * FROM " + plugin.getName() + " WHERE uuid='" + uuid + "'"); - if (!res3.isBeforeFirst()) { - // there's no such user - c.createStatement().executeUpdate("INSERT INTO " + plugin.getName() + " VALUES('0', '" + p.getName() + "', '0', '0', '0', '0', '1', '" + uuid + "')"); - return; - } - res3.next(); - int deaths = res3.getInt("deaths") + deaths_; - - c.createStatement().executeUpdate("UPDATE " + plugin.getName() + " SET deaths='" + Integer.toString(deaths) + "' WHERE uuid='" + uuid + "'"); - - } catch (SQLException e) { - e.printStackTrace(); - } - } - - public int getPoints(Player p) { - if (!plugin.getConfig().getBoolean("mysql.enabled")) { - return -1; - } - if (!mysql) { - // TODO SQLite - } - String uuid = p.getUniqueId().toString(); - Connection c = MySQL.open(); - - try { - if (oldFormat) { - c.createStatement().executeUpdate("UPDATE " + plugin.getName() + " SET uuid='" + uuid + "' WHERE player='" + p.getName() + "'"); - } - ResultSet res3 = c.createStatement().executeQuery("SELECT * FROM " + plugin.getName() + " WHERE uuid='" + uuid + "'"); - - if (res3.isBeforeFirst()) { - res3.next(); - int credits = res3.getInt("points"); - return credits; - } else { - // System.out.println("New User detected."); - } - } catch (SQLException e) { - // - } - return -1; - } - - public int getWins(Player p) { - if (!plugin.getConfig().getBoolean("mysql.enabled")) { - return -1; - } - if (!mysql) { - // TODO SQLite - } - String uuid = p.getUniqueId().toString(); - Connection c = MySQL.open(); - - try { - if (oldFormat) { - c.createStatement().executeUpdate("UPDATE " + plugin.getName() + " SET uuid='" + uuid + "' WHERE player='" + p.getName() + "'"); - } - ResultSet res3 = c.createStatement().executeQuery("SELECT * FROM " + plugin.getName() + " WHERE uuid='" + uuid + "'"); - - if (res3.isBeforeFirst()) { - res3.next(); - int wins = res3.getInt("wins"); - return wins; - } else { - // System.out.println("New User detected."); - } - } catch (SQLException e) { - // - } - return -1; - } +import org.bukkit.entity.Player; +import org.bukkit.plugin.java.JavaPlugin; +import com.comze_instancelabs.minigamesapi.ArenaConfigStrings; +import com.comze_instancelabs.minigamesapi.MinigamesAPI; + +/** + * Main sql interface. + */ +public class MainSQL +{ + + // used for rewards and stats + + /** + * plugin + */ + JavaPlugin plugin = null; + + /** + * mysql connection + */ + MySQL MySQL; + + /** + * sqlite connection + */ + SQLite SQLite; + + /** + * Set to true if tables don't contain UUIDs + */ + boolean oldFormat = false; + + /** + * Constructor + * @param plugin + */ + public MainSQL(final JavaPlugin plugin) + { + this.plugin = plugin; + + if (plugin.getConfig().getBoolean(ArenaConfigStrings.CONFIG_MYSQL_ENABLED)) + { + this.MySQL = new MySQL(plugin.getConfig().getString(ArenaConfigStrings.CONFIG_MYSQL_HOST), "3306", plugin.getConfig().getString(ArenaConfigStrings.CONFIG_MYSQL_DATABASE), plugin.getConfig().getString(ArenaConfigStrings.CONFIG_MYSQL_USER), //$NON-NLS-1$ + plugin.getConfig().getString(ArenaConfigStrings.CONFIG_MYSQL_PW)); + } + else if (plugin.getConfig().getBoolean(ArenaConfigStrings.CONFIG_SQLITE_ENABLED)) + { + this.SQLite = new SQLite(plugin.getDataFolder() + "/" + plugin.getConfig().getString(ArenaConfigStrings.CONFIG_SQLITE_DATABASE), plugin.getConfig().getString(ArenaConfigStrings.CONFIG_SQLITE_USER), plugin.getConfig().getString(ArenaConfigStrings.CONFIG_SQLITE_PW)); //$NON-NLS-1$ + } + + if (this.MySQL != null) + { + try + { + this.createTables(); + } + catch (final Exception e) + { + this.MySQL = null; + plugin.getLogger().log(Level.SEVERE, "Failed initializing MySQL. Disabling!", e); //$NON-NLS-1$ + plugin.getConfig().set(ArenaConfigStrings.CONFIG_MYSQL_ENABLED, false); + plugin.saveConfig(); + } + } + else if (this.SQLite != null) + { + try + { + this.createTables(); + } + catch (final Exception e) + { + this.SQLite = null; + plugin.getLogger().log(Level.SEVERE, "Failed initializing SqLite. Disabling!", e); //$NON-NLS-1$ + plugin.getConfig().set(ArenaConfigStrings.CONFIG_SQLITE_ENABLED, false); + plugin.saveConfig(); + } + } + } + + /** + * Creates database tables + */ + private void createTables() + { + if (this.MySQL != null) + { + try (final Connection c = this.MySQL.open()) + { + c.createStatement().execute("CREATE DATABASE IF NOT EXISTS `" + this.plugin.getConfig().getString(ArenaConfigStrings.CONFIG_MYSQL_DATABASE) + "`"); //$NON-NLS-1$ //$NON-NLS-2$ + c.createStatement() + .execute("CREATE TABLE IF NOT EXISTS " + this.plugin.getName() + " (id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, player VARCHAR(100), points INT, wins INT, loses INT, kills INT)"); //$NON-NLS-1$//$NON-NLS-2$ + try (final ResultSet res = c.createStatement().executeQuery("SHOW COLUMNS FROM `" + this.plugin.getName() + "` LIKE 'kills'")) //$NON-NLS-1$ //$NON-NLS-2$ + { + if (!res.isBeforeFirst()) + { + // old table format without kills column -> add kills column + c.createStatement().execute("ALTER TABLE " + this.plugin.getName() + " ADD kills INT"); //$NON-NLS-1$ //$NON-NLS-2$ + } + } + try (final ResultSet res2 = c.createStatement().executeQuery("SHOW COLUMNS FROM `" + this.plugin.getName() + "` LIKE 'deaths'")) //$NON-NLS-1$ //$NON-NLS-2$ + { + if (!res2.isBeforeFirst()) + { + // old table format without deaths column -> add deaths column + c.createStatement().execute("ALTER TABLE " + this.plugin.getName() + " ADD deaths INT"); //$NON-NLS-1$ //$NON-NLS-2$ + } + } + try (final ResultSet res3 = c.createStatement().executeQuery("SHOW COLUMNS FROM `" + this.plugin.getName() + "` LIKE 'uuid'")) //$NON-NLS-1$ //$NON-NLS-2$ + { + if (!res3.isBeforeFirst()) + { + // old table format without uuid column -> add uuid column + c.createStatement().execute("ALTER TABLE " + this.plugin.getName() + " ADD uuid VARCHAR(100)"); //$NON-NLS-1$ //$NON-NLS-2$ + this.oldFormat = true; + } + } + try (final ResultSet res3 = c.createStatement().executeQuery("SHOW COLUMNS FROM `" + this.plugin.getName() + "` LIKE 'gamepoints'")) //$NON-NLS-1$ //$NON-NLS-2$ + { + if (!res3.isBeforeFirst()) + { + // old table format without gamepoints column -> add gamepoints column + c.createStatement().execute("ALTER TABLE " + this.plugin.getName() + " ADD gamepoints INT"); //$NON-NLS-1$ //$NON-NLS-2$ + } + } + } + catch (final SQLException e) + { + MinigamesAPI.getAPI().getLogger().log(Level.WARNING, "exception", e); //$NON-NLS-1$ + } + } + else if (this.SQLite != null) + { + try (final Connection c = this.SQLite.open()) + { + c.createStatement() + .execute("CREATE TABLE IF NOT EXISTS " + this.plugin.getName() + " (id INTEGER PRIMARY KEY AUTOINCREMENT, player VARCHAR(100), points INT, wins INT, loses INT, kills INT, deaths INT, uuid VARCHAR(100), gamepoints INT)"); //$NON-NLS-1$ //$NON-NLS-2$ + } + catch (final SQLException e) + { + MinigamesAPI.getAPI().getLogger().log(Level.WARNING, "exception", e); //$NON-NLS-1$ + } + } + } + + /** + * Update old format database + * @param p + * @param uuid + * @param c + * @throws SQLException + */ + private void updateOldFormat(final Player p, final String uuid, final Connection c) throws SQLException + { + if (this.oldFormat) + { + try (final Statement stmt = c.createStatement()) + { + stmt.executeUpdate("UPDATE " + this.plugin.getName() + " SET uuid='" + uuid + "' WHERE player='" + p.getName() + "'"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + } + } + } + + /** + * Updates winner stats + * @param p + * @param reward + * @param addwin + */ + public void updateWinnerStats(final Player p, final int reward, final boolean addwin) + { + final String uuid = p.getUniqueId().toString(); + + final int wincount = addwin ? 1 : 0; + if (this.MySQL != null) + { + try (final Connection c = this.MySQL.open()) + { + updateOldFormat(p, uuid, c); + updateWinnerStats(p, reward, uuid, wincount, c); + } + catch (final SQLException e) + { + MinigamesAPI.getAPI().getLogger().log(Level.WARNING, "exception", e); //$NON-NLS-1$ + } + } + else if (this.SQLite != null) + { + try (final Connection c = this.SQLite.open()) + { + updateWinnerStats(p, reward, uuid, wincount, c); + } + catch (final SQLException e) + { + MinigamesAPI.getAPI().getLogger().log(Level.WARNING, "exception", e); //$NON-NLS-1$ + } + } + } + + /** + * Update winner stats + * @param p + * @param reward + * @param uuid + * @param wincount + * @param c + * @throws SQLException + */ + private void updateWinnerStats(final Player p, final int reward, final String uuid, final int wincount, final Connection c) throws SQLException + { + try (final Statement stmt = c.createStatement()) + { + try (final ResultSet res3 = stmt.executeQuery("SELECT * FROM " + this.plugin.getName() + " WHERE uuid='" + uuid + "'")) //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + { + if (!res3.isBeforeFirst()) + { + // there's no such user + c.createStatement().executeUpdate("INSERT INTO `" + this.plugin.getName() + "` (`player`, `points`, `wins`, `loses`, `kills`, `deaths`, `uuid`, `gamepoints`) " //$NON-NLS-1$ //$NON-NLS-2$ + + "VALUES('" + p.getName() + "', " + reward + ", " + wincount //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$ + + ", 0, 0, 0, '" + uuid + "', 0)"); //$NON-NLS-1$ //$NON-NLS-2$ + } + else + { + res3.next(); + final int points = res3.getInt("points") + reward; //$NON-NLS-1$ + final int wins = res3.getInt("wins") + wincount; //$NON-NLS-1$ + + c.createStatement().executeUpdate("UPDATE " + this.plugin.getName() + " SET points=" + points + ", wins=" + wins + " WHERE uuid='" + uuid + "'"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ + } + } + } + } + + /** + * Update loser stats + * @param p + */ + public void updateLoserStats(final Player p) + { + final String uuid = p.getUniqueId().toString(); + if (this.MySQL != null) + { + try (Connection c = this.MySQL.open()) + { + updateOldFormat(p, uuid, c); + updateLosterStats(p, uuid, c); + } + catch (final SQLException e) + { + MinigamesAPI.getAPI().getLogger().log(Level.WARNING, "exception", e); //$NON-NLS-1$ + } + } + else if (this.SQLite != null) + { + try (Connection c = this.SQLite.open()) + { + updateLosterStats(p, uuid, c); + } + catch (final SQLException e) + { + MinigamesAPI.getAPI().getLogger().log(Level.WARNING, "exception", e); //$NON-NLS-1$ + } + } + } + + /** + * Update loser stats + * @param p + * @param uuid + * @param c + * @throws SQLException + */ + private void updateLosterStats(final Player p, final String uuid, final Connection c) throws SQLException + { + try (final Statement stmt = c.createStatement()) + { + try (final ResultSet res3 = stmt.executeQuery("SELECT * FROM " + this.plugin.getName() + " WHERE uuid='" + uuid + "'")) //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + { + if (!res3.isBeforeFirst()) + { + // there's no such user + stmt.executeUpdate("INSERT INTO `" + this.plugin.getName() + "` (`player`, `points`, `wins`, `loses`, `kills`, `deaths`, `uuid`, `gamepoints`) " //$NON-NLS-1$ //$NON-NLS-2$ + + "VALUES('" + p.getName() + "', 0, 0, 1, 0, 0, '" + uuid + "', 0)"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + } + else + { + res3.next(); + final int loses = res3.getInt("loses") + 1; //$NON-NLS-1$ + + stmt.executeUpdate("UPDATE " + this.plugin.getName() + " SET loses=" + loses + " WHERE uuid='" + uuid + "'"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + } + } + } + } + + /** + * Update killer stats + * @param p + * @param kills_ + */ + public void updateKillerStats(final Player p, final int kills_) + { + final String uuid = p.getUniqueId().toString(); + if (this.MySQL != null) + { + try (Connection c = this.MySQL.open()) + { + updateOldFormat(p, uuid, c); + updateKillerStats(p, kills_, uuid, c); + } + catch (final SQLException e) + { + MinigamesAPI.getAPI().getLogger().log(Level.WARNING, "exception", e); //$NON-NLS-1$ + } + } + else if (this.SQLite != null) + { + try (Connection c = this.SQLite.open()) + { + updateKillerStats(p, kills_, uuid, c); + } + catch (final SQLException e) + { + MinigamesAPI.getAPI().getLogger().log(Level.WARNING, "exception", e); //$NON-NLS-1$ + } + } + } + + /** + * Update killer stats + * @param p + * @param kills_ + * @param uuid + * @param c + * @throws SQLException + */ + private void updateKillerStats(final Player p, final int kills_, final String uuid, final Connection c) throws SQLException + { + try (final Statement stmt = c.createStatement()) + { + try (final ResultSet res3 = stmt.executeQuery("SELECT * FROM " + this.plugin.getName() + " WHERE uuid='" + uuid + "'")) //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + { + if (!res3.isBeforeFirst()) + { + // there's no such user + stmt.executeUpdate("INSERT INTO " + this.plugin.getName() + " (`player`, `points`, `wins`, `loses`, `kills`, `deaths`, `uuid`, `gamepoints`) " //$NON-NLS-1$ //$NON-NLS-2$ + + "VALUES('" + p.getName() + "', 0, 0, 0, 1, 0, '" + uuid + "', 0)"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + } + else + { + res3.next(); + final int kills = res3.getInt("kills") + kills_; //$NON-NLS-1$ + + stmt.executeUpdate("UPDATE " + this.plugin.getName() + " SET kills=" + kills + " WHERE uuid='" + uuid + "'"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + } + } + } + } + + /** + * update killer stats + * @param p + * @param deaths_ + */ + public void updateDeathStats(final Player p, final int deaths_) + { + final String uuid = p.getUniqueId().toString(); + if (this.MySQL != null) + { + try (final Connection c = this.MySQL.open()) + { + updateOldFormat(p, uuid, c); + updateDeathStats(p, deaths_, uuid, c); + } + catch (final SQLException e) + { + MinigamesAPI.getAPI().getLogger().log(Level.WARNING, "exception", e); //$NON-NLS-1$ + } + } + else if (this.SQLite != null) + { + try (final Connection c = this.SQLite.open()) + { + updateDeathStats(p, deaths_, uuid, c); + } + catch (final SQLException e) + { + MinigamesAPI.getAPI().getLogger().log(Level.WARNING, "exception", e); //$NON-NLS-1$ + } + } + } + + /** + * Update death stats + * @param p + * @param deaths_ + * @param uuid + * @param c + * @throws SQLException + */ + private void updateDeathStats(final Player p, final int deaths_, final String uuid, final Connection c) throws SQLException + { + try (final Statement stmt = c.createStatement()) + { + try (final ResultSet res3 = stmt.executeQuery("SELECT * FROM " + this.plugin.getName() + " WHERE uuid='" + uuid + "'")) //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + { + if (!res3.isBeforeFirst()) + { + // there's no such user + stmt.executeUpdate("INSERT INTO " + this.plugin.getName() + " (`player`, `points`, `wins`, `loses`, `kills`, `deaths`, `uuid`, `gamepoints`) " //$NON-NLS-1$//$NON-NLS-2$ + + "VALUES('" + p.getName() + "', 0, 0, 0, 0, 1, '" + uuid + "', 0)"); //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$ + } + else + { + res3.next(); + final int deaths = res3.getInt("deaths") + deaths_; //$NON-NLS-1$ + + stmt.executeUpdate("UPDATE " + this.plugin.getName() + " SET deaths=" + Integer.toString(deaths) + " WHERE uuid='" + uuid + "'"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + } + } + } + } + + /** + * Get points + * @param p + * @return points + */ + public int getPoints(final Player p) + { + final String uuid = p.getUniqueId().toString(); + int result = -1; + if (this.MySQL != null) + { + try (final Connection c = this.MySQL.open()) + { + updateOldFormat(p, uuid, c); + result = getPoints(uuid, c); + } + catch (final SQLException e) + { + MinigamesAPI.getAPI().getLogger().log(Level.WARNING, "exception", e); //$NON-NLS-1$ + } + } + else if (this.SQLite != null) + { + try (final Connection c = this.SQLite.open()) + { + result = getPoints(uuid, c); + } + catch (final SQLException e) + { + MinigamesAPI.getAPI().getLogger().log(Level.WARNING, "exception", e); //$NON-NLS-1$ + } + } + return result; + } + + /** + * Get points + * @param uuid + * @param c + * @return points + * @throws SQLException + */ + private int getPoints(final String uuid, final Connection c) throws SQLException + { + int result = -1; + try (final Statement stmt = c.createStatement()) + { + try (final ResultSet res3 = stmt.executeQuery("SELECT * FROM " + this.plugin.getName() + " WHERE uuid='" + uuid + "'")) //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + { + if (res3.isBeforeFirst()) + { + res3.next(); + result = res3.getInt("points"); //$NON-NLS-1$ + } + } + } + return result; + } + + /** + * Get wins + * @param p + * @return wins + */ + public int getWins(final Player p) + { + final String uuid = p.getUniqueId().toString(); + int result = -1; + if (this.MySQL != null) + { + try (final Connection c = this.MySQL.open()) + { + updateOldFormat(p, uuid, c); + result = getWins(uuid, c); + } + catch (final SQLException e) + { + MinigamesAPI.getAPI().getLogger().log(Level.WARNING, "exception", e); //$NON-NLS-1$ + } + } + else if (this.SQLite != null) + { + try (final Connection c = this.SQLite.open()) + { + result = getWins(uuid, c); + } + catch (final SQLException e) + { + MinigamesAPI.getAPI().getLogger().log(Level.WARNING, "exception", e); //$NON-NLS-1$ + } + } + return result; + } + + /** + * Get wins + * @param uuid + * @param c + * @return wins + * @throws SQLException + */ + private int getWins(final String uuid, final Connection c) throws SQLException + { + int result = -1; + try (final Statement stmt = c.createStatement()) + { + try (final ResultSet res3 = stmt.executeQuery("SELECT * FROM " + this.plugin.getName() + " WHERE uuid='" + uuid + "'")) //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + { + if (res3.isBeforeFirst()) + { + res3.next(); + result = res3.getInt("wins"); //$NON-NLS-1$ + } + } + } + return result; + } + + /** + * Get game points + * @param p + * @return wins + */ + public int getGamePoints(final Player p) + { + final String uuid = p.getUniqueId().toString(); + int result = -1; + if (this.MySQL != null) + { + try (final Connection c = this.MySQL.open()) + { + updateOldFormat(p, uuid, c); + result = getGamePoints(uuid, c); + } + catch (final SQLException e) + { + MinigamesAPI.getAPI().getLogger().log(Level.WARNING, "exception", e); //$NON-NLS-1$ + } + } + else if (this.SQLite != null) + { + try (final Connection c = this.SQLite.open()) + { + result = getGamePoints(uuid, c); + } + catch (final SQLException e) + { + MinigamesAPI.getAPI().getLogger().log(Level.WARNING, "exception", e); //$NON-NLS-1$ + } + } + return result; + } + + /** + * Get game points + * @param uuid + * @param c + * @return wins + * @throws SQLException + */ + private int getGamePoints(final String uuid, final Connection c) throws SQLException + { + int result = -1; + try (final Statement stmt = c.createStatement()) + { + try (final ResultSet res3 = stmt.executeQuery("SELECT * FROM " + this.plugin.getName() + " WHERE uuid='" + uuid + "'")) //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + { + if (res3.isBeforeFirst()) + { + res3.next(); + result = res3.getInt("gamepoints"); //$NON-NLS-1$ + } + } + } + return result; + } + + /** + * Set game points + * @param p + * @param points + */ + public void setGamePoints(final Player p, int points) + { + final String uuid = p.getUniqueId().toString(); + if (this.MySQL != null) + { + try (final Connection c = this.MySQL.open()) + { + updateOldFormat(p, uuid, c); + setGamePoints(p, c, points); + } + catch (final SQLException e) + { + MinigamesAPI.getAPI().getLogger().log(Level.WARNING, "exception", e); //$NON-NLS-1$ + } + } + else if (this.SQLite != null) + { + try (final Connection c = this.SQLite.open()) + { + setGamePoints(p, c, points); + } + catch (final SQLException e) + { + MinigamesAPI.getAPI().getLogger().log(Level.WARNING, "exception", e); //$NON-NLS-1$ + } + } + } + + /** + * Set game points + * @param p + * @param c + * @param points + * @throws SQLException + */ + private void setGamePoints(final Player p, final Connection c, int points) throws SQLException + { + final String uuid = p.getUniqueId().toString(); + try (final Statement stmt = c.createStatement()) + { + try (final ResultSet res3 = stmt.executeQuery("SELECT * FROM " + this.plugin.getName() + " WHERE uuid='" + uuid + "'")) //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + { + if (!res3.isBeforeFirst()) + { + // there's no such user + stmt.executeUpdate("INSERT INTO " + this.plugin.getName() + " (`player`, `points`, `wins`, `loses`, `kills`, `deaths`, `uuid`, `gamepoints`) " //$NON-NLS-1$//$NON-NLS-2$ + + "VALUES('" + p.getName() + "', 0, 0, 0, 0, 1, '" + uuid + "', " + points + ")"); //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + } + else + { + stmt.executeUpdate("UPDATE " + this.plugin.getName() + " SET gamepoints=" + points + " WHERE uuid='" + uuid + "'"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + } + } + } + } + + /** + * Set game points + * @param p + * @param points + */ + public void addGamePoints(final Player p, int points) + { + final String uuid = p.getUniqueId().toString(); + if (this.MySQL != null) + { + try (final Connection c = this.MySQL.open()) + { + updateOldFormat(p, uuid, c); + addGamePoints(p, c, points); + } + catch (final SQLException e) + { + MinigamesAPI.getAPI().getLogger().log(Level.WARNING, "exception", e); //$NON-NLS-1$ + } + } + else if (this.SQLite != null) + { + try (final Connection c = this.SQLite.open()) + { + addGamePoints(p, c, points); + } + catch (final SQLException e) + { + MinigamesAPI.getAPI().getLogger().log(Level.WARNING, "exception", e); //$NON-NLS-1$ + } + } + } + + /** + * Set game points + * @param p + * @param c + * @param points + * @throws SQLException + */ + private void addGamePoints(final Player p, final Connection c, int points) throws SQLException + { + final String uuid = p.getUniqueId().toString(); + try (final Statement stmt = c.createStatement()) + { + try (final ResultSet res3 = stmt.executeQuery("SELECT * FROM " + this.plugin.getName() + " WHERE uuid='" + uuid + "'")) //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + { + if (!res3.isBeforeFirst()) + { + // there's no such user + stmt.executeUpdate("INSERT INTO " + this.plugin.getName() + " (`player`, `points`, `wins`, `loses`, `kills`, `deaths`, `uuid`, `gamepoints`) " //$NON-NLS-1$//$NON-NLS-2$ + + "VALUES('" + p.getName() + "', 0, 0, 0, 0, 1, '" + uuid + "', " + points + ")"); //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + } + else + { + stmt.executeUpdate("UPDATE " + this.plugin.getName() + " SET gamepoints=" + (points + res3.getInt("gamepoints") ) + " WHERE uuid='" + uuid + "'"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ + } + } + } + } + } diff --git a/API/src/main/java/com/comze_instancelabs/minigamesapi/sql/MySQL.java b/API/src/main/java/com/comze_instancelabs/minigamesapi/sql/MySQL.java index 49e085c9..7ff17de3 100644 --- a/API/src/main/java/com/comze_instancelabs/minigamesapi/sql/MySQL.java +++ b/API/src/main/java/com/comze_instancelabs/minigamesapi/sql/MySQL.java @@ -1,59 +1,61 @@ +/* + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ package com.comze_instancelabs.minigamesapi.sql; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; +import java.util.logging.Level; import com.comze_instancelabs.minigamesapi.MinigamesAPI; -import com.comze_instancelabs.minigamesapi.sql.Database; -public class MySQL extends Database { - String user = ""; - String database = ""; - String password = ""; - String port = ""; - String hostname = ""; - Connection c = null; - - public MySQL(String hostname, String portnmbr, String database, String username, String password) { - this.hostname = hostname; - this.port = portnmbr; - this.database = database; - this.user = username; - this.password = password; - } - - public Connection open() { - try { - Class.forName("com.mysql.jdbc.Driver"); - this.c = DriverManager.getConnection("jdbc:mysql://" + this.hostname + ":" + this.port + "/" + this.database, this.user, this.password); - return c; - } catch (SQLException e) { - System.out.println("Could not connect to MySQL server! Cause: " + e.getMessage()); - } catch (ClassNotFoundException e) { - System.out.println("JDBC Driver not found!"); - } - return this.c; - } - - public boolean checkConnection() { - if (this.c != null) { - return true; - } - return false; - } - - public Connection getConn() { - return this.c; - } - - public void closeConnection(Connection c) { - try { - c.close(); - } catch (SQLException e) { - if (MinigamesAPI.debug) - e.printStackTrace(); - } - c = null; - } -} \ No newline at end of file +public class MySQL +{ + String user = ""; + String database = ""; + String password = ""; + String port = ""; + String hostname = ""; + Connection c = null; + + public MySQL(final String hostname, final String portnmbr, final String database, final String username, final String password) + { + this.hostname = hostname; + this.port = portnmbr; + this.database = database; + this.user = username; + this.password = password; + } + + public Connection open() + { + try + { + Class.forName("com.mysql.jdbc.Driver"); + this.c = DriverManager.getConnection("jdbc:mysql://" + this.hostname + ":" + this.port + "/" + this.database, this.user, this.password); + return this.c; + } + catch (final SQLException e) + { + MinigamesAPI.getAPI().getLogger().log(Level.SEVERE, "Could not connect to MySQL server!", e); + } + catch (final ClassNotFoundException e) + { + MinigamesAPI.getAPI().getLogger().severe("JDBC Driver not found!"); + } + return this.c; + } + +} diff --git a/API/src/main/java/com/comze_instancelabs/minigamesapi/sql/SQLite.java b/API/src/main/java/com/comze_instancelabs/minigamesapi/sql/SQLite.java index d640437f..1865f6ac 100644 --- a/API/src/main/java/com/comze_instancelabs/minigamesapi/sql/SQLite.java +++ b/API/src/main/java/com/comze_instancelabs/minigamesapi/sql/SQLite.java @@ -1,48 +1,57 @@ +/* + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ package com.comze_instancelabs.minigamesapi.sql; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; - -import com.comze_instancelabs.minigamesapi.sql.Database; - -public class SQLite extends Database { - String user = ""; - String database = ""; - String password = ""; - Connection c = null; - - public SQLite(String database, String username, String password) { - this.database = database; - this.user = username; - this.password = password; - } - - public Connection open() { - try { - Class.forName("org.sqlite.JDBC"); - this.c = DriverManager.getConnection("jdbc:sqlite:main.db"); - return c; - } catch (SQLException e) { - System.out.println("Could not connect to SQLite database! Cause: " + e.getMessage()); - } catch (ClassNotFoundException e) { - System.out.println("JDBC Driver not found!"); - } - return this.c; - } - - public boolean checkConnection() { - if (this.c != null) { - return true; - } - return false; - } - - public Connection getConn() { - return this.c; - } - - public void closeConnection(Connection c) { - c = null; - } +import java.util.logging.Level; + +import com.comze_instancelabs.minigamesapi.MinigamesAPI; + +public class SQLite +{ + String user = ""; + String database = ""; + String password = ""; + Connection c = null; + + public SQLite(final String database, final String username, final String password) + { + this.database = database; + this.user = username; + this.password = password; + } + + public Connection open() + { + try + { + Class.forName("org.sqlite.JDBC"); + this.c = DriverManager.getConnection("jdbc:sqlite:" + this.database); + return this.c; + } + catch (final SQLException e) + { + MinigamesAPI.getAPI().getLogger().log(Level.SEVERE, "Could not connect to SQLite database!", e); + } + catch (final ClassNotFoundException e) + { + MinigamesAPI.getAPI().getLogger().log(Level.SEVERE, "JDBC Driver not found!"); + } + return this.c; + } + } diff --git a/API/src/main/java/com/comze_instancelabs/minigamesapi/statsholograms/Hologram.java b/API/src/main/java/com/comze_instancelabs/minigamesapi/statsholograms/Hologram.java index 5adfc265..f9fd1754 100644 --- a/API/src/main/java/com/comze_instancelabs/minigamesapi/statsholograms/Hologram.java +++ b/API/src/main/java/com/comze_instancelabs/minigamesapi/statsholograms/Hologram.java @@ -1,7 +1,20 @@ +/* + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ package com.comze_instancelabs.minigamesapi.statsholograms; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collections; import org.bukkit.ChatColor; @@ -11,48 +24,54 @@ import com.comze_instancelabs.minigamesapi.Effects; import com.comze_instancelabs.minigamesapi.MinigamesAPI; import com.comze_instancelabs.minigamesapi.PluginInstance; -import com.comze_instancelabs.minigamesapi.util.Util; - -public class Hologram { - - ArrayList<Integer> ids = new ArrayList<Integer>(); - PluginInstance pli; - Location l; - - public Hologram(PluginInstance pli, Location l) { - this.pli = pli; - this.l = l; - } - - public void send(Player p) { - if (pli.getMessagesConfig().getConfig().isSet("messages.stats")) { - - double ydelta = 0.25D; - - int kills_ = pli.getStatsInstance().getKills(p.getName()); - int deaths_ = pli.getStatsInstance().getDeaths(p.getName()); - int money_ = (int) MinigamesAPI.econ.getBalance(p.getName()); - - String wins = Integer.toString(pli.getStatsInstance().getWins(p.getName())); - String loses = Integer.toString(pli.getStatsInstance().getLoses(p.getName())); - String kills = Integer.toString(kills_); - String deaths = Integer.toString(deaths_); - String money = Integer.toString(money_); - String points = Integer.toString(pli.getStatsInstance().getPoints(p.getName())); - String kdr = Integer.toString(Math.max(kills_, 1) / Math.max(deaths_, 1)); - ArrayList<String> s = new ArrayList<String>(pli.getMessagesConfig().getConfig().getConfigurationSection("messages.stats").getKeys(false)); - Collections.reverse(s); - for (String key : s) { - // Each line from the config gets checked for variables like <wins> or <money> and these get replaced by the values calculated above - String msg = pli.getMessagesConfig().getConfig().getString("messages.stats." + key).replaceAll("<wins>", wins).replaceAll("<loses>", loses).replaceAll("<alltime_kills>", kills).replaceAll("<alltime_deaths>", deaths).replaceAll("<points>", points).replaceAll("<kdr>", kdr).replaceAll("<money>", money); - ids.addAll(Effects.playHologram(p, l.clone().add(0D, ydelta, 0D), ChatColor.translateAlternateColorCodes('&', msg), false, false)); - ydelta += 0.25D; - } - } - } - - public ArrayList<Integer> getIds() { - return ids; - } +public class Hologram +{ + + ArrayList<Integer> ids = new ArrayList<>(); + PluginInstance pli; + Location l; + + public Hologram(final PluginInstance pli, final Location l) + { + this.pli = pli; + this.l = l; + } + + public void send(final Player p) + { + if (this.pli.getMessagesConfig().getConfig().isSet("messages.stats")) + { + + double ydelta = 0.25D; + + final int kills_ = this.pli.getStatsInstance().getKills(p.getName()); + final int deaths_ = this.pli.getStatsInstance().getDeaths(p.getName()); + final int money_ = (int) MinigamesAPI.econ.getBalance(p.getName()); + + final String wins = Integer.toString(this.pli.getStatsInstance().getWins(p.getName())); + final String loses = Integer.toString(this.pli.getStatsInstance().getLoses(p.getName())); + final String kills = Integer.toString(kills_); + final String deaths = Integer.toString(deaths_); + final String money = Integer.toString(money_); + final String points = Integer.toString(this.pli.getStatsInstance().getPoints(p.getName())); + final String kdr = Integer.toString(Math.max(kills_, 1) / Math.max(deaths_, 1)); + final ArrayList<String> s = new ArrayList<>(this.pli.getMessagesConfig().getConfig().getConfigurationSection("messages.stats").getKeys(false)); + Collections.reverse(s); + for (final String key : s) + { + // Each line from the config gets checked for variables like <wins> or <money> and these get replaced by the values calculated above + final String msg = this.pli.getMessagesConfig().getConfig().getString("messages.stats." + key).replaceAll("<wins>", wins).replaceAll("<loses>", loses) + .replaceAll("<alltime_kills>", kills).replaceAll("<alltime_deaths>", deaths).replaceAll("<points>", points).replaceAll("<kdr>", kdr).replaceAll("<money>", money); + this.ids.addAll(Effects.playHologram(p, this.l.clone().add(0D, ydelta, 0D), ChatColor.translateAlternateColorCodes('&', msg), false, false)); + ydelta += 0.25D; + } + } + } + + public ArrayList<Integer> getIds() + { + return this.ids; + } + } diff --git a/API/src/main/java/com/comze_instancelabs/minigamesapi/statsholograms/Holograms.java b/API/src/main/java/com/comze_instancelabs/minigamesapi/statsholograms/Holograms.java index 88f07086..3fa04f63 100644 --- a/API/src/main/java/com/comze_instancelabs/minigamesapi/statsholograms/Holograms.java +++ b/API/src/main/java/com/comze_instancelabs/minigamesapi/statsholograms/Holograms.java @@ -1,3 +1,17 @@ +/* + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ package com.comze_instancelabs.minigamesapi.statsholograms; import java.lang.reflect.Constructor; @@ -5,9 +19,9 @@ import java.lang.reflect.Method; import java.util.ArrayList; import java.util.HashMap; +import java.util.logging.Level; import org.bukkit.Bukkit; -import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.entity.Player; @@ -16,97 +30,127 @@ import com.comze_instancelabs.minigamesapi.PluginInstance; import com.comze_instancelabs.minigamesapi.config.HologramsConfig; -public class Holograms { - - PluginInstance pli; - HashMap<Location, Hologram> holo = new HashMap<Location, Hologram>(); - - public Holograms(PluginInstance pli) { - this.pli = pli; - loadHolograms(); - } - - public void loadHolograms() { - HologramsConfig config = pli.getHologramsConfig(); - if (config.getConfig().isSet("holograms.")) { - for (String str : config.getConfig().getConfigurationSection("holograms.").getKeys(false)) { - String base = "holograms." + str; - try { - Location l = new Location(Bukkit.getWorld(config.getConfig().getString(base + ".world")), config.getConfig().getDouble(base + ".location.x"), config.getConfig().getDouble(base + ".location.y"), config.getConfig().getDouble(base + ".location.z"), (float) config.getConfig().getDouble(base + ".location.yaw"), (float) config.getConfig().getDouble(base + ".location.pitch")); - if (l != null && l.getWorld() != null) { - holo.put(l, new Hologram(pli, l)); - } - } catch (Exception e) { - ArenaLogger.debug("Failed loading hologram as invalid location was found: " + e.getMessage()); - } - } - } - } - - public void sendAllHolograms(Player p) { - for (Hologram h : holo.values()) { - h.send(p); - } - } - - public void addHologram(Location l) { - String base = "holograms." + Integer.toString((int) Math.round(Math.random() * 10000)); - HologramsConfig config = pli.getHologramsConfig(); - config.getConfig().set(base + ".world", l.getWorld().getName()); - config.getConfig().set(base + ".location.x", l.getX()); - config.getConfig().set(base + ".location.y", l.getY()); - config.getConfig().set(base + ".location.z", l.getZ()); - config.getConfig().set(base + ".location.yaw", l.getYaw()); - config.getConfig().set(base + ".location.pitch", l.getPitch()); - config.saveConfig(); - Hologram h = new Hologram(pli, l); - holo.put(l, h); - } - - public boolean removeHologram(Location ploc) { - HologramsConfig config = pli.getHologramsConfig(); - if (config.getConfig().isSet("holograms.")) { - for (String str : config.getConfig().getConfigurationSection("holograms.").getKeys(false)) { - String base = "holograms." + str; - Location l = new Location(Bukkit.getWorld(config.getConfig().getString(base + ".world")), config.getConfig().getDouble(base + ".location.x"), config.getConfig().getDouble(base + ".location.y"), config.getConfig().getDouble(base + ".location.z"), (float) config.getConfig().getDouble(base + ".location.yaw"), (float) config.getConfig().getDouble(base + ".location.pitch")); - if (l.distance(ploc) <= 2) { - config.getConfig().set("holograms." + str, null); - config.saveConfig(); - if (holo.containsKey(l)) { - for (Player p : Bukkit.getOnlinePlayers()) { - destroyHologram(p, holo.get(l)); - } - } - return true; - } - } - } - return false; - } - - public void destroyHologram(final Player p, Hologram h) { - String version = MinigamesAPI.getAPI().version; - try { - final Method getPlayerHandle = Class.forName("org.bukkit.craftbukkit." + version + ".entity.CraftPlayer").getMethod("getHandle"); - final Field playerConnection = Class.forName("net.minecraft.server." + version + ".EntityPlayer").getField("playerConnection"); - playerConnection.setAccessible(true); - final Method sendPacket = playerConnection.getType().getMethod("sendPacket", Class.forName("net.minecraft.server." + version + ".Packet")); - - final Constructor packetPlayOutEntityDestroyConstr = Class.forName("net.minecraft.server." + version + ".PacketPlayOutEntityDestroy").getConstructor(int[].class); - - Object destroyPacket = packetPlayOutEntityDestroyConstr.newInstance((Object) convertIntegers(h.getIds())); - sendPacket.invoke(playerConnection.get(getPlayerHandle.invoke(p)), destroyPacket); - - } catch (Exception e) { - e.printStackTrace(); - } - } - - public int[] convertIntegers(ArrayList<Integer> integers) { - int[] ret = new int[integers.size()]; - for (int i = 0; i < ret.length; i++) { - ret[i] = integers.get(i).intValue(); - } - return ret; - } +public class Holograms +{ + + PluginInstance pli; + HashMap<Location, Hologram> holo = new HashMap<>(); + + public Holograms(final PluginInstance pli) + { + this.pli = pli; + this.loadHolograms(); + } + + public void loadHolograms() + { + final HologramsConfig config = this.pli.getHologramsConfig(); + if (config.getConfig().isSet("holograms.")) + { + for (final String str : config.getConfig().getConfigurationSection("holograms.").getKeys(false)) + { + final String base = "holograms." + str; + try + { + final Location l = new Location(Bukkit.getWorld(config.getConfig().getString(base + ".world")), config.getConfig().getDouble(base + ".location.x"), + config.getConfig().getDouble(base + ".location.y"), config.getConfig().getDouble(base + ".location.z"), (float) config.getConfig().getDouble(base + ".location.yaw"), + (float) config.getConfig().getDouble(base + ".location.pitch")); + if (l != null && l.getWorld() != null) + { + this.holo.put(l, new Hologram(this.pli, l)); + } + } + catch (final Exception e) + { + ArenaLogger.debug("Failed loading hologram as invalid location was found: " + e.getMessage()); + } + } + } + } + + public void sendAllHolograms(final Player p) + { + for (final Hologram h : this.holo.values()) + { + h.send(p); + } + } + + public void addHologram(final Location l) + { + final String base = "holograms." + Integer.toString((int) Math.round(Math.random() * 10000)); + final HologramsConfig config = this.pli.getHologramsConfig(); + config.getConfig().set(base + ".world", l.getWorld().getName()); + config.getConfig().set(base + ".location.x", l.getX()); + config.getConfig().set(base + ".location.y", l.getY()); + config.getConfig().set(base + ".location.z", l.getZ()); + config.getConfig().set(base + ".location.yaw", l.getYaw()); + config.getConfig().set(base + ".location.pitch", l.getPitch()); + config.saveConfig(); + final Hologram h = new Hologram(this.pli, l); + this.holo.put(l, h); + } + + public boolean removeHologram(final Location ploc) + { + final HologramsConfig config = this.pli.getHologramsConfig(); + if (config.getConfig().isSet("holograms.")) + { + for (final String str : config.getConfig().getConfigurationSection("holograms.").getKeys(false)) + { + final String base = "holograms." + str; + final Location l = new Location(Bukkit.getWorld(config.getConfig().getString(base + ".world")), config.getConfig().getDouble(base + ".location.x"), + config.getConfig().getDouble(base + ".location.y"), config.getConfig().getDouble(base + ".location.z"), (float) config.getConfig().getDouble(base + ".location.yaw"), + (float) config.getConfig().getDouble(base + ".location.pitch")); + if (l.distance(ploc) <= 2) + { + config.getConfig().set("holograms." + str, null); + config.saveConfig(); + if (this.holo.containsKey(l)) + { + for (final Player p : Bukkit.getOnlinePlayers()) + { + this.destroyHologram(p, this.holo.get(l)); + } + this.holo.remove(l); + } + return true; + } + } + } + return false; + } + + public void destroyHologram(final Player p, final Hologram h) + { + final String version = MinigamesAPI.getAPI().internalServerVersion; + try + { + // TODO Do not use reflection :-( + final Method getPlayerHandle = Class.forName("org.bukkit.craftbukkit." + version + ".entity.CraftPlayer").getMethod("getHandle"); + final Field playerConnection = Class.forName("net.minecraft.server." + version + ".EntityPlayer").getField("playerConnection"); + playerConnection.setAccessible(true); + final Method sendPacket = playerConnection.getType().getMethod("sendPacket", Class.forName("net.minecraft.server." + version + ".Packet")); + + final Constructor<?> packetPlayOutEntityDestroyConstr = Class.forName("net.minecraft.server." + version + ".PacketPlayOutEntityDestroy").getConstructor(int[].class); + + final Object destroyPacket = packetPlayOutEntityDestroyConstr.newInstance(this.convertIntegers(h.getIds())); + sendPacket.invoke(playerConnection.get(getPlayerHandle.invoke(p)), destroyPacket); + + } + catch (final Exception e) + { + MinigamesAPI.getAPI().getLogger().log(Level.WARNING, "exception", e); + } + } + + public int[] convertIntegers(final ArrayList<Integer> integers) + { + final int[] ret = new int[integers.size()]; + for (int i = 0; i < ret.length; i++) + { + ret[i] = integers.get(i).intValue(); + } + return ret; + } } diff --git a/API/src/main/java/com/comze_instancelabs/minigamesapi/util/AClass.java b/API/src/main/java/com/comze_instancelabs/minigamesapi/util/AClass.java index ffa7710b..ad8ff943 100644 --- a/API/src/main/java/com/comze_instancelabs/minigamesapi/util/AClass.java +++ b/API/src/main/java/com/comze_instancelabs/minigamesapi/util/AClass.java @@ -1,3 +1,17 @@ +/* + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ package com.comze_instancelabs.minigamesapi.util; import java.util.ArrayList; @@ -5,60 +19,71 @@ import org.bukkit.inventory.ItemStack; import org.bukkit.plugin.java.JavaPlugin; -public class AClass { - - private JavaPlugin plugin; - private String name; - private String internalname; - private ArrayList<ItemStack> items = new ArrayList<ItemStack>(); - private ItemStack icon; - private boolean enabled = true; - - @Deprecated - public AClass(JavaPlugin plugin, String name, ArrayList<ItemStack> items) { - this(plugin, name, name, true, items, items.get(0)); - } - - public AClass(JavaPlugin plugin, String name, String internalname, ArrayList<ItemStack> items) { - this(plugin, name, internalname, true, items, items.get(0)); - } - - public AClass(JavaPlugin plugin, String name, String internalname, boolean enabled, ArrayList<ItemStack> items) { - this(plugin, name, internalname, enabled, items, items.get(0)); - } - - public AClass(JavaPlugin plugin, String name, String internalname, boolean enabled, ArrayList<ItemStack> items, ItemStack icon) { - this.plugin = plugin; - this.name = name; - this.items = items; - this.icon = icon; - this.enabled = enabled; - this.internalname = internalname; - } - - public ItemStack[] getItems() { - ItemStack[] ret = new ItemStack[items.size()]; - int c = 0; - for (ItemStack f : items) { - ret[c] = f; - c++; - } - return ret; - } - - public ItemStack getIcon() { - return this.icon; - } - - public String getName() { - return this.name; - } - - public String getInternalName() { - return this.internalname; - } - - public boolean isEnabled() { - return enabled; - } +public class AClass +{ + + private final JavaPlugin plugin; + private final String name; + private final String internalname; + private ArrayList<ItemStack> items = new ArrayList<>(); + private final ItemStack icon; + private boolean enabled = true; + + @Deprecated + public AClass(final JavaPlugin plugin, final String name, final ArrayList<ItemStack> items) + { + this(plugin, name, name, true, items, items.get(0)); + } + + public AClass(final JavaPlugin plugin, final String name, final String internalname, final ArrayList<ItemStack> items) + { + this(plugin, name, internalname, true, items, items.get(0)); + } + + public AClass(final JavaPlugin plugin, final String name, final String internalname, final boolean enabled, final ArrayList<ItemStack> items) + { + this(plugin, name, internalname, enabled, items, items.get(0)); + } + + public AClass(final JavaPlugin plugin, final String name, final String internalname, final boolean enabled, final ArrayList<ItemStack> items, final ItemStack icon) + { + this.plugin = plugin; + this.name = name; + this.items = items; + this.icon = icon; + this.enabled = enabled; + this.internalname = internalname; + } + + public ItemStack[] getItems() + { + final ItemStack[] ret = new ItemStack[this.items.size()]; + int c = 0; + for (final ItemStack f : this.items) + { + ret[c] = f; + c++; + } + return ret; + } + + public ItemStack getIcon() + { + return this.icon; + } + + public String getName() + { + return this.name; + } + + public String getInternalName() + { + return this.internalname; + } + + public boolean isEnabled() + { + return this.enabled; + } } diff --git a/API/src/main/java/com/comze_instancelabs/minigamesapi/util/ArenaBlock.java b/API/src/main/java/com/comze_instancelabs/minigamesapi/util/ArenaBlock.java index c930b544..0f02f4d0 100644 --- a/API/src/main/java/com/comze_instancelabs/minigamesapi/util/ArenaBlock.java +++ b/API/src/main/java/com/comze_instancelabs/minigamesapi/util/ArenaBlock.java @@ -1,5 +1,23 @@ +/* + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ package com.comze_instancelabs.minigamesapi.util; +import java.io.Serializable; +import java.util.ArrayList; +import java.util.Map; + import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Material; @@ -11,114 +29,130 @@ import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.potion.Potion; -import java.io.Serializable; -import java.util.ArrayList; -import java.util.Map; - -public class ArenaBlock implements Serializable { - private static final long serialVersionUID = -1894759842709524780L; - - private int x, y, z; - private String world; - private Material m; - private byte data; +public class ArenaBlock implements Serializable +{ + private static final long serialVersionUID = -1894759842709524780L; + + private final int x, y, z; + private final String world; + private final Material m; + private byte data; private ArrayList<Material> item_mats; - private ArrayList<Byte> item_data; - private ArrayList<Integer> item_amounts; - private ArrayList<String> item_displaynames; - + private ArrayList<Byte> item_data; + private ArrayList<Integer> item_amounts; + private ArrayList<String> item_displaynames; + // optional stuff - private ArrayList<Boolean> item_splash; - - private ItemStack[] inv; - - public ArenaBlock(Block b, boolean c) { - m = b.getType(); - x = b.getX(); - y = b.getY(); - z = b.getZ(); - data = b.getData(); - world = b.getWorld().getName(); - if (c) { - inv = ((Chest) b.getState()).getInventory().getContents(); - item_mats = new ArrayList<Material>(); - item_data = new ArrayList<Byte>(); - item_amounts = new ArrayList<Integer>(); - item_displaynames = new ArrayList<String>(); - item_splash = new ArrayList<Boolean>(); - - for (ItemStack i : ((Chest) b.getState()).getInventory().getContents()) { - if (i != null) { - item_mats.add(i.getType()); - item_data.add(i.getData().getData()); - item_amounts.add(i.getAmount()); - item_displaynames.add(i.getItemMeta().getDisplayName()); - if (i.getType() == Material.POTION && i.getDurability() > 0 && i.getData().getData() > 0) { - Potion potion = Potion.fromDamage(i.getDurability() & 0x3F); - item_splash.add(potion.isSplash()); - } else { - item_splash.add(false); + private ArrayList<Boolean> item_splash; + + private ItemStack[] inv; + + public ArenaBlock(final Block b, final boolean c) + { + this.m = b.getType(); + this.x = b.getX(); + this.y = b.getY(); + this.z = b.getZ(); + this.data = b.getData(); + this.world = b.getWorld().getName(); + if (c) + { + this.inv = ((Chest) b.getState()).getInventory().getContents(); + this.item_mats = new ArrayList<>(); + this.item_data = new ArrayList<>(); + this.item_amounts = new ArrayList<>(); + this.item_displaynames = new ArrayList<>(); + this.item_splash = new ArrayList<>(); + + for (final ItemStack i : ((Chest) b.getState()).getInventory().getContents()) + { + if (i != null) + { + this.item_mats.add(i.getType()); + this.item_data.add(i.getData().getData()); + this.item_amounts.add(i.getAmount()); + this.item_displaynames.add(i.getItemMeta().getDisplayName()); + if (i.getType() == Material.POTION && i.getDurability() > 0 && i.getData().getData() > 0) + { + final Potion potion = Potion.fromDamage(i.getDurability() & 0x3F); + this.item_splash.add(potion.isSplash()); + } + else + { + this.item_splash.add(false); } } } } } - - public ArenaBlock(Location l) { - m = Material.AIR; - x = l.getBlockX(); - y = l.getBlockY(); - z = l.getBlockZ(); - world = l.getWorld().getName(); + + public ArenaBlock(final Location l) + { + this.m = Material.AIR; + this.x = l.getBlockX(); + this.y = l.getBlockY(); + this.z = l.getBlockZ(); + this.world = l.getWorld().getName(); } - - public Block getBlock() { - World w = Bukkit.getWorld(world); + + public Block getBlock() + { + final World w = Bukkit.getWorld(this.world); if (w == null) + { return null; - Block b = w.getBlockAt(x, y, z); + } + final Block b = w.getBlockAt(this.x, this.y, this.z); return b; } - - public Material getMaterial() { - return m; + + public Material getMaterial() + { + return this.m; } - - public Byte getData() { - return data; + + public Byte getData() + { + return this.data; } - - public ItemStack[] getInventory() { - return inv; + + public ItemStack[] getInventory() + { + return this.inv; } - - public ArrayList<ItemStack> getNewInventory() { - int c = 0; - ArrayList<ItemStack> ret = new ArrayList<ItemStack>(); - for (int i = 0; i < item_mats.size(); i++) { - ItemStack item = new ItemStack(item_mats.get(i), item_amounts.get(i), item_data.get(i)); - ItemMeta im = item.getItemMeta(); - im.setDisplayName(item_displaynames.get(i)); + + public ArrayList<ItemStack> getNewInventory() + { + final int c = 0; + final ArrayList<ItemStack> ret = new ArrayList<>(); + for (int i = 0; i < this.item_mats.size(); i++) + { + ItemStack item = new ItemStack(this.item_mats.get(i), this.item_amounts.get(i), this.item_data.get(i)); + final ItemMeta im = item.getItemMeta(); + im.setDisplayName(this.item_displaynames.get(i)); item.setItemMeta(im); - if (item.getType() == Material.POTION && item.getDurability() > 0) { - Potion potion = Potion.fromDamage(item.getDurability() & 0x3F); - potion.setSplash(item_splash.get(i)); - item = potion.toItemStack(item_amounts.get(i)); + if (item.getType() == Material.POTION && item.getDurability() > 0) + { + final Potion potion = Potion.fromDamage(item.getDurability() & 0x3F); + potion.setSplash(this.item_splash.get(i)); + item = potion.toItemStack(this.item_amounts.get(i)); } ret.add(item); } return ret; } - - public static ItemStack getEnchantmentBook(Map<Enchantment, Integer> t) { - ItemStack book = new ItemStack(Material.ENCHANTED_BOOK, 1); - ItemMeta meta = book.getItemMeta(); - int i = 0; - for (Enchantment e : t.keySet()) { + + public static ItemStack getEnchantmentBook(final Map<Enchantment, Integer> t) + { + final ItemStack book = new ItemStack(Material.ENCHANTED_BOOK, 1); + final ItemMeta meta = book.getItemMeta(); + final int i = 0; + for (final Enchantment e : t.keySet()) + { meta.addEnchant(e, t.get(e), true); } book.setItemMeta(meta); return book; } - -} \ No newline at end of file + +} diff --git a/API/src/main/java/com/comze_instancelabs/minigamesapi/util/ArenaLobbyScoreboard.java b/API/src/main/java/com/comze_instancelabs/minigamesapi/util/ArenaLobbyScoreboard.java index 16b50b4f..5410b71a 100644 --- a/API/src/main/java/com/comze_instancelabs/minigamesapi/util/ArenaLobbyScoreboard.java +++ b/API/src/main/java/com/comze_instancelabs/minigamesapi/util/ArenaLobbyScoreboard.java @@ -1,7 +1,22 @@ +/* + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ package com.comze_instancelabs.minigamesapi.util; import java.util.ArrayList; import java.util.HashMap; +import java.util.logging.Level; import org.bukkit.Bukkit; import org.bukkit.ChatColor; @@ -13,112 +28,159 @@ import org.bukkit.scoreboard.ScoreboardManager; import com.comze_instancelabs.minigamesapi.Arena; +import com.comze_instancelabs.minigamesapi.ArenaConfigStrings; import com.comze_instancelabs.minigamesapi.MinigamesAPI; import com.comze_instancelabs.minigamesapi.PluginInstance; -public class ArenaLobbyScoreboard { - - HashMap<String, Scoreboard> ascore = new HashMap<String, Scoreboard>(); - HashMap<String, Objective> aobjective = new HashMap<String, Objective>(); - - int initialized = 0; // 0 = false; 1 = true; - boolean custom = false; - - PluginInstance pli; - - ArrayList<String> loaded_custom_strings = new ArrayList<String>(); - - public ArenaLobbyScoreboard(PluginInstance pli, JavaPlugin plugin) { - custom = plugin.getConfig().getBoolean("config.use_custom_scoreboard"); - initialized = 1; - this.pli = pli; - if (pli.getMessagesConfig().getConfig().isSet("messages.custom_lobby_scoreboard.")) { - for (String configline : pli.getMessagesConfig().getConfig().getConfigurationSection("messages.custom_lobby_scoreboard.").getKeys(false)) { - String line = ChatColor.translateAlternateColorCodes('&', pli.getMessagesConfig().getConfig().getString("messages.custom_lobby_scoreboard." + configline)); - loaded_custom_strings.add(line); - } - } - } - - public void updateScoreboard(final JavaPlugin plugin, final Arena arena) { - if (!arena.getShowScoreboard()) { - return; - } - - if (pli == null) { - pli = MinigamesAPI.getAPI().getPluginInstance(plugin); - } - - Bukkit.getScheduler().runTask(MinigamesAPI.getAPI(), new Runnable() { - public void run() { - for (String playername : arena.getAllPlayers()) { - if (!Validator.isPlayerValid(plugin, playername, arena)) { - return; - } - Player p = Bukkit.getPlayer(playername); - if (!ascore.containsKey(playername)) { - ascore.put(playername, Bukkit.getScoreboardManager().getNewScoreboard()); - } - if (!aobjective.containsKey(playername)) { - aobjective.put(playername, ascore.get(playername).registerNewObjective(playername, "dummy")); - aobjective.get(playername).setDisplaySlot(DisplaySlot.SIDEBAR); - aobjective.get(playername).setDisplayName(pli.getMessagesConfig().scoreboard_lobby_title.replaceAll("<arena>", arena.getInternalName())); - } - - try { - if (loaded_custom_strings.size() < 1) { - return; - } - for (String line : loaded_custom_strings) { - String[] line_arr = line.split(":"); - String line_ = line_arr[0]; - String score_identifier = line_arr[line_arr.length - 1]; - if (line_arr.length > 2) { - line_ += ":" + line_arr[1]; - } - int score = 0; - if (score_identifier.equalsIgnoreCase("<playercount>")) { - score = arena.getAllPlayers().size(); - } else if (score_identifier.equalsIgnoreCase("<maxplayercount>")) { - score = arena.getMaxPlayers(); - } else if (score_identifier.equalsIgnoreCase("<points>")) { - score = pli.getStatsInstance().getPoints(playername); - } else if (score_identifier.equalsIgnoreCase("<wins>")) { - score = pli.getStatsInstance().getWins(playername); - } else if (score_identifier.equalsIgnoreCase("<money>")) { - score = (int) MinigamesAPI.econ.getBalance(playername); - } - if (line_.length() < 15) { - // ascore.get(arena.getInternalName()).resetScores(Bukkit.getOfflinePlayer(ChatColor.GREEN + line_)); - Util.getScore(aobjective.get(playername), ChatColor.GREEN + line_).setScore(score); - } else { - // ascore.get(arena.getInternalName()).resetScores(Bukkit.getOfflinePlayer(ChatColor.GREEN + line_.substring(0, - // Math.min(line_.length() - 3, 13)))); - Util.getScore(aobjective.get(playername), ChatColor.GREEN + line_.substring(0, Math.min(line_.length() - 3, 13))).setScore(score); - } - } - p.setScoreboard(ascore.get(playername)); - } catch (Exception e) { - System.out.println("Failed to set custom scoreboard: "); - e.printStackTrace(); - } - } - } - }); - } - - public void removeScoreboard(String arena, Player p) { - try { - ScoreboardManager manager = Bukkit.getScoreboardManager(); - Scoreboard sc = manager.getNewScoreboard(); - - p.setScoreboard(sc); - } catch (Exception e) { - e.printStackTrace(); - } - } - - public void clearScoreboard(String arenaname) { - // TODO - } +public class ArenaLobbyScoreboard +{ + + HashMap<String, Scoreboard> ascore = new HashMap<>(); + HashMap<String, Objective> aobjective = new HashMap<>(); + + int initialized = 0; // 0 = false; 1 = true; + boolean custom = false; + + PluginInstance pli; + + ArrayList<String> loaded_custom_strings = new ArrayList<>(); + + public ArenaLobbyScoreboard(final PluginInstance pli, final JavaPlugin plugin) + { + this.custom = plugin.getConfig().getBoolean(ArenaConfigStrings.CONFIG_USE_CUSTOM_SCOREBOARD); + this.initialized = 1; + this.pli = pli; + if (pli.getMessagesConfig().getConfig().isSet("messages.custom_lobby_scoreboard.")) + { + for (final String configline : pli.getMessagesConfig().getConfig().getConfigurationSection("messages.custom_lobby_scoreboard.").getKeys(false)) + { + final String line = ChatColor.translateAlternateColorCodes('&', pli.getMessagesConfig().getConfig().getString("messages.custom_lobby_scoreboard." + configline)); + this.loaded_custom_strings.add(line); + } + } + } + + public void updateScoreboard(final JavaPlugin plugin, final Arena arena) + { + if (!arena.getShowScoreboard()) + { + return; + } + + if (this.pli == null) + { + this.pli = MinigamesAPI.getAPI().getPluginInstance(plugin); + } + + Bukkit.getScheduler().runTask(MinigamesAPI.getAPI(), () -> { + for (final String playername : arena.getAllPlayers()) + { + if (!Validator.isPlayerValid(plugin, playername, arena)) + { + return; + } + final Player p = Bukkit.getPlayer(playername); + if (!ArenaLobbyScoreboard.this.ascore.containsKey(playername)) + { + final ScoreboardManager sbm = Bukkit.getScoreboardManager(); + if (sbm != null) + { + ArenaLobbyScoreboard.this.ascore.put(playername, sbm.getNewScoreboard()); + } + } + if (!ArenaLobbyScoreboard.this.aobjective.containsKey(playername)) + { + ArenaLobbyScoreboard.this.aobjective.put(playername, ArenaLobbyScoreboard.this.ascore.get(playername).registerNewObjective(playername, "dummy")); + ArenaLobbyScoreboard.this.aobjective.get(playername).setDisplaySlot(DisplaySlot.SIDEBAR); + ArenaLobbyScoreboard.this.aobjective.get(playername) + .setDisplayName(ArenaLobbyScoreboard.this.pli.getMessagesConfig().scoreboard_lobby_title.replaceAll("<arena>", arena.getDisplayName())); + } + else + { + ArenaLobbyScoreboard.this.aobjective.get(playername).setDisplayName(ArenaLobbyScoreboard.this.pli.getMessagesConfig().scoreboard_lobby_title.replaceAll("<arena>", arena.getDisplayName())); + } + + try + { + if (ArenaLobbyScoreboard.this.loaded_custom_strings.size() < 1) + { + return; + } + for (final String line : ArenaLobbyScoreboard.this.loaded_custom_strings) + { + final String[] line_arr = line.split(":"); + String line_ = line_arr[0]; + final String score_identifier = line_arr[line_arr.length - 1]; + if (line_arr.length > 2) + { + line_ += ":" + line_arr[1]; + } + int score = 0; + if (score_identifier.equalsIgnoreCase("<playercount>")) + { + score = arena.getAllPlayers().size(); + } + else if (score_identifier.equalsIgnoreCase("<maxplayercount>")) + { + score = arena.getMaxPlayers(); + } + else if (score_identifier.equalsIgnoreCase("<points>")) + { + score = ArenaLobbyScoreboard.this.pli.getStatsInstance().getPoints(playername); + } + else if (score_identifier.equalsIgnoreCase("<wins>")) + { + score = ArenaLobbyScoreboard.this.pli.getStatsInstance().getWins(playername); + } + else if (score_identifier.equalsIgnoreCase("<money>")) + { + score = (int) MinigamesAPI.econ.getBalance(playername); + } + else if (score_identifier.equalsIgnoreCase("<kills>")) + { + score = ArenaLobbyScoreboard.this.pli.getStatsInstance().getKills(playername); + } + if (line_.length() < 15) + { + // ascore.get(arena.getInternalName()).resetScores(Bukkit.getOfflinePlayer(ChatColor.GREEN + line_)); + Util.getScore(ArenaLobbyScoreboard.this.aobjective.get(playername), ChatColor.GREEN + line_).setScore(score); + } + else + { + // ascore.get(arena.getInternalName()).resetScores(Bukkit.getOfflinePlayer(ChatColor.GREEN + line_.substring(0, + // Math.min(line_.length() - 3, 13)))); + Util.getScore(ArenaLobbyScoreboard.this.aobjective.get(playername), ChatColor.GREEN + line_.substring(0, Math.min(line_.length() - 3, 13))).setScore(score); + } + } + p.setScoreboard(ArenaLobbyScoreboard.this.ascore.get(playername)); + } + catch (final Exception e) + { + pli.getPlugin().getLogger().log(Level.SEVERE, "Failed to set custom scoreboard", e); + } + } + }); + } + + public void removeScoreboard(final String arena, final Player p) + { + try + { + final ScoreboardManager manager = Bukkit.getScoreboardManager(); + if (manager != null) + { + final Scoreboard sc = manager.getNewScoreboard(); + p.setScoreboard(sc); + } + } + catch (final Exception e) + { + MinigamesAPI.getAPI().getLogger().log(Level.WARNING, "exception", e); + } + } + + public void clearScoreboard(final String arenaname) + { + // TODO + } } diff --git a/API/src/main/java/com/comze_instancelabs/minigamesapi/util/ArenaScoreboard.java b/API/src/main/java/com/comze_instancelabs/minigamesapi/util/ArenaScoreboard.java index 7d1c808f..bcd2ea5f 100644 --- a/API/src/main/java/com/comze_instancelabs/minigamesapi/util/ArenaScoreboard.java +++ b/API/src/main/java/com/comze_instancelabs/minigamesapi/util/ArenaScoreboard.java @@ -1,7 +1,22 @@ +/* + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ package com.comze_instancelabs.minigamesapi.util; import java.util.ArrayList; import java.util.HashMap; +import java.util.logging.Level; import org.bukkit.Bukkit; import org.bukkit.ChatColor; @@ -10,205 +25,381 @@ import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.scoreboard.DisplaySlot; import org.bukkit.scoreboard.Objective; +import org.bukkit.scoreboard.Score; import org.bukkit.scoreboard.Scoreboard; import org.bukkit.scoreboard.ScoreboardManager; +import org.bukkit.scoreboard.Team; import com.comze_instancelabs.minigamesapi.Arena; +import com.comze_instancelabs.minigamesapi.ArenaConfigStrings; +import com.comze_instancelabs.minigamesapi.MinecraftVersionsType; import com.comze_instancelabs.minigamesapi.MinigamesAPI; import com.comze_instancelabs.minigamesapi.PluginInstance; -public class ArenaScoreboard { - - HashMap<String, Scoreboard> ascore = new HashMap<String, Scoreboard>(); - HashMap<String, Objective> aobjective = new HashMap<String, Objective>(); - HashMap<String, Integer> currentscore = new HashMap<String, Integer>(); - - int initialized = 0; // 0 = false; 1 = true; - boolean custom = false; - - PluginInstance pli; - - ArrayList<String> loaded_custom_strings = new ArrayList<String>(); - - public ArenaScoreboard() { - // - } - - public ArenaScoreboard(PluginInstance pli, JavaPlugin plugin) { - custom = plugin.getConfig().getBoolean("config.use_custom_scoreboard"); - initialized = 1; - this.pli = pli; - if (pli.getMessagesConfig().getConfig().isSet("messages.custom_scoreboard.")) { - for (String configline : pli.getMessagesConfig().getConfig().getConfigurationSection("messages.custom_scoreboard.").getKeys(false)) { - String line = ChatColor.translateAlternateColorCodes('&', pli.getMessagesConfig().getConfig().getString("messages.custom_scoreboard." + configline)); - loaded_custom_strings.add(line); - } - } - } - - public void updateScoreboard(final JavaPlugin plugin, final Arena arena) { - if (!arena.getShowScoreboard()) { - return; - } - - if (initialized != 1) { - custom = plugin.getConfig().getBoolean("config.use_custom_scoreboard"); - } - - if (pli == null) { - pli = MinigamesAPI.getAPI().getPluginInstance(plugin); - } - - Bukkit.getScheduler().runTask(MinigamesAPI.getAPI(), new Runnable() { - public void run() { - for (String playername : arena.getAllPlayers()) { - if (!Validator.isPlayerValid(plugin, playername, arena)) { - return; - } - Player p = Bukkit.getPlayer(playername); - if (!custom) { - if (!ascore.containsKey(arena.getInternalName())) { - ascore.put(arena.getInternalName(), Bukkit.getScoreboardManager().getNewScoreboard()); - } - if (!aobjective.containsKey(arena.getInternalName())) { - aobjective.put(arena.getInternalName(), ascore.get(arena.getInternalName()).registerNewObjective(arena.getInternalName(), "dummy")); - aobjective.get(arena.getInternalName()).setDisplaySlot(DisplaySlot.SIDEBAR); - aobjective.get(arena.getInternalName()).setDisplayName(pli.getMessagesConfig().scoreboard_title.replaceAll("<arena>", arena.getInternalName())); - } - } else { - if (!ascore.containsKey(playername)) { - ascore.put(playername, Bukkit.getScoreboardManager().getNewScoreboard()); - } - if (!aobjective.containsKey(playername)) { - aobjective.put(playername, ascore.get(playername).registerNewObjective(playername, "dummy")); - aobjective.get(playername).setDisplaySlot(DisplaySlot.SIDEBAR); - aobjective.get(playername).setDisplayName(pli.getMessagesConfig().scoreboard_title.replaceAll("<arena>", arena.getInternalName())); - } - } - - if (custom) { - try { - for (String line : loaded_custom_strings) { - String[] line_arr = line.split(":"); - String line_ = line_arr[0]; - String score_identifier = line_arr[1]; - int score = 0; - if (score_identifier.equalsIgnoreCase("<playercount>")) { - score = arena.getAllPlayers().size(); - } else if (score_identifier.equalsIgnoreCase("<lostplayercount>")) { - score = arena.getAllPlayers().size() - arena.getPlayerAlive(); - } else if (score_identifier.equalsIgnoreCase("<playeralivecount>")) { - score = arena.getPlayerAlive(); - } else if (score_identifier.equalsIgnoreCase("<points>")) { - score = pli.getStatsInstance().getPoints(playername); - } else if (score_identifier.equalsIgnoreCase("<wins>")) { - score = pli.getStatsInstance().getWins(playername); - } else if (score_identifier.equalsIgnoreCase("<money>")) { - score = (int) MinigamesAPI.econ.getBalance(playername); - } - if (line_.length() < 15) { - Util.resetScores(ascore.get(playername), ChatColor.GREEN + line_); - Util.getScore(aobjective.get(playername), ChatColor.GREEN + line_).setScore(score); - } else { - Util.resetScores(ascore.get(playername), ChatColor.GREEN + line_.substring(0, Math.min(line_.length() - 3, 13))); - Util.getScore(aobjective.get(playername), ChatColor.GREEN + line_.substring(0, Math.min(line_.length() - 3, 13))).setScore(score); - } - } - - if (ascore.get(playername) != null) { - p.setScoreboard(ascore.get(playername)); - } - } catch (Exception e) { - System.out.println("Failed to set custom scoreboard: "); - e.printStackTrace(); - } - } else { - for (String playername_ : arena.getAllPlayers()) { - if (!Validator.isPlayerOnline(playername_)) { - continue; - } - Player p_ = Bukkit.getPlayer(playername_); - if (!pli.global_lost.containsKey(playername_)) { - int score = 0; - if (currentscore.containsKey(playername_)) { - int oldscore = currentscore.get(playername_); - if (score > oldscore) { - currentscore.put(playername_, score); - } else { - score = oldscore; - } - } else { - currentscore.put(playername_, score); - } - try { - if (p_.getName().length() < 15) { - Util.getScore(aobjective.get(arena.getInternalName()), ChatColor.GREEN + p_.getName()).setScore(0); - } else { - Util.getScore(aobjective.get(arena.getInternalName()), ChatColor.GREEN + p_.getName().substring(0, p_.getName().length() - 3)).setScore(0); - ; - } - } catch (Exception e) { - } - } else if (pli.global_lost.containsKey(playername_)) { - try { - if (currentscore.containsKey(playername_)) { - int score = currentscore.get(playername_); - if (p_.getName().length() < 15) { - Util.resetScores(ascore.get(arena.getInternalName()), ChatColor.GREEN + p_.getName()); - Util.getScore(aobjective.get(arena.getInternalName()), ChatColor.RED + p_.getName()).setScore(0); - } else { - Util.resetScores(ascore.get(arena.getInternalName()), ChatColor.GREEN + p_.getName().substring(0, p_.getName().length() - 3)); - Util.getScore(aobjective.get(arena.getInternalName()), ChatColor.RED + p_.getName().substring(0, p_.getName().length() - 3)).setScore(0); - } - } - } catch (Exception e) { - } - } - } - - if (ascore.get(arena.getInternalName()) != null) { - p.setScoreboard(ascore.get(arena.getInternalName())); - } - } - - } - } - }); - } - - public void removeScoreboard(String arena, Player p) { - try { - ScoreboardManager manager = Bukkit.getScoreboardManager(); - Scoreboard sc = manager.getNewScoreboard(); - - p.setScoreboard(sc); - } catch (Exception e) { - e.printStackTrace(); - } - } - - public void clearScoreboard(String arenaname) { - if (ascore.containsKey(arenaname)) { - try { - Scoreboard sc = ascore.get(arenaname); - for (OfflinePlayer player : sc.getPlayers()) { - sc.resetScores(player); - } - } catch (Exception e) { - if (MinigamesAPI.debug) { - e.printStackTrace(); - } - } - ascore.remove(arenaname); - } - if (aobjective.containsKey(arenaname)) { - aobjective.remove(arenaname); - } - - // ascore.put(arenaname, Bukkit.getScoreboardManager().getNewScoreboard()); - } - - public void setCurrentScoreMap(HashMap<String, Integer> newcurrentscore) { - this.currentscore = newcurrentscore; - } +public class ArenaScoreboard +{ + + HashMap<String, Scoreboard> ascore = new HashMap<>(); + HashMap<String, Objective> aobjective = new HashMap<>(); + HashMap<String, Integer> currentscore = new HashMap<>(); + + int initialized = 0; // 0 = false; 1 = true; + boolean custom = false; + + PluginInstance pli; + + ArrayList<String> loaded_custom_strings = new ArrayList<>(); + + public static Scoreboard getMainScoreboard() + { + final ScoreboardManager sbm = Bukkit.getScoreboardManager(); + return sbm == null ? null : sbm.getMainScoreboard(); + } + + public static Team getMainScoreboardTeam(String team) + { + final Scoreboard main = getMainScoreboard(); + return main == null ? null : main.getTeam(team); + } + + public static boolean mainScoreboardHasPlayer(String team, Player p) + { + final Team t = getMainScoreboardTeam(team); + return t == null ? false : t.hasPlayer(p); + } + + public static void mainScoreboardAddPlayer(String team, Player p) + { + final Team t = getMainScoreboardTeam(team); + if (t != null) + { + t.addPlayer(p); + } + } + + public static void mainScoreboardRemovePlayer(String team, Player p) + { + final Team t = getMainScoreboardTeam(team); + if (t != null) + { + t.removePlayer(p); + } + } + + public static Team mainScoreboardRegisterTeam(String team) + { + final Scoreboard main = getMainScoreboard(); + if (main != null) + { + final Team t = main.getTeam(team); + if (t == null) + { + main.registerNewTeam(team); + } + } + return getMainScoreboardTeam(team); + } + + public ArenaScoreboard() + { + // + } + + public ArenaScoreboard(final PluginInstance pli, final JavaPlugin plugin) + { + this.custom = plugin.getConfig().getBoolean(ArenaConfigStrings.CONFIG_USE_CUSTOM_SCOREBOARD); + this.initialized = 1; + this.pli = pli; + if (pli.getMessagesConfig().getConfig().isSet("messages.custom_scoreboard.")) + { + for (final String configline : pli.getMessagesConfig().getConfig().getConfigurationSection("messages.custom_scoreboard.").getKeys(false)) + { + final String line = ChatColor.translateAlternateColorCodes('&', pli.getMessagesConfig().getConfig().getString("messages.custom_scoreboard." + configline)); + this.loaded_custom_strings.add(line); + } + } + } + + public void updateScoreboard(final JavaPlugin plugin, final Arena arena) + { + if (!arena.getShowScoreboard()) + { + return; + } + + if (this.initialized != 1) + { + this.custom = plugin.getConfig().getBoolean(ArenaConfigStrings.CONFIG_USE_CUSTOM_SCOREBOARD); + } + + if (this.pli == null) + { + this.pli = MinigamesAPI.getAPI().getPluginInstance(plugin); + } + + Bukkit.getScheduler().runTask(MinigamesAPI.getAPI(), () -> { + for (final String playername : arena.getAllPlayers()) + { + if (!Validator.isPlayerValid(plugin, playername, arena)) + { + return; + } + final Player p = Bukkit.getPlayer(playername); + final ScoreboardManager scoreboardManager = Bukkit.getScoreboardManager(); + if (!ArenaScoreboard.this.custom) + { + if (!ArenaScoreboard.this.ascore.containsKey(arena.getInternalName())) + { + if (scoreboardManager != null) + { + ArenaScoreboard.this.ascore.put(arena.getInternalName(), scoreboardManager.getNewScoreboard()); + } + } + if (!ArenaScoreboard.this.aobjective.containsKey(arena.getInternalName())) + { + ArenaScoreboard.this.aobjective.put(arena.getInternalName(), ArenaScoreboard.this.ascore.get(arena.getInternalName()).registerNewObjective(arena.getInternalName(), "dummy")); + ArenaScoreboard.this.aobjective.get(arena.getInternalName()).setDisplaySlot(DisplaySlot.SIDEBAR); + ArenaScoreboard.this.aobjective.get(arena.getInternalName()) + .setDisplayName(ArenaScoreboard.this.pli.getMessagesConfig().scoreboard_title.replaceAll("<arena>", arena.getDisplayName())); + } + } + else + { + if (!ArenaScoreboard.this.ascore.containsKey(playername)) + { + if (scoreboardManager != null) + { + ArenaScoreboard.this.ascore.put(playername, scoreboardManager.getNewScoreboard()); + } + } + if (!ArenaScoreboard.this.aobjective.containsKey(playername)) + { + ArenaScoreboard.this.aobjective.put(playername, ArenaScoreboard.this.ascore.get(playername).registerNewObjective(playername, "dummy")); + ArenaScoreboard.this.aobjective.get(playername).setDisplaySlot(DisplaySlot.SIDEBAR); + ArenaScoreboard.this.aobjective.get(playername).setDisplayName(ArenaScoreboard.this.pli.getMessagesConfig().scoreboard_title.replaceAll("<arena>", arena.getDisplayName())); + } + else + { + ArenaScoreboard.this.aobjective.get(playername).setDisplayName(ArenaScoreboard.this.pli.getMessagesConfig().scoreboard_title.replaceAll("<arena>", arena.getDisplayName())); + } + } + + if (ArenaScoreboard.this.custom) + { + try + { + for (final String line : ArenaScoreboard.this.loaded_custom_strings) + { + final String[] line_arr = line.split(":"); + final String line_ = line_arr[0]; + final String score_identifier = line_arr[1]; + int score1 = 0; + if (score_identifier.equalsIgnoreCase("<playercount>")) + { + score1 = arena.getAllPlayers().size(); + } + else if (score_identifier.equalsIgnoreCase("<lostplayercount>")) + { + score1 = arena.getAllPlayers().size() - arena.getPlayerAlive(); + } + else if (score_identifier.equalsIgnoreCase("<playeralivecount>")) + { + score1 = arena.getPlayerAlive(); + } + else if (score_identifier.equalsIgnoreCase("<points>")) + { + score1 = ArenaScoreboard.this.pli.getStatsInstance().getPoints(playername); + } + else if (score_identifier.equalsIgnoreCase("<wins>")) + { + score1 = ArenaScoreboard.this.pli.getStatsInstance().getWins(playername); + } + else if (score_identifier.equalsIgnoreCase("<money>")) + { + score1 = (int) MinigamesAPI.econ.getBalance(playername); + } + if (line_.length() < 15) + { + Util.resetScores(ArenaScoreboard.this.ascore.get(playername), ChatColor.GREEN + line_); + Util.getScore(ArenaScoreboard.this.aobjective.get(playername), ChatColor.GREEN + line_).setScore(score1); + } + else + { + Util.resetScores(ArenaScoreboard.this.ascore.get(playername), ChatColor.GREEN + line_.substring(0, Math.min(line_.length() - 3, 13))); + Util.getScore(ArenaScoreboard.this.aobjective.get(playername), ChatColor.GREEN + line_.substring(0, Math.min(line_.length() - 3, 13))).setScore(score1); + } + } + + if (ArenaScoreboard.this.ascore.get(playername) != null) + { + p.setScoreboard(ArenaScoreboard.this.ascore.get(playername)); + } + } + catch (final Exception e1) + { + pli.getPlugin().getLogger().log(Level.SEVERE, "Failed to set custom scoreboard", e1); + } + } + else + { + for (final String playername_ : arena.getAllPlayers()) + { + if (!Validator.isPlayerOnline(playername_)) + { + continue; + } + final Player p_ = Bukkit.getPlayer(playername_); + if (!ArenaScoreboard.this.pli.global_lost.containsKey(playername_)) + { + int score2 = 0; + if (ArenaScoreboard.this.currentscore.containsKey(playername_)) + { + final int oldscore = ArenaScoreboard.this.currentscore.get(playername_); + if (score2 > oldscore) + { + ArenaScoreboard.this.currentscore.put(playername_, score2); + } + else + { + score2 = oldscore; + } + } + else + { + ArenaScoreboard.this.currentscore.put(playername_, score2); + } + try + { + if (p_.getName().length() < 15) + { + Util.getScore(ArenaScoreboard.this.aobjective.get(arena.getInternalName()), ChatColor.GREEN + p_.getName()).setScore(0); + } + else + { + Util.getScore(ArenaScoreboard.this.aobjective.get(arena.getInternalName()), ChatColor.GREEN + p_.getName().substring(0, p_.getName().length() - 3)).setScore(0); + } + } + catch (final Exception e2) + { + // silently ignore + } + } + else if (ArenaScoreboard.this.pli.global_lost.containsKey(playername_)) + { + try + { + if (ArenaScoreboard.this.currentscore.containsKey(playername_)) + { + final int score3 = ArenaScoreboard.this.currentscore.get(playername_); + if (p_.getName().length() < 15) + { + Util.resetScores(ArenaScoreboard.this.ascore.get(arena.getInternalName()), ChatColor.GREEN + p_.getName()); + Util.getScore(ArenaScoreboard.this.aobjective.get(arena.getInternalName()), ChatColor.RED + p_.getName()).setScore(0); + } + else + { + Util.resetScores(ArenaScoreboard.this.ascore.get(arena.getInternalName()), ChatColor.GREEN + p_.getName().substring(0, p_.getName().length() - 3)); + Util.getScore(ArenaScoreboard.this.aobjective.get(arena.getInternalName()), ChatColor.RED + p_.getName().substring(0, p_.getName().length() - 3)).setScore(0); + } + } + } + catch (final Exception e3) + { + // silently ignore + } + } + } + + if (ArenaScoreboard.this.ascore.get(arena.getInternalName()) != null) + { + p.setScoreboard(ArenaScoreboard.this.ascore.get(arena.getInternalName())); + } + } + + } + }); + } + + public void removeScoreboard(final String arena, final Player p) + { + try + { + final ScoreboardManager manager = Bukkit.getScoreboardManager(); + if (manager != null) + { + final Scoreboard sc = manager.getNewScoreboard(); + + p.setScoreboard(sc); + } + } + catch (final Exception e) + { + MinigamesAPI.getAPI().getLogger().log(Level.WARNING, "exception", e); + } + } + + public static Score get(Objective objective, String name) + { + if (MinigamesAPI.SERVER_VERSION.isAtLeast(MinecraftVersionsType.V1_7_R3)) + { + return objective.getScore(name); + } + return objective.getScore(Bukkit.getOfflinePlayer(name)); + } + + public static void reset(Scoreboard sb, String name) + { + if (MinigamesAPI.SERVER_VERSION.isAtLeast(MinecraftVersionsType.V1_7_R3)) + { + sb.resetScores(name); + } + else + { + sb.resetScores(Bukkit.getOfflinePlayer(name)); + } + } + + public void clearScoreboard(final String arenaname) + { + if (this.ascore.containsKey(arenaname)) + { + try + { + final Scoreboard sc = this.ascore.get(arenaname); + if (MinigamesAPI.SERVER_VERSION.isAtLeast(MinecraftVersionsType.V1_7_R3)) + { + for (final String player : sc.getEntries()) + { + sc.resetScores(player); + } + } + else + { + for (final OfflinePlayer player : sc.getPlayers()) + { + sc.resetScores(player); + } + } + } + catch (final Exception e) + { + if (MinigamesAPI.debug) + { + MinigamesAPI.getAPI().getLogger().log(Level.WARNING, "exception", e); + } + } + this.ascore.remove(arenaname); + } + if (this.aobjective.containsKey(arenaname)) + { + this.aobjective.remove(arenaname); + } + + // ascore.put(arenaname, Bukkit.getScoreboardManager().getNewScoreboard()); + } + + public void setCurrentScoreMap(final HashMap<String, Integer> newcurrentscore) + { + this.currentscore = newcurrentscore; + } } diff --git a/API/src/main/java/com/comze_instancelabs/minigamesapi/util/BungeeUtil.java b/API/src/main/java/com/comze_instancelabs/minigamesapi/util/BungeeUtil.java index e0759bc7..55f03624 100644 --- a/API/src/main/java/com/comze_instancelabs/minigamesapi/util/BungeeUtil.java +++ b/API/src/main/java/com/comze_instancelabs/minigamesapi/util/BungeeUtil.java @@ -1,53 +1,57 @@ +/* + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ package com.comze_instancelabs.minigamesapi.util; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.IOException; +import java.util.logging.Level; import org.bukkit.Bukkit; import org.bukkit.plugin.java.JavaPlugin; import com.comze_instancelabs.minigamesapi.Arena; +import com.comze_instancelabs.minigamesapi.ChannelStrings; import com.comze_instancelabs.minigamesapi.MinigamesAPI; import com.comze_instancelabs.minigamesapi.PluginInstance; -import com.comze_instancelabs.minigamesapi.bungee.BungeeSocket; import com.google.common.io.ByteArrayDataOutput; import com.google.common.io.ByteStreams; -public class BungeeUtil { - - public static void connectToServer(JavaPlugin plugin, String player, String server) { - ByteArrayOutputStream stream = new ByteArrayOutputStream(); - DataOutputStream out = new DataOutputStream(stream); - try { - out.writeUTF("Connect"); - out.writeUTF(server); - } catch (IOException e) { - e.printStackTrace(); - } - Bukkit.getPlayer(player).sendPluginMessage(plugin, "BungeeCord", stream.toByteArray()); - } - - public static void sendSignUpdateRequest(JavaPlugin plugin, String minigame, Arena arena) { - PluginInstance pli = MinigamesAPI.getAPI().getPluginInstance(plugin); - BungeeSocket.sendSignUpdate(pli, arena); - ByteArrayDataOutput out = ByteStreams.newDataOutput(); - try { - out.writeUTF("Forward"); - out.writeUTF("ALL"); - out.writeUTF("MinigamesLib"); - - ByteArrayOutputStream msgbytes = new ByteArrayOutputStream(); - DataOutputStream msgout = new DataOutputStream(msgbytes); - msgout.writeUTF(minigame + ":" + arena.getInternalName() + ":" + arena.getArenaState().toString() + ":" + Integer.toString(arena.getAllPlayers().size()) + ":" + Integer.toString(arena.getMaxPlayers())); - - out.writeShort(msgbytes.toByteArray().length); - out.write(msgbytes.toByteArray()); - - Bukkit.getServer().sendPluginMessage(MinigamesAPI.getAPI(), "BungeeCord", out.toByteArray()); - } catch (Exception e) { - e.printStackTrace(); - } - } - +public class BungeeUtil +{ + + public static void connectToServer(final JavaPlugin plugin, final String player, final String server) + { + final ByteArrayOutputStream stream = new ByteArrayOutputStream(); + final DataOutputStream out = new DataOutputStream(stream); + try + { + out.writeUTF("Connect"); + out.writeUTF(server); + } + catch (final IOException e) + { + MinigamesAPI.getAPI().getLogger().log(Level.WARNING, "exception", e); + } + Bukkit.getPlayer(player).sendPluginMessage(plugin, ChannelStrings.CHANNEL_BUNGEE_CORD, stream.toByteArray()); + } + + public static void sendSignUpdateRequest(final JavaPlugin plugin, final String minigame, final Arena arena) + { + final PluginInstance pli = MinigamesAPI.getAPI().getPluginInstance(plugin); + MinigamesAPI.getAPI().sendSignUpdate(pli, arena); + } + } diff --git a/API/src/main/java/com/comze_instancelabs/minigamesapi/util/ChangeCause.java b/API/src/main/java/com/comze_instancelabs/minigamesapi/util/ChangeCause.java index 43024259..af1d0c8b 100644 --- a/API/src/main/java/com/comze_instancelabs/minigamesapi/util/ChangeCause.java +++ b/API/src/main/java/com/comze_instancelabs/minigamesapi/util/ChangeCause.java @@ -1,7 +1,22 @@ -package com.comze_instancelabs.minigamesapi.util; +/* + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -public enum ChangeCause { + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ +package com.comze_instancelabs.minigamesapi.util; - FADE, PHYSICS, BREAK, SPREAD, BURN, FROM_TO, ENTITY_CHANGE +public enum ChangeCause +{ + + FADE, PHYSICS, BREAK, SPREAD, BURN, FROM_TO, ENTITY_CHANGE } diff --git a/API/src/main/java/com/comze_instancelabs/minigamesapi/util/Cuboid.java b/API/src/main/java/com/comze_instancelabs/minigamesapi/util/Cuboid.java index e30fe5d6..b5175078 100644 --- a/API/src/main/java/com/comze_instancelabs/minigamesapi/util/Cuboid.java +++ b/API/src/main/java/com/comze_instancelabs/minigamesapi/util/Cuboid.java @@ -1,3 +1,17 @@ +/* + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ package com.comze_instancelabs.minigamesapi.util; import java.util.LinkedHashMap; @@ -10,250 +24,286 @@ /** * Modified by: - * + * * @author instancelabs - * + * * Original version by: * @author Pandemoneus - https://github.com/Pandemoneus */ -public final class Cuboid { - private final Location highPoints; - private final Location lowPoints; - - /** - * Constructs a new cuboid. - * - * @param startLoc - * the first point - * @param endLoc - * the second point - */ - public Cuboid(Location startLoc, Location endLoc) { - - if (startLoc != null && endLoc != null) { - final int lowx = Math.min(startLoc.getBlockX(), endLoc.getBlockX()); - final int lowy = Math.min(startLoc.getBlockY(), endLoc.getBlockY()); - final int lowz = Math.min(startLoc.getBlockZ(), endLoc.getBlockZ()); - - final int highx = Math.max(startLoc.getBlockX(), endLoc.getBlockX()); - final int highy = Math.max(startLoc.getBlockY(), endLoc.getBlockY()); - final int highz = Math.max(startLoc.getBlockZ(), endLoc.getBlockZ()); - - highPoints = new Location(startLoc.getWorld(), highx, highy, highz); - lowPoints = new Location(startLoc.getWorld(), lowx, lowy, lowz); - } else { - highPoints = null; - lowPoints = null; - } - - } - - /** - * Determines whether the passed area is within this area. - * - * @param area - * the area to check - * @return true if the area is within this area, otherwise false - */ - public boolean isAreaWithinArea(Cuboid area) { - return (containsLoc(area.highPoints) && containsLoc(area.lowPoints)); - } - - /** - * Determines whether the this cuboid contains the passed location. - * - * @param loc - * the location to check - * @return true if the location is within this cuboid, otherwise false - */ - public boolean containsLoc(Location loc) { - if (loc == null || !loc.getWorld().equals(highPoints.getWorld())) { - return false; - } - - return lowPoints.getBlockX() <= loc.getBlockX() && highPoints.getBlockX() >= loc.getBlockX() && lowPoints.getBlockZ() <= loc.getBlockZ() && highPoints.getBlockZ() >= loc.getBlockZ() && lowPoints.getBlockY() <= loc.getBlockY() && highPoints.getBlockY() >= loc.getBlockY(); - } - - public boolean containsLocWithoutY(Location loc) { - if (highPoints == null || lowPoints == null) { - return false; - } - if (loc == null || !loc.getWorld().equals(highPoints.getWorld())) { - return false; - } - - return lowPoints.getBlockX() <= loc.getBlockX() && highPoints.getBlockX() >= loc.getBlockX() && lowPoints.getBlockZ() <= loc.getBlockZ() && highPoints.getBlockZ() >= loc.getBlockZ(); - } - - public boolean containsLocWithoutYD(Location loc) { - if (highPoints == null || lowPoints == null) { - return false; - } - if (loc == null || !loc.getWorld().equals(highPoints.getWorld())) { - return false; - } - - return lowPoints.getBlockX() <= loc.getBlockX() + 2 && highPoints.getBlockX() >= loc.getBlockX() - 2 && lowPoints.getBlockZ() <= loc.getBlockZ() + 2 && highPoints.getBlockZ() >= loc.getBlockZ() - 2; - } - - /** - * Returns the volume of this cuboid. - * - * @return the volume of this cuboid - */ - public long getSize() { - return Math.abs(getXSize() * getYSize() * getZSize()); - } - - /** - * Determines a random location inside the cuboid and returns it. - * - * @return a random location within the cuboid - */ - public Location getRandomLocation() { - final World world = getWorld(); - final Random randomGenerator = new Random(); - - Location result = new Location(world, highPoints.getBlockX(), highPoints.getBlockY(), highPoints.getZ()); - - if (getSize() > 1) { - final double randomX = lowPoints.getBlockX() + randomGenerator.nextInt(getXSize()); - final double randomY = lowPoints.getBlockY() + randomGenerator.nextInt(getYSize()); - final double randomZ = lowPoints.getBlockZ() + randomGenerator.nextInt(getZSize()); - - result = new Location(world, randomX, randomY, randomZ); - } - - return result; - } - - /** - * Determines a random location inside the cuboid that is suitable for mob spawning and returns it. - * - * @return a random location inside the cuboid that is suitable for mob spawning - */ - public Location getRandomLocationForMobs() { - final Location temp = getRandomLocation(); - - return new Location(temp.getWorld(), temp.getBlockX() + 0.5, temp.getBlockY() + 0.5, temp.getBlockZ() + 0.5); - } - - /** - * Returns the x span of this cuboid. - * - * @return the x span of this cuboid - */ - public int getXSize() { - return (highPoints.getBlockX() - lowPoints.getBlockX()) + 1; - } - - /** - * Returns the y span of this cuboid. - * - * @return the y span of this cuboid - */ - public int getYSize() { - return (highPoints.getBlockY() - lowPoints.getBlockY()) + 1; - } - - /** - * Returns the z span of this cuboid. - * - * @return the z span of this cuboid - */ - public int getZSize() { - return (highPoints.getBlockZ() - lowPoints.getBlockZ()) + 1; - } - - /** - * Returns the higher location of this cuboid. - * - * @return the higher location of this cuboid - */ - public Location getHighLoc() { - return highPoints; - } - - /** - * Returns the lower location of this cuboid. - * - * @return the lower location of this cuboid - */ - public Location getLowLoc() { - return lowPoints; - } - - /** - * Returns the world this cuboid is in. - * - * @return the world this cuboid is in - */ - public World getWorld() { - return highPoints.getWorld(); - } - - /** - * Saves the cuboid to a Map. - * - * @return the cuboid in a Map - */ - public Map<String, Object> save() { - Map<String, Object> root = new LinkedHashMap<String, Object>(); - - root.put("World", this.highPoints.getWorld().getName()); - root.put("X1", this.highPoints.getBlockX()); - root.put("Y1", this.highPoints.getBlockY()); - root.put("Z1", this.highPoints.getBlockZ()); - root.put("X2", this.lowPoints.getBlockX()); - root.put("Y2", this.lowPoints.getBlockY()); - root.put("Z2", this.lowPoints.getBlockZ()); - - return root; - } - - /** - * Loads the cuboid from a Map. - * - * @param root - * the Map - * @param world - * the world it should be in - * @return the cuboid - * @throws IllegalArgumentException - */ - public static Cuboid load(Map<String, Object> root) throws IllegalArgumentException { - if (root == null) { - throw new IllegalArgumentException("Invalid root map!"); - } - - final String owner = (String) root.get("Owner"); - final World world = Bukkit.getServer().getWorld((String) root.get("World")); - final int x1 = (Integer) root.get("X1"); - final int y1 = (Integer) root.get("Y1"); - final int z1 = (Integer) root.get("Z1"); - final int x2 = (Integer) root.get("X2"); - final int y2 = (Integer) root.get("Y2"); - final int z2 = (Integer) root.get("Z2"); - - final Cuboid newArea = new Cuboid(new Location(world, x1, y1, z1), new Location(world, x2, y2, z2)); - - return newArea; - } - - /** - * {@inheritDoc} - */ - @Override - public String toString() { - return new StringBuilder("(").append(lowPoints.getBlockX()).append(", ").append(lowPoints.getBlockY()).append(", ").append(lowPoints.getBlockZ()).append(") to (").append(highPoints.getBlockX()).append(", ").append(highPoints.getBlockY()).append(", ").append(highPoints.getBlockZ()).append(")").toString(); - } - - /** - * Returns a raw representation that is easy to read for Java. - * - * @return a raw representation of this cuboid - */ - public String toRaw() { - return new StringBuilder(getWorld().getName()).append(",").append(lowPoints.getBlockX()).append(",").append(lowPoints.getBlockY()).append(",").append(lowPoints.getBlockZ()).append(",").append(highPoints.getBlockX()).append(",").append(highPoints.getBlockY()).append(",").append(highPoints.getBlockZ()).toString(); - } -} \ No newline at end of file +public final class Cuboid +{ + private final Location highPoints; + private final Location lowPoints; + + /** + * Constructs a new cuboid. + * + * @param startLoc + * the first point + * @param endLoc + * the second point + */ + public Cuboid(final Location startLoc, final Location endLoc) + { + + if (startLoc != null && endLoc != null) + { + final int lowx = Math.min(startLoc.getBlockX(), endLoc.getBlockX()); + final int lowy = Math.min(startLoc.getBlockY(), endLoc.getBlockY()); + final int lowz = Math.min(startLoc.getBlockZ(), endLoc.getBlockZ()); + + final int highx = Math.max(startLoc.getBlockX(), endLoc.getBlockX()); + final int highy = Math.max(startLoc.getBlockY(), endLoc.getBlockY()); + final int highz = Math.max(startLoc.getBlockZ(), endLoc.getBlockZ()); + + this.highPoints = new Location(startLoc.getWorld(), highx, highy, highz); + this.lowPoints = new Location(startLoc.getWorld(), lowx, lowy, lowz); + } + else + { + this.highPoints = null; + this.lowPoints = null; + } + + } + + /** + * Determines whether the passed area is within this area. + * + * @param area + * the area to check + * @return true if the area is within this area, otherwise false + */ + public boolean isAreaWithinArea(final Cuboid area) + { + return (this.containsLoc(area.highPoints) && this.containsLoc(area.lowPoints)); + } + + /** + * Determines whether the this cuboid contains the passed location. + * + * @param loc + * the location to check + * @return true if the location is within this cuboid, otherwise false + */ + public boolean containsLoc(final Location loc) + { + if (this.highPoints == null || this.lowPoints == null) + { + return false; + } + if (loc == null || loc.getWorld() == null || !loc.getWorld().equals(this.highPoints.getWorld())) + { + return false; + } + + return this.lowPoints.getBlockX() <= loc.getBlockX() && this.highPoints.getBlockX() >= loc.getBlockX() && this.lowPoints.getBlockZ() <= loc.getBlockZ() + && this.highPoints.getBlockZ() >= loc.getBlockZ() && this.lowPoints.getBlockY() <= loc.getBlockY() && this.highPoints.getBlockY() >= loc.getBlockY(); + } + + public boolean containsLocWithoutY(final Location loc) + { + if (this.highPoints == null || this.lowPoints == null) + { + return false; + } + if (loc == null || loc.getWorld() == null || !loc.getWorld().equals(this.highPoints.getWorld())) + { + return false; + } + + return this.lowPoints.getBlockX() <= loc.getBlockX() && this.highPoints.getBlockX() >= loc.getBlockX() && this.lowPoints.getBlockZ() <= loc.getBlockZ() + && this.highPoints.getBlockZ() >= loc.getBlockZ(); + } + + public boolean containsLocWithoutYD(final Location loc) + { + if (this.highPoints == null || this.lowPoints == null) + { + return false; + } + if (loc == null || loc.getWorld() == null || !loc.getWorld().equals(this.highPoints.getWorld())) + { + return false; + } + + return this.lowPoints.getBlockX() <= loc.getBlockX() + 2 && this.highPoints.getBlockX() >= loc.getBlockX() - 2 && this.lowPoints.getBlockZ() <= loc.getBlockZ() + 2 + && this.highPoints.getBlockZ() >= loc.getBlockZ() - 2; + } + + /** + * Returns the volume of this cuboid. + * + * @return the volume of this cuboid + */ + public long getSize() + { + return Math.abs(this.getXSize() * this.getYSize() * this.getZSize()); + } + + /** + * Determines a random location inside the cuboid and returns it. + * + * @return a random location within the cuboid + */ + public Location getRandomLocation() + { + final World world = this.getWorld(); + final Random randomGenerator = new Random(); + + Location result = new Location(world, this.highPoints.getBlockX(), this.highPoints.getBlockY(), this.highPoints.getZ()); + + if (this.getSize() > 1) + { + final double randomX = this.lowPoints.getBlockX() + randomGenerator.nextInt(this.getXSize()); + final double randomY = this.lowPoints.getBlockY() + randomGenerator.nextInt(this.getYSize()); + final double randomZ = this.lowPoints.getBlockZ() + randomGenerator.nextInt(this.getZSize()); + + result = new Location(world, randomX, randomY, randomZ); + } + + return result; + } + + /** + * Determines a random location inside the cuboid that is suitable for mob spawning and returns it. + * + * @return a random location inside the cuboid that is suitable for mob spawning + */ + public Location getRandomLocationForMobs() + { + final Location temp = this.getRandomLocation(); + + return new Location(temp.getWorld(), temp.getBlockX() + 0.5, temp.getBlockY() + 0.5, temp.getBlockZ() + 0.5); + } + + /** + * Returns the x span of this cuboid. + * + * @return the x span of this cuboid + */ + public int getXSize() + { + return (this.highPoints.getBlockX() - this.lowPoints.getBlockX()) + 1; + } + + /** + * Returns the y span of this cuboid. + * + * @return the y span of this cuboid + */ + public int getYSize() + { + return (this.highPoints.getBlockY() - this.lowPoints.getBlockY()) + 1; + } + + /** + * Returns the z span of this cuboid. + * + * @return the z span of this cuboid + */ + public int getZSize() + { + return (this.highPoints.getBlockZ() - this.lowPoints.getBlockZ()) + 1; + } + + /** + * Returns the higher location of this cuboid. + * + * @return the higher location of this cuboid + */ + public Location getHighLoc() + { + return this.highPoints; + } + + /** + * Returns the lower location of this cuboid. + * + * @return the lower location of this cuboid + */ + public Location getLowLoc() + { + return this.lowPoints; + } + + /** + * Returns the world this cuboid is in. + * + * @return the world this cuboid is in + */ + public World getWorld() + { + return this.highPoints.getWorld(); + } + + /** + * Saves the cuboid to a Map. + * + * @return the cuboid in a Map + */ + public Map<String, Object> save() + { + final Map<String, Object> root = new LinkedHashMap<>(); + + root.put("World", this.highPoints.getWorld().getName()); + root.put("X1", this.highPoints.getBlockX()); + root.put("Y1", this.highPoints.getBlockY()); + root.put("Z1", this.highPoints.getBlockZ()); + root.put("X2", this.lowPoints.getBlockX()); + root.put("Y2", this.lowPoints.getBlockY()); + root.put("Z2", this.lowPoints.getBlockZ()); + + return root; + } + + /** + * Loads the cuboid from a Map. + * + * @param root + * the Map + * @return the cuboid + * @throws IllegalArgumentException + */ + public static Cuboid load(final Map<String, Object> root) throws IllegalArgumentException + { + if (root == null) + { + throw new IllegalArgumentException("Invalid root map!"); + } + + final String owner = (String) root.get("Owner"); + final World world = Bukkit.getServer().getWorld((String) root.get("World")); + final int x1 = (Integer) root.get("X1"); + final int y1 = (Integer) root.get("Y1"); + final int z1 = (Integer) root.get("Z1"); + final int x2 = (Integer) root.get("X2"); + final int y2 = (Integer) root.get("Y2"); + final int z2 = (Integer) root.get("Z2"); + + final Cuboid newArea = new Cuboid(new Location(world, x1, y1, z1), new Location(world, x2, y2, z2)); + + return newArea; + } + + /** + * {@inheritDoc} + */ + @Override + public String toString() + { + return new StringBuilder("(").append(this.lowPoints.getBlockX()).append(", ").append(this.lowPoints.getBlockY()).append(", ").append(this.lowPoints.getBlockZ()).append(") to (") + .append(this.highPoints.getBlockX()).append(", ").append(this.highPoints.getBlockY()).append(", ").append(this.highPoints.getBlockZ()).append(")").toString(); + } + + /** + * Returns a raw representation that is easy to read for Java. + * + * @return a raw representation of this cuboid + */ + public String toRaw() + { + return new StringBuilder(this.getWorld().getName()).append(",").append(this.lowPoints.getBlockX()).append(",").append(this.lowPoints.getBlockY()).append(",").append(this.lowPoints.getBlockZ()) + .append(",").append(this.highPoints.getBlockX()).append(",").append(this.highPoints.getBlockY()).append(",").append(this.highPoints.getBlockZ()).toString(); + } +} diff --git a/API/src/main/java/com/comze_instancelabs/minigamesapi/util/IconMenu.java b/API/src/main/java/com/comze_instancelabs/minigamesapi/util/IconMenu.java index 8e615623..beafcbe4 100644 --- a/API/src/main/java/com/comze_instancelabs/minigamesapi/util/IconMenu.java +++ b/API/src/main/java/com/comze_instancelabs/minigamesapi/util/IconMenu.java @@ -1,3 +1,17 @@ +/* + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ package com.comze_instancelabs.minigamesapi.util; import java.util.ArrayList; @@ -16,165 +30,202 @@ import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.plugin.Plugin; -public class IconMenu implements Listener { - - private String name; - private int size; - private OptionClickEventHandler handler; - private Plugin plugin; - private Player player; - - private String[] optionNames; - private ItemStack[] optionIcons; - - public IconMenu(String name, int size, OptionClickEventHandler handler, Plugin plugin) { - this.name = name; - this.size = size; - this.handler = handler; - this.plugin = plugin; - this.optionNames = new String[size]; - this.optionIcons = new ItemStack[size]; - plugin.getServer().getPluginManager().registerEvents(this, plugin); - } - - public IconMenu setOption(int position, ItemStack icon, String name, String... info) { - if (position < 0) - position = 0; - if (optionNames == null) - this.optionNames = new String[size]; - if (optionIcons == null) - this.optionIcons = new ItemStack[size]; - optionNames[position] = name; - optionIcons[position] = setItemNameAndLore(icon, name, info); - return this; - } - - public void setSpecificTo(Player player) { - this.player = player; - } - - public boolean isSpecific() { - return player != null; - } - - public int getSize() { - return size; - } - - public void open(Player player) { - Inventory inventory = Bukkit.createInventory(player, size, name); - for (int i = 0; i < optionIcons.length; i++) { - if (optionIcons[i] != null) { - inventory.setItem(i, optionIcons[i]); - } - } - player.openInventory(inventory); - } - - public void destroy() { - HandlerList.unregisterAll(this); - handler = null; - plugin = null; - optionNames = null; - optionIcons = null; - } - - public void clear() { - optionNames = null; - optionIcons = null; - } - - @EventHandler(priority = EventPriority.HIGHEST) - void onInventoryClick(InventoryClickEvent event) { - if (event.getInventory().getTitle().equals(name) && (player == null || event.getWhoClicked() == player)) { - event.setCancelled(true); - if (event.getClick() != ClickType.LEFT) - return; - int slot = event.getRawSlot(); - if (slot >= 0 && slot < size && optionNames[slot] != null) { - Plugin plugin = this.plugin; - OptionClickEvent e = new OptionClickEvent((Player) event.getWhoClicked(), slot, optionNames[slot], optionIcons[slot]); - handler.onOptionClick(e); - ((Player) event.getWhoClicked()).updateInventory(); - if (e.willClose()) { - final Player p = (Player) event.getWhoClicked(); - Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { - public void run() { - p.closeInventory(); - } - }); - } - if (e.willDestroy()) { - destroy(); - } - } - } - } - - public interface OptionClickEventHandler { - public void onOptionClick(OptionClickEvent event); - } - - public class OptionClickEvent { - private Player player; - private int position; - private String name; - private boolean close; - private boolean destroy; - private ItemStack item; - - public OptionClickEvent(Player player, int position, String name, ItemStack item) { - this.player = player; - this.position = position; - this.name = name; - this.close = true; - this.destroy = false; - this.item = item; - } - - public Player getPlayer() { - return player; - } - - public int getPosition() { - return position; - } - - public String getName() { - return name; - } - - public boolean willClose() { - return close; - } - - public boolean willDestroy() { - return destroy; - } - - public void setWillClose(boolean close) { - this.close = close; - } - - public void setWillDestroy(boolean destroy) { - this.destroy = destroy; - } - - public ItemStack getItem() { - return item; - } - } - - private ItemStack setItemNameAndLore(ItemStack item, String name, String[] lore) { - ItemMeta im = item.getItemMeta(); - im.setDisplayName(ChatColor.translateAlternateColorCodes('&', name)); - ArrayList<String> lore_lines = new ArrayList<String>(); - for (String l : lore) { - lore_lines.add(ChatColor.translateAlternateColorCodes('&', l)); - } - im.setLore(lore_lines); - item.setItemMeta(im); - return item; - } - -} \ No newline at end of file +public class IconMenu implements Listener +{ + + private final String name; + private final int size; + private OptionClickEventHandler handler; + private Plugin plugin; + private Player player; + + private String[] optionNames; + private ItemStack[] optionIcons; + + public IconMenu(final String name, final int size, final OptionClickEventHandler handler, final Plugin plugin) + { + this.name = name; + this.size = size; + this.handler = handler; + this.plugin = plugin; + this.optionNames = new String[size]; + this.optionIcons = new ItemStack[size]; + plugin.getServer().getPluginManager().registerEvents(this, plugin); + } + + public IconMenu setOption(int pos, final ItemStack icon, final String name, final String... info) + { + int position = pos; + if (position < 0) + { + position = 0; + } + if (this.optionNames == null) + { + this.optionNames = new String[this.size]; + } + if (this.optionIcons == null) + { + this.optionIcons = new ItemStack[this.size]; + } + this.optionNames[position] = name; + this.optionIcons[position] = this.setItemNameAndLore(icon, name, info); + return this; + } + + public void setSpecificTo(final Player player) + { + this.player = player; + } + + public boolean isSpecific() + { + return this.player != null; + } + + public int getSize() + { + return this.size; + } + + public void open(final Player player) + { + if (this.optionIcons != null && this.optionIcons.length > 0) + { + final Inventory inventory = Bukkit.createInventory(player, this.size, this.name); + for (int i = 0; i < this.optionIcons.length; i++) + { + if (this.optionIcons[i] != null) + { + inventory.setItem(i, this.optionIcons[i]); + } + } + player.openInventory(inventory); + } + } + + public void destroy() + { + HandlerList.unregisterAll(this); + this.handler = null; + this.plugin = null; + this.optionNames = null; + this.optionIcons = null; + } + + public void clear() + { + this.optionNames = null; + this.optionIcons = null; + } + + @EventHandler(priority = EventPriority.HIGHEST) + void onInventoryClick(final InventoryClickEvent event) + { + if (event.getInventory().getTitle().equals(this.name) && (this.player == null || event.getWhoClicked() == this.player)) + { + event.setCancelled(true); + if (event.getClick() != ClickType.LEFT) + { + return; + } + final int slot = event.getRawSlot(); + if (slot >= 0 && slot < this.size && this.optionNames[slot] != null) + { + final Plugin plugin = this.plugin; + final OptionClickEvent e = new OptionClickEvent((Player) event.getWhoClicked(), slot, this.optionNames[slot], this.optionIcons[slot]); + this.handler.onOptionClick(e); + ((Player) event.getWhoClicked()).updateInventory(); + if (e.willClose()) + { + final Player p = (Player) event.getWhoClicked(); + Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, () -> p.closeInventory()); + } + if (e.willDestroy()) + { + this.destroy(); + } + } + } + } + + public interface OptionClickEventHandler + { + public void onOptionClick(OptionClickEvent event); + } + + public class OptionClickEvent + { + private final Player player; + private final int position; + private final String name; + private boolean close; + private boolean destroy; + private final ItemStack item; + + public OptionClickEvent(final Player player, final int position, final String name, final ItemStack item) + { + this.player = player; + this.position = position; + this.name = name; + this.close = true; + this.destroy = false; + this.item = item; + } + + public Player getPlayer() + { + return this.player; + } + + public int getPosition() + { + return this.position; + } + + public String getName() + { + return this.name; + } + + public boolean willClose() + { + return this.close; + } + + public boolean willDestroy() + { + return this.destroy; + } + + public void setWillClose(final boolean close) + { + this.close = close; + } + + public void setWillDestroy(final boolean destroy) + { + this.destroy = destroy; + } + + public ItemStack getItem() + { + return this.item; + } + } + + private ItemStack setItemNameAndLore(final ItemStack item, final String name, final String[] lore) + { + final ItemMeta im = item.getItemMeta(); + im.setDisplayName(ChatColor.translateAlternateColorCodes('&', name)); + final ArrayList<String> lore_lines = new ArrayList<>(); + for (final String l : lore) + { + lore_lines.add(ChatColor.translateAlternateColorCodes('&', l)); + } + im.setLore(lore_lines); + item.setItemMeta(im); + return item; + } + +} diff --git a/API/src/main/java/com/comze_instancelabs/minigamesapi/util/InventoryManager.java b/API/src/main/java/com/comze_instancelabs/minigamesapi/util/InventoryManager.java new file mode 100644 index 00000000..efe0d5a0 --- /dev/null +++ b/API/src/main/java/com/comze_instancelabs/minigamesapi/util/InventoryManager.java @@ -0,0 +1,58 @@ +/* + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ +package com.comze_instancelabs.minigamesapi.util; + +import java.util.HashMap; + +import org.bukkit.GameMode; +import org.bukkit.Location; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +public class InventoryManager +{ + + private static HashMap<String, ItemStack[]> armourContents = new HashMap<>(); + private static HashMap<String, ItemStack[]> inventoryContents = new HashMap<>(); + private static HashMap<String, Location> locations = new HashMap<>(); + private static HashMap<String, Integer> xplevel = new HashMap<>(); + private static HashMap<String, GameMode> gamemode = new HashMap<>(); + + public static void saveInventory(final Player player) + { + InventoryManager.armourContents.put(player.getName(), player.getInventory().getArmorContents()); + InventoryManager.inventoryContents.put(player.getName(), player.getInventory().getContents()); + InventoryManager.locations.put(player.getName(), player.getLocation()); + InventoryManager.xplevel.put(player.getName(), player.getLevel()); + InventoryManager.gamemode.put(player.getName(), player.getGameMode()); + player.getInventory().clear(); + } + + public static void restoreInventory(final Player player) + { + player.getInventory().clear(); + player.teleport(InventoryManager.locations.get(player.getName())); + + player.getInventory().setContents(InventoryManager.inventoryContents.get(player.getName())); + player.getInventory().setArmorContents(InventoryManager.armourContents.get(player.getName())); + player.setLevel(InventoryManager.xplevel.get(player.getName())); + player.setGameMode(InventoryManager.gamemode.get(player.getName())); + + InventoryManager.xplevel.remove(player.getName()); + InventoryManager.locations.remove(player.getName()); + InventoryManager.armourContents.remove(player.getName()); + InventoryManager.inventoryContents.remove(player.getName()); + } +} diff --git a/API/src/main/java/com/comze_instancelabs/minigamesapi/util/Leaderboard.java b/API/src/main/java/com/comze_instancelabs/minigamesapi/util/Leaderboard.java new file mode 100644 index 00000000..270917dc --- /dev/null +++ b/API/src/main/java/com/comze_instancelabs/minigamesapi/util/Leaderboard.java @@ -0,0 +1,262 @@ +/* + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ +package com.comze_instancelabs.minigamesapi.util; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.UUID; + +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.SkullType; +import org.bukkit.block.Block; +import org.bukkit.block.BlockFace; +import org.bukkit.block.BlockState; +import org.bukkit.block.Sign; +import org.bukkit.block.Skull; +import org.bukkit.configuration.file.FileConfiguration; + +public class Leaderboard +{ + + protected Object convertUUID(final String s) + { + if (s.matches("[0-9a-f]{8}-[0-9a-f]{4}-4[0-9]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}")) + { + return UUID.fromString(s); + } + else + { + return s; + } + } + + protected static Map<Integer, String> sortByComparator(final Map<String, Integer> unsortMap, final boolean order) + { + final List<Entry<String, Integer>> list = new LinkedList<>(unsortMap.entrySet()); + + Collections.sort(list, (o1, o2) -> { + if (order) + { + return o1.getValue().compareTo(o2.getValue()); + } + else + { + return o2.getValue().compareTo(o1.getValue()); + } + }); + + final Map<Integer, String> sortedMap = new LinkedHashMap<>(); + for (final Entry<String, Integer> entry : list) + { + for (int i = 1; i < 4; i++) + { + if (!sortedMap.containsKey(i)) + { + sortedMap.put(i, entry.getKey()); + break; + } + } + } + + return sortedMap; + } + + @SuppressWarnings("deprecation") + public Leaderboard(final Location firstPlace, final Location secondPlace, final Location thirdPlace, final Material firstBlockType, final Material secondBlockType, final Material thirdBlockType, + final BlockFace direction, final FileConfiguration configurationFile, final String configurationFormat) + { + final String[] a = configurationFormat.split("\\."); + + int playerConfigLocation = -1; + + for (int i = 0; i < a.length; i++) + { + if (a[i].equals("player")) + { + playerConfigLocation = i; + } + } + + if (playerConfigLocation == -1) + { + return; + } + + final ArrayList<String> b = new ArrayList<>(); + + for (final String ba : a) + { + if (!ba.equals("player")) + { + b.add(ba); + } + else + { + break; + } + } + + final ArrayList<String> c = new ArrayList<>(); + + for (final String ca : a) + { + if (!ca.equals("integer")) + { + c.add(ca); + } + else + { + break; + } + } + + final HashMap<String, Integer> playersEdit = new HashMap<>(); + final HashMap<String, Integer> playersKeep = new HashMap<>(); + + for (final String player : configurationFile.getConfigurationSection(b.toString().replace("[", "").replace("]", "").replace(", ", ".")).getKeys(false)) + { + playersEdit.put(player, configurationFile.getInt(c.toString().replace("[", "").replace("]", "").replace(", ", ".").replace("player", player))); + playersKeep.put(player, configurationFile.getInt(c.toString().replace("[", "").replace("]", "").replace(", ", ".").replace("player", player))); + } + + final Map<Integer, String> leaderboard = Leaderboard.sortByComparator(playersEdit, false); + + firstPlace.getBlock().setType(firstBlockType); + secondPlace.getBlock().setType(secondBlockType); + thirdPlace.getBlock().setType(thirdBlockType); + + final ArrayList<BlockState> signBlockState = new ArrayList<>(); + + final Block firstSign = firstPlace.getBlock().getRelative(direction); + final Block secondSign = secondPlace.getBlock().getRelative(direction); + final Block thirdSign = thirdPlace.getBlock().getRelative(direction); + + switch (direction) + { + case EAST: + firstSign.setTypeIdAndData(68, (byte) 0x5, true); + secondSign.setTypeIdAndData(68, (byte) 0x5, true); + thirdSign.setTypeIdAndData(68, (byte) 0x5, true); + break; + case NORTH: + firstSign.setTypeIdAndData(68, (byte) 0x2, true); + secondSign.setTypeIdAndData(68, (byte) 0x2, true); + thirdSign.setTypeIdAndData(68, (byte) 0x2, true); + break; + case SOUTH: + firstSign.setTypeIdAndData(68, (byte) 0x3, true); + secondSign.setTypeIdAndData(68, (byte) 0x3, true); + thirdSign.setTypeIdAndData(68, (byte) 0x3, true); + break; + case WEST: + firstSign.setTypeIdAndData(68, (byte) 0x4, true); + secondSign.setTypeIdAndData(68, (byte) 0x4, true); + thirdSign.setTypeIdAndData(68, (byte) 0x4, true); + break; + default: + break; + + } + + signBlockState.add(firstSign.getState()); + signBlockState.add(secondSign.getState()); + signBlockState.add(thirdSign.getState()); + + for (final BlockState bs : signBlockState) + { + if (bs instanceof Sign) + { + final Sign s = (Sign) bs; + + if (leaderboard.containsKey(signBlockState.indexOf(bs) + 1)) + { + if (this.convertUUID(leaderboard.get(signBlockState.indexOf(bs) + 1)) instanceof UUID) + { + s.setLine(1, Bukkit.getPlayer((UUID) this.convertUUID(leaderboard.get(signBlockState.indexOf(bs) + 1))).getName()); + } + else + { + s.setLine(1, leaderboard.get(signBlockState.indexOf(bs) + 1)); + } + + switch (signBlockState.indexOf(bs) + 1) + { + case 1: + s.setLine(0, ChatColor.AQUA + "" + ChatColor.BOLD + "1st"); + break; + case 2: + s.setLine(0, ChatColor.YELLOW + "" + ChatColor.BOLD + "2st"); + break; + case 3: + s.setLine(0, ChatColor.DARK_RED + "" + ChatColor.BOLD + "3st"); + break; + } + } + s.setLine(2, playersKeep.get(leaderboard.get(signBlockState.indexOf(bs) + 1)) + " Points"); + bs.getBlock().getChunk().load(); + s.update(true); + } + } + + final Location firstSkull = firstPlace.getBlock().getLocation().add(0, 1, 0); + final Location secondSkull = secondPlace.getBlock().getLocation().add(0, 1, 0); + final Location thirdSkull = thirdPlace.getBlock().getLocation().add(0, 1, 0); + + firstSkull.getBlock().setType(Material.SKULL); + secondSkull.getBlock().setType(Material.SKULL); + thirdSkull.getBlock().setType(Material.SKULL); + + final ArrayList<BlockState> skullBlockState = new ArrayList<>(); + + skullBlockState.add(firstSkull.getBlock().getState()); + skullBlockState.add(secondSkull.getBlock().getState()); + skullBlockState.add(thirdSkull.getBlock().getState()); + + for (final BlockState bs : skullBlockState) + { + if (bs instanceof Skull) + { + final Skull s = (Skull) bs; + s.setSkullType(SkullType.PLAYER); + s.setRawData((byte) 1); + s.setRotation(direction); + + if (leaderboard.containsKey(skullBlockState.indexOf(bs) + 1)) + { + if (this.convertUUID(leaderboard.get(skullBlockState.indexOf(bs) + 1)) instanceof UUID) + { + s.setOwner(Bukkit.getPlayer((UUID) this.convertUUID(leaderboard.get(skullBlockState.indexOf(bs) + 1))).getName()); + } + else + { + s.setOwner(leaderboard.get(skullBlockState.indexOf(bs) + 1)); + } + } + + bs.getBlock().getChunk().load(); + s.update(true); + } + } + } +} diff --git a/API/src/main/java/com/comze_instancelabs/minigamesapi/util/Metrics.java b/API/src/main/java/com/comze_instancelabs/minigamesapi/util/Metrics.java index fa7c4a73..7d8469f3 100644 --- a/API/src/main/java/com/comze_instancelabs/minigamesapi/util/Metrics.java +++ b/API/src/main/java/com/comze_instancelabs/minigamesapi/util/Metrics.java @@ -27,13 +27,6 @@ */ package com.comze_instancelabs.minigamesapi.util; -import org.bukkit.Bukkit; -import org.bukkit.configuration.InvalidConfigurationException; -import org.bukkit.configuration.file.YamlConfiguration; -import org.bukkit.plugin.Plugin; -import org.bukkit.plugin.PluginDescriptionFile; -import org.bukkit.scheduler.BukkitTask; - import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.File; @@ -54,710 +47,830 @@ import java.util.logging.Level; import java.util.zip.GZIPOutputStream; -public class Metrics { - - /** - * The current revision number - */ - private final static int REVISION = 7; - - /** - * The base url of the metrics domain - */ - private static final String BASE_URL = "http://report.mcstats.org"; - - /** - * The url used to report a server's status - */ - private static final String REPORT_URL = "/plugin/%s"; - - /** - * Interval of time to ping (in minutes) - */ - private static final int PING_INTERVAL = 15; - - /** - * The plugin this metrics submits for - */ - private final Plugin plugin; - - /** - * All of the custom graphs to submit to metrics - */ - private final Set<Graph> graphs = Collections.synchronizedSet(new HashSet<Graph>()); - - /** - * The plugin configuration file - */ - private final YamlConfiguration configuration; - - /** - * The plugin configuration file - */ - private final File configurationFile; - - /** - * Unique server id - */ - private final String guid; - - /** - * Debug mode - */ - private final boolean debug; - - /** - * Lock for synchronization - */ - private final Object optOutLock = new Object(); - - /** - * The scheduled task - */ - private volatile BukkitTask task = null; - - public Metrics(final Plugin plugin) throws IOException { - if (plugin == null) { - throw new IllegalArgumentException("Plugin cannot be null"); - } - - this.plugin = plugin; - - // load the config - configurationFile = getConfigFile(); - configuration = YamlConfiguration.loadConfiguration(configurationFile); - - // add some defaults - configuration.addDefault("opt-out", false); - configuration.addDefault("guid", UUID.randomUUID().toString()); - configuration.addDefault("debug", false); - - // Do we need to create the file? - if (configuration.get("guid", null) == null) { - configuration.options().header("http://mcstats.org").copyDefaults(true); - configuration.save(configurationFile); - } - - // Load the guid then - guid = configuration.getString("guid"); - debug = configuration.getBoolean("debug", false); - } - - /** - * Construct and create a Graph that can be used to separate specific plotters to their own graphs on the metrics website. Plotters can be added - * to the graph object returned. - * - * @param name - * The name of the graph - * @return Graph object created. Will never return NULL under normal circumstances unless bad parameters are given - */ - public Graph createGraph(final String name) { - if (name == null) { - throw new IllegalArgumentException("Graph name cannot be null"); - } - - // Construct the graph object - final Graph graph = new Graph(name); - - // Now we can add our graph - graphs.add(graph); - - // and return back - return graph; - } - - /** - * Add a Graph object to BukkitMetrics that represents data for the plugin that should be sent to the backend - * - * @param graph - * The name of the graph - */ - public void addGraph(final Graph graph) { - if (graph == null) { - throw new IllegalArgumentException("Graph cannot be null"); - } - - graphs.add(graph); - } - - /** - * Start measuring statistics. This will immediately create an async repeating task as the plugin and send the initial data to the metrics - * backend, and then after that it will post in increments of PING_INTERVAL * 1200 ticks. - * - * @return True if statistics measuring is running, otherwise false. - */ - public boolean start() { - synchronized (optOutLock) { - // Did we opt out? - if (isOptOut()) { - return false; - } - - // Is metrics already running? - if (task != null) { - return true; - } - - // Begin hitting the server with glorious data - task = plugin.getServer().getScheduler().runTaskTimerAsynchronously(plugin, new Runnable() { - - private boolean firstPost = true; - - public void run() { - try { - // This has to be synchronized or it can collide with the disable method. - synchronized (optOutLock) { - // Disable Task, if it is running and the server owner decided to opt-out - if (isOptOut() && task != null) { - task.cancel(); - task = null; - // Tell all plotters to stop gathering information. - for (Graph graph : graphs) { - graph.onOptOut(); - } - } - } - - // We use the inverse of firstPost because if it is the first time we are posting, - // it is not a interval ping, so it evaluates to FALSE - // Each time thereafter it will evaluate to TRUE, i.e PING! - postPlugin(!firstPost); - - // After the first post we set firstPost to false - // Each post thereafter will be a ping - firstPost = false; - } catch (IOException e) { - if (debug) { - Bukkit.getLogger().log(Level.INFO, "[Metrics] " + e.getMessage()); - } - } - } - }, 0, PING_INTERVAL * 1200); - - return true; - } - } - - /** - * Has the server owner denied plugin metrics? - * - * @return true if metrics should be opted out of it - */ - public boolean isOptOut() { - synchronized (optOutLock) { - try { - // Reload the metrics file - configuration.load(getConfigFile()); - } catch (IOException ex) { - if (debug) { - Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage()); - } - return true; - } catch (InvalidConfigurationException ex) { - if (debug) { - Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage()); - } - return true; - } - return configuration.getBoolean("opt-out", false); - } - } - - /** - * Enables metrics for the server by setting "opt-out" to false in the config file and starting the metrics task. - * - * @throws java.io.IOException - */ - public void enable() throws IOException { - // This has to be synchronized or it can collide with the check in the task. - synchronized (optOutLock) { - // Check if the server owner has already set opt-out, if not, set it. - if (isOptOut()) { - configuration.set("opt-out", false); - configuration.save(configurationFile); - } - - // Enable Task, if it is not running - if (task == null) { - start(); - } - } - } - - /** - * Disables metrics for the server by setting "opt-out" to true in the config file and canceling the metrics task. - * - * @throws java.io.IOException - */ - public void disable() throws IOException { - // This has to be synchronized or it can collide with the check in the task. - synchronized (optOutLock) { - // Check if the server owner has already set opt-out, if not, set it. - if (!isOptOut()) { - configuration.set("opt-out", true); - configuration.save(configurationFile); - } - - // Disable Task, if it is running - if (task != null) { - task.cancel(); - task = null; - } - } - } - - /** - * Gets the File object of the config file that should be used to store data such as the GUID and opt-out status - * - * @return the File object for the config file - */ - public File getConfigFile() { - // I believe the easiest way to get the base folder (e.g craftbukkit set via -P) for plugins to use - // is to abuse the plugin object we already have - // plugin.getDataFolder() => base/plugins/PluginA/ - // pluginsFolder => base/plugins/ - // The base is not necessarily relative to the startup directory. - File pluginsFolder = plugin.getDataFolder().getParentFile(); - - // return => base/plugins/PluginMetrics/config.yml - return new File(new File(pluginsFolder, "PluginMetrics"), "config.yml"); - } - - /** - * Generic method that posts a plugin to the metrics website - */ - private void postPlugin(final boolean isPing) throws IOException { - // Server software specific section - PluginDescriptionFile description = plugin.getDescription(); - String pluginName = description.getName(); - boolean onlineMode = Bukkit.getServer().getOnlineMode(); // TRUE if online mode is enabled - String pluginVersion = description.getVersion(); - String serverVersion = Bukkit.getVersion(); - int playersOnline = Bukkit.getServer().getOnlinePlayers().length; - - // END server software specific section -- all code below does not use any code outside of this class / Java - - // Construct the post data - StringBuilder json = new StringBuilder(1024); - json.append('{'); - - // The plugin's description file containg all of the plugin data such as name, version, author, etc - appendJSONPair(json, "guid", guid); - appendJSONPair(json, "plugin_version", pluginVersion); - appendJSONPair(json, "server_version", serverVersion); - appendJSONPair(json, "players_online", Integer.toString(playersOnline)); - - // New data as of R6 - String osname = System.getProperty("os.name"); - String osarch = System.getProperty("os.arch"); - String osversion = System.getProperty("os.version"); - String java_version = System.getProperty("java.version"); - int coreCount = Runtime.getRuntime().availableProcessors(); - - // normalize os arch .. amd64 -> x86_64 - if (osarch.equals("amd64")) { - osarch = "x86_64"; - } - - appendJSONPair(json, "osname", osname); - appendJSONPair(json, "osarch", osarch); - appendJSONPair(json, "osversion", osversion); - appendJSONPair(json, "cores", Integer.toString(coreCount)); - appendJSONPair(json, "auth_mode", onlineMode ? "1" : "0"); - appendJSONPair(json, "java_version", java_version); - - // If we're pinging, append it - if (isPing) { - appendJSONPair(json, "ping", "1"); - } - - if (graphs.size() > 0) { - synchronized (graphs) { - json.append(','); - json.append('"'); - json.append("graphs"); - json.append('"'); - json.append(':'); - json.append('{'); - - boolean firstGraph = true; - - final Iterator<Graph> iter = graphs.iterator(); - - while (iter.hasNext()) { - Graph graph = iter.next(); - - StringBuilder graphJson = new StringBuilder(); - graphJson.append('{'); - - for (Plotter plotter : graph.getPlotters()) { - appendJSONPair(graphJson, plotter.getColumnName(), Integer.toString(plotter.getValue())); - } - - graphJson.append('}'); - - if (!firstGraph) { - json.append(','); - } - - json.append(escapeJSON(graph.getName())); - json.append(':'); - json.append(graphJson); - - firstGraph = false; - } - - json.append('}'); - } - } - - // close json - json.append('}'); - - // Create the url - URL url = new URL(BASE_URL + String.format(REPORT_URL, urlEncode(pluginName))); - - // Connect to the website - URLConnection connection; - - // Mineshafter creates a socks proxy, so we can safely bypass it - // It does not reroute POST requests so we need to go around it - if (isMineshafterPresent()) { - connection = url.openConnection(Proxy.NO_PROXY); - } else { - connection = url.openConnection(); - } - - byte[] uncompressed = json.toString().getBytes(); - byte[] compressed = gzip(json.toString()); - - // Headers - connection.addRequestProperty("User-Agent", "MCStats/" + REVISION); - connection.addRequestProperty("Content-Type", "application/json"); - connection.addRequestProperty("Content-Encoding", "gzip"); - connection.addRequestProperty("Content-Length", Integer.toString(compressed.length)); - connection.addRequestProperty("Accept", "application/json"); - connection.addRequestProperty("Connection", "close"); - - connection.setDoOutput(true); - - if (debug) { - System.out.println("[Metrics] Prepared request for " + pluginName + " uncompressed=" + uncompressed.length + " compressed=" + compressed.length); - } - - // Write the data - OutputStream os = connection.getOutputStream(); - os.write(compressed); - os.flush(); - - // Now read the response - final BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); - String response = reader.readLine(); - - // close resources - os.close(); - reader.close(); - - if (response == null || response.startsWith("ERR") || response.startsWith("7")) { - if (response == null) { - response = "null"; - } else if (response.startsWith("7")) { - response = response.substring(response.startsWith("7,") ? 2 : 1); - } - - throw new IOException(response); - } else { - // Is this the first update this hour? - if (response.equals("1") || response.contains("This is your first update this hour")) { - synchronized (graphs) { - final Iterator<Graph> iter = graphs.iterator(); - - while (iter.hasNext()) { - final Graph graph = iter.next(); - - for (Plotter plotter : graph.getPlotters()) { - plotter.reset(); - } - } - } - } - } - } - - /** - * GZip compress a string of bytes - * - * @param input - * @return - */ - public static byte[] gzip(String input) { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - GZIPOutputStream gzos = null; - - try { - gzos = new GZIPOutputStream(baos); - gzos.write(input.getBytes("UTF-8")); - } catch (IOException e) { - e.printStackTrace(); - } finally { - if (gzos != null) - try { - gzos.close(); - } catch (IOException ignore) { - } - } - - return baos.toByteArray(); - } - - /** - * Check if mineshafter is present. If it is, we need to bypass it to send POST requests - * - * @return true if mineshafter is installed on the server - */ - private boolean isMineshafterPresent() { - try { - Class.forName("mineshafter.MineServer"); - return true; - } catch (Exception e) { - return false; - } - } - - /** - * Appends a json encoded key/value pair to the given string builder. - * - * @param json - * @param key - * @param value - * @throws UnsupportedEncodingException - */ - private static void appendJSONPair(StringBuilder json, String key, String value) throws UnsupportedEncodingException { - boolean isValueNumeric = false; - - try { - if (value.equals("0") || !value.endsWith("0")) { - Double.parseDouble(value); - isValueNumeric = true; - } - } catch (NumberFormatException e) { - isValueNumeric = false; - } - - if (json.charAt(json.length() - 1) != '{') { - json.append(','); - } - - json.append(escapeJSON(key)); - json.append(':'); - - if (isValueNumeric) { - json.append(value); - } else { - json.append(escapeJSON(value)); - } - } - - /** - * Escape a string to create a valid JSON string - * - * @param text - * @return - */ - private static String escapeJSON(String text) { - StringBuilder builder = new StringBuilder(); - - builder.append('"'); - for (int index = 0; index < text.length(); index++) { - char chr = text.charAt(index); - - switch (chr) { - case '"': - case '\\': - builder.append('\\'); - builder.append(chr); - break; - case '\b': - builder.append("\\b"); - break; - case '\t': - builder.append("\\t"); - break; - case '\n': - builder.append("\\n"); - break; - case '\r': - builder.append("\\r"); - break; - default: - if (chr < ' ') { - String t = "000" + Integer.toHexString(chr); - builder.append("\\u" + t.substring(t.length() - 4)); - } else { - builder.append(chr); - } - break; - } - } - builder.append('"'); - - return builder.toString(); - } - - /** - * Encode text as UTF-8 - * - * @param text - * the text to encode - * @return the encoded text, as UTF-8 - */ - private static String urlEncode(final String text) throws UnsupportedEncodingException { - return URLEncoder.encode(text, "UTF-8"); - } - - /** - * Represents a custom graph on the website - */ - public static class Graph { - - /** - * The graph's name, alphanumeric and spaces only :) If it does not comply to the above when submitted, it is rejected - */ - private final String name; - - /** - * The set of plotters that are contained within this graph - */ - private final Set<Plotter> plotters = new LinkedHashSet<Plotter>(); - - private Graph(final String name) { - this.name = name; - } - - /** - * Gets the graph's name - * - * @return the Graph's name - */ - public String getName() { - return name; - } - - /** - * Add a plotter to the graph, which will be used to plot entries - * - * @param plotter - * the plotter to add to the graph - */ - public void addPlotter(final Plotter plotter) { - plotters.add(plotter); - } - - /** - * Remove a plotter from the graph - * - * @param plotter - * the plotter to remove from the graph - */ - public void removePlotter(final Plotter plotter) { - plotters.remove(plotter); - } - - /** - * Gets an <b>unmodifiable</b> set of the plotter objects in the graph - * - * @return an unmodifiable {@link java.util.Set} of the plotter objects - */ - public Set<Plotter> getPlotters() { - return Collections.unmodifiableSet(plotters); - } - - @Override - public int hashCode() { - return name.hashCode(); - } - - @Override - public boolean equals(final Object object) { - if (!(object instanceof Graph)) { - return false; - } - - final Graph graph = (Graph) object; - return graph.name.equals(name); - } - - /** - * Called when the server owner decides to opt-out of BukkitMetrics while the server is running. - */ - protected void onOptOut() { - } - } - - /** - * Interface used to collect custom data for a plugin - */ - public static abstract class Plotter { - - /** - * The plot's name - */ - private final String name; - - /** - * Construct a plotter with the default plot name - */ - public Plotter() { - this("Default"); - } - - /** - * Construct a plotter with a specific plot name - * - * @param name - * the name of the plotter to use, which will show up on the website - */ - public Plotter(final String name) { - this.name = name; - } - - /** - * Get the current value for the plotted point. Since this function defers to an external function it may or may not return immediately thus - * cannot be guaranteed to be thread friendly or safe. This function can be called from any thread so care should be taken when accessing - * resources that need to be synchronized. - * - * @return the current value for the point to be plotted. - */ - public abstract int getValue(); - - /** - * Get the column name for the plotted point - * - * @return the plotted point's column name - */ - public String getColumnName() { - return name; - } - - /** - * Called after the website graphs have been updated - */ - public void reset() { - } - - @Override - public int hashCode() { - return getColumnName().hashCode(); - } - - @Override - public boolean equals(final Object object) { - if (!(object instanceof Plotter)) { - return false; - } +import org.bukkit.Bukkit; +import org.bukkit.configuration.InvalidConfigurationException; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.plugin.Plugin; +import org.bukkit.plugin.PluginDescriptionFile; +import org.bukkit.scheduler.BukkitTask; - final Plotter plotter = (Plotter) object; - return plotter.name.equals(name) && plotter.getValue() == getValue(); - } - } -} \ No newline at end of file +import com.comze_instancelabs.minigamesapi.MinigamesAPI; + +public class Metrics +{ + + /** + * The current revision number + */ + private final static int REVISION = 7; + + /** + * The base url of the metrics domain + */ + private static final String BASE_URL = "http://report.mcstats.org"; + + /** + * The url used to report a server's status + */ + private static final String REPORT_URL = "/plugin/%s"; + + /** + * Interval of time to ping (in minutes) + */ + private static final int PING_INTERVAL = 15; + + /** + * The plugin this metrics submits for + */ + private final Plugin plugin; + + /** + * All of the custom graphs to submit to metrics + */ + private final Set<Graph> graphs = Collections.synchronizedSet(new HashSet<Graph>()); + + /** + * The plugin configuration file + */ + private final YamlConfiguration configuration; + + /** + * The plugin configuration file + */ + private final File configurationFile; + + /** + * Unique server id + */ + private final String guid; + + /** + * Debug mode + */ + private final boolean debug; + + /** + * Lock for synchronization + */ + private final Object optOutLock = new Object(); + + /** + * The scheduled task + */ + private volatile BukkitTask task = null; + + public Metrics(final Plugin plugin) throws IOException + { + if (plugin == null) + { + throw new IllegalArgumentException("Plugin cannot be null"); + } + + this.plugin = plugin; + + // load the config + this.configurationFile = this.getConfigFile(); + this.configuration = YamlConfiguration.loadConfiguration(this.configurationFile); + + // add some defaults + this.configuration.addDefault("opt-out", false); + this.configuration.addDefault("guid", UUID.randomUUID().toString()); + this.configuration.addDefault("debug", false); + + // Do we need to create the file? + if (this.configuration.get("guid", null) == null) + { + this.configuration.options().header("http://mcstats.org").copyDefaults(true); + this.configuration.save(this.configurationFile); + } + + // Load the guid then + this.guid = this.configuration.getString("guid"); + this.debug = this.configuration.getBoolean("debug", false); + } + + /** + * Construct and create a Graph that can be used to separate specific plotters to their own graphs on the metrics website. Plotters can be added to the graph object returned. + * + * @param name + * The name of the graph + * @return Graph object created. Will never return NULL under normal circumstances unless bad parameters are given + */ + public Graph createGraph(final String name) + { + if (name == null) + { + throw new IllegalArgumentException("Graph name cannot be null"); + } + + // Construct the graph object + final Graph graph = new Graph(name); + + // Now we can add our graph + this.graphs.add(graph); + + // and return back + return graph; + } + + /** + * Add a Graph object to BukkitMetrics that represents data for the plugin that should be sent to the backend + * + * @param graph + * The name of the graph + */ + public void addGraph(final Graph graph) + { + if (graph == null) + { + throw new IllegalArgumentException("Graph cannot be null"); + } + + this.graphs.add(graph); + } + + /** + * Start measuring statistics. This will immediately create an async repeating task as the plugin and send the initial data to the metrics backend, and then after that it will post in increments + * of PING_INTERVAL * 1200 ticks. + * + * @return True if statistics measuring is running, otherwise false. + */ + public boolean start() + { + synchronized (this.optOutLock) + { + // Did we opt out? + if (this.isOptOut()) + { + return false; + } + + // Is metrics already running? + if (this.task != null) + { + return true; + } + + // Begin hitting the server with glorious data + this.task = this.plugin.getServer().getScheduler().runTaskTimerAsynchronously(this.plugin, new Runnable() { + + private boolean firstPost = true; + + @Override + public void run() + { + try + { + // This has to be synchronized or it can collide with the disable method. + synchronized (Metrics.this.optOutLock) + { + // Disable Task, if it is running and the server owner decided to opt-out + if (Metrics.this.isOptOut() && Metrics.this.task != null) + { + Metrics.this.task.cancel(); + Metrics.this.task = null; + // Tell all plotters to stop gathering information. + for (final Graph graph : Metrics.this.graphs) + { + graph.onOptOut(); + } + } + } + + // We use the inverse of firstPost because if it is the first time we are posting, + // it is not a interval ping, so it evaluates to FALSE + // Each time thereafter it will evaluate to TRUE, i.e PING! + Metrics.this.postPlugin(!this.firstPost); + + // After the first post we set firstPost to false + // Each post thereafter will be a ping + this.firstPost = false; + } + catch (final IOException e) + { + if (Metrics.this.debug) + { + Bukkit.getLogger().log(Level.INFO, "[Metrics] " + e.getMessage()); + } + } + } + }, 0, Metrics.PING_INTERVAL * 1200); + + return true; + } + } + + /** + * Has the server owner denied plugin metrics? + * + * @return true if metrics should be opted out of it + */ + public boolean isOptOut() + { + synchronized (this.optOutLock) + { + try + { + // Reload the metrics file + this.configuration.load(this.getConfigFile()); + } + catch (final IOException ex) + { + if (this.debug) + { + Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage()); + } + return true; + } + catch (final InvalidConfigurationException ex) + { + if (this.debug) + { + Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage()); + } + return true; + } + return this.configuration.getBoolean("opt-out", false); + } + } + + /** + * Enables metrics for the server by setting "opt-out" to false in the config file and starting the metrics task. + * + * @throws java.io.IOException + */ + public void enable() throws IOException + { + // This has to be synchronized or it can collide with the check in the task. + synchronized (this.optOutLock) + { + // Check if the server owner has already set opt-out, if not, set it. + if (this.isOptOut()) + { + this.configuration.set("opt-out", false); + this.configuration.save(this.configurationFile); + } + + // Enable Task, if it is not running + if (this.task == null) + { + this.start(); + } + } + } + + /** + * Disables metrics for the server by setting "opt-out" to true in the config file and canceling the metrics task. + * + * @throws java.io.IOException + */ + public void disable() throws IOException + { + // This has to be synchronized or it can collide with the check in the task. + synchronized (this.optOutLock) + { + // Check if the server owner has already set opt-out, if not, set it. + if (!this.isOptOut()) + { + this.configuration.set("opt-out", true); + this.configuration.save(this.configurationFile); + } + + // Disable Task, if it is running + if (this.task != null) + { + this.task.cancel(); + this.task = null; + } + } + } + + /** + * Gets the File object of the config file that should be used to store data such as the GUID and opt-out status + * + * @return the File object for the config file + */ + public File getConfigFile() + { + // I believe the easiest way to get the base folder (e.g craftbukkit set via -P) for plugins to use + // is to abuse the plugin object we already have + // plugin.getDataFolder() => base/plugins/PluginA/ + // pluginsFolder => base/plugins/ + // The base is not necessarily relative to the startup directory. + final File pluginsFolder = this.plugin.getDataFolder().getParentFile(); + + // return => base/plugins/PluginMetrics/config.yml + return new File(new File(pluginsFolder, "PluginMetrics"), "config.yml"); + } + + /** + * Generic method that posts a plugin to the metrics website + */ + private void postPlugin(final boolean isPing) throws IOException + { + // Server software specific section + final PluginDescriptionFile description = this.plugin.getDescription(); + final String pluginName = description.getName(); + final boolean onlineMode = Bukkit.getServer().getOnlineMode(); // TRUE if online mode is enabled + final String pluginVersion = description.getVersion(); + final String serverVersion = Bukkit.getVersion(); + final int playersOnline = Bukkit.getServer().getOnlinePlayers().size(); + + // END server software specific section -- all code below does not use any code outside of this class / Java + + // Construct the post data + final StringBuilder json = new StringBuilder(1024); + json.append('{'); + + // The plugin's description file containg all of the plugin data such as name, version, author, etc + Metrics.appendJSONPair(json, "guid", this.guid); + Metrics.appendJSONPair(json, "plugin_version", pluginVersion); + Metrics.appendJSONPair(json, "server_version", serverVersion); + Metrics.appendJSONPair(json, "players_online", Integer.toString(playersOnline)); + + // New data as of R6 + final String osname = System.getProperty("os.name"); + String osarch = System.getProperty("os.arch"); + final String osversion = System.getProperty("os.version"); + final String java_version = System.getProperty("java.version"); + final int coreCount = Runtime.getRuntime().availableProcessors(); + + // normalize os arch .. amd64 -> x86_64 + if (osarch.equals("amd64")) + { + osarch = "x86_64"; + } + + Metrics.appendJSONPair(json, "osname", osname); + Metrics.appendJSONPair(json, "osarch", osarch); + Metrics.appendJSONPair(json, "osversion", osversion); + Metrics.appendJSONPair(json, "cores", Integer.toString(coreCount)); + Metrics.appendJSONPair(json, "auth_mode", onlineMode ? "1" : "0"); + Metrics.appendJSONPair(json, "java_version", java_version); + + // If we're pinging, append it + if (isPing) + { + Metrics.appendJSONPair(json, "ping", "1"); + } + + if (this.graphs.size() > 0) + { + synchronized (this.graphs) + { + json.append(','); + json.append('"'); + json.append("graphs"); + json.append('"'); + json.append(':'); + json.append('{'); + + boolean firstGraph = true; + + final Iterator<Graph> iter = this.graphs.iterator(); + + while (iter.hasNext()) + { + final Graph graph = iter.next(); + + final StringBuilder graphJson = new StringBuilder(); + graphJson.append('{'); + + for (final Plotter plotter : graph.getPlotters()) + { + Metrics.appendJSONPair(graphJson, plotter.getColumnName(), Integer.toString(plotter.getValue())); + } + + graphJson.append('}'); + + if (!firstGraph) + { + json.append(','); + } + + json.append(Metrics.escapeJSON(graph.getName())); + json.append(':'); + json.append(graphJson); + + firstGraph = false; + } + + json.append('}'); + } + } + + // close json + json.append('}'); + + // Create the url + final URL url = new URL(Metrics.BASE_URL + String.format(Metrics.REPORT_URL, Metrics.urlEncode(pluginName))); + + // Connect to the website + URLConnection connection; + + // Mineshafter creates a socks proxy, so we can safely bypass it + // It does not reroute POST requests so we need to go around it + if (this.isMineshafterPresent()) + { + connection = url.openConnection(Proxy.NO_PROXY); + } + else + { + connection = url.openConnection(); + } + + final byte[] uncompressed = json.toString().getBytes(); + final byte[] compressed = Metrics.gzip(json.toString()); + + // Headers + connection.addRequestProperty("User-Agent", "MCStats/" + Metrics.REVISION); + connection.addRequestProperty("Content-Type", "application/json"); + connection.addRequestProperty("Content-Encoding", "gzip"); + connection.addRequestProperty("Content-Length", Integer.toString(compressed.length)); + connection.addRequestProperty("Accept", "application/json"); + connection.addRequestProperty("Connection", "close"); + + connection.setDoOutput(true); + + if (this.debug) + { + plugin.getLogger().fine("[Metrics] Prepared request for " + pluginName + " uncompressed=" + uncompressed.length + " compressed=" + compressed.length); + } + + // Write the data + final OutputStream os = connection.getOutputStream(); + os.write(compressed); + os.flush(); + + // Now read the response + final BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); + String response = reader.readLine(); + + // close resources + os.close(); + reader.close(); + + if (response == null || response.startsWith("ERR") || response.startsWith("7")) + { + if (response == null) + { + response = "null"; + } + else if (response.startsWith("7")) + { + response = response.substring(response.startsWith("7,") ? 2 : 1); + } + + throw new IOException(response); + } + else + { + // Is this the first update this hour? + if (response.equals("1") || response.contains("This is your first update this hour")) + { + synchronized (this.graphs) + { + final Iterator<Graph> iter = this.graphs.iterator(); + + while (iter.hasNext()) + { + final Graph graph = iter.next(); + + for (final Plotter plotter : graph.getPlotters()) + { + plotter.reset(); + } + } + } + } + } + } + + /** + * GZip compress a string of bytes + * + * @param input + * @return + */ + public static byte[] gzip(final String input) + { + final ByteArrayOutputStream baos = new ByteArrayOutputStream(); + GZIPOutputStream gzos = null; + + try + { + gzos = new GZIPOutputStream(baos); + gzos.write(input.getBytes("UTF-8")); + } + catch (final IOException e) + { + MinigamesAPI.getAPI().getLogger().log(Level.WARNING, "exception", e); + } + finally + { + if (gzos != null) + { + try + { + gzos.close(); + } + catch (final IOException ignore) + { + // silently ignore + } + } + } + + return baos.toByteArray(); + } + + /** + * Check if mineshafter is present. If it is, we need to bypass it to send POST requests + * + * @return true if mineshafter is installed on the server + */ + private boolean isMineshafterPresent() + { + try + { + Class.forName("mineshafter.MineServer"); + return true; + } + catch (final Exception e) + { + return false; + } + } + + /** + * Appends a json encoded key/value pair to the given string builder. + * + * @param json + * @param key + * @param value + * @throws UnsupportedEncodingException + */ + private static void appendJSONPair(final StringBuilder json, final String key, final String value) throws UnsupportedEncodingException + { + boolean isValueNumeric = false; + + try + { + if (value.equals("0") || !value.endsWith("0")) + { + Double.parseDouble(value); + isValueNumeric = true; + } + } + catch (final NumberFormatException e) + { + isValueNumeric = false; + } + + if (json.charAt(json.length() - 1) != '{') + { + json.append(','); + } + + json.append(Metrics.escapeJSON(key)); + json.append(':'); + + if (isValueNumeric) + { + json.append(value); + } + else + { + json.append(Metrics.escapeJSON(value)); + } + } + + /** + * Escape a string to create a valid JSON string + * + * @param text + * @return + */ + private static String escapeJSON(final String text) + { + final StringBuilder builder = new StringBuilder(); + + builder.append('"'); + for (int index = 0; index < text.length(); index++) + { + final char chr = text.charAt(index); + + switch (chr) + { + case '"': + case '\\': + builder.append('\\'); + builder.append(chr); + break; + case '\b': + builder.append("\\b"); + break; + case '\t': + builder.append("\\t"); + break; + case '\n': + builder.append("\\n"); + break; + case '\r': + builder.append("\\r"); + break; + default: + if (chr < ' ') + { + final String t = "000" + Integer.toHexString(chr); + builder.append("\\u" + t.substring(t.length() - 4)); + } + else + { + builder.append(chr); + } + break; + } + } + builder.append('"'); + + return builder.toString(); + } + + /** + * Encode text as UTF-8 + * + * @param text + * the text to encode + * @return the encoded text, as UTF-8 + */ + private static String urlEncode(final String text) throws UnsupportedEncodingException + { + return URLEncoder.encode(text, "UTF-8"); + } + + /** + * Represents a custom graph on the website + */ + public static class Graph + { + + /** + * The graph's name, alphanumeric and spaces only :) If it does not comply to the above when submitted, it is rejected + */ + private final String name; + + /** + * The set of plotters that are contained within this graph + */ + private final Set<Plotter> plotters = new LinkedHashSet<>(); + + private Graph(final String name) + { + this.name = name; + } + + /** + * Gets the graph's name + * + * @return the Graph's name + */ + public String getName() + { + return this.name; + } + + /** + * Add a plotter to the graph, which will be used to plot entries + * + * @param plotter + * the plotter to add to the graph + */ + public void addPlotter(final Plotter plotter) + { + this.plotters.add(plotter); + } + + /** + * Remove a plotter from the graph + * + * @param plotter + * the plotter to remove from the graph + */ + public void removePlotter(final Plotter plotter) + { + this.plotters.remove(plotter); + } + + /** + * Gets an <b>unmodifiable</b> set of the plotter objects in the graph + * + * @return an unmodifiable {@link java.util.Set} of the plotter objects + */ + public Set<Plotter> getPlotters() + { + return Collections.unmodifiableSet(this.plotters); + } + + @Override + public int hashCode() + { + return this.name.hashCode(); + } + + @Override + public boolean equals(final Object object) + { + if (!(object instanceof Graph)) + { + return false; + } + + final Graph graph = (Graph) object; + return graph.name.equals(this.name); + } + + /** + * Called when the server owner decides to opt-out of BukkitMetrics while the server is running. + */ + protected void onOptOut() + { + // silently ignore + } + } + + /** + * Interface used to collect custom data for a plugin + */ + public static abstract class Plotter + { + + /** + * The plot's name + */ + private final String name; + + /** + * Construct a plotter with the default plot name + */ + public Plotter() + { + this("Default"); + } + + /** + * Construct a plotter with a specific plot name + * + * @param name + * the name of the plotter to use, which will show up on the website + */ + public Plotter(final String name) + { + this.name = name; + } + + /** + * Get the current value for the plotted point. Since this function defers to an external function it may or may not return immediately thus cannot be guaranteed to be thread friendly or safe. + * This function can be called from any thread so care should be taken when accessing resources that need to be synchronized. + * + * @return the current value for the point to be plotted. + */ + public abstract int getValue(); + + /** + * Get the column name for the plotted point + * + * @return the plotted point's column name + */ + public String getColumnName() + { + return this.name; + } + + /** + * Called after the website graphs have been updated + */ + public void reset() + { + // silently ignore + } + + @Override + public int hashCode() + { + return this.getColumnName().hashCode(); + } + + @Override + public boolean equals(final Object object) + { + if (!(object instanceof Plotter)) + { + return false; + } + + final Plotter plotter = (Plotter) object; + return plotter.name.equals(this.name) && plotter.getValue() == this.getValue(); + } + } +} diff --git a/API/src/main/java/com/comze_instancelabs/minigamesapi/util/ParticleEffectNew.java b/API/src/main/java/com/comze_instancelabs/minigamesapi/util/ParticleEffectNew.java index 07de1cb6..bd1cecd7 100644 --- a/API/src/main/java/com/comze_instancelabs/minigamesapi/util/ParticleEffectNew.java +++ b/API/src/main/java/com/comze_instancelabs/minigamesapi/util/ParticleEffectNew.java @@ -1,209 +1,237 @@ +/* + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ package com.comze_instancelabs.minigamesapi.util; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; +import java.util.logging.Level; import org.bukkit.Location; -import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import com.comze_instancelabs.minigamesapi.MinigamesAPI; //modified by instancelabs -public enum ParticleEffectNew { - /** - * Each ParticleEffect has the packet name, and the environment in which it will be successfully displayed. - */ - HUGE_EXPLOSION("hugeexplosion", Environment.ANY), // works in any block type - LARGE_EXPLODE("largeexplode", Environment.ANY), FIREWORK_SPARK("fireworksSpark", Environment.ANY), TOWN_AURA("townaura", Environment.ANY), CRIT("crit", Environment.ANY), MAGIC_CRIT("magicCrit", Environment.ANY), SMOKE("smoke", Environment.ANY), MOB_SPELL("mobSpell", Environment.ANY), MOB_SPELL_AMBIENT("mobSpellAmbient", Environment.ANY), SPELL("spell", Environment.ANY), INSTANT_SPELL("instantSpell", Environment.ANY), WITCH_MAGIC("witchMagic", Environment.ANY), NOTE("note", Environment.ANY), PORTAL("portal", Environment.ANY), ENCHANTMENT_TABLE( - "enchantmenttable", Environment.ANY), EXPLODE("explode", Environment.ANY), FLAME("flame", Environment.ANY), LAVA("lava", Environment.ANY), FOOTSTEP("footstep", Environment.ANY), LARGE_SMOKE("largesmoke", Environment.ANY), CLOUD("cloud", Environment.ANY), RED_DUST("reddust", Environment.ANY), SNOWBALL_POOF("snowballpoof", Environment.ANY), DRIP_WATER("dripWater", Environment.ANY), DRIP_LAVA("dripLava", Environment.ANY), SNOW_SHOVEL("snowshovel", Environment.ANY), SLIME("slime", Environment.ANY), HEART("heart", Environment.ANY), ANGRY_VILLAGER( - "angryVillager", Environment.ANY), HAPPY_VILLAGER("happerVillager", Environment.ANY), - // ICONCRACK is not reliable and should not be added to the API, across different sized texture packs it displays a different item) - ICONCRACK("iconcrack_%id%", Environment.UKNOWN), //Guessing it is any, but didn't test - TILECRACK("tilecrack_%id%_%data%", Environment.UKNOWN), // Guessing it is any, but didn't test - SPLASH("splash", Environment.AIR), // only works in air - BUBBLE("bubble", Environment.IN_WATER), // only works in water - SUSPEND("suspend", Environment.UKNOWN), // Can't figure out what this does - DEPTH_SUSPEND("depthSuspend", Environment.UKNOWN); // Can't figure out what this does - - private final String packetName; - private final Environment environment; - - private int xStack, yStack, zStack; - private int _id = 1; - private int _data = 0; - - /** - * Each particle effect has a packet name, and an environment for developers - * - * @param packetName - * @param environment - */ - ParticleEffectNew(String packetName, Environment environment) { - this.packetName = packetName; - this.environment = environment; - } - - /** - * Setting the stack in the x,y,z axis makes another emitter in both directions on each block for length of the stack - * - * @param stackXAxis - * @param stackYAxis - * @param stackZAxis - */ - public void setStack(int stackXAxis, int stackYAxis, int stackZAxis) { - xStack = stackXAxis; - yStack = stackYAxis; - zStack = stackZAxis; - } - - /** - * This is used for the icon/tile crack and sets the id - * - * @param id - */ - public void setId(int id) { - _id = id; - } - - /** - * This is used for tile crack and sets the block data - * - * @param data - */ - public void setData(int data) { - _data = data; - } - - /** - * This is used to send a particle effect to only one player, no one else will see this. - * - * @param player - * @param count - * @param speed - */ - /* - * public void animateToPlayer(Player player, int count, float speed) { if (player == null) return; - * - * CraftPlayer craftPlayer = (CraftPlayer) player; - * - * try { craftPlayer.getHandle().playerConnection.sendPacket(getParticle(player.getLocation(), xStack, yStack, zStack, speed, count)); } catch - * (Exception e) { e.printStackTrace(); } } - */ - - // added - /** - * This is used to send a particle effect to only one player at a given location, no one else will see this. - * - * @param player - * @param count - * @param speed - */ - /* - * public void animateToPlayer(Player player, Location loc, int count, float speed) { if (player == null) return; - * - * CraftPlayer craftPlayer = (CraftPlayer) player; - * - * try { craftPlayer.getHandle().playerConnection.sendPacket(getParticle(loc, xStack, yStack, zStack, speed, count)); } catch (Exception e) { - * e.printStackTrace(); } } - */ - - /** - * This is used to send a particle effect to a location and all players near it will see it - * - * @param location - * @param count - * @param speed - */ - /* - * public void animateAtLocation(Location location, int count, float speed) { if (location == null) return; - * - * try { for (Entity entity : location.getWorld().getEntities()) { if (entity instanceof CraftPlayer) { if - * (entity.getLocation().distance(location) < 333) { // Not sure what max render distance is for particles, so made up 333 CraftPlayer craftPlayer - * = (CraftPlayer) entity; craftPlayer.getHandle().playerConnection.sendPacket(getParticle(location, xStack, yStack, zStack, speed, count)); } } } - * } catch (Exception e) { e.printStackTrace(); } } - */ - - /** - * Returns the environment that the particle must be in for it to be seen - * - * @return - */ - public Environment getEnvironment() { - return environment; - } - - /** - * Enum that depicts in what environments a particle effect will be seen - */ - public enum Environment { - ANY, AIR, IN_WATER, UKNOWN; - } - - /** - * Returns the actual packet that is sent to a player This will replace id and data variables for icon/tile crack as well - * - * @param location - * @param offsetX - * @param offsetY - * @param offsetZ - * @param speed - * @param count - * @return - * @throws Exception - */ - /* - * private PacketPlayOutWorldParticles getParticle(Location location, float offsetX, float offsetY, float offsetZ, float speed, int count) throws - * Exception { PacketPlayOutWorldParticles packet = new PacketPlayOutWorldParticles(); setValue(packet, "a", packetName.replace("%id%", "" + - * _id).replace("%data%", "" + _data)); setValue(packet, "b", (float) location.getX()); setValue(packet, "c", (float) location.getY()); - * setValue(packet, "d", (float) location.getZ()); setValue(packet, "e", offsetX); setValue(packet, "f", offsetY); setValue(packet, "g", offsetZ); - * setValue(packet, "h", speed); setValue(packet, "i", count); return packet; } - */ - - /** - * Reflection to set the values of the packet - * - * @param instance - * @param fieldName - * @param value - * @throws Exception - */ - private static void setValue(Object instance, String fieldName, Object value) throws Exception { - Field field = instance.getClass().getDeclaredField(fieldName); - field.setAccessible(true); - field.set(instance, value); - } - - public void animateReflected(Player p, Location location, float speed, int count) { - try { - Method getHandle = Class.forName("org.bukkit.craftbukkit." + MinigamesAPI.getAPI().version + ".entity.CraftPlayer").getMethod("getHandle"); - Field playerConnection = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().version + ".EntityPlayer").getField("playerConnection"); - playerConnection.setAccessible(true); - Method sendPacket = playerConnection.getType().getMethod("sendPacket", Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().version + ".Packet")); - - String packetname = "PacketPlayOutWorldParticles"; - if (MinigamesAPI.getAPI().version.equalsIgnoreCase("v1_6_R2")) { - packetname = "Packet63WorldParticles"; - } - - Constructor packetConstr = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().version + "." + packetname).getConstructor(); - - Object packet = packetConstr.newInstance(); - setValue(packet, "a", packetName.replace("%id%", "" + _id).replace("%data%", "" + _data)); - setValue(packet, "b", (float) location.getX()); - setValue(packet, "c", (float) location.getY()); - setValue(packet, "d", (float) location.getZ()); - setValue(packet, "e", 0F); - setValue(packet, "f", 0F); - setValue(packet, "g", 0F); - setValue(packet, "h", speed); - setValue(packet, "i", count); - - sendPacket.invoke(playerConnection.get(getHandle.invoke(p)), packet); - } catch (Exception e) { - e.printStackTrace(); - } - } -} \ No newline at end of file +public enum ParticleEffectNew +{ + /** + * Each ParticleEffect has the packet name, and the environment in which it will be successfully displayed. + */ + HUGE_EXPLOSION("hugeexplosion", Environment.ANY), // works in any block type + LARGE_EXPLODE("largeexplode", Environment.ANY), FIREWORK_SPARK("fireworksSpark", Environment.ANY), TOWN_AURA("townaura", Environment.ANY), CRIT("crit", Environment.ANY), MAGIC_CRIT("magicCrit", + Environment.ANY), SMOKE("smoke", Environment.ANY), MOB_SPELL("mobSpell", Environment.ANY), MOB_SPELL_AMBIENT("mobSpellAmbient", Environment.ANY), SPELL("spell", + Environment.ANY), INSTANT_SPELL("instantSpell", Environment.ANY), WITCH_MAGIC("witchMagic", Environment.ANY), NOTE("note", Environment.ANY), PORTAL("portal", + Environment.ANY), ENCHANTMENT_TABLE("enchantmenttable", Environment.ANY), EXPLODE("explode", Environment.ANY), FLAME("flame", Environment.ANY), LAVA("lava", + Environment.ANY), FOOTSTEP("footstep", Environment.ANY), LARGE_SMOKE("largesmoke", Environment.ANY), CLOUD("cloud", Environment.ANY), RED_DUST("reddust", + Environment.ANY), SNOWBALL_POOF("snowballpoof", Environment.ANY), DRIP_WATER("dripWater", Environment.ANY), DRIP_LAVA("dripLava", + Environment.ANY), SNOW_SHOVEL("snowshovel", Environment.ANY), SLIME("slime", Environment.ANY), HEART("heart", + Environment.ANY), ANGRY_VILLAGER("angryVillager", Environment.ANY), HAPPY_VILLAGER("happerVillager", Environment.ANY), + // ICONCRACK is not reliable and should not be added to the API, across different sized texture packs it displays a different item) + ICONCRACK("iconcrack_%id%", Environment.UKNOWN), // Guessing it is any, but didn't test + TILECRACK("tilecrack_%id%_%data%", Environment.UKNOWN), // Guessing it is any, but didn't test + SPLASH("splash", Environment.AIR), // only works in air + BUBBLE("bubble", Environment.IN_WATER), // only works in water + SUSPEND("suspend", Environment.UKNOWN), // Can't figure out what this does + DEPTH_SUSPEND("depthSuspend", Environment.UKNOWN); // Can't figure out what this does + + private final String packetName; + private final Environment environment; + + private int xStack, yStack, zStack; + private int _id = 1; + private int _data = 0; + + /** + * Each particle effect has a packet name, and an environment for developers + * + * @param packetName + * @param environment + */ + ParticleEffectNew(final String packetName, final Environment environment) + { + this.packetName = packetName; + this.environment = environment; + } + + /** + * Setting the stack in the x,y,z axis makes another emitter in both directions on each block for length of the stack + * + * @param stackXAxis + * @param stackYAxis + * @param stackZAxis + */ + public void setStack(final int stackXAxis, final int stackYAxis, final int stackZAxis) + { + this.xStack = stackXAxis; + this.yStack = stackYAxis; + this.zStack = stackZAxis; + } + + /** + * This is used for the icon/tile crack and sets the id + * + * @param id + */ + public void setId(final int id) + { + this._id = id; + } + + /** + * This is used for tile crack and sets the block data + * + * @param data + */ + public void setData(final int data) + { + this._data = data; + } + + /** + * This is used to send a particle effect to only one player, no one else will see this. + * + * @param player + * @param count + * @param speed + */ + /* + * public void animateToPlayer(Player player, int count, float speed) { if (player == null) return; + * + * CraftPlayer craftPlayer = (CraftPlayer) player; + * + * try { craftPlayer.getHandle().playerConnection.sendPacket(getParticle(player.getLocation(), xStack, yStack, zStack, speed, count)); } catch (Exception e) { logtrace } } + */ + + // added + /** + * This is used to send a particle effect to only one player at a given location, no one else will see this. + * + * @param player + * @param count + * @param speed + */ + /* + * public void animateToPlayer(Player player, Location loc, int count, float speed) { if (player == null) return; + * + * CraftPlayer craftPlayer = (CraftPlayer) player; + * + * try { craftPlayer.getHandle().playerConnection.sendPacket(getParticle(loc, xStack, yStack, zStack, speed, count)); } catch (Exception e) { logtrace } } + */ + + /** + * This is used to send a particle effect to a location and all players near it will see it + * + * @param location + * @param count + * @param speed + */ + /* + * public void animateAtLocation(Location location, int count, float speed) { if (location == null) return; + * + * try { for (Entity entity : location.getWorld().getEntities()) { if (entity instanceof CraftPlayer) { if (entity.getLocation().distance(location) < 333) { // Not sure what max render distance is + * for particles, so made up 333 CraftPlayer craftPlayer = (CraftPlayer) entity; craftPlayer.getHandle().playerConnection.sendPacket(getParticle(location, xStack, yStack, zStack, speed, count)); } + * } } } catch (Exception e) { logtrace } } + */ + + /** + * Returns the environment that the particle must be in for it to be seen + * + * @return + */ + public Environment getEnvironment() + { + return this.environment; + } + + /** + * Enum that depicts in what environments a particle effect will be seen + */ + public enum Environment + { + ANY, AIR, IN_WATER, UKNOWN; + } + + /** + * Returns the actual packet that is sent to a player This will replace id and data variables for icon/tile crack as well + * + * @param location + * @param offsetX + * @param offsetY + * @param offsetZ + * @param speed + * @param count + * @return + * @throws Exception + */ + /* + * private PacketPlayOutWorldParticles getParticle(Location location, float offsetX, float offsetY, float offsetZ, float speed, int count) throws Exception { PacketPlayOutWorldParticles packet = + * new PacketPlayOutWorldParticles(); setValue(packet, "a", packetName.replace("%id%", "" + _id).replace("%data%", "" + _data)); setValue(packet, "b", (float) location.getX()); setValue(packet, + * "c", (float) location.getY()); setValue(packet, "d", (float) location.getZ()); setValue(packet, "e", offsetX); setValue(packet, "f", offsetY); setValue(packet, "g", offsetZ); setValue(packet, + * "h", speed); setValue(packet, "i", count); return packet; } + */ + + /** + * Reflection to set the values of the packet + * + * @param instance + * @param fieldName + * @param value + * @throws Exception + */ + private static void setValue(final Object instance, final String fieldName, final Object value) throws Exception + { + final Field field = instance.getClass().getDeclaredField(fieldName); + field.setAccessible(true); + field.set(instance, value); + } + + public void animateReflected(final Player p, final Location location, final float speed, final int count) + { + try + { + final Method getHandle = Class.forName("org.bukkit.craftbukkit." + MinigamesAPI.getAPI().internalServerVersion + ".entity.CraftPlayer").getMethod("getHandle"); + final Field playerConnection = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().internalServerVersion + ".EntityPlayer").getField("playerConnection"); + playerConnection.setAccessible(true); + final Method sendPacket = playerConnection.getType().getMethod("sendPacket", Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().internalServerVersion + ".Packet")); + + String packetname = "PacketPlayOutWorldParticles"; + if (MinigamesAPI.getAPI().internalServerVersion.equalsIgnoreCase("v1_6_R2")) + { + packetname = "Packet63WorldParticles"; + } + + final Constructor packetConstr = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().internalServerVersion + "." + packetname).getConstructor(); + + final Object packet = packetConstr.newInstance(); + ParticleEffectNew.setValue(packet, "a", this.packetName.replace("%id%", "" + this._id).replace("%data%", "" + this._data)); + ParticleEffectNew.setValue(packet, "b", (float) location.getX()); + ParticleEffectNew.setValue(packet, "c", (float) location.getY()); + ParticleEffectNew.setValue(packet, "d", (float) location.getZ()); + ParticleEffectNew.setValue(packet, "e", 0F); + ParticleEffectNew.setValue(packet, "f", 0F); + ParticleEffectNew.setValue(packet, "g", 0F); + ParticleEffectNew.setValue(packet, "h", speed); + ParticleEffectNew.setValue(packet, "i", count); + + sendPacket.invoke(playerConnection.get(getHandle.invoke(p)), packet); + } + catch (final Exception e) + { + MinigamesAPI.getAPI().getLogger().log(Level.WARNING, "exception", e); + } + } +} diff --git a/API/src/main/java/com/comze_instancelabs/minigamesapi/util/PlayerPickupItemHelper.java b/API/src/main/java/com/comze_instancelabs/minigamesapi/util/PlayerPickupItemHelper.java new file mode 100644 index 00000000..5232fb9a --- /dev/null +++ b/API/src/main/java/com/comze_instancelabs/minigamesapi/util/PlayerPickupItemHelper.java @@ -0,0 +1,142 @@ +/* + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +package com.comze_instancelabs.minigamesapi.util; + +import java.util.function.Consumer; + +import org.bukkit.Bukkit; +import org.bukkit.entity.Item; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityPickupItemEvent; +import org.bukkit.event.player.PlayerPickupItemEvent; +import org.bukkit.plugin.Plugin; + +import com.comze_instancelabs.minigamesapi.MinecraftVersionsType; +import com.comze_instancelabs.minigamesapi.MinigamesAPI; + +/** + * @author mepeisen + * + */ +public class PlayerPickupItemHelper +{ + + final Consumer<CustomPickupEvent> handler; + + public PlayerPickupItemHelper(Plugin plugin, Consumer<CustomPickupEvent> handler) + { + this.handler = handler; + if (MinigamesAPI.SERVER_VERSION.isAtLeast(MinecraftVersionsType.V1_12)) + { + Bukkit.getPluginManager().registerEvents(new EntityPickup(), plugin); + } + else + { + Bukkit.getPluginManager().registerEvents(new PlayerPickup(), plugin); + } + } + + private final class PlayerPickup implements Listener + { + @EventHandler + public void onPlayerPickupItem(PlayerPickupItemEvent event) { + handler.accept(new CustomPickupEvent() { + + @Override + public Player getPlayer() + { + return event.getPlayer(); + } + + @Override + public Item getItem() + { + return event.getItem(); + } + + @Override + public int getRemaining() + { + return event.getRemaining(); + } + + @Override + public boolean isCancelled() + { + return event.isCancelled(); + } + + @Override + public void setCancelled(boolean cancel) + { + event.setCancelled(cancel); + }}); + } + } + + private final class EntityPickup implements Listener + { + @EventHandler + public void onPlayerPickupItem(EntityPickupItemEvent event) { + if (event.getEntity() instanceof Player) + { + handler.accept(new CustomPickupEvent() { + + @Override + public Player getPlayer() + { + return (Player) event.getEntity(); + } + + @Override + public Item getItem() + { + return event.getItem(); + } + + @Override + public int getRemaining() + { + return event.getRemaining(); + } + + @Override + public boolean isCancelled() + { + return event.isCancelled(); + } + + @Override + public void setCancelled(boolean cancel) + { + event.setCancelled(cancel); + }}); + } + } + } + + public interface CustomPickupEvent + { + Player getPlayer(); + Item getItem(); + int getRemaining(); + boolean isCancelled(); + void setCancelled(boolean cancel); + } + +} diff --git a/API/src/main/java/com/comze_instancelabs/minigamesapi/util/ShopItem.java b/API/src/main/java/com/comze_instancelabs/minigamesapi/util/ShopItem.java index c7839242..6a870c2d 100644 --- a/API/src/main/java/com/comze_instancelabs/minigamesapi/util/ShopItem.java +++ b/API/src/main/java/com/comze_instancelabs/minigamesapi/util/ShopItem.java @@ -1,3 +1,17 @@ +/* + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ package com.comze_instancelabs.minigamesapi.util; import java.util.ArrayList; @@ -7,14 +21,17 @@ import com.comze_instancelabs.minigamesapi.PluginInstance; -public class ShopItem extends AClass { - - public ShopItem(JavaPlugin plugin, String name, String internalname, boolean enabled, ArrayList<ItemStack> items, ItemStack icon) { - super(plugin, name, internalname, enabled, items, icon); - } - - public boolean usesItems(PluginInstance pli) { - return pli.getShopConfig().getConfig().getBoolean("config.shop_items." + this.getInternalName() + ".uses_items"); - } - +public class ShopItem extends AClass +{ + + public ShopItem(final JavaPlugin plugin, final String name, final String internalname, final boolean enabled, final ArrayList<ItemStack> items, final ItemStack icon) + { + super(plugin, name, internalname, enabled, items, icon); + } + + public boolean usesItems(final PluginInstance pli) + { + return pli.getShopConfig().getConfig().getBoolean("config.shop_items." + this.getInternalName() + ".uses_items"); + } + } diff --git a/API/src/main/java/com/comze_instancelabs/minigamesapi/util/Signs.java b/API/src/main/java/com/comze_instancelabs/minigamesapi/util/Signs.java new file mode 100644 index 00000000..aa7fe12f --- /dev/null +++ b/API/src/main/java/com/comze_instancelabs/minigamesapi/util/Signs.java @@ -0,0 +1,100 @@ +/* + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +package com.comze_instancelabs.minigamesapi.util; + +import java.util.Arrays; + +/** + * Utility class for signs. + * + * @author mepeisen + */ +public class Signs +{ + + /** a string of sqaures. */ + private static final String squares; + + /** mid size squares. */ + private static final char[] squares_mid = new char[10]; + /** full size squares. */ + private static final char[] squares_full = new char[10]; + /** medium size squares. */ + private static final char[] squares_medium = new char[10]; + /** light size squares. */ + private static final char[] squares_light = new char[10]; + + /** mid size squares. */ + private static final String ssquares_mid; + /** full size squares. */ + private static final String ssquares_full; + /** medium size squares. */ + private static final String ssquares_medium; + /** light size squares. */ + private static final String ssquares_light; + + static + { + Arrays.fill(squares_mid, (char) 0x25A0); + Arrays.fill(squares_full, (char) 0x2588); + Arrays.fill(squares_medium, (char) 0x2592); + Arrays.fill(squares_light, (char) 0x2591); + final StringBuilder builder = new StringBuilder(); + for (int i = 0; i < 11; i++) + { + builder.append((char) 0x25A0); + } + squares = builder.toString(); + ssquares_mid = new String(squares_mid); + ssquares_full = new String(squares_full); + ssquares_medium = new String(squares_medium); + ssquares_light = new String(squares_light); + } + + /** + * Formats the source string from messages config to be used ingame. + * @param src source string + * @return formatted string. + */ + public static final String format(String src) + { + return replaceSquares(replaceColorCodes(src)); + } + + /** + * Replaces color codes from message strings. + * @param src source string + * @return formatted string. + */ + public static final String replaceColorCodes(String src) + { + return src.replaceAll("&", "§"); //$NON-NLS-1$ //$NON-NLS-2$ + } + + /** + * Replaces "[...]" characters with squares of different sizes. + * @param src source string. + * @return formatted string. + */ + public static final String replaceSquares(String src) + { + return src.replace("[]", new String(ssquares_mid)). //$NON-NLS-1$ + replace("[1]", new String(ssquares_full). //$NON-NLS-1$ + replace("[2]", new String(ssquares_medium)). //$NON-NLS-1$ + replace("[3]", new String(ssquares_light))); //$NON-NLS-1$ + } + +} diff --git a/API/src/main/java/com/comze_instancelabs/minigamesapi/util/SmartArenaBlock.java b/API/src/main/java/com/comze_instancelabs/minigamesapi/util/SmartArenaBlock.java index 548e15a8..3f84b584 100644 --- a/API/src/main/java/com/comze_instancelabs/minigamesapi/util/SmartArenaBlock.java +++ b/API/src/main/java/com/comze_instancelabs/minigamesapi/util/SmartArenaBlock.java @@ -1,9 +1,24 @@ +/* + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ package com.comze_instancelabs.minigamesapi.util; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; +import java.util.logging.Level; import org.bukkit.Bukkit; import org.bukkit.Location; @@ -11,6 +26,7 @@ import org.bukkit.World; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; +import org.bukkit.block.BlockState; import org.bukkit.block.Chest; import org.bukkit.block.Dispenser; import org.bukkit.block.DoubleChest; @@ -24,235 +40,339 @@ import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.potion.Potion; -public class SmartArenaBlock implements Serializable { - private static final long serialVersionUID = -1894759842709524780L; - - private int x, y, z; - private String world; - private Material m; - private byte data; - private ArrayList<Material> item_mats; - private ArrayList<Byte> item_data; - private ArrayList<Integer> item_amounts; - private ArrayList<String> item_displaynames; - private HashMap<Integer, ArrayList<Integer>> item_enchid; - private HashMap<Integer, ArrayList<Integer>> item_enchid_lv; - private HashMap<Integer, ArrayList<Integer>> enchbook_id; - private HashMap<Integer, ArrayList<Integer>> enchbook_id_lv; - private ArrayList<Short> item_durability; - private ArrayList<Integer> item_pos; - - // Sign lines - private ArrayList<String> sign_lines = new ArrayList<String>(); - - // Sign lines - private String skull_owner = ""; - private BlockFace skull_rotation = BlockFace.SELF; - - // optional stuff - private ArrayList<Boolean> item_splash; - - private ItemStack[] inv; - - boolean isDoubleChest = false; - DoubleChest doubleChest = null; - - public SmartArenaBlock(Block b, boolean c, boolean s) { - m = b.getType(); - x = b.getX(); - y = b.getY(); - z = b.getZ(); - data = b.getData(); - world = b.getWorld().getName(); - if (m.equals(Material.SKULL)) { - if (b.getState() instanceof Skull) { - skull_owner = ((Skull) b.getState()).getOwner(); - skull_rotation = ((Skull) b.getState()).getRotation(); - } - } - if (m.equals(Material.DROPPER)) { - if (b.getState() instanceof Dropper) { - setInventory(((Dropper) b.getState()).getInventory()); - } - } - if (m.equals(Material.DISPENSER)) { - if (b.getState() instanceof Dispenser) { - setInventory(((Dispenser) b.getState()).getInventory()); - } - } - if (s) { - Sign sign = (Sign) b.getState(); - if (sign != null) { - sign_lines.addAll(Arrays.asList(sign.getLines())); - } - } else if (c) { - Chest chest = (Chest) b.getState(); - setInventory(chest.getInventory()); - } - } - - public SmartArenaBlock(Location l, Material m, byte data) { - this.m = m; - x = l.getBlockX(); - y = l.getBlockY(); - z = l.getBlockZ(); - world = l.getWorld().getName(); - this.data = data; - } - - public Block getBlock() { - World w = Bukkit.getWorld(world); - if (w == null) - return null; - Block b = w.getBlockAt(x, y, z); - return b; - } - - public Material getMaterial() { - return m; - } - - public Byte getData() { - return data; - } - - public void setData(byte data) { - this.data = data; - } - - public ItemStack[] getInventory() { - return inv; - } - - public HashMap<Integer, ItemStack> getNewInventory() { - HashMap<Integer, ItemStack> ret = new HashMap<Integer, ItemStack>(); - for (int i = 0; i < item_mats.size(); i++) { - ItemStack item = new ItemStack(item_mats.get(i), item_amounts.get(i), item_data.get(i)); - item.setDurability(item_durability.get(i)); - ItemMeta im = item.getItemMeta(); - im.setDisplayName(item_displaynames.get(i)); - - if (item_enchid.size() > i && item_enchid.get(i) != null) { - int c = 0; - for (Integer ench : item_enchid.get(i)) { - im.addEnchant(Enchantment.getById(ench), item_enchid_lv.get(i).get(c), true); - c++; - } - } - - item.setItemMeta(im); - if (item.getType() == Material.POTION && item.getDurability() > 0) { - Potion potion = Potion.fromDamage(item.getDurability() & 0x3F); - if (item_splash.size() > i) { - potion.setSplash(item_splash.get(i)); - } - } else if (item.getType() == Material.ENCHANTED_BOOK) { - ItemStack neww = new ItemStack(Material.ENCHANTED_BOOK); - EnchantmentStorageMeta meta = (EnchantmentStorageMeta) neww.getItemMeta(); - int c_ = 0; - if (enchbook_id.size() > i) { - for (Integer ench : enchbook_id.get(i)) { - try { - meta.addStoredEnchant(Enchantment.getById(ench), enchbook_id_lv.get(i).get(c_), true); - } catch (Exception e) { - System.out.println("Failed applying enchantment to enchantment book at reset."); - } - c_++; - } - } - neww.setItemMeta(meta); - item = neww; - } - int pos = i; - if (i < item_pos.size()) { - pos = item_pos.get(i); - } - ret.put(pos, item); - } - return ret; - } - - public void setInventory(Inventory inventory) { - inv = inventory.getContents(); - item_mats = new ArrayList<Material>(); - item_data = new ArrayList<Byte>(); - item_amounts = new ArrayList<Integer>(); - item_displaynames = new ArrayList<String>(); - item_splash = new ArrayList<Boolean>(); - item_pos = new ArrayList<Integer>(); - item_enchid = new HashMap<Integer, ArrayList<Integer>>(); - item_enchid_lv = new HashMap<Integer, ArrayList<Integer>>(); - enchbook_id = new HashMap<Integer, ArrayList<Integer>>(); - enchbook_id_lv = new HashMap<Integer, ArrayList<Integer>>(); - item_durability = new ArrayList<Short>(); - - if (inventory.getHolder() instanceof DoubleChest) { - isDoubleChest = true; - doubleChest = (DoubleChest) inventory.getHolder(); - } - - int pos = 0; - for (ItemStack i : inventory.getContents()) { - if (i != null) { - item_mats.add(i.getType()); - item_data.add(i.getData().getData()); - item_amounts.add(i.getAmount()); - item_displaynames.add(i.getItemMeta().getDisplayName()); - item_durability.add(i.getDurability()); - if (i.getType() == Material.POTION && i.getDurability() > 0) { - Potion potion = Potion.fromDamage(i.getDurability() & 0x3F); - item_splash.add(potion.isSplash()); - } else if (i.getType() == Material.ENCHANTED_BOOK) { - EnchantmentStorageMeta meta = (EnchantmentStorageMeta) i.getItemMeta(); - ArrayList<Integer> tempid = new ArrayList<Integer>(); - ArrayList<Integer> templv = new ArrayList<Integer>(); - for (Enchantment ench : meta.getStoredEnchants().keySet()) { - tempid.add(ench.getId()); - templv.add(meta.getStoredEnchants().get(ench)); - } - enchbook_id.put(pos, tempid); - enchbook_id_lv.put(pos, templv); - item_splash.add(false); - } else { - item_splash.add(false); - } - item_pos.add(pos); - if (i.getItemMeta().getEnchants().size() > 0) { - ArrayList<Integer> tempid = new ArrayList<Integer>(); - ArrayList<Integer> templv = new ArrayList<Integer>(); - for (Enchantment ench : i.getItemMeta().getEnchants().keySet()) { - tempid.add(ench.getId()); - templv.add(i.getItemMeta().getEnchants().get(ench)); - } - item_enchid.put(pos, tempid); - item_enchid_lv.put(pos, templv); - } else { - item_enchid.put(pos, new ArrayList<Integer>()); - item_enchid_lv.put(pos, new ArrayList<Integer>()); - } - } - pos++; - } - } - - public ArrayList<String> getSignLines() { - return this.sign_lines; - } - - public boolean isDoubleChest() { - return isDoubleChest; - } - - public DoubleChest getDoubleChest() { - return doubleChest; - } - - public String getSkullOwner() { - return skull_owner; - } - - public BlockFace getSkullORotation() { - return skull_rotation; - } +import com.comze_instancelabs.minigamesapi.MinigamesAPI; -} \ No newline at end of file +public class SmartArenaBlock implements Serializable +{ + private static final long serialVersionUID = -1894759842709524780L; + + private final int x, y, z; + private final String world; + private final Material m; + private byte data; + private ArrayList<Material> item_mats; + private ArrayList<Byte> item_data; + private ArrayList<Integer> item_amounts; + private ArrayList<String> item_displaynames; + private HashMap<Integer, ArrayList<Integer>> item_enchid; + private HashMap<Integer, ArrayList<Integer>> item_enchid_lv; + private HashMap<Integer, ArrayList<Integer>> enchbook_id; + private HashMap<Integer, ArrayList<Integer>> enchbook_id_lv; + private ArrayList<Short> item_durability; + private ArrayList<Integer> item_pos; + + // Sign lines + private final ArrayList<String> sign_lines = new ArrayList<>(); + + // Sign lines + private String skull_owner = ""; + private BlockFace skull_rotation = BlockFace.SELF; + + // optional stuff + private ArrayList<Boolean> item_splash; + + private ItemStack[] inv; + + boolean isDoubleChest = false; + DoubleChest doubleChest = null; + + public SmartArenaBlock(final Block b, final boolean isChest, final boolean isSign) + { + this.m = b.getType(); + this.x = b.getX(); + this.y = b.getY(); + this.z = b.getZ(); + this.data = b.getData(); + this.world = b.getWorld().getName(); + if (this.m.equals(Material.SKULL)) + { + if (b.getState() instanceof Skull) + { + this.skull_owner = ((Skull) b.getState()).getOwner(); + this.skull_rotation = ((Skull) b.getState()).getRotation(); + } + } + if (this.m.equals(Material.DROPPER)) + { + if (b.getState() instanceof Dropper) + { + this.setInventory(((Dropper) b.getState()).getInventory()); + } + } + if (this.m.equals(Material.DISPENSER)) + { + if (b.getState() instanceof Dispenser) + { + this.setInventory(((Dispenser) b.getState()).getInventory()); + } + } + if (isSign) + { + final Sign sign = (Sign) b.getState(); + if (sign != null) + { + this.sign_lines.addAll(Arrays.asList(sign.getLines())); + } + } + else if (isChest) + { + final Chest chest = (Chest) b.getState(); + this.setInventory(chest.getInventory()); + } + if (MinigamesAPI.debug) + { + MinigamesAPI.getAPI().getLogger().fine("Added smart arena block @ " + this.x + "/" + this.y + "/" + this.z + " with material " + this.m); + } + } + + public SmartArenaBlock(final BlockState b, final boolean isChest, final boolean isSign) + { + this.m = b.getType(); + this.x = b.getX(); + this.y = b.getY(); + this.z = b.getZ(); + this.data = b.getData().getData(); + this.world = b.getWorld().getName(); + if (this.m.equals(Material.SKULL)) + { + if (b instanceof Skull) + { + this.skull_owner = ((Skull) b).getOwner(); + this.skull_rotation = ((Skull) b).getRotation(); + } + } + if (this.m.equals(Material.DROPPER)) + { + if (b instanceof Dropper) + { + this.setInventory(((Dropper) b).getInventory()); + } + } + if (this.m.equals(Material.DISPENSER)) + { + if (b instanceof Dispenser) + { + this.setInventory(((Dispenser) b).getInventory()); + } + } + if (isSign) + { + final Sign sign = (Sign) b; + if (sign != null) + { + this.sign_lines.addAll(Arrays.asList(sign.getLines())); + } + } + else if (isChest) + { + final Chest chest = (Chest) b; + this.setInventory(chest.getInventory()); + } + } + + public SmartArenaBlock(final Location l, final Material m, final byte data) + { + this.m = m; + this.x = l.getBlockX(); + this.y = l.getBlockY(); + this.z = l.getBlockZ(); + this.world = l.getWorld().getName(); + this.data = data; + } + + public Block getBlock() + { + final World w = Bukkit.getWorld(this.world); + if (w == null) + { + return null; + } + final Block b = w.getBlockAt(this.x, this.y, this.z); + return b; + } + + public Material getMaterial() + { + return this.m; + } + + public Byte getData() + { + return this.data; + } + + public void setData(final byte data) + { + this.data = data; + } + + public ItemStack[] getInventory() + { + return this.inv; + } + + public HashMap<Integer, ItemStack> getNewInventory() + { + final HashMap<Integer, ItemStack> ret = new HashMap<>(); + for (int i = 0; i < this.item_mats.size(); i++) + { + ItemStack item = new ItemStack(this.item_mats.get(i), this.item_amounts.get(i), this.item_data.get(i)); + item.setDurability(this.item_durability.get(i)); + final ItemMeta im = item.getItemMeta(); + im.setDisplayName(this.item_displaynames.get(i)); + + if (this.item_enchid.size() > i && this.item_enchid.get(i) != null) + { + int c = 0; + for (final Integer ench : this.item_enchid.get(i)) + { + im.addEnchant(Enchantment.getById(ench), this.item_enchid_lv.get(i).get(c), true); + c++; + } + } + + item.setItemMeta(im); + if (item.getType() == Material.POTION && item.getDurability() > 0) + { + final Potion potion = Potion.fromDamage(item.getDurability() & 0x3F); + if (this.item_splash.size() > i) + { + potion.setSplash(this.item_splash.get(i)); + } + } + else if (item.getType() == Material.ENCHANTED_BOOK) + { + final ItemStack neww = new ItemStack(Material.ENCHANTED_BOOK); + final EnchantmentStorageMeta meta = (EnchantmentStorageMeta) neww.getItemMeta(); + int c_ = 0; + if (this.enchbook_id.size() > i) + { + for (final Integer ench : this.enchbook_id.get(i)) + { + try + { + meta.addStoredEnchant(Enchantment.getById(ench), this.enchbook_id_lv.get(i).get(c_), true); + } + catch (final Exception e) + { + MinigamesAPI.getAPI().getLogger().log(Level.WARNING, "Failed applying enchantment to enchantment book at reset.", e); + } + c_++; + } + } + neww.setItemMeta(meta); + item = neww; + } + int pos = i; + if (i < this.item_pos.size()) + { + pos = this.item_pos.get(i); + } + ret.put(pos, item); + } + return ret; + } + + public void setInventory(final Inventory inventory) + { + this.inv = inventory.getContents(); + this.item_mats = new ArrayList<>(); + this.item_data = new ArrayList<>(); + this.item_amounts = new ArrayList<>(); + this.item_displaynames = new ArrayList<>(); + this.item_splash = new ArrayList<>(); + this.item_pos = new ArrayList<>(); + this.item_enchid = new HashMap<>(); + this.item_enchid_lv = new HashMap<>(); + this.enchbook_id = new HashMap<>(); + this.enchbook_id_lv = new HashMap<>(); + this.item_durability = new ArrayList<>(); + + if (inventory.getHolder() instanceof DoubleChest) + { + this.isDoubleChest = true; + this.doubleChest = (DoubleChest) inventory.getHolder(); + } + + int pos = 0; + for (final ItemStack i : inventory.getContents()) + { + if (i != null) + { + this.item_mats.add(i.getType()); + this.item_data.add(i.getData().getData()); + this.item_amounts.add(i.getAmount()); + this.item_displaynames.add(i.getItemMeta().getDisplayName()); + this.item_durability.add(i.getDurability()); + if (i.getType() == Material.POTION && i.getDurability() > 0) + { + final Potion potion = Potion.fromDamage(i.getDurability() & 0x3F); + this.item_splash.add(potion.isSplash()); + } + else if (i.getType() == Material.ENCHANTED_BOOK) + { + final EnchantmentStorageMeta meta = (EnchantmentStorageMeta) i.getItemMeta(); + final ArrayList<Integer> tempid = new ArrayList<>(); + final ArrayList<Integer> templv = new ArrayList<>(); + for (final Enchantment ench : meta.getStoredEnchants().keySet()) + { + tempid.add(ench.getId()); + templv.add(meta.getStoredEnchants().get(ench)); + } + this.enchbook_id.put(pos, tempid); + this.enchbook_id_lv.put(pos, templv); + this.item_splash.add(false); + } + else + { + this.item_splash.add(false); + } + this.item_pos.add(pos); + if (i.getItemMeta().getEnchants().size() > 0) + { + final ArrayList<Integer> tempid = new ArrayList<>(); + final ArrayList<Integer> templv = new ArrayList<>(); + for (final Enchantment ench : i.getItemMeta().getEnchants().keySet()) + { + tempid.add(ench.getId()); + templv.add(i.getItemMeta().getEnchants().get(ench)); + } + this.item_enchid.put(pos, tempid); + this.item_enchid_lv.put(pos, templv); + } + else + { + this.item_enchid.put(pos, new ArrayList<Integer>()); + this.item_enchid_lv.put(pos, new ArrayList<Integer>()); + } + } + pos++; + } + } + + public ArrayList<String> getSignLines() + { + return this.sign_lines; + } + + public boolean isDoubleChest() + { + return this.isDoubleChest; + } + + public DoubleChest getDoubleChest() + { + return this.doubleChest; + } + + public String getSkullOwner() + { + return this.skull_owner; + } + + public BlockFace getSkullORotation() + { + return this.skull_rotation; + } + +} diff --git a/API/src/main/java/com/comze_instancelabs/minigamesapi/util/Updater.java b/API/src/main/java/com/comze_instancelabs/minigamesapi/util/UpdaterBukkit.java similarity index 56% rename from API/src/main/java/com/comze_instancelabs/minigamesapi/util/Updater.java rename to API/src/main/java/com/comze_instancelabs/minigamesapi/util/UpdaterBukkit.java index 30b5619d..904dfd80 100644 --- a/API/src/main/java/com/comze_instancelabs/minigamesapi/util/Updater.java +++ b/API/src/main/java/com/comze_instancelabs/minigamesapi/util/UpdaterBukkit.java @@ -1,3 +1,17 @@ +/* + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ package com.comze_instancelabs.minigamesapi.util; /* @@ -17,6 +31,7 @@ import java.net.URL; import java.net.URLConnection; import java.util.Enumeration; +import java.util.logging.Level; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; @@ -26,57 +41,61 @@ import org.json.simple.JSONObject; import org.json.simple.JSONValue; +import com.comze_instancelabs.minigamesapi.MinigamesAPI; + /** * Check dev.bukkit.org to find updates for a given plugin, and download the updates if needed. - * <p/> - * <b>VERY, VERY IMPORTANT</b>: Because there are no standards for adding auto-update toggles in your plugin's config, this system provides NO CHECK WITH YOUR CONFIG to make sure the user has allowed auto-updating. - * <br> - * It is a <b>BUKKIT POLICY</b> that you include a boolean value in your config that prevents the auto-updater from running <b>AT ALL</b>. - * <br> + * <p> + * <b>VERY, VERY IMPORTANT</b>: Because there are no standards for adding auto-update toggles in your plugin's config, this system provides NO CHECK WITH YOUR CONFIG to make sure the user has allowed + * auto-updating. <br> + * It is a <b>BUKKIT POLICY</b> that you include a boolean value in your config that prevents the auto-updater from running <b>AT ALL</b>. <br> * If you fail to include this option in your config, your plugin will be <b>REJECTED</b> when you attempt to submit it to dev.bukkit.org. - * <p/> - * An example of a good configuration option would be something similar to 'auto-update: true' - if this value is set to false you may NOT run the auto-updater. - * <br> + * </p> + * <p> + * An example of a good configuration option would be something similar to 'auto-update: true' - if this value is set to false you may NOT run the auto-updater. <br> * If you are unsure about these rules, please read the plugin submission guidelines: http://goo.gl/8iU5l + * </p> * * @author Gravity * @version 2.0 */ -public class Updater { - - private Plugin plugin; - private UpdateType type; - private String versionName; - private String versionLink; - private String versionType; - private String versionGameVersion; - - private boolean announce; // Whether to announce file downloads - - private URL url; // Connecting to RSS - private File file; // The plugin's file - private Thread thread; // Updater thread - - private int id = -1; // Project's Curse ID - private String apiKey = null; // BukkitDev ServerMods API key - private static final String TITLE_VALUE = "name"; // Gets remote file's title - private static final String LINK_VALUE = "downloadUrl"; // Gets remote file's download link - private static final String TYPE_VALUE = "releaseType"; // Gets remote file's release type - private static final String VERSION_VALUE = "gameVersion"; // Gets remote file's build version - private static final String QUERY = "/servermods/files?projectIds="; // Path to GET - private static final String HOST = "https://api.curseforge.com"; // Slugs will be appended to this to get to the project's RSS feed - +public class UpdaterBukkit +{ + + private Plugin plugin; + private UpdateType type; + private String versionName; + private String versionLink; + private String versionType; + private String versionGameVersion; + + private boolean announce; // Whether to announce file downloads + + private URL url; // Connecting to RSS + private File file; // The plugin's file + private Thread thread; // Updater thread + + private int id = -1; // Project's Curse ID + private String apiKey = null; // BukkitDev ServerMods API key + private static final String TITLE_VALUE = "name"; // Gets remote file's title + private static final String LINK_VALUE = "downloadUrl"; // Gets remote file's download link + private static final String TYPE_VALUE = "releaseType"; // Gets remote file's release type + private static final String VERSION_VALUE = "gameVersion"; // Gets remote file's build version + private static final String QUERY = "/servermods/files?projectIds="; // Path to GET + private static final String HOST = "https://api.curseforge.com"; // Slugs will be appended to this to get to the project's RSS feed + private static final String[] NO_UPDATE_TAG = { "-DEV", "-PRE", "-SNAPSHOT" }; // If the version number contains one of these, don't update. - private static final int BYTE_SIZE = 1024; // Used for downloading files - private YamlConfiguration config; // Config file - private String updateFolder;// The folder that downloads will be placed in - private Updater.UpdateResult result = Updater.UpdateResult.SUCCESS; // Used for determining the outcome of the update process - + private static final int BYTE_SIZE = 1024; // Used for downloading files + private YamlConfiguration config; // Config file + private String updateFolder; // The folder that downloads will be placed in + private UpdaterBukkit.UpdateResult result = UpdaterBukkit.UpdateResult.SUCCESS; // Used for determining the outcome of the update process + /** * Gives the dev the result of the update process. Can be obtained by called getResult(). */ - public enum UpdateResult { + public enum UpdateResult + { /** * The updater found an update, and has readied it to be loaded the next time the server restarts/reloads. */ @@ -114,11 +133,12 @@ public enum UpdateResult { */ UPDATE_AVAILABLE } - + /** * Allows the dev to specify the type of update that will be run. */ - public enum UpdateType { + public enum UpdateType + { /** * Run a version check, and then if the file is out of date, download the newest version. */ @@ -132,225 +152,280 @@ public enum UpdateType { */ NO_DOWNLOAD } - + /** * Initialize the updater * - * @param plugin The plugin that is checking for an update. - * @param id The dev.bukkit.org id of the project - * @param file The file that the plugin is running from, get this by doing this.getFile() from within your main class. - * @param type Specify the type of update this will be. See {@link UpdateType} - * @param announce True if the program should announce the progress of new updates in console + * @param plugin + * The plugin that is checking for an update. + * @param id + * The dev.bukkit.org id of the project + * @param file + * The file that the plugin is running from, get this by doing this.getFile() from within your main class. + * @param type + * Specify the type of update this will be. See {@link UpdateType} + * @param announce + * True if the program should announce the progress of new updates in console */ - public Updater(Plugin plugin, int id, File file, UpdateType type, boolean announce) { + public UpdaterBukkit(final Plugin plugin, final int id, final File file, final UpdateType type, final boolean announce) + { this.plugin = plugin; this.type = type; this.announce = announce; this.file = file; this.id = id; this.updateFolder = plugin.getServer().getUpdateFolder(); - + final File pluginFile = plugin.getDataFolder().getParentFile(); final File updaterFile = new File(pluginFile, "Updater"); final File updaterConfigFile = new File(updaterFile, "config.yml"); - - if (!updaterFile.exists()) { + + if (!updaterFile.exists()) + { updaterFile.mkdir(); } - if (!updaterConfigFile.exists()) { - try { + if (!updaterConfigFile.exists()) + { + try + { updaterConfigFile.createNewFile(); - } catch (final IOException e) { - plugin.getLogger().severe("The updater could not create a configuration in " + updaterFile.getAbsolutePath()); - e.printStackTrace(); + } + catch (final IOException e) + { + plugin.getLogger().log(Level.SEVERE, "The updater could not create a configuration in " + updaterFile.getAbsolutePath(), e); } } this.config = YamlConfiguration.loadConfiguration(updaterConfigFile); - - this.config.options().header("This configuration file affects all plugins using the Updater system (version 2+ - http://forums.bukkit.org/threads/96681/ )" + '\n' - + "If you wish to use your API key, read http://wiki.bukkit.org/ServerMods_API and place it below." + '\n' - + "Some updating systems will not adhere to the disabled value, but these may be turned off in their plugin's configuration."); + + this.config.options() + .header("This configuration file affects all plugins using the Updater system (version 2+ - http://forums.bukkit.org/threads/96681/ )" + '\n' + + "If you wish to use your API key, read http://wiki.bukkit.org/ServerMods_API and place it below." + '\n' + + "Some updating systems will not adhere to the disabled value, but these may be turned off in their plugin's configuration."); this.config.addDefault("api-key", "PUT_API_KEY_HERE"); this.config.addDefault("disable", false); - - if (this.config.get("api-key", null) == null) { + + if (this.config.get("api-key", null) == null) + { this.config.options().copyDefaults(true); - try { + try + { this.config.save(updaterConfigFile); - } catch (final IOException e) { - plugin.getLogger().severe("The updater could not save the configuration in " + updaterFile.getAbsolutePath()); - e.printStackTrace(); + } + catch (final IOException e) + { + plugin.getLogger().log(Level.SEVERE, "The updater could not save the configuration in " + updaterFile.getAbsolutePath(), e); } } - - if (this.config.getBoolean("disable")) { + + if (this.config.getBoolean("disable")) + { this.result = UpdateResult.DISABLED; return; } - + String key = this.config.getString("api-key"); - if (key.equalsIgnoreCase("PUT_API_KEY_HERE") || key.equals("")) { + if (key.equalsIgnoreCase("PUT_API_KEY_HERE") || key.equals("")) + { key = null; } - + this.apiKey = key; - - try { - this.url = new URL(Updater.HOST + Updater.QUERY + id); - } catch (final MalformedURLException e) { - plugin.getLogger().severe("The project ID provided for updating, " + id + " is invalid."); + + try + { + this.url = new URL(UpdaterBukkit.HOST + UpdaterBukkit.QUERY + id); + } + catch (final MalformedURLException e) + { + plugin.getLogger().log(Level.SEVERE, "The project ID provided for updating, " + id + " is invalid.", e); this.result = UpdateResult.FAIL_BADID; - e.printStackTrace(); } - + this.thread = new Thread(new UpdateRunnable()); this.thread.start(); } - + /** * Get the result of the update process. */ - public Updater.UpdateResult getResult() { + public UpdaterBukkit.UpdateResult getResult() + { this.waitForThread(); return this.result; } - + /** * Get the latest version's release type (release, beta, or alpha). */ - public String getLatestType() { + public String getLatestType() + { this.waitForThread(); return this.versionType; } - + /** * Get the latest version's game version. */ - public String getLatestGameVersion() { + public String getLatestGameVersion() + { this.waitForThread(); return this.versionGameVersion; } - + /** * Get the latest version's name. */ - public String getLatestName() { + public String getLatestName() + { this.waitForThread(); return this.versionName; } - + /** * Get the latest version's file link. */ - public String getLatestFileLink() { + public String getLatestFileLink() + { this.waitForThread(); return this.versionLink; } - + /** - * As the result of Updater output depends on the thread's completion, it is necessary to wait for the thread to finish - * before allowing anyone to check the result. + * As the result of Updater output depends on the thread's completion, it is necessary to wait for the thread to finish before allowing anyone to check the result. */ - private void waitForThread() { - if ((this.thread != null) && this.thread.isAlive()) { - try { + private void waitForThread() + { + if ((this.thread != null) && this.thread.isAlive()) + { + try + { this.thread.join(); - } catch (final InterruptedException e) { - e.printStackTrace(); + } + catch (final InterruptedException e) + { + // silently ignore } } } - + /** * Save an update from dev.bukkit.org into the server's update folder. */ - private void saveFile(File folder, String file, String u) { - if (!folder.exists()) { + private void saveFile(final File folder, final String file, final String u) + { + if (!folder.exists()) + { folder.mkdir(); } BufferedInputStream in = null; FileOutputStream fout = null; - try { + try + { // Download the file final URL url = new URL(u); final int fileLength = url.openConnection().getContentLength(); in = new BufferedInputStream(url.openStream()); fout = new FileOutputStream(folder.getAbsolutePath() + "/" + file); - - final byte[] data = new byte[Updater.BYTE_SIZE]; + + final byte[] data = new byte[UpdaterBukkit.BYTE_SIZE]; int count; - if (this.announce) { + if (this.announce) + { this.plugin.getLogger().info("About to download a new update: " + this.versionName); } long downloaded = 0; - while ((count = in.read(data, 0, Updater.BYTE_SIZE)) != -1) { + while ((count = in.read(data, 0, UpdaterBukkit.BYTE_SIZE)) != -1) + { downloaded += count; fout.write(data, 0, count); final int percent = (int) ((downloaded * 100) / fileLength); - if (this.announce && ((percent % 10) == 0)) { + if (this.announce && ((percent % 10) == 0)) + { this.plugin.getLogger().info("Downloading update: " + percent + "% of " + fileLength + " bytes."); } } - //Just a quick check to make sure we didn't leave any files from last time... - for (final File xFile : new File(this.plugin.getDataFolder().getParent(), this.updateFolder).listFiles()) { - if (xFile.getName().endsWith(".zip")) { + // Just a quick check to make sure we didn't leave any files from last time... + for (final File xFile : new File(this.plugin.getDataFolder().getParent(), this.updateFolder).listFiles()) + { + if (xFile.getName().endsWith(".zip")) + { xFile.delete(); } } // Check to see if it's a zip file, if it is, unzip it. final File dFile = new File(folder.getAbsolutePath() + "/" + file); - if (dFile.getName().endsWith(".zip")) { + if (dFile.getName().endsWith(".zip")) + { // Unzip this.unzip(dFile.getCanonicalPath()); } - if (this.announce) { + if (this.announce) + { this.plugin.getLogger().info("Finished updating."); } - } catch (final Exception ex) { + } + catch (final Exception ex) + { this.plugin.getLogger().warning("The auto-updater tried to download a new update, but was unsuccessful."); - this.result = Updater.UpdateResult.FAIL_DOWNLOAD; - } finally { - try { - if (in != null) { + this.result = UpdaterBukkit.UpdateResult.FAIL_DOWNLOAD; + } + finally + { + try + { + if (in != null) + { in.close(); } - if (fout != null) { + if (fout != null) + { fout.close(); } - } catch (final Exception ex) { + } + catch (final Exception ex) + { + // silently ignore } } } - + /** * Part of Zip-File-Extractor, modified by Gravity for use with Bukkit */ - private void unzip(String file) { - try { + private void unzip(final String file) + { + try + { final File fSourceZip = new File(file); final String zipPath = file.substring(0, file.length() - 4); ZipFile zipFile = new ZipFile(fSourceZip); Enumeration<? extends ZipEntry> e = zipFile.entries(); - while (e.hasMoreElements()) { + while (e.hasMoreElements()) + { ZipEntry entry = e.nextElement(); File destinationFilePath = new File(zipPath, entry.getName()); destinationFilePath.getParentFile().mkdirs(); - if (entry.isDirectory()) { + if (entry.isDirectory()) + { continue; - } else { + } + else + { final BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry)); int b; - final byte buffer[] = new byte[Updater.BYTE_SIZE]; + final byte buffer[] = new byte[UpdaterBukkit.BYTE_SIZE]; final FileOutputStream fos = new FileOutputStream(destinationFilePath); - final BufferedOutputStream bos = new BufferedOutputStream(fos, Updater.BYTE_SIZE); - while ((b = bis.read(buffer, 0, Updater.BYTE_SIZE)) != -1) { + final BufferedOutputStream bos = new BufferedOutputStream(fos, UpdaterBukkit.BYTE_SIZE); + while ((b = bis.read(buffer, 0, UpdaterBukkit.BYTE_SIZE)) != -1) + { bos.write(buffer, 0, b); } bos.flush(); bos.close(); bis.close(); final String name = destinationFilePath.getName(); - if (name.endsWith(".jar") && this.pluginFile(name)) { + if (name.endsWith(".jar") && this.pluginFile(name)) + { destinationFilePath.renameTo(new File(this.plugin.getDataFolder().getParent(), this.updateFolder + "/" + name)); } } @@ -360,11 +435,14 @@ private void unzip(String file) { e = null; zipFile.close(); zipFile = null; - + // Move any plugin data folders that were included to the right place, Bukkit won't do this for us. - for (final File dFile : new File(zipPath).listFiles()) { - if (dFile.isDirectory()) { - if (this.pluginFile(dFile.getName())) { + for (final File dFile : new File(zipPath).listFiles()) + { + if (dFile.isDirectory()) + { + if (this.pluginFile(dFile.getName())) + { final File oFile = new File(this.plugin.getDataFolder().getParent(), dFile.getName()); // Get current dir final File[] contents = oFile.listFiles(); // List of existing files in the current dir for (final File cFile : dFile.listFiles()) // Loop through all the files in the new dir @@ -372,15 +450,19 @@ private void unzip(String file) { boolean found = false; for (final File xFile : contents) // Loop through contents to see if it exists { - if (xFile.getName().equals(cFile.getName())) { + if (xFile.getName().equals(cFile.getName())) + { found = true; break; } } - if (!found) { + if (!found) + { // Move the new file into the current dir cFile.renameTo(new File(oFile.getCanonicalFile() + "/" + cFile.getName())); - } else { + } + else + { // This file already exists, so we don't need it anymore. cFile.delete(); } @@ -391,68 +473,85 @@ private void unzip(String file) { } new File(zipPath).delete(); fSourceZip.delete(); - } catch (final IOException ex) { - this.plugin.getLogger().warning("The auto-updater tried to unzip a new update file, but was unsuccessful."); - this.result = Updater.UpdateResult.FAIL_DOWNLOAD; - ex.printStackTrace(); + } + catch (final IOException ex) + { + this.plugin.getLogger().log(Level.WARNING, "The auto-updater tried to unzip a new update file, but was unsuccessful.", ex); + this.result = UpdaterBukkit.UpdateResult.FAIL_DOWNLOAD; } new File(file).delete(); } - + /** * Check if the name of a jar is one of the plugins currently installed, used for extracting the correct files out of a zip. */ - private boolean pluginFile(String name) { - for (final File file : new File("plugins").listFiles()) { - if (file.getName().equals(name)) { + private boolean pluginFile(final String name) + { + for (final File file : new File("plugins").listFiles()) + { + if (file.getName().equals(name)) + { return true; } } return false; } - + /** * Check to see if the program should continue by evaluation whether the plugin is already updated, or shouldn't be updated */ - private boolean versionCheck(String title) { - if (this.type != UpdateType.NO_VERSION_CHECK) { + private boolean versionCheck(final String title) + { + if (this.type != UpdateType.NO_VERSION_CHECK) + { final String version = this.plugin.getDescription().getVersion(); - if (title.split(" v").length == 2) { + if (title.split(" v").length == 2) + { final String remoteVersion = title.split(" v")[1].split(" ")[0]; // Get the newest file's version number int remVer = -1, curVer = 0; - try { + try + { remVer = this.calVer(remoteVersion); curVer = this.calVer(version); - } catch (final NumberFormatException nfe) { + } + catch (final NumberFormatException nfe) + { remVer = -1; } - if (this.hasTag(version) || version.equalsIgnoreCase(remoteVersion) || (curVer >= remVer)) { + if (this.hasTag(version) || version.equalsIgnoreCase(remoteVersion) || (curVer >= remVer)) + { // We already have the latest version, or this build is tagged for no-update - this.result = Updater.UpdateResult.NO_UPDATE; + this.result = UpdaterBukkit.UpdateResult.NO_UPDATE; return false; } - } else { + } + else + { // The file's name did not contain the string 'vVersion' final String authorInfo = this.plugin.getDescription().getAuthors().size() == 0 ? "" : " (" + this.plugin.getDescription().getAuthors().get(0) + ")"; this.plugin.getLogger().warning("The author of this plugin" + authorInfo + " has misconfigured their Auto Update system"); this.plugin.getLogger().warning("Files uploaded to BukkitDev should contain the version number, seperated from the name by a 'v', such as PluginName v1.0"); this.plugin.getLogger().warning("Please notify the author of this error."); - this.result = Updater.UpdateResult.FAIL_NOVERSION; + this.result = UpdaterBukkit.UpdateResult.FAIL_NOVERSION; return false; } } return true; } - + /** * Used to calculate the version string as an Integer */ - private Integer calVer(String s) throws NumberFormatException { - if (s.contains(".")) { + private Integer calVer(final String s) throws NumberFormatException + { + if (s.contains(".")) + { final StringBuilder sb = new StringBuilder(); - for (int i = 0; i < s.length(); i++) { + for (int i = 0; i < s.length(); i++) + { final Character c = s.charAt(i); - if (Character.isLetterOrDigit(c)) { + if (Character.isLetterOrDigit(c)) + { sb.append(c); } } @@ -460,85 +559,107 @@ private Integer calVer(String s) throws NumberFormatException { } return Integer.parseInt(s); } - + /** * Evaluate whether the version number is marked showing that it should not be updated by this program */ - private boolean hasTag(String version) { - for (final String string : Updater.NO_UPDATE_TAG) { - if (version.contains(string)) { + private boolean hasTag(final String version) + { + for (final String string : UpdaterBukkit.NO_UPDATE_TAG) + { + if (version.contains(string)) + { return true; } } return false; } - - private boolean read() { - try { + + private boolean read() + { + try + { final URLConnection conn = this.url.openConnection(); conn.setConnectTimeout(5000); - - if (this.apiKey != null) { + + if (this.apiKey != null) + { conn.addRequestProperty("X-API-Key", this.apiKey); } conn.addRequestProperty("User-Agent", "Updater (by Gravity)"); - + conn.setDoOutput(true); - + final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); final String response = reader.readLine(); - + final JSONArray array = (JSONArray) JSONValue.parse(response); - - if (array.size() == 0) { + + if (array.size() == 0) + { this.plugin.getLogger().warning("The updater could not find any files for the project id " + this.id); this.result = UpdateResult.FAIL_BADID; return false; } - - this.versionName = (String) ((JSONObject) array.get(array.size() - 1)).get(Updater.TITLE_VALUE); - this.versionLink = (String) ((JSONObject) array.get(array.size() - 1)).get(Updater.LINK_VALUE); - this.versionType = (String) ((JSONObject) array.get(array.size() - 1)).get(Updater.TYPE_VALUE); - this.versionGameVersion = (String) ((JSONObject) array.get(array.size() - 1)).get(Updater.VERSION_VALUE); - + + this.versionName = (String) ((JSONObject) array.get(array.size() - 1)).get(UpdaterBukkit.TITLE_VALUE); + this.versionLink = (String) ((JSONObject) array.get(array.size() - 1)).get(UpdaterBukkit.LINK_VALUE); + this.versionType = (String) ((JSONObject) array.get(array.size() - 1)).get(UpdaterBukkit.TYPE_VALUE); + this.versionGameVersion = (String) ((JSONObject) array.get(array.size() - 1)).get(UpdaterBukkit.VERSION_VALUE); + return true; - } catch (final IOException e) { - if (e.getMessage().contains("HTTP response code: 403")) { + } + catch (final IOException e) + { + if (e.getMessage().contains("HTTP response code: 403")) + { this.plugin.getLogger().warning("dev.bukkit.org rejected the API key provided in plugins/Updater/config.yml"); this.plugin.getLogger().warning("Please double-check your configuration to ensure it is correct."); this.result = UpdateResult.FAIL_APIKEY; - } else { + } + else + { this.plugin.getLogger().warning("The updater could not contact dev.bukkit.org for updating."); - this.plugin.getLogger().warning("If you have not recently modified your configuration and this is the first time you are seeing this message, the site may be experiencing temporary downtime."); + this.plugin.getLogger() + .warning("If you have not recently modified your configuration and this is the first time you are seeing this message, the site may be experiencing temporary downtime."); this.result = UpdateResult.FAIL_DBO; } - e.printStackTrace(); + MinigamesAPI.getAPI().getLogger().log(Level.WARNING, "exception", e); return false; } } - - private class UpdateRunnable implements Runnable { - + + private class UpdateRunnable implements Runnable + { + @Override - public void run() { - if (Updater.this.url != null) { + public void run() + { + if (UpdaterBukkit.this.url != null) + { // Obtain the results of the project's file feed - if (Updater.this.read()) { - if (Updater.this.versionCheck(Updater.this.versionName)) { - if ((Updater.this.versionLink != null) && (Updater.this.type != UpdateType.NO_DOWNLOAD)) { - String name = Updater.this.file.getName(); + if (UpdaterBukkit.this.read()) + { + if (UpdaterBukkit.this.versionCheck(UpdaterBukkit.this.versionName)) + { + if ((UpdaterBukkit.this.versionLink != null) && (UpdaterBukkit.this.type != UpdateType.NO_DOWNLOAD)) + { + String name = UpdaterBukkit.this.file.getName(); // If it's a zip file, it shouldn't be downloaded as the plugin's name - if (Updater.this.versionLink.endsWith(".zip")) { - final String[] split = Updater.this.versionLink.split("/"); + if (UpdaterBukkit.this.versionLink.endsWith(".zip")) + { + final String[] split = UpdaterBukkit.this.versionLink.split("/"); name = split[split.length - 1]; } - Updater.this.saveFile(new File(Updater.this.plugin.getDataFolder().getParent(), Updater.this.updateFolder), name, Updater.this.versionLink); - } else { - Updater.this.result = UpdateResult.UPDATE_AVAILABLE; + UpdaterBukkit.this.saveFile(new File(UpdaterBukkit.this.plugin.getDataFolder().getParent(), UpdaterBukkit.this.updateFolder), name, UpdaterBukkit.this.versionLink); + } + else + { + UpdaterBukkit.this.result = UpdateResult.UPDATE_AVAILABLE; } } } } } } -} \ No newline at end of file +} diff --git a/API/src/main/java/com/comze_instancelabs/minigamesapi/util/UpdaterNexus.java b/API/src/main/java/com/comze_instancelabs/minigamesapi/util/UpdaterNexus.java new file mode 100644 index 00000000..f39d6f83 --- /dev/null +++ b/API/src/main/java/com/comze_instancelabs/minigamesapi/util/UpdaterNexus.java @@ -0,0 +1,135 @@ +/* + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +package com.comze_instancelabs.minigamesapi.util; + +import java.io.BufferedReader; +import java.io.File; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.URL; +import java.net.URLConnection; +import java.util.logging.Level; + +import org.bukkit.plugin.Plugin; +import org.json.simple.JSONObject; +import org.json.simple.JSONValue; + +import com.comze_instancelabs.minigamesapi.MinigamesAPI; + +/** + * Checks for updates by querying a nexus updater. + * + * @author mepeisen + */ +public class UpdaterNexus implements Runnable +{ + + /** the plugin to be checked. */ + private final Plugin plugin; + + /** the file to be checked. */ + private final File file; + + /** the asynchronous update thread. */ + private final Thread thread; + + /** the url to be queried for updates. */ + private final String queryUrl; + + /** the queried group id. */ + private final String groupId; + + /** + * Constructor + * + * @param plugin + * the plugin that will be checked. + * @param file + * The file that the plugin is running from, get this by doing this.getFile() from within your main class. + */ + public UpdaterNexus(final Plugin plugin, final File file) + { + this(plugin, file, "http://nexus.xworlds.eu/minigames/query", "com.github.MCE-Plugins"); //$NON-NLS-1$//$NON-NLS-2$ + } + + /** + * Constructor + * + * @param plugin + * the plugin that will be checked. + * @param file + * The file that the plugin is running from, get this by doing this.getFile() from within your main class. + * @param queryUrl + * the url to be queried + * @param groupId + * the queried group id + */ + private UpdaterNexus(final Plugin plugin, final File file, final String queryUrl, String groupId) + { + this.plugin = plugin; + this.file = file; + this.queryUrl = queryUrl; + this.groupId = groupId; + + this.thread = new Thread(this); + this.thread.start(); + } + + @Override + public void run() + { + final String version = this.plugin.getDescription().getVersion().split("-")[0]; //$NON-NLS-1$ + + try + { + final URL url = new URL( + this.queryUrl + "?group=" + this.groupId + "&artifact=" + this.plugin.getName() + "&version=" + version + "&server=" + MinigamesAPI.SERVER_VERSION.mavenVersionString()); //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$//$NON-NLS-4$ + final URLConnection conn = url.openConnection(); + conn.setConnectTimeout(5000); + + final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); + final String response = reader.readLine(); + + final JSONObject array = (JSONObject) JSONValue.parse(response); + if (array.size() == 0) + { + this.plugin.getLogger().log(Level.WARNING, "Invalid response while checking plugin version"); //$NON-NLS-1$ + } + if ((Boolean)array.get("success")) //$NON-NLS-1$ + { + final JSONObject data = (JSONObject) array.get("data"); //$NON-NLS-1$ + if (! ((Boolean) data.get("upToDate"))) //$NON-NLS-1$ + { + final JSONObject vobj = (JSONObject) data.get("version"); //$NON-NLS-1$ + final String newversion = (String) vobj.get("version"); //$NON-NLS-1$ + final String downloadurl = (String) vobj.get("url"); //$NON-NLS-1$ + + this.plugin.getLogger().log(Level.WARNING, "We found a new version #" + newversion + ". You can download the new version at " + downloadurl); //$NON-NLS-1$ //$NON-NLS-2$ + // TODO Auto-Updating + } + } + else + { + this.plugin.getLogger().log(Level.WARNING, "Error while checking plugin version " + array.get("msg")); //$NON-NLS-1$ //$NON-NLS-2$ + } + } + catch (final IOException e) + { + this.plugin.getLogger().log(Level.WARNING, "Unable to check plugin version", e); //$NON-NLS-1$ + } + } + +} diff --git a/API/src/main/java/com/comze_instancelabs/minigamesapi/util/Util.java b/API/src/main/java/com/comze_instancelabs/minigamesapi/util/Util.java index 5a107d67..b6aa6fdd 100644 --- a/API/src/main/java/com/comze_instancelabs/minigamesapi/util/Util.java +++ b/API/src/main/java/com/comze_instancelabs/minigamesapi/util/Util.java @@ -1,34 +1,49 @@ +/* + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ package com.comze_instancelabs.minigamesapi.util; -import java.io.EOFException; import java.io.File; -import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; -import java.io.PrintWriter; +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; import java.lang.reflect.Method; -import java.nio.channels.ClosedChannelException; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; import java.util.Map; import java.util.Random; +import java.util.function.Predicate; +import java.util.logging.Level; import org.bukkit.Bukkit; import org.bukkit.ChatColor; +import org.bukkit.Chunk; import org.bukkit.Color; -import org.bukkit.Effect; import org.bukkit.FireworkEffect; import org.bukkit.FireworkEffect.Type; +import org.bukkit.GameMode; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.OfflinePlayer; +import org.bukkit.Particle; import org.bukkit.World; import org.bukkit.block.Block; import org.bukkit.block.BlockState; -import org.bukkit.block.Chest; import org.bukkit.block.Sign; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.enchantments.Enchantment; @@ -52,946 +67,1269 @@ import org.bukkit.scoreboard.Score; import org.bukkit.scoreboard.Scoreboard; import org.bukkit.util.Vector; -import org.bukkit.util.io.BukkitObjectInputStream; import org.bukkit.util.io.BukkitObjectOutputStream; import com.comze_instancelabs.minigamesapi.Arena; +import com.comze_instancelabs.minigamesapi.ArenaConfigStrings; import com.comze_instancelabs.minigamesapi.ArenaLogger; import com.comze_instancelabs.minigamesapi.ArenaSetup; import com.comze_instancelabs.minigamesapi.ArenaState; +import com.comze_instancelabs.minigamesapi.MinecraftVersionsType; import com.comze_instancelabs.minigamesapi.MinigamesAPI; import com.comze_instancelabs.minigamesapi.PluginInstance; import com.comze_instancelabs.minigamesapi.config.ArenasConfig; -import com.comze_instancelabs.minigamesapi.config.MessagesConfig; - -public class Util { - - public static void clearInv(Player p) { - if (p != null) { - ArenaLogger.debug("Clearing inventory of " + p.getName()); - p.getInventory().clear(); - p.updateInventory(); - p.getInventory().setHelmet(null); - p.getInventory().setChestplate(null); - p.getInventory().setLeggings(null); - p.getInventory().setBoots(null); - p.updateInventory(); - } - } - - public static void teleportPlayerFixed(final Player p, final Location l) { - ArenaLogger.debug("Teleporting " + p.getName()); - if (p.isInsideVehicle()) { - Entity ent = p.getVehicle(); - p.leaveVehicle(); - ent.eject(); - } - if (l != null) { - if (l.getWorld() == null) { - return; - } - p.teleport(l, TeleportCause.PLUGIN); - p.setFallDistance(-1F); - p.setVelocity(new Vector(0D, 0D, 0D)); - l.getWorld().refreshChunk(l.getChunk().getX(), l.getChunk().getZ()); - } else { - System.out.println("Couldn't teleport Player " + p.getName() + ", the location was not valid. Probably forgot to set a spawn/lobby?"); - } - p.setFireTicks(0); - p.setHealth(20D); - } - - public static void teleportAllPlayers(ArrayList<String> players, final Location l) { - Long delay = 1L; - for (String pl : players) { - if (!Validator.isPlayerOnline(pl)) { - continue; - } - final Player p = Bukkit.getPlayer(pl); - Bukkit.getScheduler().runTaskLater(MinigamesAPI.getAPI(), new Runnable() { - public void run() { - Util.teleportPlayerFixed(p, l); - } - }, delay); - delay++; - } - } - - public static HashMap<String, Location> teleportAllPlayers(ArrayList<String> players, ArrayList<Location> locs) { - HashMap<String, Location> pspawnloc = new HashMap<String, Location>(); - int currentid = 0; - int locslength = locs.size(); - for (String p_ : players) { - Player p = Bukkit.getPlayer(p_); - Util.teleportPlayerFixed(p, locs.get(currentid)); - pspawnloc.put(p_, locs.get(currentid)); - currentid++; - if (currentid > locslength - 1) { - currentid = 0; - } - } - return pspawnloc; - } - - public static Location getComponentForArena(JavaPlugin plugin, String arenaname, String component, String count) { - if (Validator.isArenaValid(plugin, arenaname)) { - String base = "arenas." + arenaname + "." + component + count; - PluginInstance pli = MinigamesAPI.getAPI().getPluginInstance(plugin); - if (!pli.getArenasConfig().getConfig().isSet(base + ".world") || Bukkit.getWorld(pli.getArenasConfig().getConfig().getString(base + ".world")) == null) { - return null; - } - return new Location(Bukkit.getWorld(pli.getArenasConfig().getConfig().getString(base + ".world")), pli.getArenasConfig().getConfig().getDouble(base + ".location.x"), pli.getArenasConfig().getConfig().getDouble(base + ".location.y"), pli.getArenasConfig().getConfig().getDouble(base + ".location.z"), (float) pli.getArenasConfig().getConfig().getDouble(base + ".location.yaw"), (float) pli.getArenasConfig().getConfig().getDouble(base + ".location.pitch")); - } - return null; - } - - public static Location getComponentForArena(JavaPlugin plugin, String arenaname, String component) { - if (Validator.isArenaValid(plugin, arenaname)) { - String base = "arenas." + arenaname + "." + component; - PluginInstance pli = MinigamesAPI.getAPI().getPluginInstance(plugin); - if (!pli.getArenasConfig().getConfig().isSet(base + ".world") || Bukkit.getWorld(pli.getArenasConfig().getConfig().getString(base + ".world")) == null) { - return null; - } - return new Location(Bukkit.getWorld(pli.getArenasConfig().getConfig().getString(base + ".world")), pli.getArenasConfig().getConfig().getDouble(base + ".location.x"), pli.getArenasConfig().getConfig().getDouble(base + ".location.y"), pli.getArenasConfig().getConfig().getDouble(base + ".location.z"), (float) pli.getArenasConfig().getConfig().getDouble(base + ".location.yaw"), (float) pli.getArenasConfig().getConfig().getDouble(base + ".location.pitch")); - } - return null; - } - - public static Location getComponentForArenaRaw(JavaPlugin plugin, String arenaname, String component) { - String base = "arenas." + arenaname + "." + component; - PluginInstance pli = MinigamesAPI.getAPI().getPluginInstance(plugin); - if (pli.getArenasConfig().getConfig().isSet(base)) { - return new Location(Bukkit.getWorld(pli.getArenasConfig().getConfig().getString(base + ".world")), pli.getArenasConfig().getConfig().getDouble(base + ".location.x"), pli.getArenasConfig().getConfig().getDouble(base + ".location.y"), pli.getArenasConfig().getConfig().getDouble(base + ".location.z"), (float) pli.getArenasConfig().getConfig().getDouble(base + ".location.yaw"), (float) pli.getArenasConfig().getConfig().getDouble(base + ".location.pitch")); - } - return null; - } - - public static boolean isComponentForArenaValid(JavaPlugin plugin, String arenaname, String component) { - if (Validator.isArenaValid(plugin, arenaname)) { - return isComponentForArenaValidRaw(plugin, arenaname, component); - } - return false; - } - - public static boolean isComponentForArenaValidRaw(JavaPlugin plugin, String arenaname, String component) { - String base = "arenas." + arenaname + "." + component; - return MinigamesAPI.getAPI().getPluginInstance(plugin).getArenasConfig().getConfig().isSet(base); - } - - public static void saveComponentForArena(JavaPlugin plugin, String arenaname, String component, Location comploc) { - String base = "arenas." + arenaname + "." + component; - ArenasConfig config = MinigamesAPI.getAPI().getPluginInstance(plugin).getArenasConfig(); - config.getConfig().set(base + ".world", comploc.getWorld().getName()); - config.getConfig().set(base + ".location.x", comploc.getX()); - config.getConfig().set(base + ".location.y", comploc.getY()); - config.getConfig().set(base + ".location.z", comploc.getZ()); - config.getConfig().set(base + ".location.yaw", comploc.getYaw()); - config.getConfig().set(base + ".location.pitch", comploc.getPitch()); - config.saveConfig(); - } - - public static void saveMainLobby(JavaPlugin plugin, Location comploc) { - String base = "mainlobby"; - ArenasConfig config = MinigamesAPI.getAPI().getPluginInstance(plugin).getArenasConfig(); - config.getConfig().set(base + ".world", comploc.getWorld().getName()); - config.getConfig().set(base + ".location.x", comploc.getX()); - config.getConfig().set(base + ".location.y", comploc.getY()); - config.getConfig().set(base + ".location.z", comploc.getZ()); - config.getConfig().set(base + ".location.yaw", comploc.getYaw()); - config.getConfig().set(base + ".location.pitch", comploc.getPitch()); - config.saveConfig(); - } - - public static Location getMainLobby(JavaPlugin plugin) { - FileConfiguration config = MinigamesAPI.getAPI().getPluginInstance(plugin).getArenasConfig().getConfig(); - if (!config.isSet("mainlobby")) { - Bukkit.getConsoleSender().sendMessage(ChatColor.RED + "You forgot to set the mainlobby!"); - } - return new Location(plugin.getServer().getWorld(config.getString("mainlobby.world")), config.getDouble("mainlobby.location.x"), config.getDouble("mainlobby.location.y"), config.getDouble("mainlobby.location.z"), (float) config.getDouble("mainlobby.location.yaw"), (float) config.getDouble("mainlobby.location.pitch")); - } - - public static ArrayList<Location> getAllSpawns(JavaPlugin plugin, String arena) { - FileConfiguration config = MinigamesAPI.getAPI().getPluginInstance(plugin).getArenasConfig().getConfig(); - ArrayList<Location> ret = new ArrayList<Location>(); - if (config.isSet("arenas." + arena + ".spawns")) { - for (String spawn : config.getConfigurationSection("arenas." + arena + ".spawns.").getKeys(false)) { - ret.add(getComponentForArena(plugin, arena, "spawns." + spawn)); - } - } - return ret; - } - - public static void saveArenaToFile(JavaPlugin plugin, String arena) { - File f = new File(plugin.getDataFolder() + "/" + arena); - Cuboid c = new Cuboid(Util.getComponentForArena(plugin, arena, "bounds.low"), Util.getComponentForArena(plugin, arena, "bounds.high")); - Location start = c.getLowLoc(); - Location end = c.getHighLoc(); - - int width = end.getBlockX() - start.getBlockX(); - int length = end.getBlockZ() - start.getBlockZ(); - int height = end.getBlockY() - start.getBlockY(); - - MinigamesAPI.getAPI().getLogger().info("BOUNDS: " + Integer.toString(width) + " " + Integer.toString(height) + " " + Integer.toString(length)); - MinigamesAPI.getAPI().getLogger().info("BLOCKS TO SAVE: " + Integer.toString(width * height * length)); - - FileOutputStream fos; - ObjectOutputStream oos = null; - try { - fos = new FileOutputStream(f); - oos = new BukkitObjectOutputStream(fos); - } catch (IOException e) { - e.printStackTrace(); - } - - for (int i = 0; i <= width; i++) { - for (int j = 0; j <= height; j++) { - for (int k = 0; k <= length; k++) { - Block change = c.getWorld().getBlockAt(start.getBlockX() + i, start.getBlockY() + j, start.getBlockZ() + k); - - ArenaBlock bl = new ArenaBlock(change, change.getType().equals(Material.CHEST)); - - try { - oos.writeObject(bl); - } catch (IOException e) { - System.out.println(e.getMessage()); - } - } - } - } - - try { - oos.close(); - } catch (IOException e) { - e.printStackTrace(); - } - - MinigamesAPI.getAPI().getLogger().info("saved"); - } - - public static void loadArenaFromFileSYNC(final JavaPlugin plugin, final Arena arena) { - int failcount = 0; - final ArrayList<ArenaBlock> failedblocks = new ArrayList<ArenaBlock>(); - - File f = new File(plugin.getDataFolder() + "/" + arena.getInternalName()); - if (!f.exists()) { - plugin.getLogger().warning("Could not find arena file for " + arena.getInternalName()); - arena.setArenaState(ArenaState.JOIN); - Bukkit.getScheduler().runTask(plugin, new Runnable() { - public void run() { - Util.updateSign(plugin, arena); - } - }); - return; - } - FileInputStream fis = null; - BukkitObjectInputStream ois = null; - try { - fis = new FileInputStream(f); - ois = new BukkitObjectInputStream(fis); - } catch (IOException e) { - e.printStackTrace(); - } - - try { - while (true) { - Object b = null; - try { - b = ois.readObject(); - } catch (EOFException e) { - MinigamesAPI.getAPI().getLogger().info("Finished restoring map for " + arena.getInternalName() + " with old reset method."); - - arena.setArenaState(ArenaState.JOIN); - Bukkit.getScheduler().runTask(plugin, new Runnable() { - public void run() { - Util.updateSign(plugin, arena); - } - }); - } catch (ClosedChannelException e) { - System.out.println("Something is wrong with your arena file and the reset might not be successful. Also, you're using an outdated reset method."); - } catch (Exception e) { - e.printStackTrace(); - arena.setArenaState(ArenaState.JOIN); - Bukkit.getScheduler().runTask(plugin, new Runnable() { - public void run() { - Util.updateSign(plugin, arena); - } - }); - } - - if (b != null) { - ArenaBlock ablock = (ArenaBlock) b; - try { - Block b_ = ablock.getBlock().getWorld().getBlockAt(ablock.getBlock().getLocation()); - if (!b_.getType().toString().equalsIgnoreCase(ablock.getMaterial().toString())) { - b_.setType(ablock.getMaterial()); - b_.setData(ablock.getData()); - } - if (b_.getType() == Material.CHEST) { - ((Chest) b_.getState()).getInventory().setContents(ablock.getInventory()); - ((Chest) b_.getState()).update(); - } - } catch (IllegalStateException e) { - failcount += 1; - failedblocks.add(ablock); - } - } else { - break; - } - } - - } catch (Exception e) { - e.printStackTrace(); - } - - try { - ois.close(); - } catch (IOException e) { - e.printStackTrace(); - } - - Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(MinigamesAPI.getAPI(), new Runnable() { - public void run() { - for (ArenaBlock ablock : failedblocks) { - Block b_ = ablock.getBlock().getWorld().getBlockAt(ablock.getBlock().getLocation()); - if (!b_.getType().toString().equalsIgnoreCase(ablock.getMaterial().toString())) { - b_.setType(ablock.getMaterial()); - b_.setData(ablock.getData()); - } - if (b_.getType() == Material.CHEST) { - ((Chest) b_.getState()).getInventory().setContents(ablock.getInventory()); - ((Chest) b_.getState()).update(); - } - } - } - }, 40L); - MinigamesAPI.getAPI().getLogger().info("Successfully finished!"); - - return; - } - - public static Sign getSignFromArena(JavaPlugin plugin, String arena) { - PluginInstance pli = MinigamesAPI.getAPI().getPluginInstance(plugin); - if (!pli.getArenasConfig().getConfig().isSet("arenas." + arena + ".sign.world")) { - return null; - } - Location b_ = new Location(Bukkit.getServer().getWorld(pli.getArenasConfig().getConfig().getString("arenas." + arena + ".sign.world")), pli.getArenasConfig().getConfig().getInt("arenas." + arena + ".sign.loc.x"), pli.getArenasConfig().getConfig().getInt("arenas." + arena + ".sign.loc.y"), pli.getArenasConfig().getConfig().getInt("arenas." + arena + ".sign.loc.z")); - if (b_ != null) { - if (b_.getWorld() != null) { - if (b_.getBlock().getState() != null) { - BlockState bs = b_.getBlock().getState(); - Sign s_ = null; - if (bs instanceof Sign) { - s_ = (Sign) bs; - } - return s_; - } - } - } - return null; - } - - public static Location getSignLocationFromArena(JavaPlugin plugin, String arena) { - Sign s = getSignFromArena(plugin, arena); - if (s != null) { - return s.getBlock().getLocation(); - } else { - return null; - } - } - - public static Arena getArenaBySignLocation(JavaPlugin plugin, Location sign) { - for (Arena arena : MinigamesAPI.getAPI().getPluginInstance(plugin).getArenas()) { - if (sign != null && arena.getArena().getSignLocation() != null) { - if (sign.getWorld().getName().equalsIgnoreCase(arena.getSignLocation().getWorld().getName())) { - if (sign.distance(arena.getArena().getSignLocation()) < 1) { - return arena; - } - } - } - } - return null; - } - - public static void updateSign(JavaPlugin plugin, Arena arena) { - Sign s = getSignFromArena(plugin, arena.getInternalName()); - if (s != null) { - ArenaLogger.debug("Updating sign for arena " + arena.getInternalName() + " in " + plugin.getName()); - int count = arena.getAllPlayers().size(); - int maxcount = arena.getMaxPlayers(); - PluginInstance pli = MinigamesAPI.getAPI().getPluginInstance(plugin); - String state = arena.getArenaState().toString().toLowerCase(); - if (pli.cached_sign_states.containsKey(state)) { - s.setLine(0, pli.cached_sign_states.get(state).get(0).replaceAll("&", "§").replace("<count>", Integer.toString(count)).replace("<maxcount>", Integer.toString(maxcount)).replace("<arena>", arena.getDisplayName()).replace("[]", new String(MessagesConfig.squares_mid)).replace("[1]", new String(MessagesConfig.squares_full).replace("[2]", new String(MessagesConfig.squares_medium)).replace("[3]", new String(MessagesConfig.squares_light)))); - s.setLine(1, pli.cached_sign_states.get(state).get(1).replaceAll("&", "§").replace("<count>", Integer.toString(count)).replace("<maxcount>", Integer.toString(maxcount)).replace("<arena>", arena.getDisplayName()).replace("[]", new String(MessagesConfig.squares_mid)).replace("[1]", new String(MessagesConfig.squares_full).replace("[2]", new String(MessagesConfig.squares_medium)).replace("[3]", new String(MessagesConfig.squares_light)))); - s.setLine(2, pli.cached_sign_states.get(state).get(2).replaceAll("&", "§").replace("<count>", Integer.toString(count)).replace("<maxcount>", Integer.toString(maxcount)).replace("<arena>", arena.getDisplayName()).replace("[]", new String(MessagesConfig.squares_mid)).replace("[1]", new String(MessagesConfig.squares_full).replace("[2]", new String(MessagesConfig.squares_medium)).replace("[3]", new String(MessagesConfig.squares_light)))); - s.setLine(3, pli.cached_sign_states.get(state).get(3).replaceAll("&", "§").replace("<count>", Integer.toString(count)).replace("<maxcount>", Integer.toString(maxcount)).replace("<arena>", arena.getDisplayName()).replace("[]", new String(MessagesConfig.squares_mid)).replace("[1]", new String(MessagesConfig.squares_full).replace("[2]", new String(MessagesConfig.squares_medium)).replace("[3]", new String(MessagesConfig.squares_light)))); - } else { - s.setLine(0, pli.getMessagesConfig().getConfig().getString("signs." + state + ".0").replaceAll("&", "§").replace("<count>", Integer.toString(count)).replace("<maxcount>", Integer.toString(maxcount)).replace("<arena>", arena.getDisplayName()).replace("[]", new String(MessagesConfig.squares_mid)).replace("[1]", new String(MessagesConfig.squares_full).replace("[2]", new String(MessagesConfig.squares_medium)).replace("[3]", new String(MessagesConfig.squares_light)))); - s.setLine(1, pli.getMessagesConfig().getConfig().getString("signs." + state + ".1").replaceAll("&", "§").replace("<count>", Integer.toString(count)).replace("<maxcount>", Integer.toString(maxcount)).replace("<arena>", arena.getDisplayName()).replace("[]", new String(MessagesConfig.squares_mid)).replace("[1]", new String(MessagesConfig.squares_full).replace("[2]", new String(MessagesConfig.squares_medium)).replace("[3]", new String(MessagesConfig.squares_light)))); - s.setLine(2, pli.getMessagesConfig().getConfig().getString("signs." + state + ".2").replaceAll("&", "§").replace("<count>", Integer.toString(count)).replace("<maxcount>", Integer.toString(maxcount)).replace("<arena>", arena.getDisplayName()).replace("[]", new String(MessagesConfig.squares_mid)).replace("[1]", new String(MessagesConfig.squares_full).replace("[2]", new String(MessagesConfig.squares_medium)).replace("[3]", new String(MessagesConfig.squares_light)))); - s.setLine(3, pli.getMessagesConfig().getConfig().getString("signs." + state + ".3").replaceAll("&", "§").replace("<count>", Integer.toString(count)).replace("<maxcount>", Integer.toString(maxcount)).replace("<arena>", arena.getDisplayName()).replace("[]", new String(MessagesConfig.squares_mid)).replace("[1]", new String(MessagesConfig.squares_full).replace("[2]", new String(MessagesConfig.squares_medium)).replace("[3]", new String(MessagesConfig.squares_light)))); - } - s.getBlock().getChunk().load(); - s.update(); - if (pli.color_background_wool_of_signs) { - org.bukkit.material.Sign s_ = (org.bukkit.material.Sign) s.getBlock().getState().getData(); - Block attachedBlock = s.getBlock().getRelative(s_.getAttachedFace()); - byte data = (byte) 5; - if (arena.getArenaState() == ArenaState.INGAME) { - data = (byte) 14; - } else if (arena.getArenaState() == ArenaState.RESTARTING) { - data = (byte) 4; - } - attachedBlock.setData(data); - } - } - try { - if (plugin.isEnabled()) { - BungeeUtil.sendSignUpdateRequest(plugin, plugin.getName(), arena); - } - } catch (Exception e) { - System.out.println("Failed sending bungee sign update: " + e.getMessage()); - } - } - - public static void updateSign(JavaPlugin plugin, Arena arena, SignChangeEvent event) { - int count = arena.getAllPlayers().size(); - int maxcount = arena.getMaxPlayers(); - PluginInstance pli = MinigamesAPI.getAPI().getPluginInstance(plugin); - String arenastate = arena.getArenaState().toString().toLowerCase(); - event.setLine(0, pli.getMessagesConfig().getConfig().getString("signs." + arenastate + ".0").replaceAll("&", "§").replace("<count>", Integer.toString(count)).replace("<maxcount>", Integer.toString(maxcount)).replace("<arena>", arena.getDisplayName()).replace("[]", new String(MessagesConfig.squares_mid)).replace("[1]", new String(MessagesConfig.squares_full).replace("[2]", new String(MessagesConfig.squares_medium)).replace("[3]", new String(MessagesConfig.squares_light)))); - event.setLine(1, pli.getMessagesConfig().getConfig().getString("signs." + arenastate + ".1").replaceAll("&", "§").replace("<count>", Integer.toString(count)).replace("<maxcount>", Integer.toString(maxcount)).replace("<arena>", arena.getDisplayName()).replace("[]", new String(MessagesConfig.squares_mid)).replace("[1]", new String(MessagesConfig.squares_full).replace("[2]", new String(MessagesConfig.squares_medium)).replace("[3]", new String(MessagesConfig.squares_light)))); - event.setLine(2, pli.getMessagesConfig().getConfig().getString("signs." + arenastate + ".2").replaceAll("&", "§").replace("<count>", Integer.toString(count)).replace("<maxcount>", Integer.toString(maxcount)).replace("<arena>", arena.getDisplayName()).replace("[]", new String(MessagesConfig.squares_mid)).replace("[1]", new String(MessagesConfig.squares_full).replace("[2]", new String(MessagesConfig.squares_medium)).replace("[3]", new String(MessagesConfig.squares_light)))); - event.setLine(3, pli.getMessagesConfig().getConfig().getString("signs." + arenastate + ".3").replaceAll("&", "§").replace("<count>", Integer.toString(count)).replace("<maxcount>", Integer.toString(maxcount)).replace("<arena>", arena.getDisplayName()).replace("[]", new String(MessagesConfig.squares_mid)).replace("[1]", new String(MessagesConfig.squares_full).replace("[2]", new String(MessagesConfig.squares_medium)).replace("[3]", new String(MessagesConfig.squares_light)))); - if (pli.color_background_wool_of_signs) { - org.bukkit.material.Sign s_ = (org.bukkit.material.Sign) event.getBlock().getState().getData(); - Block attachedBlock = event.getBlock().getRelative(s_.getAttachedFace()); - byte data = (byte) 5; - if (arena.getArenaState() == ArenaState.INGAME) { - data = (byte) 14; - } else if (arena.getArenaState() == ArenaState.RESTARTING) { - data = (byte) 4; - } - attachedBlock.setData(data); - } - } - - // used for random and leave sign - public static void updateSign(JavaPlugin plugin, SignChangeEvent event, String arenastate) { - PluginInstance pli = MinigamesAPI.getAPI().getPluginInstance(plugin); - event.setLine(0, pli.getMessagesConfig().getConfig().getString("signs." + arenastate + ".0").replaceAll("&", "§").replace("[]", new String(MessagesConfig.squares_mid)).replace("[1]", new String(MessagesConfig.squares_full).replace("[2]", new String(MessagesConfig.squares_medium)).replace("[3]", new String(MessagesConfig.squares_light)))); - event.setLine(1, pli.getMessagesConfig().getConfig().getString("signs." + arenastate + ".1").replaceAll("&", "§").replace("[]", new String(MessagesConfig.squares_mid)).replace("[1]", new String(MessagesConfig.squares_full).replace("[2]", new String(MessagesConfig.squares_medium)).replace("[3]", new String(MessagesConfig.squares_light)))); - event.setLine(2, pli.getMessagesConfig().getConfig().getString("signs." + arenastate + ".2").replaceAll("&", "§").replace("[]", new String(MessagesConfig.squares_mid)).replace("[1]", new String(MessagesConfig.squares_full).replace("[2]", new String(MessagesConfig.squares_medium)).replace("[3]", new String(MessagesConfig.squares_light)))); - event.setLine(3, pli.getMessagesConfig().getConfig().getString("signs." + arenastate + ".3").replaceAll("&", "§").replace("[]", new String(MessagesConfig.squares_mid)).replace("[1]", new String(MessagesConfig.squares_full).replace("[2]", new String(MessagesConfig.squares_medium)).replace("[3]", new String(MessagesConfig.squares_light)))); - } - - public static ArrayList<Arena> loadArenas(JavaPlugin plugin, ArenasConfig cf) { - ArrayList<Arena> ret = new ArrayList<Arena>(); - FileConfiguration config = cf.getConfig(); - if (!config.isSet("arenas")) { - return ret; - } - for (String arena : config.getConfigurationSection("arenas.").getKeys(false)) { - if (Validator.isArenaValid(plugin, arena, cf.getConfig())) { - ret.add(initArena(plugin, arena)); - } - } - return ret; - } - - public static Arena initArena(JavaPlugin plugin, String arena) { - Arena a = new Arena(plugin, arena); - ArenaSetup s = MinigamesAPI.getAPI().getPluginInstance(plugin).arenaSetup; - a.init(getSignLocationFromArena(plugin, arena), getAllSpawns(plugin, arena), getMainLobby(plugin), getComponentForArena(plugin, arena, "lobby"), s.getPlayerCount(plugin, arena, true), s.getPlayerCount(plugin, arena, false), s.getArenaVIP(plugin, arena)); - return a; - } - - public static boolean isNumeric(String s) { - return s.matches("[-+]?\\d*\\.?\\d+"); - } - - // example items: 351:6#ALL_DAMAGE:2#KNOCKBACK:2*1=NAME:LORE;267*1;3*64;3*64 - public static ArrayList<ItemStack> parseItems(String rawitems) { - ArrayList<ItemStack> ret = new ArrayList<ItemStack>(); - - try { - String[] a = rawitems.split(";"); - - for (String rawitem : a) { - // crackshot support - if (rawitem.startsWith("crackshot:")) { - String[] guntype = rawitem.split(":"); - if (guntype.length > 1) { - if (guntype[1].length() > 1) { - ItemStack gun = new ItemStack(Material.WOOD_HOE); - ItemMeta gunmeta = gun.getItemMeta(); - gunmeta.setDisplayName(rawitem); - gun.setItemMeta(gunmeta); - ret.add(gun); - } - } - continue; - } - - // Potioneffects support - if (rawitem.startsWith("potioneffect:")) { - String[] potioneffecttype = rawitem.split(":"); - if (potioneffecttype.length > 1) { - String str = potioneffecttype[1]; - if (potioneffecttype.length > 2) { - str += ":" + potioneffecttype[2]; - } - if (str.length() > 1) { - if (!str.contains(":")) { - // duration - rawitem += ":99999"; - } - if (!str.contains("#")) { - // level - rawitem += "#1"; - } - ItemStack gun = new ItemStack(Material.WOOD_HOE); - ItemMeta gunmeta = gun.getItemMeta(); - gunmeta.setDisplayName(rawitem); - gun.setItemMeta(gunmeta); - ret.add(gun); - } - } - continue; - } - - int nameindex = rawitem.indexOf("="); - String[] c = rawitem.split("\\*"); - int optional_armor_color_index = -1; - String itemid = c[0]; - String itemdata = "0"; - String[] enchantments_ = itemid.split("#"); - String[] enchantments = new String[enchantments_.length - 1]; - if (enchantments_.length > 1) { - for (int i = 1; i < enchantments_.length; i++) { - enchantments[i - 1] = enchantments_[i]; - } - } - itemid = enchantments_[0]; - String[] d = itemid.split(":"); - if (d.length > 1) { - itemid = d[0]; - itemdata = d[1]; - } - String itemamount = "1"; - if (c.length > 1) { - itemamount = c[1]; - optional_armor_color_index = c[1].indexOf("#"); - if (optional_armor_color_index > 0) { - itemamount = c[1].substring(0, optional_armor_color_index); - } - } - if (nameindex > -1) { - itemamount = c[1].substring(0, c[1].indexOf("=")); - } - int itemid_int = isNumeric(itemid) ? Integer.parseInt(itemid) : 0; - if (itemid_int < 1) { - System.out.println("Invalid item id: " + itemid); - continue; - } - int itemamount_int = isNumeric(itemamount) ? Integer.parseInt(itemamount) : 1; - int itemdata_int = isNumeric(itemdata) ? Integer.parseInt(itemdata) : 0; - ItemStack nitem = new ItemStack(itemid_int, itemamount_int, (short) itemdata_int); - ItemMeta m = nitem.getItemMeta(); - if (nitem.getType() != Material.ENCHANTED_BOOK) { - for (String enchant : enchantments) { - String[] e = enchant.split(":"); - String ench = e[0]; - String lv = "1"; - if (e.length > 1) { - lv = e[1]; - } - if (Enchantment.getByName(ench) != null) { - m.addEnchant(Enchantment.getByName(ench), Integer.parseInt(lv), true); - } - } - } - - if (nameindex > -1) { - String namelore = rawitem.substring(nameindex + 1); - String name = ""; - String lore = ""; - int i = namelore.indexOf(":"); - if (i > -1) { - name = namelore.substring(0, i); - lore = namelore.substring(i + 1); - } else { - name = namelore; - } - m.setDisplayName(ChatColor.translateAlternateColorCodes('&', name)); - m.setLore(Arrays.asList(lore)); - } - - // RGB Color support for Armor - if (optional_armor_color_index > -1) { - m.setDisplayName(c[1].substring(optional_armor_color_index)); - } - - nitem.setItemMeta(m); - if (nitem.getType() == Material.ENCHANTED_BOOK) { - try { - EnchantmentStorageMeta meta = (EnchantmentStorageMeta) nitem.getItemMeta(); - for (String enchant : enchantments) { - String[] e = enchant.split(":"); - String ench = e[0]; - String lv = "1"; - if (e.length > 1) { - lv = e[1]; - } - if (Enchantment.getByName(ench) != null) { - meta.addStoredEnchant(Enchantment.getByName(ench), Integer.parseInt(lv), true); - } - } - nitem.setItemMeta(meta); - } catch (Exception e) { - System.out.println("Failed parsing enchanted book. " + e.getMessage()); - } - } - ret.add(nitem); - } - if (ret == null || ret.size() < 1) { - MinigamesAPI.getAPI().getLogger().severe("Found invalid class in config!"); - } - } catch (Exception e) { - ret.add(new ItemStack(Material.STAINED_GLASS_PANE)); - System.out.println("Failed to load class items: " + e.getMessage() + " at [1] " + e.getStackTrace()[1].getLineNumber() + " [0] " + e.getStackTrace()[0].getLineNumber()); - if (MinigamesAPI.debug) { - e.printStackTrace(); - } - ItemStack rose = new ItemStack(Material.RED_ROSE); - ItemMeta im = rose.getItemMeta(); - im.setDisplayName(ChatColor.RED + "Sowwy, failed to load class."); - rose.setItemMeta(im); - ret.add(rose); - } - return ret; - } - - public static void giveLobbyItems(JavaPlugin plugin, Player p) { - ArenaLogger.debug("Giving lobby items to " + p.getName()); - PluginInstance pli = MinigamesAPI.getAPI().getPluginInstance(plugin); - ItemStack classes_item = new ItemStack(plugin.getConfig().getInt("config.selection_items.classes_selection_item")); - if (classes_item.getType() != Material.AIR) { - ItemMeta cimeta = classes_item.getItemMeta(); - cimeta.setDisplayName(pli.getMessagesConfig().classes_item); - classes_item.setItemMeta(cimeta); - } - - if (!plugin.getConfig().getBoolean("config.bungee.game_on_join")) { - ItemStack exit_item = new ItemStack(plugin.getConfig().getInt("config.selection_items.exit_item")); - if (exit_item.getType() != Material.AIR) { - ItemMeta exitimeta = exit_item.getItemMeta(); - exitimeta.setDisplayName(pli.getMessagesConfig().exit_item); - exit_item.setItemMeta(exitimeta); - } - p.getInventory().setItem(8, exit_item); - p.updateInventory(); - } - - ItemStack achievement_item = new ItemStack(plugin.getConfig().getInt("config.selection_items.achievement_item")); - if (achievement_item.getType() != Material.AIR) { - ItemMeta achievement_itemmeta = achievement_item.getItemMeta(); - achievement_itemmeta.setDisplayName(pli.getMessagesConfig().achievement_item); - achievement_item.setItemMeta(achievement_itemmeta); - } - - ItemStack shop_item = new ItemStack(plugin.getConfig().getInt("config.selection_items.shop_selection_item")); - if (shop_item.getType() != Material.AIR) { - ItemMeta shop_itemmeta = shop_item.getItemMeta(); - shop_itemmeta.setDisplayName(pli.getMessagesConfig().shop_item); - shop_item.setItemMeta(shop_itemmeta); - } - - if (plugin.getConfig().getBoolean("config.classes_enabled")) { - p.getInventory().addItem(classes_item); - } - if (pli.isAchievementGuiEnabled() && pli.getAchievementsConfig().getConfig().getBoolean("config.enabled")) { - p.getInventory().addItem(achievement_item); - } - if (plugin.getConfig().getBoolean("config.shop_enabled")) { - p.getInventory().addItem(shop_item); - } - p.updateInventory(); - - // custom lobby item - if (plugin.getConfig().getBoolean("config.extra_lobby_item.item0.enabled")) { - ItemStack custom_item0 = new ItemStack(plugin.getConfig().getInt("config.extra_lobby_item.item0.item")); - if (custom_item0.getType() != Material.AIR) { - ItemMeta custom_item0meta = custom_item0.getItemMeta(); - custom_item0meta.setDisplayName(plugin.getConfig().getString("config.extra_lobby_item.item0.name")); - custom_item0.setItemMeta(custom_item0meta); - } - p.getInventory().addItem(custom_item0); - p.updateInventory(); - } - } - - public static void giveSpectatorItems(JavaPlugin plugin, Player p) { - PluginInstance pli = MinigamesAPI.getAPI().getPluginInstance(plugin); - ItemStack s_item = new ItemStack(plugin.getConfig().getInt("config.selection_items.spectator_item")); - ItemMeta s_imeta = s_item.getItemMeta(); - s_imeta.setDisplayName(pli.getMessagesConfig().spectator_item); - s_item.setItemMeta(s_imeta); - - ItemStack exit_item = new ItemStack(plugin.getConfig().getInt("config.selection_items.exit_item")); - ItemMeta exitimeta = exit_item.getItemMeta(); - exitimeta.setDisplayName(pli.getMessagesConfig().exit_item); - exit_item.setItemMeta(exitimeta); - - p.getInventory().addItem(s_item); - p.getInventory().setItem(8, exit_item); - p.updateInventory(); - } - - public static void sendMessage(Player p, String arenaname, String msgraw) { - String[] msgs = msgraw.replaceAll("<player>", p.getName()).replaceAll("<arena>", arenaname).split(";"); - for (String msg : msgs) { - p.sendMessage(msgs); - } - } - - public static void sendMessage(JavaPlugin plugin, Player p, String msgraw) { - if (msgraw.equalsIgnoreCase("")) { - return; - } - String[] msgs = msgraw.replaceAll("<player>", p.getName()).replaceAll("<game>", plugin.getName()).split(";"); - for (String msg : msgs) { - p.sendMessage(msg); - } - } - - public static ItemStack getCustomHead(String name) { - ItemStack item = new ItemStack(Material.SKULL_ITEM, 1, (short) 3); - SkullMeta skullmeta = (SkullMeta) item.getItemMeta(); - skullmeta.setOwner(name); - item.setItemMeta(skullmeta); - return item; - } - - public static void spawnPowerup(JavaPlugin plugin, Arena a, Location l, ItemStack item) { - World w = l.getWorld(); - Chicken c = w.spawn(l, Chicken.class); - c.addPotionEffect(new PotionEffect(PotionEffectType.INVISIBILITY, 100000, 100000)); - Item i = w.dropItem(l, item); - c.setPassenger(i); - if (plugin.getConfig().getBoolean("config.powerup_spawning.broadcast")) { - for (String p_ : a.getAllPlayers()) { - if (Validator.isPlayerOnline(p_)) { - Player p = Bukkit.getPlayer(p_); - p.sendMessage(MinigamesAPI.getAPI().getPluginInstance(plugin).getMessagesConfig().powerup_spawned); - } - } - } - if (plugin.getConfig().getBoolean("config.powerup_spawning.spawn_firework")) { - spawnFirework(l); - } - } - - static Random r = new Random(); - - public static void spawnFirework(Player p) { - spawnFirework(p.getLocation()); - } - - public static void spawnFirework(Location l) { - Firework fw = (Firework) l.getWorld().spawnEntity(l, EntityType.FIREWORK); - FireworkMeta fwm = fw.getFireworkMeta(); - FireworkEffect effect = FireworkEffect.builder().flicker(r.nextBoolean()).withColor(Color.AQUA).withFade(Color.ORANGE).with(Type.STAR).trail(r.nextBoolean()).build(); - fwm.addEffect(effect); - int rp = r.nextInt(2) + 1; - fwm.setPower(rp); - fw.setFireworkMeta(fwm); - } - - public static Color hexToRgb(String colorStr) { - return Color.fromRGB(Integer.valueOf(colorStr.substring(1, 3), 16), Integer.valueOf(colorStr.substring(3, 5), 16), Integer.valueOf(colorStr.substring(5, 7), 16)); - } - - public static class ValueComparator implements Comparator<String> { - Map<String, Double> base; - - public ValueComparator(Map<String, Double> base) { - this.base = base; - } - - public int compare(String a, String b) { - if (base.get(a) >= base.get(b)) { - return -1; - } else { - return 1; - } - } - } - - public static class CompassPlayer { - Player p = null; - Double d = null; - - public CompassPlayer(Player p, Double d) { - this.p = p; - this.d = d; - } - - public Player getPlayer() { - return p; - } - - public Double getDistance() { - return d; - } - } - - public static CompassPlayer getNearestPlayer(Player p, Arena a) { - CompassPlayer ret = null; - double distance = 10000; - for (String p_ : a.getAllPlayers()) { - if (!p_.equalsIgnoreCase(p.getName()) && !MinigamesAPI.getAPI().getPluginInstance(a.getPlugin()).containsGlobalLost(p_)) { - if (Validator.isPlayerOnline(p_)) { - double newdist = Bukkit.getPlayer(p_).getLocation().distance(p.getLocation()); - if (newdist < distance) { - distance = newdist; - ret = new CompassPlayer(Bukkit.getPlayer(p_), distance); - } - } - } - } - return ret; - } - - static boolean windows = false; - - public static void restartServer() { - String system = System.getProperty("os.name"); - String startDir = System.getProperty("user.dir"); - String fileName = "start.sh"; - String jarFile = "craftbukkit.jar"; - if (system.contains("Windows")) { - fileName = "start.bat"; - windows = true; - } - if (Bukkit.getVersion().contains("Spigot")) { - jarFile = "spigot.jar"; - } - System.out.println(Bukkit.getVersion()); - System.out.println(system); - System.out.println(startDir); - final File f = new File(startDir + "\\" + fileName); - if (!f.exists()) { - PrintWriter writer; - try { - - writer = new PrintWriter(f, "UTF-8"); - if (windows) { - writer.println("@ECHO OFF"); - } else { - writer.println("#!/bin/bash"); - } - writer.println("java -Xms1024M -Xmx1024M -jar " + jarFile); - if (windows) { - writer.println("PAUSE"); - } - writer.close(); - } catch (Exception e) { - e.printStackTrace(); - } - } - - Runtime.getRuntime().addShutdownHook(new Thread() { - public void run() { - try { - if (windows) { - Runtime.getRuntime().exec("CMD /C START \"" + f.getPath() + "\""); - } else { - Runtime.getRuntime().exec("sh " + f); - } - } catch (IOException e) { - e.printStackTrace(); - } - } - }); - Bukkit.getScheduler().runTaskLater(MinigamesAPI.getAPI(), new Runnable() { - public void run() { - Bukkit.getServer().shutdown(); - } - }, 20L); - } - - public static void sendStatsMessage(PluginInstance pli, Player p) { - if (pli.getMessagesConfig().getConfig().isSet("messages.stats")) { - int kills_ = pli.getStatsInstance().getKills(p.getName()); - int deaths_ = pli.getStatsInstance().getDeaths(p.getName()); - int money_ = 0; - if (MinigamesAPI.economy) { - money_ = (int) MinigamesAPI.econ.getBalance(p.getName()); - } - - String wins = Integer.toString(pli.getStatsInstance().getWins(p.getName())); - String loses = Integer.toString(pli.getStatsInstance().getLoses(p.getName())); - String kills = Integer.toString(kills_); - String deaths = Integer.toString(deaths_); - String money = Integer.toString(money_); - String points = Integer.toString(pli.getStatsInstance().getPoints(p.getName())); - String kdr = Integer.toString(Math.max(kills_, 1) / Math.max(deaths_, 1)); - for (String key : pli.getMessagesConfig().getConfig().getConfigurationSection("messages.stats").getKeys(false)) { - // Each line from the config gets checked for variables like <wins> or <money> and these get replaced by the values calculated above - String msg = pli.getMessagesConfig().getConfig().getString("messages.stats." + key).replaceAll("<wins>", wins).replaceAll("<loses>", loses).replaceAll("<alltime_kills>", kills).replaceAll("<alltime_deaths>", deaths).replaceAll("<points>", points).replaceAll("<kdr>", kdr).replaceAll("<money>", money); - Util.sendMessage(pli.getPlugin(), p, ChatColor.translateAlternateColorCodes('&', msg)); - } - } - } - - public static void pushBack(Location l, Player p) { - Vector direction = l.toVector().subtract(p.getLocation().toVector()).normalize(); - p.setVelocity(direction); - if (p.isInsideVehicle()) { - p.getVehicle().setVelocity(direction.multiply(2D)); - } - p.playEffect(p.getLocation(), Effect.POTION_BREAK, 5); - } - - public static Score getScore(Objective obj, String text) { - Score s = null; - Method getScore_ = null; - try { - if (MinigamesAPI.getAPI().below1710) { - getScore_ = obj.getClass().getDeclaredMethod("getScore", OfflinePlayer.class); - getScore_.setAccessible(true); - s = (Score) getScore_.invoke(obj, Bukkit.getOfflinePlayer(text)); - } else { - getScore_ = obj.getClass().getDeclaredMethod("getScore", String.class); - getScore_.setAccessible(true); - s = (Score) getScore_.invoke(obj, text); - } - } catch (Exception e) { - if (MinigamesAPI.debug) { - e.printStackTrace(); - } - } - return s; - } - - public static void resetScores(Scoreboard obj, String text) { - Method resetScores_ = null; - try { - if (MinigamesAPI.getAPI().below1710) { - resetScores_ = obj.getClass().getDeclaredMethod("resetScores", OfflinePlayer.class); - resetScores_.setAccessible(true); - resetScores_.invoke(obj, Bukkit.getOfflinePlayer(text)); - } else { - resetScores_ = obj.getClass().getDeclaredMethod("resetScores", String.class); - resetScores_.setAccessible(true); - resetScores_.invoke(obj, text); - } - } catch (Exception e) { - if (MinigamesAPI.debug) { - e.printStackTrace(); - } - } - } +public class Util +{ + + public static HashMap<String, ItemStack[]> armourContents = new HashMap<>(); + public static HashMap<String, ItemStack[]> inventoryContents = new HashMap<>(); + public static HashMap<String, Location> locations = new HashMap<>(); + public static HashMap<String, Integer> xplevel = new HashMap<>(); + public static HashMap<String, GameMode> gamemode = new HashMap<>(); + + public static void clearInv(final Player p) + { + if (p != null) + { + ArenaLogger.debug("Clearing inventory of " + p.getName()); + p.getInventory().clear(); + p.updateInventory(); + p.getInventory().setHelmet(null); + p.getInventory().setChestplate(null); + p.getInventory().setLeggings(null); + p.getInventory().setBoots(null); + p.updateInventory(); + } + } + + @SuppressWarnings("deprecation") + public static void teleportPlayerFixed(final Player p, final Location l) + { + ArenaLogger.debug("Teleporting " + p.getName()); + if (p.isInsideVehicle()) + { + final Entity ent = p.getVehicle(); + p.leaveVehicle(); + ent.eject(); + } + if (l != null) + { + if (l.getWorld() == null) + { + return; + } + p.teleport(l, TeleportCause.PLUGIN); + p.setFallDistance(-1F); + p.setVelocity(new Vector(0D, 0D, 0D)); + + final Chunk chunk = l.getChunk(); + if (MinigamesAPI.SERVER_VERSION.isBelow(MinecraftVersionsType.V1_8)) + { + l.getWorld().refreshChunk(chunk.getX(), chunk.getZ()); + } + else + { + try + { + final Method getChunkHandle = chunk.getClass().getMethod("getHandle"); + final Method getPlayerHandle = p.getClass().getMethod("getHandle"); + final Object handle = getPlayerHandle.invoke(p); + final Field playerConnection = handle.getClass().getField("playerConnection"); + playerConnection.setAccessible(true); + final Method sendPacket = playerConnection.getType().getMethod("sendPacket", Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().internalServerVersion + ".Packet")); + final Class<?> chunkClazz = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().internalServerVersion + ".Chunk"); + final Object packet; + if (MinigamesAPI.SERVER_VERSION.isAtLeast(MinecraftVersionsType.V1_9_R2)) + { + final Constructor<?> constr = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().internalServerVersion + ".PacketPlayOutMapChunk").getConstructor(chunkClazz, int.class); + packet = constr.newInstance(getChunkHandle.invoke(chunk), 20); + } + else + { + final Constructor<?> constr = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().internalServerVersion + ".PacketPlayOutMapChunk").getConstructor(chunkClazz, boolean.class, int.class); + packet = constr.newInstance(getChunkHandle.invoke(chunk), false, 20); + } + sendPacket.invoke(playerConnection.get(handle), packet); + + // ((CraftPlayer)p).getHandle().playerConnection.sendPacket(new PacketPlayOutMapChunk(((CraftChunk)chunk).getHandle(), true, 65535)); + chunk.unload(true); + chunk.load(); + } + catch (Exception ex) + { + MinigamesAPI.getAPI().getLogger().log(Level.WARNING, "exception", ex); + } + } + } + else + { + MinigamesAPI.getAPI().getLogger().warning("Couldn't teleport Player " + p.getName() + ", the location was not valid. Probably forgot to set a spawn/lobby?"); + } + p.setFireTicks(0); + p.addPotionEffect(new PotionEffect(PotionEffectType.HEAL, 20 * 2, 30)); + } + + public static void teleportAllPlayers(final ArrayList<String> players, final Location l) + { + Long delay = 1L; + for (final String pl : players) + { + if (!Validator.isPlayerOnline(pl)) + { + continue; + } + final Player p = Bukkit.getPlayer(pl); + Bukkit.getScheduler().runTaskLater(MinigamesAPI.getAPI(), () -> Util.teleportPlayerFixed(p, l), delay); + delay++; + } + } + + public static HashMap<String, Location> teleportAllPlayers(final ArrayList<String> players, final ArrayList<Location> locs) + { + final HashMap<String, Location> pspawnloc = new HashMap<>(); + int currentid = 0; + final int locslength = locs.size(); + for (final String p_ : players) + { + final Player p = Bukkit.getPlayer(p_); + Util.teleportPlayerFixed(p, locs.get(currentid)); + pspawnloc.put(p_, locs.get(currentid)); + currentid++; + if (currentid > locslength - 1) + { + currentid = 0; + } + } + return pspawnloc; + } + + public static Location getComponentForArena(final JavaPlugin plugin, final String arenaname, final String component, final String count) + { + if (Validator.isArenaValid(plugin, arenaname)) + { + final String base = ArenaConfigStrings.ARENAS_PREFIX + arenaname + "." + component + count; + final PluginInstance pli = MinigamesAPI.getAPI().getPluginInstance(plugin); + if (!pli.getArenasConfig().getConfig().isSet(base + ".world") || Bukkit.getWorld(pli.getArenasConfig().getConfig().getString(base + ".world")) == null) + { + return null; + } + return new Location(Bukkit.getWorld(pli.getArenasConfig().getConfig().getString(base + ".world")), pli.getArenasConfig().getConfig().getDouble(base + ".location.x"), + pli.getArenasConfig().getConfig().getDouble(base + ".location.y"), pli.getArenasConfig().getConfig().getDouble(base + ".location.z"), + (float) pli.getArenasConfig().getConfig().getDouble(base + ".location.yaw"), (float) pli.getArenasConfig().getConfig().getDouble(base + ".location.pitch")); + } + return null; + } + + public static Location getComponentForArena(final JavaPlugin plugin, final String arenaname, final String component) + { + if (Validator.isArenaValid(plugin, arenaname)) + { + final String base = ArenaConfigStrings.ARENAS_PREFIX + arenaname + "." + component; + final PluginInstance pli = MinigamesAPI.getAPI().getPluginInstance(plugin); + if (!pli.getArenasConfig().getConfig().isSet(base + ".world") || Bukkit.getWorld(pli.getArenasConfig().getConfig().getString(base + ".world")) == null) + { + return null; + } + return new Location(Bukkit.getWorld(pli.getArenasConfig().getConfig().getString(base + ".world")), pli.getArenasConfig().getConfig().getDouble(base + ".location.x"), + pli.getArenasConfig().getConfig().getDouble(base + ".location.y"), pli.getArenasConfig().getConfig().getDouble(base + ".location.z"), + (float) pli.getArenasConfig().getConfig().getDouble(base + ".location.yaw"), (float) pli.getArenasConfig().getConfig().getDouble(base + ".location.pitch")); + } + return null; + } + + public static Location getComponentForArenaRaw(final JavaPlugin plugin, final String arenaname, final String component) + { + final String base = ArenaConfigStrings.ARENAS_PREFIX + arenaname + "." + component; + final PluginInstance pli = MinigamesAPI.getAPI().getPluginInstance(plugin); + if (pli.getArenasConfig().getConfig().isSet(base)) + { + return new Location(Bukkit.getWorld(pli.getArenasConfig().getConfig().getString(base + ".world")), pli.getArenasConfig().getConfig().getDouble(base + ".location.x"), + pli.getArenasConfig().getConfig().getDouble(base + ".location.y"), pli.getArenasConfig().getConfig().getDouble(base + ".location.z"), + (float) pli.getArenasConfig().getConfig().getDouble(base + ".location.yaw"), (float) pli.getArenasConfig().getConfig().getDouble(base + ".location.pitch")); + } + return null; + } + + public static boolean isComponentForArenaValid(final JavaPlugin plugin, final String arenaname, final String component) + { + if (Validator.isArenaValid(plugin, arenaname)) + { + return Util.isComponentForArenaValidRaw(plugin, arenaname, component); + } + return false; + } + + public static boolean isComponentForArenaValidRaw(final JavaPlugin plugin, final String arenaname, final String component) + { + final String base = ArenaConfigStrings.ARENAS_PREFIX + arenaname + "." + component; + return MinigamesAPI.getAPI().getPluginInstance(plugin).getArenasConfig().getConfig().isSet(base); + } + + public static void saveComponentForArena(final JavaPlugin plugin, final String arenaname, final String component, final Location comploc) + { + final String base = ArenaConfigStrings.ARENAS_PREFIX + arenaname + "." + component; + final ArenasConfig config = MinigamesAPI.getAPI().getPluginInstance(plugin).getArenasConfig(); + config.getConfig().set(base + ".world", comploc.getWorld().getName()); + config.getConfig().set(base + ".location.x", comploc.getX()); + config.getConfig().set(base + ".location.y", comploc.getY()); + config.getConfig().set(base + ".location.z", comploc.getZ()); + config.getConfig().set(base + ".location.yaw", comploc.getYaw()); + config.getConfig().set(base + ".location.pitch", comploc.getPitch()); + config.saveConfig(); + } + + public static void saveMainLobby(final JavaPlugin plugin, final Location comploc) + { + final String base = "mainlobby"; + final ArenasConfig config = MinigamesAPI.getAPI().getPluginInstance(plugin).getArenasConfig(); + config.getConfig().set(base + ".world", comploc.getWorld().getName()); + config.getConfig().set(base + ".location.x", comploc.getX()); + config.getConfig().set(base + ".location.y", comploc.getY()); + config.getConfig().set(base + ".location.z", comploc.getZ()); + config.getConfig().set(base + ".location.yaw", comploc.getYaw()); + config.getConfig().set(base + ".location.pitch", comploc.getPitch()); + config.saveConfig(); + } + + public static Location getMainLobby(final JavaPlugin plugin) + { + final FileConfiguration config = MinigamesAPI.getAPI().getPluginInstance(plugin).getArenasConfig().getConfig(); + if (!config.isSet("mainlobby")) + { + Bukkit.getConsoleSender().sendMessage(ChatColor.RED + "You forgot to set the mainlobby!"); + return null; + } + return new Location(plugin.getServer().getWorld(config.getString("mainlobby.world")), config.getDouble("mainlobby.location.x"), config.getDouble("mainlobby.location.y"), + config.getDouble("mainlobby.location.z"), (float) config.getDouble("mainlobby.location.yaw"), (float) config.getDouble("mainlobby.location.pitch")); + } + + public static ArrayList<Location> getAllSpawns(final JavaPlugin plugin, final String arena) + { + final FileConfiguration config = MinigamesAPI.getAPI().getPluginInstance(plugin).getArenasConfig().getConfig(); + final ArrayList<Location> ret = new ArrayList<>(); + if (config.isSet(ArenaConfigStrings.ARENAS_PREFIX + arena + ".spawns")) + { + for (final String spawn : config.getConfigurationSection(ArenaConfigStrings.ARENAS_PREFIX + arena + ".spawns.").getKeys(false)) + { + ret.add(Util.getComponentForArena(plugin, arena, "spawns." + spawn)); + } + } + return ret; + } + + public static void saveArenaToFile(final JavaPlugin plugin, final String arena) + { + final File f = new File(plugin.getDataFolder() + "/" + arena); + final Cuboid c = new Cuboid(Util.getComponentForArena(plugin, arena, ArenaConfigStrings.BOUNDS_LOW), Util.getComponentForArena(plugin, arena, ArenaConfigStrings.BOUNDS_HIGH)); + final Location start = c.getLowLoc(); + final Location end = c.getHighLoc(); + + final int width = end.getBlockX() - start.getBlockX(); + final int length = end.getBlockZ() - start.getBlockZ(); + final int height = end.getBlockY() - start.getBlockY(); + + MinigamesAPI.getAPI().getLogger().info("Bounds: " + Integer.toString(width) + " " + Integer.toString(height) + " " + Integer.toString(length)); + MinigamesAPI.getAPI().getLogger().info("Blocks to save: " + Integer.toString(width * height * length)); + + FileOutputStream fos; + ObjectOutputStream oos = null; + try + { + fos = new FileOutputStream(f); + oos = new BukkitObjectOutputStream(fos); + } + catch (final IOException e) + { + MinigamesAPI.getAPI().getLogger().log(Level.WARNING, "exception", e); + } + + for (int i = 0; i <= width; i++) + { + for (int j = 0; j <= height; j++) + { + for (int k = 0; k <= length; k++) + { + final Block change = c.getWorld().getBlockAt(start.getBlockX() + i, start.getBlockY() + j, start.getBlockZ() + k); + + final ArenaBlock bl = new ArenaBlock(change, change.getType().equals(Material.CHEST)); + + try + { + oos.writeObject(bl); + } + catch (final IOException e) + { + MinigamesAPI.getAPI().getLogger().log(Level.WARNING, "io error", e); + } + } + } + } + + try + { + oos.close(); + } + catch (final IOException e) + { + MinigamesAPI.getAPI().getLogger().log(Level.WARNING, "exception", e); + } + + MinigamesAPI.getAPI().getLogger().info("saved"); + } + + public static Sign getSignFromArena(final JavaPlugin plugin, final String arena) + { + final PluginInstance pli = MinigamesAPI.getAPI().getPluginInstance(plugin); + if (!pli.getArenasConfig().getConfig().isSet(ArenaConfigStrings.ARENAS_PREFIX + arena + ".sign.world")) + { + return null; + } + final Location b_ = new Location(Bukkit.getServer().getWorld(pli.getArenasConfig().getConfig().getString(ArenaConfigStrings.ARENAS_PREFIX + arena + ".sign.world")), + pli.getArenasConfig().getConfig().getInt(ArenaConfigStrings.ARENAS_PREFIX + arena + ".sign.loc.x"), pli.getArenasConfig().getConfig().getInt(ArenaConfigStrings.ARENAS_PREFIX + arena + ".sign.loc.y"), + pli.getArenasConfig().getConfig().getInt(ArenaConfigStrings.ARENAS_PREFIX + arena + ".sign.loc.z")); + if (b_ != null) + { + if (b_.getWorld() != null) + { + if (b_.getBlock().getState() != null) + { + final BlockState bs = b_.getBlock().getState(); + Sign s_ = null; + if (bs instanceof Sign) + { + s_ = (Sign) bs; + } + return s_; + } + } + } + return null; + } + + public static Sign getSpecSignFromArena(final JavaPlugin plugin, final String arena) + { + final PluginInstance pli = MinigamesAPI.getAPI().getPluginInstance(plugin); + if (!pli.getArenasConfig().getConfig().isSet(ArenaConfigStrings.ARENAS_PREFIX + arena + ".specsign.world")) + { + return null; + } + final Location b_ = new Location(Bukkit.getServer().getWorld(pli.getArenasConfig().getConfig().getString(ArenaConfigStrings.ARENAS_PREFIX + arena + ".specsign.world")), + pli.getArenasConfig().getConfig().getInt(ArenaConfigStrings.ARENAS_PREFIX + arena + ".specsign.loc.x"), pli.getArenasConfig().getConfig().getInt(ArenaConfigStrings.ARENAS_PREFIX + arena + ".specsign.loc.y"), + pli.getArenasConfig().getConfig().getInt(ArenaConfigStrings.ARENAS_PREFIX + arena + ".specsign.loc.z")); + if (b_ != null) + { + if (b_.getWorld() != null) + { + if (b_.getBlock().getState() != null) + { + final BlockState bs = b_.getBlock().getState(); + Sign s_ = null; + if (bs instanceof Sign) + { + s_ = (Sign) bs; + } + return s_; + } + } + } + return null; + } + + public static Location getSignLocationFromArena(final JavaPlugin plugin, final String arena) + { + final Sign s = Util.getSignFromArena(plugin, arena); + if (s != null) + { + return s.getBlock().getLocation(); + } + else + { + return null; + } + } + + public static Location getSpecSignLocationFromArena(final JavaPlugin plugin, final String arena) + { + final Sign s = Util.getSpecSignFromArena(plugin, arena); + if (s != null) + { + return s.getBlock().getLocation(); + } + else + { + return null; + } + } + + public static Arena getArenaBySignLocation(final JavaPlugin plugin, final Location sign) + { + for (final Arena arena : MinigamesAPI.getAPI().getPluginInstance(plugin).getArenas()) + { + if (sign != null && arena.getSignLocation() != null) + { + if (sign.getWorld().getName().equalsIgnoreCase(arena.getSignLocation().getWorld().getName())) + { + if (sign.distance(arena.getSignLocation()) < 1) + { + return arena; + } + } + } + } + return null; + } + + public static Arena getArenaBySpecSignLocation(final JavaPlugin plugin, final Location sign) + { + for (final Arena arena : MinigamesAPI.getAPI().getPluginInstance(plugin).getArenas()) + { + if (sign != null && arena.getSpecSignLocation() != null) + { + if (sign.getWorld().getName().equalsIgnoreCase(arena.getSpecSignLocation().getWorld().getName())) + { + if (sign.distance(arena.getSpecSignLocation()) < 1) + { + return arena; + } + } + } + } + return null; + } + + public static void updateSign(final JavaPlugin plugin, final Arena arena) + { + if (arena == null) + { + return; + } + + Sign s = Util.getSignFromArena(plugin, arena.getInternalName()); + if (s != null) + { + ArenaLogger.debug("Updating sign for arena " + arena.getInternalName() + " in " + plugin.getName()); + final int count = arena.getAllPlayers().size(); + final int maxcount = arena.getMaxPlayers(); + final PluginInstance pli = MinigamesAPI.getAPI().getPluginInstance(plugin); + final String state = arena.getArenaState().toString().toLowerCase(); + if (pli.cached_sign_states.containsKey(state)) + { + s.setLine(0, + Signs.replaceSquares(pli.cached_sign_states.get(state).get(0).replaceAll("&", "§").replace("<count>", Integer.toString(count)).replace("<maxcount>", Integer.toString(maxcount)) + .replace("<arena>", arena.getDisplayName()))); + s.setLine(1, + Signs.replaceSquares(pli.cached_sign_states.get(state).get(1).replaceAll("&", "§").replace("<count>", Integer.toString(count)).replace("<maxcount>", Integer.toString(maxcount)) + .replace("<arena>", arena.getDisplayName()))); + s.setLine(2, + Signs.replaceSquares(pli.cached_sign_states.get(state).get(2).replaceAll("&", "§").replace("<count>", Integer.toString(count)).replace("<maxcount>", Integer.toString(maxcount)) + .replace("<arena>", arena.getDisplayName()))); + s.setLine(3, + Signs.replaceSquares(pli.cached_sign_states.get(state).get(3).replaceAll("&", "§").replace("<count>", Integer.toString(count)).replace("<maxcount>", Integer.toString(maxcount)) + .replace("<arena>", arena.getDisplayName()))); + } + else + { + s.setLine(0, + Signs.replaceSquares(pli.getMessagesConfig().getConfig().getString("signs." + state + ".0").replaceAll("&", "§").replace("<count>", Integer.toString(count)) + .replace("<maxcount>", Integer.toString(maxcount)).replace("<arena>", arena.getDisplayName()))); + s.setLine(1, + Signs.replaceSquares(pli.getMessagesConfig().getConfig().getString("signs." + state + ".1").replaceAll("&", "§").replace("<count>", Integer.toString(count)) + .replace("<maxcount>", Integer.toString(maxcount)).replace("<arena>", arena.getDisplayName()))); + s.setLine(2, + Signs.replaceSquares(pli.getMessagesConfig().getConfig().getString("signs." + state + ".2").replaceAll("&", "§").replace("<count>", Integer.toString(count)) + .replace("<maxcount>", Integer.toString(maxcount)).replace("<arena>", arena.getDisplayName()))); + s.setLine(3, + Signs.replaceSquares(pli.getMessagesConfig().getConfig().getString("signs." + state + ".3").replaceAll("&", "§").replace("<count>", Integer.toString(count)) + .replace("<maxcount>", Integer.toString(maxcount)).replace("<arena>", arena.getDisplayName()))); + } + s.getBlock().getChunk().load(); + s.update(); + if (pli.color_background_wool_of_signs) + { + final org.bukkit.material.Sign s_ = (org.bukkit.material.Sign) s.getBlock().getState().getData(); + final Block attachedBlock = s.getBlock().getRelative(s_.getAttachedFace()); + byte data = (byte) 5; + if (arena.getArenaState() == ArenaState.INGAME) + { + data = (byte) 14; + } + else if (arena.getArenaState() == ArenaState.RESTARTING) + { + data = (byte) 4; + } + attachedBlock.setData(data); + } + } + try + { + if (plugin.isEnabled()) + { + BungeeUtil.sendSignUpdateRequest(plugin, plugin.getName(), arena); + } + } + catch (final Exception e) + { + MinigamesAPI.getAPI().getLogger().log(Level.WARNING, "Failed sending bungee sign update: ", e); + } + + s = Util.getSpecSignFromArena(plugin, arena.getInternalName()); + if (s != null) + { + ArenaLogger.debug("Updating spectator sign for arena " + arena.getInternalName() + " in " + plugin.getName()); + final int count = arena.getAllPlayers().size(); + final int maxcount = arena.getMaxPlayers(); + final PluginInstance pli = MinigamesAPI.getAPI().getPluginInstance(plugin); + final String state = "spec"; + if (pli.cached_sign_states.containsKey(state)) + { + s.setLine(0, + Signs.replaceSquares(pli.cached_sign_states.get(state).get(0).replaceAll("&", "§").replace("<count>", Integer.toString(count)).replace("<maxcount>", Integer.toString(maxcount)) + .replace("<arena>", arena.getDisplayName()))); + s.setLine(1, + Signs.replaceSquares(pli.cached_sign_states.get(state).get(1).replaceAll("&", "§").replace("<count>", Integer.toString(count)).replace("<maxcount>", Integer.toString(maxcount)) + .replace("<arena>", arena.getDisplayName()))); + s.setLine(2, + Signs.replaceSquares(pli.cached_sign_states.get(state).get(2).replaceAll("&", "§").replace("<count>", Integer.toString(count)).replace("<maxcount>", Integer.toString(maxcount)) + .replace("<arena>", arena.getDisplayName()))); + s.setLine(3, + Signs.replaceSquares(pli.cached_sign_states.get(state).get(3).replaceAll("&", "§").replace("<count>", Integer.toString(count)).replace("<maxcount>", Integer.toString(maxcount)) + .replace("<arena>", arena.getDisplayName()))); + } + else + { + s.setLine(0, + Signs.replaceSquares(pli.getMessagesConfig().getConfig().getString("signs." + state + ".0").replaceAll("&", "§").replace("<count>", Integer.toString(count)) + .replace("<maxcount>", Integer.toString(maxcount)).replace("<arena>", arena.getDisplayName()))); + s.setLine(1, + Signs.replaceSquares(pli.getMessagesConfig().getConfig().getString("signs." + state + ".1").replaceAll("&", "§").replace("<count>", Integer.toString(count)) + .replace("<maxcount>", Integer.toString(maxcount)).replace("<arena>", arena.getDisplayName()))); + s.setLine(2, + Signs.replaceSquares(pli.getMessagesConfig().getConfig().getString("signs." + state + ".2").replaceAll("&", "§").replace("<count>", Integer.toString(count)) + .replace("<maxcount>", Integer.toString(maxcount)).replace("<arena>", arena.getDisplayName()))); + s.setLine(3, + Signs.replaceSquares(pli.getMessagesConfig().getConfig().getString("signs." + state + ".3").replaceAll("&", "§").replace("<count>", Integer.toString(count)) + .replace("<maxcount>", Integer.toString(maxcount)).replace("<arena>", arena.getDisplayName()))); + } + s.getBlock().getChunk().load(); + s.update(); + } + try + { + if (plugin.isEnabled()) + { + BungeeUtil.sendSignUpdateRequest(plugin, plugin.getName(), arena); + } + } + catch (final Exception e) + { + MinigamesAPI.getAPI().getLogger().log(Level.WARNING, "Failed sending bungee sign update: ", e); + } + } + + public static void updateSign(final JavaPlugin plugin, final Arena arena, final SignChangeEvent event) + { + final int count = arena.getAllPlayers().size(); + final int maxcount = arena.getMaxPlayers(); + final PluginInstance pli = MinigamesAPI.getAPI().getPluginInstance(plugin); + final String arenastate = arena.getArenaState().toString().toLowerCase(); + event.setLine(0, + Signs.replaceSquares(pli.getMessagesConfig().getConfig().getString("signs." + arenastate + ".0").replaceAll("&", "§").replace("<count>", Integer.toString(count)) + .replace("<maxcount>", Integer.toString(maxcount)).replace("<arena>", arena.getDisplayName()))); + event.setLine(1, + Signs.replaceSquares(pli.getMessagesConfig().getConfig().getString("signs." + arenastate + ".1").replaceAll("&", "§").replace("<count>", Integer.toString(count)) + .replace("<maxcount>", Integer.toString(maxcount)).replace("<arena>", arena.getDisplayName()))); + event.setLine(2, + Signs.replaceSquares(pli.getMessagesConfig().getConfig().getString("signs." + arenastate + ".2").replaceAll("&", "§").replace("<count>", Integer.toString(count)) + .replace("<maxcount>", Integer.toString(maxcount)).replace("<arena>", arena.getDisplayName()))); + event.setLine(3, + Signs.replaceSquares(pli.getMessagesConfig().getConfig().getString("signs." + arenastate + ".3").replaceAll("&", "§").replace("<count>", Integer.toString(count)) + .replace("<maxcount>", Integer.toString(maxcount)).replace("<arena>", arena.getDisplayName()))); + if (pli.color_background_wool_of_signs) + { + final org.bukkit.material.Sign s_ = (org.bukkit.material.Sign) event.getBlock().getState().getData(); + final Block attachedBlock = event.getBlock().getRelative(s_.getAttachedFace()); + byte data = (byte) 5; + if (arena.getArenaState() == ArenaState.INGAME) + { + data = (byte) 14; + } + else if (arena.getArenaState() == ArenaState.RESTARTING) + { + data = (byte) 4; + } + attachedBlock.setData(data); + } + } + + public static void updateSpecSign(final JavaPlugin plugin, final Arena arena, final SignChangeEvent event) + { + final int count = arena.getAllPlayers().size(); + final int maxcount = arena.getMaxPlayers(); + final PluginInstance pli = MinigamesAPI.getAPI().getPluginInstance(plugin); + event.setLine(0, + Signs.replaceSquares(pli.getMessagesConfig().getConfig().getString("signs.spec.0").replaceAll("&", "§").replace("<count>", Integer.toString(count)) + .replace("<maxcount>", Integer.toString(maxcount)).replace("<arena>", arena.getDisplayName()))); + event.setLine(1, + Signs.replaceSquares(pli.getMessagesConfig().getConfig().getString("signs.spec.1").replaceAll("&", "§").replace("<count>", Integer.toString(count)) + .replace("<maxcount>", Integer.toString(maxcount)).replace("<arena>", arena.getDisplayName()))); + event.setLine(2, + Signs.replaceSquares(pli.getMessagesConfig().getConfig().getString("signs.spec.2").replaceAll("&", "§").replace("<count>", Integer.toString(count)) + .replace("<maxcount>", Integer.toString(maxcount)).replace("<arena>", arena.getDisplayName()))); + event.setLine(3, + Signs.replaceSquares(pli.getMessagesConfig().getConfig().getString("signs.spec.3").replaceAll("&", "§").replace("<count>", Integer.toString(count)) + .replace("<maxcount>", Integer.toString(maxcount)).replace("<arena>", arena.getDisplayName()))); + if (pli.color_background_wool_of_signs) + { + final org.bukkit.material.Sign s_ = (org.bukkit.material.Sign) event.getBlock().getState().getData(); + final Block attachedBlock = event.getBlock().getRelative(s_.getAttachedFace()); + byte data = (byte) 5; + if (arena.getArenaState() == ArenaState.INGAME) + { + data = (byte) 14; + } + else if (arena.getArenaState() == ArenaState.RESTARTING) + { + data = (byte) 4; + } + attachedBlock.setData(data); + } + } + + // used for random and leave sign + public static void updateSign(final JavaPlugin plugin, final SignChangeEvent event, final String arenastate) + { + final PluginInstance pli = MinigamesAPI.getAPI().getPluginInstance(plugin); + event.setLine(0, Signs.replaceSquares(pli.getMessagesConfig().getConfig().getString("signs." + arenastate + ".0").replaceAll("&", "§"))); + event.setLine(1, Signs.replaceSquares(pli.getMessagesConfig().getConfig().getString("signs." + arenastate + ".1").replaceAll("&", "§"))); + event.setLine(2, Signs.replaceSquares(pli.getMessagesConfig().getConfig().getString("signs." + arenastate + ".2").replaceAll("&", "§"))); + event.setLine(3, Signs.replaceSquares(pli.getMessagesConfig().getConfig().getString("signs." + arenastate + ".3").replaceAll("&", "§"))); + } + + public static ArrayList<Arena> loadArenas(final JavaPlugin plugin, final ArenasConfig cf) + { + final ArrayList<Arena> ret = new ArrayList<>(); + final FileConfiguration config = cf.getConfig(); + if (!config.isSet("arenas")) + { + return ret; + } + for (final String arena : config.getConfigurationSection(ArenaConfigStrings.ARENAS_PREFIX).getKeys(false)) + { + if (Validator.isArenaValid(plugin, arena, cf.getConfig())) + { + ret.add(Util.initArena(plugin, arena)); + } + } + return ret; + } + + public static Arena initArena(final JavaPlugin plugin, final String arena) + { + final Arena a = new Arena(plugin, arena); + final ArenaSetup s = MinigamesAPI.getAPI().getPluginInstance(plugin).arenaSetup; + a.init(Util.getSignLocationFromArena(plugin, arena), Util.getAllSpawns(plugin, arena), Util.getMainLobby(plugin), Util.getComponentForArena(plugin, arena, "lobby"), + s.getPlayerCount(plugin, arena, true), s.getPlayerCount(plugin, arena, false), s.getArenaVIP(plugin, arena)); + return a; + } + + public static boolean isNumeric(final String s) + { + return s.matches("[-+]?\\d*\\.?\\d+"); + } + + // example items: 351:6#ALL_DAMAGE:2#KNOCKBACK:2*1=NAME:LORE;267*1;3*64;3*64 + public static ArrayList<ItemStack> parseItems(final String rawitems) + { + final ArrayList<ItemStack> ret = new ArrayList<>(); + + try + { + final String[] a = rawitems.split(";"); + + for (String rawitem : a) + { + // crackshot support + if (rawitem.startsWith("crackshot:")) + { + final String[] guntype = rawitem.split(":"); + if (guntype.length > 1) + { + if (guntype[1].length() > 1) + { + final ItemStack gun = new ItemStack(Material.WOOD_HOE); + final ItemMeta gunmeta = gun.getItemMeta(); + gunmeta.setDisplayName(rawitem); + gun.setItemMeta(gunmeta); + ret.add(gun); + } + } + continue; + } + + // Potioneffects support + if (rawitem.startsWith("potioneffect:")) + { + final String[] potioneffecttype = rawitem.split(":"); + if (potioneffecttype.length > 1) + { + String str = potioneffecttype[1]; + if (potioneffecttype.length > 2) + { + str += ":" + potioneffecttype[2]; + } + if (str.length() > 1) + { + if (!str.contains(":")) + { + // duration + rawitem += ":99999"; + } + if (!str.contains("#")) + { + // level + rawitem += "#1"; + } + final ItemStack gun = new ItemStack(Material.WOOD_HOE); + final ItemMeta gunmeta = gun.getItemMeta(); + gunmeta.setDisplayName(rawitem); + gun.setItemMeta(gunmeta); + ret.add(gun); + } + } + continue; + } + + final int nameindex = rawitem.indexOf("="); + final String[] c = rawitem.split("\\*"); + int optional_armor_color_index = -1; + String itemid = c[0]; + String itemdata = "0"; + final String[] enchantments_ = itemid.split("#"); + final String[] enchantments = new String[enchantments_.length - 1]; + if (enchantments_.length > 1) + { + for (int i = 1; i < enchantments_.length; i++) + { + enchantments[i - 1] = enchantments_[i]; + } + } + itemid = enchantments_[0]; + final String[] d = itemid.split(":"); + if (d.length > 1) + { + itemid = d[0]; + itemdata = d[1]; + } + String itemamount = "1"; + if (c.length > 1) + { + itemamount = c[1]; + optional_armor_color_index = c[1].indexOf("#"); + if (optional_armor_color_index > 0) + { + itemamount = c[1].substring(0, optional_armor_color_index); + } + } + if (nameindex > -1) + { + itemamount = c[1].substring(0, c[1].indexOf("=")); + } + final int itemid_int = Util.isNumeric(itemid) ? Integer.parseInt(itemid) : 0; + if (itemid_int < 1) + { + MinigamesAPI.getAPI().getLogger().log(Level.WARNING, "Invalid item id: " + itemid); + continue; + } + final int itemamount_int = Util.isNumeric(itemamount) ? Integer.parseInt(itemamount) : 1; + final int itemdata_int = Util.isNumeric(itemdata) ? Integer.parseInt(itemdata) : 0; + final ItemStack nitem = new ItemStack(itemid_int, itemamount_int, (short) itemdata_int); + final ItemMeta m = nitem.getItemMeta(); + if (nitem.getType() != Material.ENCHANTED_BOOK) + { + for (final String enchant : enchantments) + { + final String[] e = enchant.split(":"); + final String ench = e[0]; + String lv = "1"; + if (e.length > 1) + { + lv = e[1]; + } + if (Enchantment.getByName(ench) != null) + { + m.addEnchant(Enchantment.getByName(ench), Integer.parseInt(lv), true); + } + } + } + + if (nameindex > -1) + { + final String namelore = rawitem.substring(nameindex + 1); + String name = ""; + String lore = ""; + final int i = namelore.indexOf(":"); + if (i > -1) + { + name = namelore.substring(0, i); + lore = namelore.substring(i + 1); + } + else + { + name = namelore; + } + m.setDisplayName(ChatColor.translateAlternateColorCodes('&', name)); + m.setLore(Arrays.asList(lore)); + } + + // RGB Color support for Armor + if (optional_armor_color_index > -1) + { + m.setDisplayName(c[1].substring(optional_armor_color_index)); + } + + nitem.setItemMeta(m); + if (nitem.getType() == Material.ENCHANTED_BOOK) + { + try + { + final EnchantmentStorageMeta meta = (EnchantmentStorageMeta) nitem.getItemMeta(); + for (final String enchant : enchantments) + { + final String[] e = enchant.split(":"); + final String ench = e[0]; + String lv = "1"; + if (e.length > 1) + { + lv = e[1]; + } + if (Enchantment.getByName(ench) != null) + { + meta.addStoredEnchant(Enchantment.getByName(ench), Integer.parseInt(lv), true); + } + } + nitem.setItemMeta(meta); + } + catch (final Exception e) + { + MinigamesAPI.getAPI().getLogger().log(Level.WARNING, "Failed parsing enchanted book. ", e); + } + } + ret.add(nitem); + } + if (ret == null || ret.size() < 1) + { + MinigamesAPI.getAPI().getLogger().severe("Found invalid class in config!"); + } + } + catch (final Exception e) + { + ret.add(new ItemStack(Material.STAINED_GLASS_PANE)); + MinigamesAPI.getAPI().getLogger().log(Level.WARNING, "Failed to load class items", e); + final ItemStack rose = new ItemStack(Material.RED_ROSE); + final ItemMeta im = rose.getItemMeta(); + im.setDisplayName(ChatColor.RED + "Sowwy, failed to load class."); + rose.setItemMeta(im); + ret.add(rose); + } + return ret; + } + + public static void giveLobbyItems(final JavaPlugin plugin, final Player p) + { + ArenaLogger.debug("Giving lobby items to " + p.getName()); + final PluginInstance pli = MinigamesAPI.getAPI().getPluginInstance(plugin); + final ItemStack classes_item = new ItemStack(plugin.getConfig().getInt(ArenaConfigStrings.CONFIG_CLASS_SELECTION_ITEM)); + if (classes_item.getType() != Material.AIR) + { + final ItemMeta cimeta = classes_item.getItemMeta(); + cimeta.setDisplayName(pli.getMessagesConfig().classes_item); + classes_item.setItemMeta(cimeta); + } + + if (!plugin.getConfig().getBoolean(ArenaConfigStrings.CONFIG_BUNGEE_GAME_ON_JOIN)) + { + final ItemStack exit_item = new ItemStack(plugin.getConfig().getInt(ArenaConfigStrings.CONFIG_EXIT_ITEM)); + if (exit_item.getType() != Material.AIR) + { + final ItemMeta exitimeta = exit_item.getItemMeta(); + exitimeta.setDisplayName(pli.getMessagesConfig().exit_item); + exit_item.setItemMeta(exitimeta); + } + p.getInventory().setItem(8, exit_item); + p.updateInventory(); + } + + final ItemStack achievement_item = new ItemStack(plugin.getConfig().getInt(ArenaConfigStrings.CONFIG_ACHIEVEMENT_ITEMS)); + if (achievement_item.getType() != Material.AIR) + { + final ItemMeta achievement_itemmeta = achievement_item.getItemMeta(); + achievement_itemmeta.setDisplayName(pli.getMessagesConfig().achievement_item); + achievement_item.setItemMeta(achievement_itemmeta); + } + + final ItemStack shop_item = new ItemStack(plugin.getConfig().getInt(ArenaConfigStrings.CONFIG_SHOP_SELECTION_ITEM)); + if (shop_item.getType() != Material.AIR) + { + final ItemMeta shop_itemmeta = shop_item.getItemMeta(); + shop_itemmeta.setDisplayName(pli.getMessagesConfig().shop_item); + shop_item.setItemMeta(shop_itemmeta); + } + + if (plugin.getConfig().getBoolean(ArenaConfigStrings.CONFIG_CLASSES_ENABLED)) + { + p.getInventory().addItem(classes_item); + } + if (pli.isAchievementGuiEnabled() && pli.getAchievementsConfig().getConfig().getBoolean("config.enabled")) + { + p.getInventory().addItem(achievement_item); + } + if (plugin.getConfig().getBoolean(ArenaConfigStrings.CONFIG_SHOP_ENABLED)) + { + p.getInventory().addItem(shop_item); + } + p.updateInventory(); + + // custom lobby item + if (plugin.getConfig().getBoolean(ArenaConfigStrings.CONFIG_EXTRA_LOBBY_ITEM_PREFIX + "item0" + ArenaConfigStrings.CONFIG_EXTRA_LOBBY_ITEM_ENABLED_SUFFIX)) + { + final ItemStack custom_item0 = new ItemStack(plugin.getConfig().getInt(ArenaConfigStrings.CONFIG_EXTRA_LOBBY_ITEM_PREFIX + "item0" + ArenaConfigStrings.CONFIG_EXTRA_LOBBY_ITEM_ITEM_SUFFIX)); + if (custom_item0.getType() != Material.AIR) + { + final ItemMeta custom_item0meta = custom_item0.getItemMeta(); + custom_item0meta.setDisplayName(plugin.getConfig().getString(ArenaConfigStrings.CONFIG_EXTRA_LOBBY_ITEM_PREFIX + "item0" + ArenaConfigStrings.CONFIG_EXTRA_LOBBY_ITEM_NAME_SUFFIX)); + custom_item0.setItemMeta(custom_item0meta); + } + p.getInventory().addItem(custom_item0); + p.updateInventory(); + } + } + + public static void giveSpectatorItems(final JavaPlugin plugin, final Player p) + { + final PluginInstance pli = MinigamesAPI.getAPI().getPluginInstance(plugin); + final ItemStack s_item = new ItemStack(plugin.getConfig().getInt(ArenaConfigStrings.CONFIG_SPECTATOR_ITEM)); + final ItemMeta s_imeta = s_item.getItemMeta(); + s_imeta.setDisplayName(pli.getMessagesConfig().spectator_item); + s_item.setItemMeta(s_imeta); + + final ItemStack exit_item = new ItemStack(plugin.getConfig().getInt(ArenaConfigStrings.CONFIG_EXIT_ITEM)); + final ItemMeta exitimeta = exit_item.getItemMeta(); + exitimeta.setDisplayName(pli.getMessagesConfig().exit_item); + exit_item.setItemMeta(exitimeta); + + p.getInventory().addItem(s_item); + p.getInventory().setItem(8, exit_item); + p.updateInventory(); + } + + public static void sendMessage(final Player p, final String arenaname, final String msgraw) + { + final String[] msgs = msgraw.replaceAll("<player>", p.getName()).replaceAll("<arena>", arenaname).split(";"); + for (final String msg : msgs) + { + p.sendMessage(msgs); + } + } + + public static void sendMessage(final JavaPlugin plugin, final Player p, final String msgraw) + { + if (msgraw.equalsIgnoreCase("")) + { + return; + } + final String[] msgs = msgraw.replace("<player>", p.getName()).replace("<game>", plugin.getName()).split(";"); + for (final String msg : msgs) + { + p.sendMessage(msg); + } + } + + public static ItemStack getCustomHead(final String name) + { + final ItemStack item = new ItemStack(Material.SKULL_ITEM, 1, (short) 3); + final SkullMeta skullmeta = (SkullMeta) item.getItemMeta(); + skullmeta.setOwner(name); + item.setItemMeta(skullmeta); + return item; + } + + public static void spawnPowerup(final JavaPlugin plugin, final Arena a, final Location l, final ItemStack item) + { + final World w = l.getWorld(); + final Chicken c = w.spawn(l, Chicken.class); + c.addPotionEffect(new PotionEffect(PotionEffectType.INVISIBILITY, 100000, 100000)); + final Item i = w.dropItem(l, item); + c.setPassenger(i); + if (plugin.getConfig().getBoolean(ArenaConfigStrings.CONFIG_POWERUP_BROADCAST)) + { + for (final String p_ : a.getAllPlayers()) + { + if (Validator.isPlayerOnline(p_)) + { + final Player p = Bukkit.getPlayer(p_); + p.sendMessage(MinigamesAPI.getAPI().getPluginInstance(plugin).getMessagesConfig().powerup_spawned); + } + } + } + if (plugin.getConfig().getBoolean(ArenaConfigStrings.CONFIG_POWERUP_FIREWORKS)) + { + Util.spawnFirework(l); + } + } + + static Random r = new Random(); + + public static void spawnFirework(final Player p) + { + Util.spawnFirework(p.getLocation()); + } + + public static void spawnFirework(final Location l) + { + final Firework fw = (Firework) l.getWorld().spawnEntity(l, EntityType.FIREWORK); + final FireworkMeta fwm = fw.getFireworkMeta(); + final FireworkEffect effect = FireworkEffect.builder().flicker(Util.r.nextBoolean()).withColor(Color.AQUA).withFade(Color.ORANGE).with(Type.BURST).trail(Util.r.nextBoolean()).build(); + fwm.addEffect(effect); + final int rp = Util.r.nextInt(2) + 1; + fwm.setPower(rp); + fw.setFireworkMeta(fwm); + } + + public static Color hexToRgb(final String colorStr) + { + return Color.fromRGB(Integer.valueOf(colorStr.substring(1, 3), 16), Integer.valueOf(colorStr.substring(3, 5), 16), Integer.valueOf(colorStr.substring(5, 7), 16)); + } + + public static class ValueComparator implements Comparator<String> + { + Map<String, Double> base; + + public ValueComparator(final Map<String, Double> base) + { + this.base = base; + } + + @Override + public int compare(final String a, final String b) + { + if (this.base.get(a) >= this.base.get(b)) + { + return -1; + } + else + { + return 1; + } + } + } + + public static class CompassPlayer + { + Player p = null; + Double d = null; + + public CompassPlayer(final Player p, final Double d) + { + this.p = p; + this.d = d; + } + + public Player getPlayer() + { + return this.p; + } + + public Double getDistance() + { + return this.d; + } + } + + public static CompassPlayer getNearestPlayer(final Player p, final Arena a) + { + CompassPlayer ret = null; + double distance = 10000; + for (final String p_ : a.getAllPlayers()) + { + if (!p_.equalsIgnoreCase(p.getName()) && !MinigamesAPI.getAPI().getPluginInstance(a.getPlugin()).containsGlobalLost(p_)) + { + if (Validator.isPlayerOnline(p_)) + { + final double newdist = Bukkit.getPlayer(p_).getLocation().distance(p.getLocation()); + if (newdist < distance) + { + distance = newdist; + ret = new CompassPlayer(Bukkit.getPlayer(p_), distance); + } + } + } + } + return ret; + } + + public static void sendStatsMessage(final PluginInstance pli, final Player p) + { + if (pli.getMessagesConfig().getConfig().isSet("messages.stats")) + { + final int kills_ = pli.getStatsInstance().getKills(p.getName()); + final int deaths_ = pli.getStatsInstance().getDeaths(p.getName()); + int money_ = 0; + if (MinigamesAPI.getAPI().economyAvailable()) + { + money_ = (int) MinigamesAPI.econ.getBalance(p.getName()); + } + + final String wins = Integer.toString(pli.getStatsInstance().getWins(p.getName())); + final String loses = Integer.toString(pli.getStatsInstance().getLoses(p.getName())); + final String kills = Integer.toString(kills_); + final String deaths = Integer.toString(deaths_); + final String money = Integer.toString(money_); + final String points = Integer.toString(pli.getStatsInstance().getPoints(p.getName())); + final String kdr = Integer.toString(Math.max(kills_, 1) / Math.max(deaths_, 1)); + for (final String key : pli.getMessagesConfig().getConfig().getConfigurationSection("messages.stats").getKeys(false)) + { + // Each line from the config gets checked for variables like <wins> or <money> and these get replaced by the values calculated above + final String msg = pli.getMessagesConfig().getConfig().getString("messages.stats." + key).replaceAll("<wins>", wins).replaceAll("<loses>", loses).replaceAll("<alltime_kills>", kills) + .replaceAll("<alltime_deaths>", deaths).replaceAll("<points>", points).replaceAll("<kdr>", kdr).replaceAll("<money>", money); + Util.sendMessage(pli.getPlugin(), p, ChatColor.translateAlternateColorCodes('&', msg)); + } + } + } + + public static void pushBack(final Location l, final Player p) + { + final Vector direction = l.toVector().subtract(p.getLocation().toVector()).normalize(); + p.setVelocity(direction); + if (p.isInsideVehicle()) + { + p.getVehicle().setVelocity(direction.multiply(2.2D)); + } + if (MinigamesAPI.SERVER_VERSION.isAtLeast(MinecraftVersionsType.V1_9)) + { + p.spawnParticle(Particle.PORTAL, p.getLocation(), 10); + } + } + + public static Score getScore(final Objective obj, final String text) + { + Score s = null; + Method getScore_ = null; + try + { + if (MinigamesAPI.SERVER_VERSION.isBelow(MinecraftVersionsType.V1_7_R4)) + { + getScore_ = obj.getClass().getDeclaredMethod("getScore", OfflinePlayer.class); + getScore_.setAccessible(true); + s = (Score) getScore_.invoke(obj, Bukkit.getOfflinePlayer(text)); + } + else + { + getScore_ = obj.getClass().getDeclaredMethod("getScore", String.class); + getScore_.setAccessible(true); + s = (Score) getScore_.invoke(obj, text); + } + } + catch (final Exception e) + { + if (MinigamesAPI.debug) + { + MinigamesAPI.getAPI().getLogger().log(Level.WARNING, "exception", e); + } + } + return s; + } + + public static void resetScores(final Scoreboard obj, final String text) + { + Method resetScores_ = null; + try + { + if (MinigamesAPI.SERVER_VERSION.isBelow(MinecraftVersionsType.V1_7_R4)) + { + resetScores_ = obj.getClass().getDeclaredMethod("resetScores", OfflinePlayer.class); + resetScores_.setAccessible(true); + resetScores_.invoke(obj, Bukkit.getOfflinePlayer(text)); + } + else + { + resetScores_ = obj.getClass().getDeclaredMethod("resetScores", String.class); + resetScores_.setAccessible(true); + resetScores_.invoke(obj, text); + } + } + catch (final Exception e) + { + if (MinigamesAPI.debug) + { + MinigamesAPI.getAPI().getLogger().log(Level.WARNING, "exception", e); + } + } + } + + public static void saveInventory(final Player player) + { + Util.armourContents.put(player.getName(), player.getInventory().getArmorContents()); + Util.inventoryContents.put(player.getName(), player.getInventory().getContents()); + Util.locations.put(player.getName(), player.getLocation()); + Util.xplevel.put(player.getName(), player.getLevel()); + Util.gamemode.put(player.getName(), player.getGameMode()); + player.getInventory().clear(); + } + + public static void restoreInventory(final Player player) + { + player.getInventory().clear(); + player.teleport(Util.locations.get(player.getName())); + + player.getInventory().setContents(Util.inventoryContents.get(player.getName())); + player.getInventory().setArmorContents(Util.armourContents.get(player.getName())); + player.setLevel(Util.xplevel.get(player.getName())); + player.setGameMode(Util.gamemode.get(player.getName())); + + Util.xplevel.remove(player.getName()); + Util.locations.remove(player.getName()); + Util.armourContents.remove(player.getName()); + Util.inventoryContents.remove(player.getName()); + } + + /** + * @param boundaries + */ + public static void clearDrops(Cuboid boundaries) + { + clearEntites(boundaries, e -> e instanceof Item); + } + + /** + * @param boundaries + */ + public static void clearEntites(Cuboid boundaries, Predicate<Entity> predicate) + { + if (boundaries != null && boundaries.getLowLoc() != null && boundaries.getHighLoc() != null) + { + // iterate through nearby entities + final Chunk lowChunk = boundaries.getLowLoc().getChunk(); + final Chunk highChunk = boundaries.getHighLoc().getChunk(); + final World world = boundaries.getWorld(); + for (int x = lowChunk.getX(); x <= highChunk.getX(); x++) + { + for (int z = lowChunk.getZ(); z <= highChunk.getZ(); z++) + { + final Chunk chunk = world.getChunkAt(x, z); + final Entity[] entities = chunk.getEntities(); + if (entities != null) + { + for (final Entity entity : entities) + { + if (predicate.test(entity) && boundaries.containsLoc(entity.getLocation())) + { + entity.remove(); + } + } + } + } + } + } + } } diff --git a/API/src/main/java/com/comze_instancelabs/minigamesapi/util/Validator.java b/API/src/main/java/com/comze_instancelabs/minigamesapi/util/Validator.java index 4c7f9e36..69b35995 100644 --- a/API/src/main/java/com/comze_instancelabs/minigamesapi/util/Validator.java +++ b/API/src/main/java/com/comze_instancelabs/minigamesapi/util/Validator.java @@ -1,5 +1,21 @@ +/* + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ package com.comze_instancelabs.minigamesapi.util; +import java.util.UUID; + import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.configuration.file.FileConfiguration; @@ -7,91 +23,149 @@ import org.bukkit.plugin.java.JavaPlugin; import com.comze_instancelabs.minigamesapi.Arena; +import com.comze_instancelabs.minigamesapi.ArenaConfigStrings; import com.comze_instancelabs.minigamesapi.ArenaLogger; import com.comze_instancelabs.minigamesapi.MinigamesAPI; +import com.comze_instancelabs.minigamesapi.PluginInstance; -public class Validator { - - /*** - * returns true if given player is online - * - * @param arena - * @return - */ - public static boolean isPlayerOnline(String player) { - Player p = Bukkit.getPlayer(player); - if (p != null) { - return true; - } - return false; - } - - /*** - * returns true if given player is online and in arena - * - * @param arena - * @return - */ - public static boolean isPlayerValid(JavaPlugin plugin, String player, Arena arena) { - return isPlayerValid(plugin, player, arena.getInternalName()); - } - - /*** - * returns true if given player is online and in arena - * - * @param arena - * @return - */ - public static boolean isPlayerValid(JavaPlugin plugin, String player, String arena) { - if (!isPlayerOnline(player)) { - return false; - } - if (!MinigamesAPI.getAPI().getPluginInstance(plugin).global_players.containsKey(player)) { - return false; - } - if (!MinigamesAPI.getAPI().getPluginInstance(plugin).global_players.get(player).getInternalName().equalsIgnoreCase(arena)) { - return false; - } - return true; - } - - /*** - * returns true if given arena was set up correctly - * - * @param arena - * @return - */ - public static boolean isArenaValid(JavaPlugin plugin, Arena arena) { - return isArenaValid(plugin, arena.getInternalName()); - } - - /*** - * returns true if given arena was set up correctly - * - * @param arena - * @return - */ - public static boolean isArenaValid(JavaPlugin plugin, String arena) { - FileConfiguration config = MinigamesAPI.getAPI().getPluginInstance(plugin).getArenasConfig().getConfig(); - if (!config.isSet("arenas." + arena + ".lobby") || !config.isSet("arenas." + arena + ".spawns.spawn0")) { - ArenaLogger.debug(ChatColor.AQUA + arena + " is invalid! lobby:" + config.isSet("arenas." + arena + ".lobby") + " spawns.spawn0:" + config.isSet("arenas." + arena + ".spawns.spawn0")); - return false; - } - return true; - } - - /*** - * returns true if given arena was set up correctly - * - * @param arena - * @return - */ - public static boolean isArenaValid(JavaPlugin plugin, String arena, FileConfiguration cf) { - FileConfiguration config = cf; - if (!config.isSet("arenas." + arena + ".lobby") || !config.isSet("arenas." + arena + ".spawns.spawn0")) { - return false; - } - return true; - } - +/** + * Validation helpers. + * + * @author instancelabs + */ +public class Validator +{ + + /*** + * returns true if given player is online + * + * @param player + * name of the player. + * @return true if the player is online. + */ + public static boolean isPlayerOnline(final String player) + { + final Player p = Bukkit.getPlayer(player); + if (p != null) + { + return true; + } + return false; + } + + /*** + * returns true if given player is online + * + * @param player + * name of the player. + * @return true if the player is online. + */ + public static boolean isPlayerOnline(final UUID player) + { + final Player p = Bukkit.getPlayer(player); + if (p != null) + { + return true; + } + return false; + } + + /*** + * returns true if given player is online and in arena + * + * @param plugin + * minigame java plugin. + * @param player + * the player name + * @param arena + * the arena + * @return {@code true} if the player is online and in given arena. + */ + public static boolean isPlayerValid(final JavaPlugin plugin, final String player, final Arena arena) + { + return Validator.isPlayerValid(plugin, player, arena.getInternalName()); + } + + /*** + * returns true if given player is online and in arena + * + * @param plugin + * the minigame java plugin + * @param player + * the player name + * @param arena + * the arena name + * @return {@code true} if the player is online and in given arena. + */ + public static boolean isPlayerValid(final JavaPlugin plugin, final String player, final String arena) + { + if (!Validator.isPlayerOnline(player)) + { + return false; + } + final PluginInstance pli = MinigamesAPI.getAPI().getPluginInstance(plugin); + if (!pli.global_players.containsKey(player)) + { + return false; + } + if (!pli.global_players.get(player).getInternalName().equalsIgnoreCase(arena)) + { + return false; + } + return true; + } + + /*** + * returns true if given arena was set up correctly; if it contains a lobby and at leats one spawn. + * + * @param plugin + * the minigame java plugin + * @param arena + * the arena to test + * @return {@code true} if the arena is valid + */ + public static boolean isArenaValid(final JavaPlugin plugin, final Arena arena) + { + return Validator.isArenaValid(plugin, arena.getInternalName()); + } + + /*** + * returns true if given arena was set up correctly + * + * @param plugin + * the minigame java plugin + * @param arena + * the arena to test + * @return {@code true} if the arena is valid + */ + public static boolean isArenaValid(final JavaPlugin plugin, final String arena) + { + final FileConfiguration config = MinigamesAPI.getAPI().getPluginInstance(plugin).getArenasConfig().getConfig(); + return isArenaValid(plugin, arena, config); + } + + /*** + * returns true if given arena was set up correctly + * + * @param plugin + * the minigame java plugin + * @param arena + * the arena to test + * @param cf + * the configuration to test + * @return {@code true} if the arena is valid + */ + public static boolean isArenaValid(final JavaPlugin plugin, final String arena, final FileConfiguration cf) + { + final FileConfiguration config = cf; + final boolean hasLobby = config.isSet(ArenaConfigStrings.ARENAS_PREFIX + arena + ".lobby"); + final boolean hasSpawn0 = config.isSet(ArenaConfigStrings.ARENAS_PREFIX + arena + ".spawns.spawn0"); + if (!hasLobby || !hasSpawn0) + { + ArenaLogger.debug(ChatColor.AQUA + arena + " is invalid! lobby:" + hasLobby + " spawns.spawn0:" + hasSpawn0); //$NON-NLS-1$ //$NON-NLS-2$ + return false; + } + return true; + } + } diff --git a/API/src/main/resources/config.yml b/API/src/main/resources/config.yml index aa8cbd60..e30466d6 100644 --- a/API/src/main/resources/config.yml +++ b/API/src/main/resources/config.yml @@ -1,4 +1,6 @@ -# MinigamesAPI Config # -# If you want bugfree versions, turn this to true: -config: - auto_updating: true +# MinigamesAPI Config # +# If you want bugfree versions, turn this to true: +# NO USE TRUE MODE! +config: + auto_updating: false +signs_updating_time: 20 diff --git a/API/src/main/resources/plugin.yml b/API/src/main/resources/plugin.yml index 05a2b086..e9c0eb82 100644 --- a/API/src/main/resources/plugin.yml +++ b/API/src/main/resources/plugin.yml @@ -1,17 +1,17 @@ -name: MinigamesLib -main: com.comze_instancelabs.minigamesapi.MinigamesAPI -version: 1.13.1 -author: InstanceLabs -softdepend: [Vault] -commands: - mapi: - description: Main command - usage: /mapi [action] - aliases: [mgapi, mglib] - party: - description: Main Party command - usage: /party [action] - start: - description: Start shortcut - usage: /start [action] - aliases: [startmg, startminigame] +name: MinigamesLib +main: com.comze_instancelabs.minigamesapi.MinigamesAPI +version: ${minigames.releaseversion}-${minigames.timestamp} +author: [InstanceLabs, MysticCity, MasteroftheHell, TheMrQuake, mepeisen] +softdepend: [Vault] +commands: + mapi: + description: Main command + usage: /mapi [action] + aliases: [mgapi, mglib] + party: + description: Main Party command + usage: /party [action] + start: + description: Start shortcut + usage: /start [action] + aliases: [startmg, startminigame] diff --git a/API/src/test/java/com/comze_instancelabs/minigamesapi/test/ArenaLoggerTest.java b/API/src/test/java/com/comze_instancelabs/minigamesapi/test/ArenaLoggerTest.java new file mode 100644 index 00000000..33a8a61b --- /dev/null +++ b/API/src/test/java/com/comze_instancelabs/minigamesapi/test/ArenaLoggerTest.java @@ -0,0 +1,637 @@ +/* + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +package com.comze_instancelabs.minigamesapi.test; + +import static com.comze_instancelabs.minigamesapi.spigottest.ArgUtil.argEquals; +import static com.comze_instancelabs.minigamesapi.spigottest.ArgUtil.argSupplier; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.argThat; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.powermock.api.mockito.PowerMockito.mock; +import static org.powermock.api.mockito.PowerMockito.when; + +import java.util.logging.Level; +import java.util.logging.LogRecord; +import java.util.logging.Logger; + +import org.junit.Test; +import org.mockito.ArgumentMatcher; + +import com.comze_instancelabs.minigamesapi.ArenaLogger; + +/** + * Test class for the arena logger. + * + * @author mepeisen + * @see ArenaLogger + */ +public class ArenaLoggerTest +{ + + /** arena name */ + private static final String ARENA = "ARENA"; //$NON-NLS-1$ + /** some message */ + private static final String MESSAGE = "SOME-MESSAGE"; //$NON-NLS-1$ + /** resulting message */ + private static final String RESULT = "[arena:" + ARENA + "] " + MESSAGE; //$NON-NLS-1$ //$NON-NLS-2$ + /** resulting message */ + private static final String RESULT_ENTRY = "[arena:" + ARENA + "] ENTRY"; //$NON-NLS-1$ //$NON-NLS-2$ + /** resulting message */ + private static final String RESULT_RETURN = "[arena:" + ARENA + "] RETURN"; //$NON-NLS-1$ //$NON-NLS-2$ + /** resulting message */ + private static final String RESULT_THROW = "[arena:" + ARENA + "] THROW"; //$NON-NLS-1$ //$NON-NLS-2$ + /** source class for logp */ + static final String SOURCE_CLASS = ArenaLoggerTest.class.getName(); + /** source method for logp */ + static final String SOURCE_METHOD = "someMethod"; //$NON-NLS-1$ + + /** + * Tests log method + */ + @Test + public void testSevere() + { + // prolog + final Logger logger = mock(Logger.class); + + // test + final ArenaLogger arenaLogger = new ArenaLogger(logger, ARENA); + arenaLogger.severe(MESSAGE); + + // epilog + verify(logger, times(1)).log(Level.SEVERE, RESULT); + } + + /** + * Tests log method + */ + @Test + public void testSevereLambda() + { + // prolog + final Logger logger = mock(Logger.class); + + // test + final ArenaLogger arenaLogger = new ArenaLogger(logger, ARENA); + arenaLogger.severe(() -> MESSAGE); + + // epilog + verify(logger, times(1)).log(argEquals(Level.SEVERE), argSupplier(RESULT)); + } + + /** + * Tests log method + */ + @Test + public void testWarning() + { + // prolog + final Logger logger = mock(Logger.class); + + // test + final ArenaLogger arenaLogger = new ArenaLogger(logger, ARENA); + arenaLogger.warning(MESSAGE); + + // epilog + verify(logger, times(1)).log(Level.WARNING, RESULT); + } + + /** + * Tests log method + */ + @Test + public void testWarningLambda() + { + // prolog + final Logger logger = mock(Logger.class); + + // test + final ArenaLogger arenaLogger = new ArenaLogger(logger, ARENA); + arenaLogger.warning(() -> MESSAGE); + + // epilog + verify(logger, times(1)).log(argEquals(Level.WARNING), argSupplier(RESULT)); + } + + /** + * Tests log method + */ + @Test + public void testInfo() + { + // prolog + final Logger logger = mock(Logger.class); + + // test + final ArenaLogger arenaLogger = new ArenaLogger(logger, ARENA); + arenaLogger.info(MESSAGE); + + // epilog + verify(logger, times(1)).log(Level.INFO, RESULT); + } + + /** + * Tests log method + */ + @Test + public void testInfoLambda() + { + // prolog + final Logger logger = mock(Logger.class); + + // test + final ArenaLogger arenaLogger = new ArenaLogger(logger, ARENA); + arenaLogger.info(() -> MESSAGE); + + // epilog + verify(logger, times(1)).log(argEquals(Level.INFO), argSupplier(RESULT)); + } + + /** + * Tests log method + */ + @Test + public void testConfig() + { + // prolog + final Logger logger = mock(Logger.class); + + // test + final ArenaLogger arenaLogger = new ArenaLogger(logger, ARENA); + arenaLogger.config(MESSAGE); + + // epilog + verify(logger, times(1)).log(Level.CONFIG, RESULT); + } + + /** + * Tests log method + */ + @Test + public void testConfigLambda() + { + // prolog + final Logger logger = mock(Logger.class); + + // test + final ArenaLogger arenaLogger = new ArenaLogger(logger, ARENA); + arenaLogger.config(() -> MESSAGE); + + // epilog + verify(logger, times(1)).log(argEquals(Level.CONFIG), argSupplier(RESULT)); + } + + /** + * Tests log method + */ + @Test + public void testFine() + { + // prolog + final Logger logger = mock(Logger.class); + + // test + final ArenaLogger arenaLogger = new ArenaLogger(logger, ARENA); + arenaLogger.fine(MESSAGE); + + // epilog + verify(logger, times(1)).log(Level.FINE, RESULT); + } + + /** + * Tests log method + */ + @Test + public void testFineLambda() + { + // prolog + final Logger logger = mock(Logger.class); + + // test + final ArenaLogger arenaLogger = new ArenaLogger(logger, ARENA); + arenaLogger.fine(() -> MESSAGE); + + // epilog + verify(logger, times(1)).log(argEquals(Level.FINE), argSupplier(RESULT)); + } + + /** + * Tests log method + */ + @Test + public void testFiner() + { + // prolog + final Logger logger = mock(Logger.class); + + // test + final ArenaLogger arenaLogger = new ArenaLogger(logger, ARENA); + arenaLogger.finer(MESSAGE); + + // epilog + verify(logger, times(1)).log(Level.FINER, RESULT); + } + + /** + * Tests log method + */ + @Test + public void testFinerLambda() + { + // prolog + final Logger logger = mock(Logger.class); + + // test + final ArenaLogger arenaLogger = new ArenaLogger(logger, ARENA); + arenaLogger.finer(() -> MESSAGE); + + // epilog + verify(logger, times(1)).log(argEquals(Level.FINER), argSupplier(RESULT)); + } + + /** + * Tests log method + */ + @Test + public void testFinest() + { + // prolog + final Logger logger = mock(Logger.class); + + // test + final ArenaLogger arenaLogger = new ArenaLogger(logger, ARENA); + arenaLogger.finest(MESSAGE); + + // epilog + verify(logger, times(1)).log(Level.FINEST, RESULT); + } + + /** + * Tests log method + */ + @Test + public void testFinestLambda() + { + // prolog + final Logger logger = mock(Logger.class); + + // test + final ArenaLogger arenaLogger = new ArenaLogger(logger, ARENA); + arenaLogger.finest(() -> MESSAGE); + + // epilog + verify(logger, times(1)).log(argEquals(Level.FINEST), argSupplier(RESULT)); + } + + /** + * Tests log method + */ + @Test + public void testLog() + { + // prolog + final Logger logger = mock(Logger.class); + + // test + final ArenaLogger arenaLogger = new ArenaLogger(logger, ARENA); + arenaLogger.log(Level.FINEST, MESSAGE); + + // epilog + verify(logger, times(1)).log(Level.FINEST, RESULT); + } + + /** + * Tests log method + */ + @Test + public void testLogLambda() + { + // prolog + final Logger logger = mock(Logger.class); + + // test + final ArenaLogger arenaLogger = new ArenaLogger(logger, ARENA); + arenaLogger.log(Level.FINEST, () -> MESSAGE); + + // epilog + verify(logger, times(1)).log(argEquals(Level.FINEST), argSupplier(RESULT)); + } + + /** + * Tests log method + */ + @Test + public void testLog2() + { + // prolog + final Logger logger = mock(Logger.class); + + // test + final ArenaLogger arenaLogger = new ArenaLogger(logger, ARENA); + final Object someObject = new Object(); + arenaLogger.log(Level.FINEST, MESSAGE, someObject); + + // epilog + verify(logger, times(1)).log(Level.FINEST, RESULT, someObject); + } + + /** + * Tests log method + */ + @Test + public void testLog3() + { + // prolog + final Logger logger = mock(Logger.class); + + // test + final ArenaLogger arenaLogger = new ArenaLogger(logger, ARENA); + final Object[] someObject = new Object[]{}; + arenaLogger.log(Level.FINEST, MESSAGE, someObject); + + // epilog + verify(logger, times(1)).log(Level.FINEST, RESULT, someObject); + } + + /** + * Tests log method + */ + @Test + public void testLog4() + { + // prolog + final Logger logger = mock(Logger.class); + + // test + final ArenaLogger arenaLogger = new ArenaLogger(logger, ARENA); + final Throwable someObject = new Exception(); + arenaLogger.log(Level.FINEST, MESSAGE, someObject); + + // epilog + verify(logger, times(1)).log(Level.FINEST, RESULT, someObject); + } + + /** + * Tests log method + */ + @Test + public void testLog4Lambda() + { + // prolog + final Logger logger = mock(Logger.class); + + // test + final ArenaLogger arenaLogger = new ArenaLogger(logger, ARENA); + final Throwable someObject = new Exception(); + arenaLogger.log(Level.FINEST, someObject, () -> MESSAGE); + + // epilog + verify(logger, times(1)).log(argEquals(Level.FINEST), argEquals(someObject), argSupplier(RESULT)); + } + + /** + * Tests log method + */ + @Test + public void testLogp() + { + // prolog + final Logger logger = mock(Logger.class); + + // test + final ArenaLogger arenaLogger = new ArenaLogger(logger, ARENA); + arenaLogger.logp(Level.FINEST, SOURCE_CLASS, SOURCE_METHOD, MESSAGE); + + // epilog + verify(logger, times(1)).logp(Level.FINEST, SOURCE_CLASS, SOURCE_METHOD, RESULT); + } + + /** + * Tests log method + */ + @Test + public void testLogpLambda() + { + // prolog + final Logger logger = mock(Logger.class); + + // test + final ArenaLogger arenaLogger = new ArenaLogger(logger, ARENA); + arenaLogger.logp(Level.FINEST, SOURCE_CLASS, SOURCE_METHOD, () -> MESSAGE); + + // epilog + verify(logger, times(1)).logp(argEquals(Level.FINEST), argEquals(SOURCE_CLASS), argEquals(SOURCE_METHOD), argSupplier(RESULT)); + } + + /** + * Tests log method + */ + @Test + public void testLogp2() + { + // prolog + final Logger logger = mock(Logger.class); + + // test + final ArenaLogger arenaLogger = new ArenaLogger(logger, ARENA); + final Object someObject = new Object(); + arenaLogger.logp(Level.FINEST, SOURCE_CLASS, SOURCE_METHOD, MESSAGE, someObject); + + // epilog + verify(logger, times(1)).logp(Level.FINEST, SOURCE_CLASS, SOURCE_METHOD, RESULT, someObject); + } + + /** + * Tests log method + */ + @Test + public void testLogp3() + { + // prolog + final Logger logger = mock(Logger.class); + + // test + final ArenaLogger arenaLogger = new ArenaLogger(logger, ARENA); + final Object[] someObject = new Object[]{}; + arenaLogger.logp(Level.FINEST, SOURCE_CLASS, SOURCE_METHOD, MESSAGE, someObject); + + // epilog + verify(logger, times(1)).logp(Level.FINEST, SOURCE_CLASS, SOURCE_METHOD, RESULT, someObject); + } + + /** + * Tests log method + */ + @Test + public void testLogp4() + { + // prolog + final Logger logger = mock(Logger.class); + + // test + final ArenaLogger arenaLogger = new ArenaLogger(logger, ARENA); + final Throwable someObject = new Exception(); + arenaLogger.logp(Level.FINEST, SOURCE_CLASS, SOURCE_METHOD, MESSAGE, someObject); + + // epilog + verify(logger, times(1)).logp(Level.FINEST, SOURCE_CLASS, SOURCE_METHOD, RESULT, someObject); + } + + /** + * Tests log method + */ + @Test + public void testLogp4Lambda() + { + // prolog + final Logger logger = mock(Logger.class); + + // test + final ArenaLogger arenaLogger = new ArenaLogger(logger, ARENA); + final Throwable someObject = new Exception(); + arenaLogger.logp(Level.FINEST, SOURCE_CLASS, SOURCE_METHOD, someObject, () -> MESSAGE); + + // epilog + verify(logger, times(1)).logp(argEquals(Level.FINEST), argEquals(SOURCE_CLASS), argEquals(SOURCE_METHOD), argEquals(someObject), argSupplier(RESULT)); + } + + /** + * Tests entering method + */ + @Test + public void testEntering() + { + // prolog + final Logger logger = mock(Logger.class); + + // test + final ArenaLogger arenaLogger = new ArenaLogger(logger, ARENA); + arenaLogger.entering(SOURCE_CLASS, SOURCE_METHOD); + + // epilog + verify(logger, times(1)).logp(Level.FINER, SOURCE_CLASS, SOURCE_METHOD, RESULT_ENTRY); + } + + /** + * Tests entering method + */ + @Test + public void testEntering2() + { + // prolog + final Logger logger = mock(Logger.class); + + // test + final ArenaLogger arenaLogger = new ArenaLogger(logger, ARENA); + final Object someObject = new Object(); + arenaLogger.entering(SOURCE_CLASS, SOURCE_METHOD, someObject); + + // epilog + verify(logger, times(1)).logp(Level.FINER, SOURCE_CLASS, SOURCE_METHOD, RESULT_ENTRY + " {0}", someObject); //$NON-NLS-1$ + } + + /** + * Tests entering method + */ + @Test + public void testEntering3() + { + // prolog + final Logger logger = mock(Logger.class); + when(logger.isLoggable(any())).thenReturn(Boolean.TRUE); + + // test + final ArenaLogger arenaLogger = new ArenaLogger(logger, ARENA); + final Object[] someObject = new Object[]{new Object(), new Object()}; + arenaLogger.entering(SOURCE_CLASS, SOURCE_METHOD, someObject); + + // epilog + verify(logger, times(1)).logp(Level.FINER, SOURCE_CLASS, SOURCE_METHOD, RESULT_ENTRY + " {0} {1}", someObject); //$NON-NLS-1$ + } + + /** + * Tests exiting method + */ + @Test + public void testExiting() + { + // prolog + final Logger logger = mock(Logger.class); + + // test + final ArenaLogger arenaLogger = new ArenaLogger(logger, ARENA); + arenaLogger.exiting(SOURCE_CLASS, SOURCE_METHOD); + + // epilog + verify(logger, times(1)).logp(Level.FINER, SOURCE_CLASS, SOURCE_METHOD, RESULT_RETURN); + } + + /** + * Tests exiting method + */ + @Test + public void testExiting2() + { + // prolog + final Logger logger = mock(Logger.class); + + // test + final ArenaLogger arenaLogger = new ArenaLogger(logger, ARENA); + final Object someObject = new Object(); + arenaLogger.exiting(SOURCE_CLASS, SOURCE_METHOD, someObject); + + // epilog + verify(logger, times(1)).logp(Level.FINER, SOURCE_CLASS, SOURCE_METHOD, RESULT_RETURN + " {0}", someObject); //$NON-NLS-1$ + } + + /** + * Tests throwing method + */ + @Test + public void testThrowing() + { + // prolog + final Logger logger = mock(Logger.class); + when(logger.isLoggable(any())).thenReturn(Boolean.TRUE); + + // test + final ArenaLogger arenaLogger = new ArenaLogger(logger, ARENA); + final Throwable someObject = new Exception(); + arenaLogger.throwing(SOURCE_CLASS, SOURCE_METHOD, someObject); + + // epilog + verify(logger, times(1)).log(argThat(new ArgumentMatcher<LogRecord>() { + + @Override + public boolean matches(Object argument) + { + final LogRecord lr = (LogRecord) argument; + final boolean m1 = lr.getSourceClassName().equals(SOURCE_CLASS); + final boolean m2 = lr.getSourceMethodName().equals(SOURCE_METHOD); + final boolean m3 = lr.getThrown().equals(someObject); + final boolean m4 = RESULT_THROW.equals(lr.getMessage()); + return m1 && m2 && m3 && m4(lr) && m4; + } + + private boolean m4(final LogRecord lr) + { + return Level.FINER == lr.getLevel(); + } + })); + } + +} diff --git a/API/src/test/java/com/comze_instancelabs/minigamesapi/test/ArenaPlayerTest.java b/API/src/test/java/com/comze_instancelabs/minigamesapi/test/ArenaPlayerTest.java new file mode 100644 index 00000000..90002b34 --- /dev/null +++ b/API/src/test/java/com/comze_instancelabs/minigamesapi/test/ArenaPlayerTest.java @@ -0,0 +1,235 @@ +/* + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +package com.comze_instancelabs.minigamesapi.test; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; +import static org.mockito.Matchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; +import static org.powermock.api.mockito.PowerMockito.mockStatic; + +import org.bukkit.Bukkit; +import org.bukkit.GameMode; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +import com.comze_instancelabs.minigamesapi.Arena; +import com.comze_instancelabs.minigamesapi.ArenaPlayer; +import com.comze_instancelabs.minigamesapi.util.AClass; + +/** + * Test case for the arena player class. + * + * @author mepeisen + * @see ArenaPlayer + */ +@RunWith(PowerMockRunner.class) +@PrepareForTest(Bukkit.class) +public class ArenaPlayerTest +{ + + /** + * tests if the player instances are created as needed. + */ + @Test + public void testCreatePlayerInstance() + { + // prolog + final String name = "ArenaPlayerTest#testCreatePlayerInstance"; //$NON-NLS-1$ + + final Player player = mock(Player.class); + when(player.getName()).thenReturn(name); + + mockStatic(Bukkit.class); + when(Bukkit.getPlayer(anyString())).thenReturn(player); + + // test + final ArenaPlayer arenaPlayer = ArenaPlayer.getPlayerInstance(name); + assertEquals(name, arenaPlayer.getPlayer().getName()); + } + + /** + * tests if the player instances are returned when already known. + */ + @Test + public void testCreatePlayerInstanceTwice() + { + // prolog + final String name = "ArenaPlayerTest#testCreatePlayerInstanceTwice"; //$NON-NLS-1$ + + final Player player = mock(Player.class); + when(player.getName()).thenReturn(name); + + mockStatic(Bukkit.class); + when(Bukkit.getPlayer(anyString())).thenReturn(player); + + // test + final ArenaPlayer arenaPlayer1 = ArenaPlayer.getPlayerInstance(name); + final ArenaPlayer arenaPlayer2 = ArenaPlayer.getPlayerInstance(name); + assertSame(arenaPlayer1, arenaPlayer2); + } + + /** + * tests the inventory setting + */ + @Test + public void testInventories() + { + // prolog + final String name = "ArenaPlayerTest#testInventories"; //$NON-NLS-1$ + + final Player player = mock(Player.class); + when(player.getName()).thenReturn(name); + + mockStatic(Bukkit.class); + when(Bukkit.getPlayer(anyString())).thenReturn(player); + + // test + final ArenaPlayer arenaPlayer = ArenaPlayer.getPlayerInstance(name); + assertNull(arenaPlayer.getInventory()); + assertNull(arenaPlayer.getArmorInventory()); + + final ItemStack[] inv = new ItemStack[]{new ItemStack(Material.AIR, 1)}; + final ItemStack[] armor_inv = new ItemStack[]{new ItemStack(Material.STONE, 1), new ItemStack(Material.WOOD, 1)}; + arenaPlayer.setInventories(inv, armor_inv); + + assertArrayEquals(inv, arenaPlayer.getInventory()); + assertArrayEquals(armor_inv, arenaPlayer.getArmorInventory()); + } + + /** + * tests the original gamemode setting + */ + @Test + public void testOriginalGamemode() + { + // prolog + final String name = "ArenaPlayerTest#testOriginalGamemode"; //$NON-NLS-1$ + + final Player player = mock(Player.class); + when(player.getName()).thenReturn(name); + + mockStatic(Bukkit.class); + when(Bukkit.getPlayer(anyString())).thenReturn(player); + + // test + final ArenaPlayer arenaPlayer = ArenaPlayer.getPlayerInstance(name); + assertEquals(GameMode.SURVIVAL, arenaPlayer.getOriginalGamemode()); + arenaPlayer.setOriginalGamemode(GameMode.CREATIVE); + assertEquals(GameMode.CREATIVE, arenaPlayer.getOriginalGamemode()); + } + + /** + * tests the original xp level + */ + @Test + public void testOriginalXpLevel() + { + // prolog + final String name = "ArenaPlayerTest#testOriginalXpLevel"; //$NON-NLS-1$ + + final Player player = mock(Player.class); + when(player.getName()).thenReturn(name); + + mockStatic(Bukkit.class); + when(Bukkit.getPlayer(anyString())).thenReturn(player); + + // test + final ArenaPlayer arenaPlayer = ArenaPlayer.getPlayerInstance(name); + assertEquals(0, arenaPlayer.getOriginalXplvl()); + arenaPlayer.setOriginalXplvl(100); + assertEquals(100, arenaPlayer.getOriginalXplvl()); + } + + /** + * tests the no reward flag + */ + @Test + public void testNoReward() + { + // prolog + final String name = "ArenaPlayerTest#testNoReward"; //$NON-NLS-1$ + + final Player player = mock(Player.class); + when(player.getName()).thenReturn(name); + + mockStatic(Bukkit.class); + when(Bukkit.getPlayer(anyString())).thenReturn(player); + + // test + final ArenaPlayer arenaPlayer = ArenaPlayer.getPlayerInstance(name); + assertFalse(arenaPlayer.isNoReward()); + arenaPlayer.setNoReward(true); + assertTrue(arenaPlayer.isNoReward()); + } + + /** + * tests the arena field + */ + @Test + public void testArena() + { + // prolog + final String name = "ArenaPlayerTest#testArena"; //$NON-NLS-1$ + + final Arena arena = mock(Arena.class); + final Player player = mock(Player.class); + when(player.getName()).thenReturn(name); + + mockStatic(Bukkit.class); + when(Bukkit.getPlayer(anyString())).thenReturn(player); + + // test + final ArenaPlayer arenaPlayer = ArenaPlayer.getPlayerInstance(name); + assertNull(arenaPlayer.getCurrentArena()); + arenaPlayer.setCurrentArena(arena); + assertSame(arena, arenaPlayer.getCurrentArena()); + } + + /** + * tests the class field + */ + @Test + public void testClass() + { + // prolog + final String name = "ArenaPlayerTest#testArena"; //$NON-NLS-1$ + + final AClass clazz = mock(AClass.class); + final Player player = mock(Player.class); + when(player.getName()).thenReturn(name); + + mockStatic(Bukkit.class); + when(Bukkit.getPlayer(anyString())).thenReturn(player); + + // test + final ArenaPlayer arenaPlayer = ArenaPlayer.getPlayerInstance(name); + assertNull(arenaPlayer.getCurrentClass()); + arenaPlayer.setCurrentClass(clazz); + assertSame(clazz, arenaPlayer.getCurrentClass()); + } + +} diff --git a/API/src/test/java/com/comze_instancelabs/minigamesapi/test/ArenaStateTest.java b/API/src/test/java/com/comze_instancelabs/minigamesapi/test/ArenaStateTest.java new file mode 100644 index 00000000..fd656660 --- /dev/null +++ b/API/src/test/java/com/comze_instancelabs/minigamesapi/test/ArenaStateTest.java @@ -0,0 +1,72 @@ +/* + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +package com.comze_instancelabs.minigamesapi.test; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +import com.comze_instancelabs.minigamesapi.ArenaState; + +/** + * Test case for arena states enumeration. + * + * @author mepeisen + * + * @see ArenaState + */ +public class ArenaStateTest +{ + + /** + * Test the ordinals + */ + @Test + public void testOrdinals() + { + assertEquals(0, ArenaState.JOIN.ordinal()); + assertEquals(1, ArenaState.STARTING.ordinal()); + assertEquals(2, ArenaState.INGAME.ordinal()); + assertEquals(3, ArenaState.RESTARTING.ordinal()); + } + + /** + * Test the values method + */ + @Test + public void testValues() + { + final ArenaState[] types = ArenaState.values(); + assertEquals(4, types.length); + assertEquals(ArenaState.JOIN, types[0]); + assertEquals(ArenaState.STARTING, types[1]); + assertEquals(ArenaState.INGAME, types[2]); + assertEquals(ArenaState.RESTARTING, types[3]); + } + + /** + * Test the valueOf method + */ + @Test + public void testValueOf() + { + assertEquals(ArenaState.JOIN, ArenaState.valueOf("JOIN")); //$NON-NLS-1$ + assertEquals(ArenaState.STARTING, ArenaState.valueOf("STARTING")); //$NON-NLS-1$ + assertEquals(ArenaState.INGAME, ArenaState.valueOf("INGAME")); //$NON-NLS-1$ + assertEquals(ArenaState.RESTARTING, ArenaState.valueOf("RESTARTING")); //$NON-NLS-1$ + } + +} diff --git a/API/src/test/java/com/comze_instancelabs/minigamesapi/test/ArenaTest.java b/API/src/test/java/com/comze_instancelabs/minigamesapi/test/ArenaTest.java new file mode 100644 index 00000000..210e9330 --- /dev/null +++ b/API/src/test/java/com/comze_instancelabs/minigamesapi/test/ArenaTest.java @@ -0,0 +1,455 @@ +/* + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +package com.comze_instancelabs.minigamesapi.test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.powermock.api.mockito.PowerMockito.mock; + +import java.util.ArrayList; +import java.util.UUID; + +import org.bukkit.GameMode; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.World; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; +import org.bukkit.util.Vector; +import org.junit.Test; + +import com.comze_instancelabs.minigamesapi.Arena; +import com.comze_instancelabs.minigamesapi.ArenaConfigStrings; +import com.comze_instancelabs.minigamesapi.ArenaPlayer; +import com.comze_instancelabs.minigamesapi.ArenaState; +import com.comze_instancelabs.minigamesapi.ArenaType; +import com.comze_instancelabs.minigamesapi.ChannelStrings; +import com.comze_instancelabs.minigamesapi.testutil.TestUtil; + +/** + * The tester for the arena class. + * + * @author mepeisen + * + * @see Arena + */ +public class ArenaTest extends TestUtil +{ + + /** the default arena name. */ + private static final String ARENA = "junit-arena"; //$NON-NLS-1$ + + /** the default arena name. */ + private static final String ARENA2 = "junit-arena2"; //$NON-NLS-1$ + + /** the default arena name. */ + private static final String ARENA3 = "junit-arena3"; //$NON-NLS-1$ + + /** the player name. */ + private static final String PLAYER1 = "player1"; //$NON-NLS-1$ + + /** the player name. */ + private static final String PLAYER2 = "player2"; //$NON-NLS-1$ + + /** the player name. */ + private static final String PLAYER3 = "player3"; //$NON-NLS-1$ + + /** the junit minigame. */ + private static final String MINIGAME = "$JUNIT-ARENA-TEST"; //$NON-NLS-1$ + + /** + * Tests the arena class constructor. + */ + @Test + public void testConstructor() + { + final Minigame minigame = this.minigameTest.setupMinigame(MINIGAME + "Constructor"); //$NON-NLS-1$ + final Arena arena = new Arena(minigame.javaPlugin, ARENA); + + assertSame(arena.getPlugin(), minigame.javaPlugin); + assertSame(arena.getPluginInstance(), minigame.pluginInstance); + assertEquals(ARENA, arena.getInternalName()); + assertEquals(ARENA, arena.getInternalName()); + assertEquals(ARENA, arena.getName()); + assertEquals(ArenaType.DEFAULT, arena.getArenaType()); + + assertSame(arena, arena.getArena()); + } + + /** + * Tests the arena class constructor. + */ + @Test + public void testConstructorType() + { + final Minigame minigame = this.minigameTest.setupMinigame(MINIGAME + "ConstructorType"); //$NON-NLS-1$ + final Arena arena = new Arena(minigame.javaPlugin, ARENA, ArenaType.JUMPNRUN); + + assertSame(arena.getPlugin(), minigame.javaPlugin); + assertSame(arena.getPluginInstance(), minigame.pluginInstance); + assertEquals(ARENA, arena.getInternalName()); + assertEquals(ARENA, arena.getInternalName()); + assertEquals(ARENA, arena.getName()); + assertEquals(ArenaType.JUMPNRUN, arena.getArenaType()); + } + + /** + * Tests the init method call. + */ + @Test + public void testInit() + { + this.initWorld("world"); //$NON-NLS-1$ + final Minigame minigame = this.minigameTest.setupMinigame(MINIGAME + "Init", (mg) -> { //$NON-NLS-1$ + mg.addArenaComponentToConfig(ARENA3, "lobby", "world", 1, 1, 1, 80, 80); //$NON-NLS-1$ //$NON-NLS-2$ + mg.addArenaComponentToConfig(ARENA3, "spawns.spawn0", "world", 1, 1, 1, 80, 80); //$NON-NLS-1$ //$NON-NLS-2$ + + mg.addArenaComponentToConfig(ARENA3, ArenaConfigStrings.BOUNDS_LOW, "world", 1, 2, 3, 80, 80); //$NON-NLS-1$ + mg.addArenaComponentToConfig(ARENA3, ArenaConfigStrings.BOUNDS_HIGH, "world", 2, 3, 4, 80, 80); //$NON-NLS-1$ + + mg.addArenaComponentToConfig(ARENA3, ArenaConfigStrings.LOBBY_BOUNDS_LOW, "world", 3, 4, 5, 80, 80); //$NON-NLS-1$ + mg.addArenaComponentToConfig(ARENA3, ArenaConfigStrings.LOBBY_BOUNDS_HIGH, "world", 4, 5, 6, 80, 80); //$NON-NLS-1$ + + mg.addArenaComponentToConfig(ARENA3, ArenaConfigStrings.SPEC_BOUNDS_LOW, "world", 5, 6, 7, 80, 80); //$NON-NLS-1$ + mg.addArenaComponentToConfig(ARENA3, ArenaConfigStrings.SPEC_BOUNDS_HIGH, "world", 6, 7, 8, 80, 80); //$NON-NLS-1$ + + mg.addArenaComponentToConfig(ARENA3, ArenaConfigStrings.SPEC_SPAWN, "world", 9, 10, 11, 80, 80); //$NON-NLS-1$ + + mg.arenasYml.set("arenas." + ARENA3 + ".displayname", "FOO"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + mg.arenasYml.set("arenas." + ARENA3 + ".showscoreboard", Boolean.FALSE); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + }); + + // 1) normal init with unknown arena + final Arena arena = new Arena(minigame.javaPlugin, ARENA); + + final Location signLoc = new Location(null, 1, 1, 1); + + final ArrayList<Location> spawns = new ArrayList<>(); + spawns.add(new Location(null, 2, 2, 2)); + spawns.add(new Location(null, 3, 3, 3)); + + final Location mainlobby = new Location(null, 4, 4, 4); + + final Location waitinglobby = new Location(null, 5, 5, 5); + + arena.init(signLoc, spawns, mainlobby, waitinglobby, 10, 2, false); + + assertEquals(1, arena.getSignLocation().getX(), 0); + assertEquals(1, arena.getSignLocation().getY(), 0); + assertEquals(1, arena.getSignLocation().getZ(), 0); + + assertEquals(2, arena.getSpawns().size()); + assertEquals(2, arena.getSpawns().get(0).getX(), 0); + assertEquals(2, arena.getSpawns().get(0).getY(), 0); + assertEquals(2, arena.getSpawns().get(0).getZ(), 0); + assertEquals(3, arena.getSpawns().get(1).getX(), 0); + assertEquals(3, arena.getSpawns().get(1).getY(), 0); + assertEquals(3, arena.getSpawns().get(1).getZ(), 0); + + assertEquals(4, arena.getMainLobby().getX(), 0); + assertEquals(4, arena.getMainLobby().getY(), 0); + assertEquals(4, arena.getMainLobby().getZ(), 0); + + assertEquals(5, arena.getWaitingLobby().getX(), 0); + assertEquals(5, arena.getWaitingLobby().getY(), 0); + assertEquals(5, arena.getWaitingLobby().getZ(), 0); + + assertFalse(arena.isVIPArena()); + assertEquals(2, arena.getMinPlayers()); + assertEquals(10, arena.getMaxPlayers()); + + assertTrue(arena.isSuccessfullyInit()); + + // default values + assertTrue(arena.getShowScoreboard()); + assertFalse(arena.getAlwaysPvP()); + + // setters + arena.setAlwaysPvP(true); + assertTrue(arena.getAlwaysPvP()); + + final Location l2 = new Location(null, -1, -2, -3); + arena.setSignLocation(l2); + assertEquals(-1, arena.getSignLocation().getX(), 0); + assertEquals(-2, arena.getSignLocation().getY(), 0); + assertEquals(-3, arena.getSignLocation().getZ(), 0); + + arena.setMinPlayers(17); + arena.setMaxPlayers(25); + assertEquals(17, arena.getMinPlayers()); + assertEquals(25, arena.getMaxPlayers()); + + arena.setVIPArena(true); + assertTrue(arena.isVIPArena()); + assertEquals(ArenaState.JOIN, arena.getArenaState()); + + // player management + assertEquals(0, arena.getAllPlayers().size()); + arena.addPlayer(PLAYER1); + assertEquals(1, arena.getAllPlayers().size()); + assertEquals(PLAYER1, arena.getAllPlayers().get(0)); + assertTrue(arena.containsPlayer(PLAYER1)); + assertFalse(arena.containsPlayer(PLAYER2)); + assertFalse(arena.containsPlayer(PLAYER3)); + arena.addPlayer(PLAYER2); + assertEquals(2, arena.getAllPlayers().size()); + assertEquals(PLAYER1, arena.getAllPlayers().get(0)); + assertEquals(PLAYER2, arena.getAllPlayers().get(1)); + assertTrue(arena.containsPlayer(PLAYER1)); + assertTrue(arena.containsPlayer(PLAYER2)); + assertFalse(arena.containsPlayer(PLAYER3)); + arena.addPlayer(PLAYER3); + assertEquals(3, arena.getAllPlayers().size()); + assertEquals(PLAYER1, arena.getAllPlayers().get(0)); + assertEquals(PLAYER2, arena.getAllPlayers().get(1)); + assertEquals(PLAYER3, arena.getAllPlayers().get(2)); + assertTrue(arena.containsPlayer(PLAYER1)); + assertTrue(arena.containsPlayer(PLAYER2)); + assertTrue(arena.containsPlayer(PLAYER3)); + arena.removePlayer(PLAYER2); + assertEquals(2, arena.getAllPlayers().size()); + assertEquals(PLAYER1, arena.getAllPlayers().get(0)); + assertEquals(PLAYER3, arena.getAllPlayers().get(1)); + assertTrue(arena.containsPlayer(PLAYER1)); + assertFalse(arena.containsPlayer(PLAYER2)); + assertTrue(arena.containsPlayer(PLAYER3)); + + + + // 2) init without spawns, deprecated method (should be changed to init as soon as we remove the method) + final Arena arena2 = new Arena(minigame.javaPlugin, ARENA2); + arena2.initArena(signLoc, null, mainlobby, waitinglobby, 5, 4, true); + + assertEquals(1, arena2.getSignLocation().getX(), 0); + assertEquals(1, arena2.getSignLocation().getY(), 0); + assertEquals(1, arena2.getSignLocation().getZ(), 0); + + assertEquals(0, arena2.getSpawns().size()); + assertEquals(4, arena2.getMainLobby().getX(), 0); + assertEquals(4, arena2.getMainLobby().getY(), 0); + assertEquals(4, arena2.getMainLobby().getZ(), 0); + + assertEquals(5, arena2.getWaitingLobby().getX(), 0); + assertEquals(5, arena2.getWaitingLobby().getY(), 0); + assertEquals(5, arena2.getWaitingLobby().getZ(), 0); + + assertTrue(arena2.isVIPArena()); + assertEquals(4, arena2.getMinPlayers()); + assertEquals(5, arena2.getMaxPlayers()); + + assertTrue(arena2.isSuccessfullyInit()); + + + + // 3) init configured arena + final Arena arena3 = new Arena(minigame.javaPlugin, ARENA3); + arena3.init(signLoc, null, mainlobby, waitinglobby, 5, 4, true); + + assertEquals(1, arena3.getBoundaries().getLowLoc().getX(), 0); + assertEquals(2, arena3.getBoundaries().getLowLoc().getY(), 0); + assertEquals(3, arena3.getBoundaries().getLowLoc().getZ(), 0); + assertEquals(2, arena3.getBoundaries().getHighLoc().getX(), 0); + assertEquals(3, arena3.getBoundaries().getHighLoc().getY(), 0); + assertEquals(4, arena3.getBoundaries().getHighLoc().getZ(), 0); + + assertEquals(3, arena3.getLobbyBoundaries().getLowLoc().getX(), 0); + assertEquals(4, arena3.getLobbyBoundaries().getLowLoc().getY(), 0); + assertEquals(5, arena3.getLobbyBoundaries().getLowLoc().getZ(), 0); + assertEquals(4, arena3.getLobbyBoundaries().getHighLoc().getX(), 0); + assertEquals(5, arena3.getLobbyBoundaries().getHighLoc().getY(), 0); + assertEquals(6, arena3.getLobbyBoundaries().getHighLoc().getZ(), 0); + + assertEquals(5, arena3.getSpecBoundaries().getLowLoc().getX(), 0); + assertEquals(6, arena3.getSpecBoundaries().getLowLoc().getY(), 0); + assertEquals(7, arena3.getSpecBoundaries().getLowLoc().getZ(), 0); + assertEquals(6, arena3.getSpecBoundaries().getHighLoc().getX(), 0); + assertEquals(7, arena3.getSpecBoundaries().getHighLoc().getY(), 0); + assertEquals(8, arena3.getSpecBoundaries().getHighLoc().getZ(), 0); + + // additional configs + assertEquals("FOO", arena3.getDisplayName()); //$NON-NLS-1$ + assertFalse(arena3.getShowScoreboard()); + } + + /** + * Tests joining the lobby and waiting for the game to start. + */ + @Test + public void testJoinLobbyAndWait() + { + final World world = this.initFlatWorld("world"); //$NON-NLS-1$ + final Minigame minigame = this.minigameTest.setupMinigame(MINIGAME + "NormalGame", (mg) -> { //$NON-NLS-1$ + mg.addArenaComponentToConfig(ARENA, "lobby", "world", 1, 1, 1, 80, 80); //$NON-NLS-1$ //$NON-NLS-2$ + mg.addArenaComponentToConfig(ARENA, "spawns.spawn0", "world", 1, 1, 1, 80, 80); //$NON-NLS-1$ //$NON-NLS-2$ + + mg.addArenaComponentToConfig(ARENA, "sign", "world", 1, 1, 1, 80, 80); //$NON-NLS-1$ //$NON-NLS-2$ + + mg.addArenaComponentToConfig(ARENA, ArenaConfigStrings.BOUNDS_LOW, "world", 1, 2, 3, 80, 80); //$NON-NLS-1$ + mg.addArenaComponentToConfig(ARENA, ArenaConfigStrings.BOUNDS_HIGH, "world", 2, 3, 4, 80, 80); //$NON-NLS-1$ + + mg.addArenaComponentToConfig(ARENA, ArenaConfigStrings.LOBBY_BOUNDS_LOW, "world", 3, 4, 5, 80, 80); //$NON-NLS-1$ + mg.addArenaComponentToConfig(ARENA, ArenaConfigStrings.LOBBY_BOUNDS_HIGH, "world", 4, 5, 6, 80, 80); //$NON-NLS-1$ + + mg.addArenaComponentToConfig(ARENA, ArenaConfigStrings.SPEC_BOUNDS_LOW, "world", 5, 6, 7, 80, 80); //$NON-NLS-1$ + mg.addArenaComponentToConfig(ARENA, ArenaConfigStrings.SPEC_BOUNDS_HIGH, "world", 6, 7, 8, 80, 80); //$NON-NLS-1$ + + mg.addArenaComponentToConfig(ARENA, ArenaConfigStrings.SPEC_SPAWN, "world", 9, 10, 11, 80, 80); //$NON-NLS-1$ + + mg.arenasYml.set("arenas." + ARENA + ".author", "JUNIT-AUTHOR"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + mg.arenasYml.set("arenas." + ARENA + ".description", "JUNIT TEST CASE"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + + // old config name, ensures it is migrated to newer version because config.version is not set... + mg.javaPlugin.getConfig().set("config.exit_item", Integer.valueOf(1)); + + //mg.add + }); + + minigame.pluginInstance.getMessagesConfig().you_joined_arena = "<player> joined <arena> of <game>"; //$NON-NLS-1$ + minigame.pluginInstance.getMessagesConfig().minigame_description = "description"; //$NON-NLS-1$ + minigame.pluginInstance.getMessagesConfig().author_of_the_map = "<arena> was created by <author>"; //$NON-NLS-1$ + minigame.pluginInstance.getMessagesConfig().description_of_the_map = "<arena> description: <description>"; //$NON-NLS-1$ + minigame.pluginInstance.getMessagesConfig().broadcast_player_joined = "<player> joined arena <count>/<maxcount>"; //$NON-NLS-1$ + + minigame.pluginInstance.getMessagesConfig().exit_item = "EXIT"; //$NON-NLS-1$ + + final Arena arena = new Arena(minigame.javaPlugin, ARENA); + final Location signLoc = new Location(world, 1, 1, 1); + final ArrayList<Location> spawns = new ArrayList<>(); + spawns.add(new Location(world, 2, 2, 2)); + spawns.add(new Location(world, 3, 3, 3)); + final Location mainlobby = new Location(world, 4, 4, 4); + final Location waitinglobby = new Location(world, 5, 5, 5); + arena.init(signLoc, null, mainlobby, waitinglobby, 5, 3, false); + + final Player player1 = this.mockOnlinePlayer(PLAYER1, UUID.randomUUID()); + final Player player2 = this.mockOnlinePlayer(PLAYER2, UUID.randomUUID()); + player1.getInventory().addItem(new ItemStack(Material.APPLE, 12)); + player1.getInventory().setBoots(new ItemStack(Material.GOLD_BOOTS, 1)); + when(player1.getGameMode()).thenReturn(GameMode.CREATIVE); + when(player1.getLevel()).thenReturn(16); + when(player2.getGameMode()).thenReturn(GameMode.ADVENTURE); + when(player2.getLevel()).thenReturn(17); + when(player2.isInsideVehicle()).thenReturn(true); + final Entity vehicle = mock(Entity.class); + when(player2.getVehicle()).thenReturn(vehicle); + + // join the lobby + arena.joinPlayerLobby(PLAYER1); + arena.joinPlayerLobby(PLAYER2); + assertTrue(arena.containsPlayer(PLAYER1)); + assertTrue(arena.containsPlayer(PLAYER2)); + + // verify messages + verify(player1, times(1)).sendMessage(PLAYER1 + " joined " + ARENA + " of " + MINIGAME + "NormalGame"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + verify(player2, times(1)).sendMessage(PLAYER2 + " joined " + ARENA + " of " + MINIGAME + "NormalGame"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + verify(player1, times(1)).sendMessage("description"); //$NON-NLS-1$ + verify(player2, times(1)).sendMessage("description"); //$NON-NLS-1$ + verify(player1, times(1)).sendMessage(ARENA + " was created by JUNIT-AUTHOR"); //$NON-NLS-1$ + verify(player2, times(1)).sendMessage(ARENA + " was created by JUNIT-AUTHOR"); //$NON-NLS-1$ + verify(player1, times(1)).sendMessage(ARENA + " description: JUNIT TEST CASE"); //$NON-NLS-1$ + verify(player2, times(1)).sendMessage(ARENA + " description: JUNIT TEST CASE"); //$NON-NLS-1$ + + verify(player1, times(1)).sendMessage(PLAYER2 + " joined arena 2/5"); //$NON-NLS-1$ + + for (int i = 0; i < 15; i++) this.tick(); + + // verify saved inv/gamemode etc. + final ArenaPlayer aplayer1 = ArenaPlayer.getPlayerInstance(PLAYER1); + final ArenaPlayer aplayer2 = ArenaPlayer.getPlayerInstance(PLAYER2); + assertEquals(GameMode.CREATIVE, aplayer1.getOriginalGamemode()); + assertEquals(16, aplayer1.getOriginalXplvl()); + assertEquals(GameMode.ADVENTURE, aplayer2.getOriginalGamemode()); + assertEquals(17, aplayer2.getOriginalXplvl()); + + final ItemStack[] savedInv = aplayer1.getInventory(); + assertNotNull(savedInv[0]); + assertEquals(12, savedInv[0].getAmount()); + assertEquals(Material.APPLE, savedInv[0].getType()); + for (int i = 1; i < savedInv.length - 5; i++) assertNull(savedInv[i]); // -5 to skip the armory contents (the boots) + final ItemStack[] savedArmor = aplayer1.getArmorInventory(); + assertNotNull(savedArmor[0]); + assertEquals(1, savedArmor[0].getAmount()); + assertEquals(Material.GOLD_BOOTS, savedArmor[0].getType()); + for (int i = 1; i < savedArmor.length; i++) assertNull(savedArmor[i]); + + // check for cleared/lobby inventory + final ItemStack exitItem = new ItemStack(1); + final ItemMeta exitItemMeta = exitItem.getItemMeta(); + exitItemMeta.setDisplayName("EXIT"); //$NON-NLS-1$ + exitItem.setItemMeta(exitItemMeta); + final ItemStack[] newInv = player1.getInventory().getContents(); + for (int i = 0; i < newInv.length; i++) + { + // check for giveLobbyItems + if (i == 8) assertEquals(exitItem, newInv[i]); + else assertNull(newInv[i]); + } + final ItemStack[] newArmor = player1.getInventory().getArmorContents(); + for (int i = 0; i < newArmor.length; i++) assertNull(newArmor[i]); + + // verify set game mode survival + verify(player1, times(1)).setGameMode(GameMode.SURVIVAL); + verify(player2, times(1)).setGameMode(GameMode.SURVIVAL); + + // verify set potion effect (heal) + // TODO Why are there three heal invocations? + verify(player1, times(2)).addPotionEffect(new PotionEffect(PotionEffectType.HEAL, 20 * 2, 50)); + verify(player2, times(2)).addPotionEffect(new PotionEffect(PotionEffectType.HEAL, 20 * 2, 50)); + verify(player1, times(1)).addPotionEffect(new PotionEffect(PotionEffectType.HEAL, 20 * 2, 30)); // From Util.teleportFixed + verify(player2, times(1)).addPotionEffect(new PotionEffect(PotionEffectType.HEAL, 20 * 2, 30)); // From Util.teleportFixed + + // verify teleport to lobby + verify(player1, times(1)).teleport(waitinglobby, TeleportCause.PLUGIN); + verify(player1, times(1)).setFallDistance(-1F); + verify(player1, times(1)).setVelocity(new Vector(0D, 0D, 0D)); + verify(player1, times(1)).setFireTicks(0); + verify(player2, times(1)).teleport(waitinglobby, TeleportCause.PLUGIN); + verify(player2, times(1)).setFallDistance(-1F); + verify(player2, times(1)).setVelocity(new Vector(0D, 0D, 0D)); + verify(player2, times(1)).setFireTicks(0); + verify(player2, times(1)).leaveVehicle(); + verify(vehicle, times(1)).eject(); + + // sign updates (bungee) + verifyPluginMessage(this.minigameTest.api, ChannelStrings.CHANNEL_BUNGEE_CORD, + "Forward", //$NON-NLS-1$ + "ALL", //$NON-NLS-1$ + ChannelStrings.SUBCHANNEL_MINIGAMESLIB_SIGN, + new Object[]{MINIGAME + "NormalGame:" + ARENA + ":" + ArenaState.JOIN.name() + ":1:5"}); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + + verifyPluginMessage(this.minigameTest.api, ChannelStrings.CHANNEL_BUNGEE_CORD, + "Forward", //$NON-NLS-1$ + "ALL", //$NON-NLS-1$ + ChannelStrings.SUBCHANNEL_MINIGAMESLIB_SIGN, + new Object[]{MINIGAME + "NormalGame:" + ARENA + ":" + ArenaState.JOIN.name() + ":2:5"}); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + + // TODO sendAllHolograms + // TODO sign updates (in current world) Util.updateSign + } + +} diff --git a/API/src/test/java/com/comze_instancelabs/minigamesapi/test/ArenaTypeTest.java b/API/src/test/java/com/comze_instancelabs/minigamesapi/test/ArenaTypeTest.java new file mode 100644 index 00000000..4c681f3b --- /dev/null +++ b/API/src/test/java/com/comze_instancelabs/minigamesapi/test/ArenaTypeTest.java @@ -0,0 +1,69 @@ +/* + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +package com.comze_instancelabs.minigamesapi.test; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +import com.comze_instancelabs.minigamesapi.ArenaType; + +/** + * Test case for arena types enumeration. + * + * @author mepeisen + * + * @see ArenaType + */ +public class ArenaTypeTest +{ + + /** + * Test the ordinals + */ + @Test + public void testOrdinals() + { + assertEquals(0, ArenaType.DEFAULT.ordinal()); + assertEquals(1, ArenaType.JUMPNRUN.ordinal()); + assertEquals(2, ArenaType.REGENERATION.ordinal()); + } + + /** + * Test the values method + */ + @Test + public void testValues() + { + final ArenaType[] types = ArenaType.values(); + assertEquals(3, types.length); + assertEquals(ArenaType.DEFAULT, types[0]); + assertEquals(ArenaType.JUMPNRUN, types[1]); + assertEquals(ArenaType.REGENERATION, types[2]); + } + + /** + * Test the valueOf method + */ + @Test + public void testValueOf() + { + assertEquals(ArenaType.DEFAULT, ArenaType.valueOf("DEFAULT")); //$NON-NLS-1$ + assertEquals(ArenaType.JUMPNRUN, ArenaType.valueOf("JUMPNRUN")); //$NON-NLS-1$ + assertEquals(ArenaType.REGENERATION, ArenaType.valueOf("REGENERATION")); //$NON-NLS-1$ + } + +} diff --git a/API/src/test/java/com/comze_instancelabs/minigamesapi/test/NestedIteratorTest.java b/API/src/test/java/com/comze_instancelabs/minigamesapi/test/NestedIteratorTest.java new file mode 100644 index 00000000..1ed3ecb7 --- /dev/null +++ b/API/src/test/java/com/comze_instancelabs/minigamesapi/test/NestedIteratorTest.java @@ -0,0 +1,231 @@ +/* + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +package com.comze_instancelabs.minigamesapi.test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.NoSuchElementException; +import java.util.TreeMap; + +import org.junit.Test; + +import com.comze_instancelabs.minigamesapi.SmartReset; + +/** + * Test case for smart resets nested iterator + * + * @author mepeisen + */ +public class NestedIteratorTest +{ + + /** + * Tests an empty nested map. + */ + @Test + public void testEmpty() + { + final Map<Integer, Map<Integer, Integer>> map = new HashMap<>(); + final Iterator<Integer> iter = new SmartReset.NestedIterator<>(map.values().iterator()); + assertFalse(iter.hasNext()); + } + + /** + * Tests an empty nested map. + */ + @Test(expected=NoSuchElementException.class) + public void testEmpty2() + { + final Map<Integer, Map<Integer, Integer>> map = new HashMap<>(); + final Iterator<Integer> iter = new SmartReset.NestedIterator<>(map.values().iterator()); + iter.next(); + } + + /** + * Tests an empty nested map. + */ + @Test(expected=IllegalStateException.class) + public void testEmpty3() + { + final Map<Integer, Map<Integer, Integer>> map = new HashMap<>(); + final Iterator<Integer> iter = new SmartReset.NestedIterator<>(map.values().iterator()); + iter.remove(); + } + + /** + * Tests a simple map. + */ + @Test + public void testSimple() + { + final Map<Integer, Map<Integer, Integer>> map = new HashMap<>(); + final Map<Integer, Integer> map1 = new HashMap<>(); + map.put(Integer.valueOf(10), map1); + map1.put(Integer.valueOf(10), Integer.valueOf(10)); + + final Iterator<Integer> iter = new SmartReset.NestedIterator<>(map.values().iterator()); + assertTrue(iter.hasNext()); + assertEquals(Integer.valueOf(10), iter.next()); + assertFalse(iter.hasNext()); + } + + /** + * Tests a simple map. + */ + @Test(expected=NoSuchElementException.class) + public void testSimple2() + { + final Map<Integer, Map<Integer, Integer>> map = new HashMap<>(); + final Map<Integer, Integer> map1 = new HashMap<>(); + map.put(Integer.valueOf(10), map1); + map1.put(Integer.valueOf(10), Integer.valueOf(10)); + + final Iterator<Integer> iter = new SmartReset.NestedIterator<>(map.values().iterator()); + iter.next(); + iter.next(); + } + + /** + * Tests a simple map. + */ + @Test(expected=NoSuchElementException.class) + public void testSimple3() + { + final Map<Integer, Map<Integer, Integer>> map = new HashMap<>(); + final Map<Integer, Integer> map1 = new HashMap<>(); + map.put(Integer.valueOf(10), map1); + map1.put(Integer.valueOf(10), Integer.valueOf(10)); + + final Iterator<Integer> iter = new SmartReset.NestedIterator<>(map.values().iterator()); + iter.next(); + iter.remove(); + assertEquals(0, map1.size()); + iter.next(); + } + + /** + * Tests a simple map. + */ + @Test(expected=IllegalStateException.class) + public void testSimple4() + { + final Map<Integer, Map<Integer, Integer>> map = new HashMap<>(); + final Map<Integer, Integer> map1 = new HashMap<>(); + map.put(Integer.valueOf(10), map1); + map1.put(Integer.valueOf(10), Integer.valueOf(10)); + + final Iterator<Integer> iter = new SmartReset.NestedIterator<>(map.values().iterator()); + iter.remove(); + } + + /** + * Tests a simple map. + */ + @Test(expected=IllegalStateException.class) + public void testSimple5() + { + final Map<Integer, Map<Integer, Integer>> map = new HashMap<>(); + final Map<Integer, Integer> map1 = new HashMap<>(); + map.put(Integer.valueOf(10), map1); + map1.put(Integer.valueOf(10), Integer.valueOf(10)); + + final Iterator<Integer> iter = new SmartReset.NestedIterator<>(map.values().iterator()); + iter.next(); + iter.remove(); + iter.remove(); + } + + /** + * Tests a empty nested map. + */ + @Test + public void testNestEmpty() + { + final Map<Integer, Map<Integer, Integer>> map = new HashMap<>(); + final Map<Integer, Integer> map1 = new HashMap<>(); + map.put(Integer.valueOf(10), map1); + + final Iterator<Integer> iter = new SmartReset.NestedIterator<>(map.values().iterator()); + assertFalse(iter.hasNext()); + } + + /** + * Tests a empty nested map. + */ + @Test(expected=NoSuchElementException.class) + public void testNestEmpty2() + { + final Map<Integer, Map<Integer, Integer>> map = new HashMap<>(); + final Map<Integer, Integer> map1 = new HashMap<>(); + map.put(Integer.valueOf(10), map1); + + final Iterator<Integer> iter = new SmartReset.NestedIterator<>(map.values().iterator()); + iter.next(); + } + + /** + * Tests a empty nested map. + */ + @Test(expected=IllegalStateException.class) + public void testNestEmpty3() + { + final Map<Integer, Map<Integer, Integer>> map = new HashMap<>(); + final Map<Integer, Integer> map1 = new HashMap<>(); + map.put(Integer.valueOf(10), map1); + + final Iterator<Integer> iter = new SmartReset.NestedIterator<>(map.values().iterator()); + iter.remove(); + } + + /** + * Tests a complex nested map. + */ + @Test + public void testNestComplex() + { + final Map<Integer, Map<Integer, Integer>> map = new TreeMap<>(); + final Map<Integer, Integer> map1 = new TreeMap<>(); + final Map<Integer, Integer> map2 = new TreeMap<>(); + final Map<Integer, Integer> map3 = new TreeMap<>(); + map.put(Integer.valueOf(10), map1); + map.put(Integer.valueOf(20), map2); + map.put(Integer.valueOf(30), map3); + map1.put(Integer.valueOf(10), Integer.valueOf(10)); + map1.put(Integer.valueOf(11), Integer.valueOf(11)); + map1.put(Integer.valueOf(12), Integer.valueOf(12)); + map3.put(Integer.valueOf(30), Integer.valueOf(30)); + map3.put(Integer.valueOf(31), Integer.valueOf(31)); + + final Iterator<Integer> iter = new SmartReset.NestedIterator<>(map.values().iterator()); + assertTrue(iter.hasNext()); + assertEquals(Integer.valueOf(10), iter.next()); + assertTrue(iter.hasNext()); + assertEquals(Integer.valueOf(11), iter.next()); + assertTrue(iter.hasNext()); + assertEquals(Integer.valueOf(12), iter.next()); + assertTrue(iter.hasNext()); + assertEquals(Integer.valueOf(30), iter.next()); + assertTrue(iter.hasNext()); + assertEquals(Integer.valueOf(31), iter.next()); + assertFalse(iter.hasNext()); + } + +} diff --git a/API/src/test/java/com/comze_instancelabs/minigamesapi/test/PartyTest.java b/API/src/test/java/com/comze_instancelabs/minigamesapi/test/PartyTest.java new file mode 100644 index 00000000..c87b5886 --- /dev/null +++ b/API/src/test/java/com/comze_instancelabs/minigamesapi/test/PartyTest.java @@ -0,0 +1,397 @@ +/* + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +package com.comze_instancelabs.minigamesapi.test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.doCallRealMethod; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.powermock.api.mockito.PowerMockito.mockStatic; + +import java.util.HashMap; +import java.util.UUID; + +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.powermock.reflect.Whitebox; + +import com.comze_instancelabs.minigamesapi.MinigamesAPI; +import com.comze_instancelabs.minigamesapi.Party; +import com.comze_instancelabs.minigamesapi.config.PartyMessagesConfig; + +/** + * Test for the party class + * + * @author mepeisen + * + * @see Party + */ +@RunWith(PowerMockRunner.class) +@PrepareForTest({Bukkit.class, MinigamesAPI.class}) +public class PartyTest +{ + + /** owner name. */ + private static final UUID OWNER = UUID.randomUUID(); + + /** friend name. */ + private static final UUID FRIEND_1 = UUID.randomUUID(); + + /** friend name. */ + private static final UUID FRIEND_2 = UUID.randomUUID(); + + /** + * Test that owner name is returned. + */ + @Test + public void testReturnsOwner() + { + final Party party = new Party(OWNER); + assertEquals(OWNER, party.getOwner()); + } + + /** + * Test that party is empty upon creation. + */ + @Test + public void testEmpty() + { + final Party party = new Party(OWNER); + assertEquals(0, party.getPlayers().size()); + } + + /** + * Simple Mock minigames api. + */ + private void mockAPI() + { + final MinigamesAPI api = mock(MinigamesAPI.class); + final PartyMessagesConfig messages = mock(PartyMessagesConfig.class); + Whitebox.setInternalState(api, "partymessages", messages); //$NON-NLS-1$ + messages.you_joined_party = "JOINED PARTY <player>"; //$NON-NLS-1$ + messages.player_joined_party = "PLAYER <player> JOINED"; //$NON-NLS-1$ + messages.you_left_party = "LEFT PARTY <player>"; //$NON-NLS-1$ + messages.player_left_party = "PLAYER <player> LEFT"; //$NON-NLS-1$ + messages.party_disbanded = "DISBAND"; //$NON-NLS-1$ + Whitebox.setInternalState(api, "global_party", new HashMap<>()); //$NON-NLS-1$ + + mockStatic(MinigamesAPI.class); + when(MinigamesAPI.getAPI()).thenReturn(api); + + when(api.createParty(any(UUID.class))).thenCallRealMethod(); + when(api.getParties()).thenCallRealMethod(); + when(api.hasParty(any(UUID.class))).thenCallRealMethod(); + when(api.getParty(any(UUID.class))).thenCallRealMethod(); + doCallRealMethod().when(api).removeParty(any(UUID.class)); + } + + /** + * Test that player is added to party + */ + @Test + public void testPlayerAdded() + { + // prolog + final Player player1 = mock(Player.class); + when(player1.getName()).thenReturn(FRIEND_1.toString()); + when(player1.getUniqueId()).thenReturn(FRIEND_1); + + mockStatic(Bukkit.class); + when(Bukkit.getPlayer(FRIEND_1)).thenReturn(player1); + + final Player owner = mock(Player.class); + when(owner.getName()).thenReturn(OWNER.toString()); + when(owner.getUniqueId()).thenReturn(OWNER); + + when(Bukkit.getPlayer(OWNER)).thenReturn(owner); + + this.mockAPI(); + + // test + final Party party = new Party(OWNER); + party.addPlayer(FRIEND_1); + assertEquals(1, party.getPlayers().size()); + assertEquals(FRIEND_1, party.getPlayers().get(0)); + + // epilog + verify(player1, times(1)).sendMessage("JOINED PARTY " + OWNER.toString()); //$NON-NLS-1$ + } + + /** + * Test that player is contained in party + */ + @Test + public void testPlayerContains() + { + // prolog + final Player player1 = mock(Player.class); + when(player1.getName()).thenReturn(FRIEND_1.toString()); + when(player1.getUniqueId()).thenReturn(FRIEND_1); + + mockStatic(Bukkit.class); + when(Bukkit.getPlayer(FRIEND_1)).thenReturn(player1); + + final Player owner = mock(Player.class); + when(owner.getName()).thenReturn(OWNER.toString()); + when(owner.getUniqueId()).thenReturn(OWNER); + + when(Bukkit.getPlayer(OWNER)).thenReturn(owner); + + this.mockAPI(); + + // test + final Party party = new Party(OWNER); + party.addPlayer(FRIEND_1); + assertTrue(party.containsPlayer(FRIEND_1)); + assertFalse(party.containsPlayer(FRIEND_2)); + } + + /** + * Test that two players are added to party + */ + @Test + public void testPlayer2Added() + { + // prolog + final Player player1 = mock(Player.class); + when(player1.getName()).thenReturn(FRIEND_1.toString()); + when(player1.getUniqueId()).thenReturn(FRIEND_1); + + mockStatic(Bukkit.class); + when(Bukkit.getPlayer(FRIEND_1)).thenReturn(player1); + + final Player player2 = mock(Player.class); + when(player2.getName()).thenReturn(FRIEND_2.toString()); + when(player2.getUniqueId()).thenReturn(FRIEND_2); + + when(Bukkit.getPlayer(FRIEND_2)).thenReturn(player2); + + final Player owner = mock(Player.class); + when(owner.getName()).thenReturn(OWNER.toString()); + when(owner.getUniqueId()).thenReturn(OWNER); + + when(Bukkit.getPlayer(OWNER)).thenReturn(owner); + + this.mockAPI(); + + // test + final Party party = new Party(OWNER); + party.addPlayer(FRIEND_1); + party.addPlayer(FRIEND_2); + assertEquals(2, party.getPlayers().size()); + assertEquals(FRIEND_1, party.getPlayers().get(0)); + assertEquals(FRIEND_2, party.getPlayers().get(1)); + + // epilog + verify(player1, times(1)).sendMessage("JOINED PARTY " + OWNER.toString()); //$NON-NLS-1$ + verify(player2, times(1)).sendMessage("JOINED PARTY " + OWNER.toString()); //$NON-NLS-1$ + verify(player1, times(1)).sendMessage("PLAYER " + FRIEND_2.toString() + " JOINED"); //$NON-NLS-1$ //$NON-NLS-2$ + } + + /** + * Test that player hast left the party + */ + @Test + public void testPlayerLeft() + { + // prolog + final Player player1 = mock(Player.class); + when(player1.getName()).thenReturn(FRIEND_1.toString()); + when(player1.getUniqueId()).thenReturn(FRIEND_1); + + mockStatic(Bukkit.class); + when(Bukkit.getPlayer(FRIEND_1)).thenReturn(player1); + + final Player owner = mock(Player.class); + when(owner.getName()).thenReturn(OWNER.toString()); + when(owner.getUniqueId()).thenReturn(OWNER); + + when(Bukkit.getPlayer(OWNER)).thenReturn(owner); + + this.mockAPI(); + + // test + final Party party = new Party(OWNER); + party.addPlayer(FRIEND_1); + party.removePlayer(FRIEND_1); + assertEquals(0, party.getPlayers().size()); + + // epilog + verify(player1, times(1)).sendMessage("JOINED PARTY " + OWNER.toString()); //$NON-NLS-1$ + verify(player1, times(1)).sendMessage("LEFT PARTY " + OWNER.toString()); //$NON-NLS-1$ + } + + /** + * Test that two players are added and one left the party + */ + @Test + public void testPlayer2Left() + { + // prolog + final Player player1 = mock(Player.class); + when(player1.getName()).thenReturn(FRIEND_1.toString()); + when(player1.getUniqueId()).thenReturn(FRIEND_1); + + mockStatic(Bukkit.class); + when(Bukkit.getPlayer(FRIEND_1)).thenReturn(player1); + + final Player owner = mock(Player.class); + when(owner.getName()).thenReturn(OWNER.toString()); + when(owner.getUniqueId()).thenReturn(OWNER); + + when(Bukkit.getPlayer(OWNER)).thenReturn(owner); + + final Player player2 = mock(Player.class); + when(player2.getName()).thenReturn(FRIEND_2.toString()); + when(player2.getUniqueId()).thenReturn(FRIEND_2); + + when(Bukkit.getPlayer(FRIEND_2)).thenReturn(player2); + + this.mockAPI(); + + // test + final Party party = new Party(OWNER); + party.addPlayer(FRIEND_1); + party.addPlayer(FRIEND_2); + assertTrue(party.removePlayer(FRIEND_1)); + assertEquals(1, party.getPlayers().size()); + assertEquals(FRIEND_2, party.getPlayers().get(0)); + + // epilog + verify(player1, times(1)).sendMessage("JOINED PARTY " + OWNER.toString()); //$NON-NLS-1$ + verify(player2, times(1)).sendMessage("JOINED PARTY " + OWNER.toString()); //$NON-NLS-1$ + verify(player1, times(1)).sendMessage("PLAYER " + FRIEND_2.toString() + " JOINED"); //$NON-NLS-1$ //$NON-NLS-2$ + verify(player1, times(1)).sendMessage("LEFT PARTY " + OWNER.toString()); //$NON-NLS-1$ + verify(player2, times(1)).sendMessage("PLAYER " + FRIEND_1.toString() + " LEFT"); //$NON-NLS-1$ //$NON-NLS-2$ + } + + /** + * Test that players are informed about disband + */ + @Test + public void testDisbandClearsList() + { + // prolog + final Player player1 = mock(Player.class); + when(player1.getName()).thenReturn(FRIEND_1.toString()); + when(player1.getUniqueId()).thenReturn(FRIEND_1); + + mockStatic(Bukkit.class); + when(Bukkit.getPlayer(FRIEND_1)).thenReturn(player1); + + final Player player2 = mock(Player.class); + when(player2.getName()).thenReturn(FRIEND_2.toString()); + when(player2.getUniqueId()).thenReturn(FRIEND_2); + + when(Bukkit.getPlayer(FRIEND_2)).thenReturn(player2); + + final Player owner = mock(Player.class); + when(owner.getName()).thenReturn(OWNER.toString()); + when(owner.getUniqueId()).thenReturn(OWNER); + + when(Bukkit.getPlayer(OWNER)).thenReturn(owner); + + this.mockAPI(); + + // test + // TODO clearing the list should not depend on finding it in global_party + final Party party = MinigamesAPI.getAPI().createParty(OWNER); + party.addPlayer(FRIEND_1); + party.addPlayer(FRIEND_2); + party.disband(); + assertEquals(0, party.getPlayers().size()); + } + + /** + * Test that players are informed about disband + */ + @Test + public void testDisbandInformsPlayers() + { + // prolog + final Player player1 = mock(Player.class); + when(player1.getName()).thenReturn(FRIEND_1.toString()); + when(player1.getUniqueId()).thenReturn(FRIEND_1); + + mockStatic(Bukkit.class); + when(Bukkit.getPlayer(FRIEND_1)).thenReturn(player1); + + final Player player2 = mock(Player.class); + when(player2.getName()).thenReturn(FRIEND_2.toString()); + when(player2.getUniqueId()).thenReturn(FRIEND_2); + + when(Bukkit.getPlayer(FRIEND_2)).thenReturn(player2); + + final Player owner = mock(Player.class); + when(owner.getName()).thenReturn(OWNER.toString()); + when(owner.getUniqueId()).thenReturn(OWNER); + + when(Bukkit.getPlayer(OWNER)).thenReturn(owner); + + this.mockAPI(); + + // test + final Party party = new Party(OWNER); + party.addPlayer(FRIEND_1); + party.addPlayer(FRIEND_2); + party.disband(); + + // epilog + verify(player1, times(1)).sendMessage("JOINED PARTY " + OWNER.toString()); //$NON-NLS-1$ + verify(player2, times(1)).sendMessage("JOINED PARTY " + OWNER.toString()); //$NON-NLS-1$ + verify(player1, times(1)).sendMessage("PLAYER " + FRIEND_2.toString() + " JOINED"); //$NON-NLS-1$ //$NON-NLS-2$ + verify(player1, times(1)).sendMessage("DISBAND"); //$NON-NLS-1$ + verify(player2, times(1)).sendMessage("DISBAND"); //$NON-NLS-1$ + } + + /** + * Test if disband removes from global party map + */ + @Test + public void testDisbandRemovesFromApi() + { + // prolog + final Player player1 = mock(Player.class); + when(player1.getName()).thenReturn(FRIEND_1.toString()); + when(player1.getUniqueId()).thenReturn(FRIEND_1); + + mockStatic(Bukkit.class); + when(Bukkit.getPlayer(FRIEND_1)).thenReturn(player1); + + final Player player2 = mock(Player.class); + when(player2.getName()).thenReturn(FRIEND_2.toString()); + when(player2.getUniqueId()).thenReturn(FRIEND_2); + + when(Bukkit.getPlayer(FRIEND_2)).thenReturn(player2); + + this.mockAPI(); + + // test + final Party party = MinigamesAPI.getAPI().createParty(OWNER); + party.disband(); + assertFalse(MinigamesAPI.getAPI().hasParty(OWNER)); + } + +} diff --git a/API/src/test/java/com/comze_instancelabs/minigamesapi/test/ValidatorTest.java b/API/src/test/java/com/comze_instancelabs/minigamesapi/test/ValidatorTest.java new file mode 100644 index 00000000..6fa1b5d1 --- /dev/null +++ b/API/src/test/java/com/comze_instancelabs/minigamesapi/test/ValidatorTest.java @@ -0,0 +1,109 @@ +/* + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +package com.comze_instancelabs.minigamesapi.test; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.util.UUID; + +import org.junit.Test; + +import com.comze_instancelabs.minigamesapi.Arena; +import com.comze_instancelabs.minigamesapi.testutil.TestUtil; +import com.comze_instancelabs.minigamesapi.util.Validator; + +/** + * The tester for the validator class. + * + * @author mepeisen + * + * @see Validator + */ +public class ValidatorTest extends TestUtil +{ + + /** the default arena name. */ + private static final String ARENA = "junit-arena"; //$NON-NLS-1$ + + /** the default arena name. */ + private static final String ARENA_EXISTING = "existing-arena"; //$NON-NLS-1$ + + /** the default arena name. */ + private static final String ARENA_VALID = "valid-arena"; //$NON-NLS-1$ + + /** the junit minigame. */ + private static final String MINIGAME = "$JUNIT-VALIDATOR-TEST"; //$NON-NLS-1$ + + /** + * tests the validator isPlayerOnline + */ + @Test + public void testIsPlayerOnline() + { + this.mockOnlinePlayer("PLAYER_ONLINE", UUID.randomUUID()); //$NON-NLS-1$ + assertTrue(Validator.isPlayerOnline("PLAYER_ONLINE")); //$NON-NLS-1$ + assertFalse(Validator.isPlayerOnline("PLAYER_OFFLINE")); //$NON-NLS-1$ + } + + /** + * tests the validator isPlayerValid + */ + @Test + public void testIsPlayerValid() + { + this.mockOnlinePlayer("PLAYER_ONLINE", UUID.randomUUID()); //$NON-NLS-1$ + this.mockOnlinePlayer("PLAYER_ARENA", UUID.randomUUID()); //$NON-NLS-1$ + final Minigame minigame = this.minigameTest.setupMinigame(MINIGAME + "isPlayerValid"); //$NON-NLS-1$ + final Arena arena = new Arena(minigame.javaPlugin, ARENA); + final Arena arenaValid = new Arena(minigame.javaPlugin, ARENA_VALID); + minigame.pluginInstance.global_players.put("PLAYER_ARENA", arenaValid); //$NON-NLS-1$ + + assertFalse(Validator.isPlayerValid(minigame.javaPlugin, "PLAYER_OFFLINE", arena)); //$NON-NLS-1$ + assertFalse(Validator.isPlayerValid(minigame.javaPlugin, "PLAYER_OFFLINE", arenaValid)); //$NON-NLS-1$ + assertFalse(Validator.isPlayerValid(minigame.javaPlugin, "PLAYER_ONLINE", arena)); //$NON-NLS-1$ + assertFalse(Validator.isPlayerValid(minigame.javaPlugin, "PLAYER_ONLINE", arenaValid)); //$NON-NLS-1$ + assertFalse(Validator.isPlayerValid(minigame.javaPlugin, "PLAYER_ARENA", arena)); //$NON-NLS-1$ + assertTrue(Validator.isPlayerValid(minigame.javaPlugin, "PLAYER_ARENA", arenaValid)); //$NON-NLS-1$ + } + + /** + * Tests the validator isArenaValid + */ + @Test + public void testArenaIsValid() + { + final Minigame minigame = this.minigameTest.setupMinigame(MINIGAME + "isArenaValid", (mg) -> { //$NON-NLS-1$ + mg.addArenaComponentToConfig(ARENA_EXISTING, "lobby", "world", 1, 1, 1, 80, 80); //$NON-NLS-1$ //$NON-NLS-2$ + + mg.addArenaComponentToConfig(ARENA_VALID, "lobby", "world", 1, 1, 1, 80, 80); //$NON-NLS-1$ //$NON-NLS-2$ + mg.addArenaComponentToConfig(ARENA_VALID, "spawns.spawn0", "world", 1, 1, 1, 80, 80); //$NON-NLS-1$ //$NON-NLS-2$ + }); + + // check if unknown arena is not valid + final Arena arena = new Arena(minigame.javaPlugin, ARENA); + assertFalse(Validator.isArenaValid(minigame.javaPlugin, arena)); + + // check if known arena is not valid + final Arena arenaExisting = new Arena(minigame.javaPlugin, ARENA_EXISTING); + assertFalse(Validator.isArenaValid(minigame.javaPlugin, arenaExisting)); + + // check if unknown arena is not valid + final Arena arenaValid = new Arena(minigame.javaPlugin, ARENA_VALID); + assertTrue(Validator.isArenaValid(minigame.javaPlugin, arenaValid)); + } + +} diff --git a/API/src/test/java/com/comze_instancelabs/minigamesapi/test/VersionTypeTest.java b/API/src/test/java/com/comze_instancelabs/minigamesapi/test/VersionTypeTest.java new file mode 100644 index 00000000..8a233dbf --- /dev/null +++ b/API/src/test/java/com/comze_instancelabs/minigamesapi/test/VersionTypeTest.java @@ -0,0 +1,336 @@ +/* + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +package com.comze_instancelabs.minigamesapi.test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +import com.comze_instancelabs.minigamesapi.MinecraftVersionsType; + +/** + * Test for the version types. + * + * @author mepeisen + * @see MinecraftVersionsType + */ +public class VersionTypeTest +{ + + /** + * tests the ordinal values. + */ + @Test + public void testOrdinals() + { + assertEquals(0, MinecraftVersionsType.Unknown.ordinal()); + assertEquals(1, MinecraftVersionsType.V1_7.ordinal()); + assertEquals(2, MinecraftVersionsType.V1_7_R1.ordinal()); + assertEquals(3, MinecraftVersionsType.V1_7_R2.ordinal()); + assertEquals(4, MinecraftVersionsType.V1_7_R3.ordinal()); + assertEquals(5, MinecraftVersionsType.V1_7_R4.ordinal()); + assertEquals(6, MinecraftVersionsType.V1_8.ordinal()); + assertEquals(7, MinecraftVersionsType.V1_8_R1.ordinal()); + assertEquals(8, MinecraftVersionsType.V1_8_R2.ordinal()); + assertEquals(9, MinecraftVersionsType.V1_8_R3.ordinal()); + assertEquals(10, MinecraftVersionsType.V1_9.ordinal()); + assertEquals(11, MinecraftVersionsType.V1_9_R1.ordinal()); + assertEquals(12, MinecraftVersionsType.V1_9_R2.ordinal()); + assertEquals(13, MinecraftVersionsType.V1_10.ordinal()); + assertEquals(14, MinecraftVersionsType.V1_10_R1.ordinal()); + } + + /** + * Tests the supported flags. + */ + @Test + public void testSupported() + { + assertFalse(MinecraftVersionsType.Unknown.isSupported()); + assertTrue(MinecraftVersionsType.V1_7.isSupported()); + assertTrue(MinecraftVersionsType.V1_7_R1.isSupported()); + assertTrue(MinecraftVersionsType.V1_7_R2.isSupported()); + assertTrue(MinecraftVersionsType.V1_7_R3.isSupported()); + assertTrue(MinecraftVersionsType.V1_7_R4.isSupported()); + assertTrue(MinecraftVersionsType.V1_8.isSupported()); + assertTrue(MinecraftVersionsType.V1_8_R1.isSupported()); + assertTrue(MinecraftVersionsType.V1_8_R2.isSupported()); + assertTrue(MinecraftVersionsType.V1_9.isSupported()); + assertTrue(MinecraftVersionsType.V1_9_R1.isSupported()); + assertTrue(MinecraftVersionsType.V1_9_R2.isSupported()); + assertTrue(MinecraftVersionsType.V1_10.isSupported()); + assertTrue(MinecraftVersionsType.V1_10_R1.isSupported()); + } + + /** + * tests the isEqual method + */ + @Test + public void testEquals() + { + assertTrue(MinecraftVersionsType.V1_7.isEqual(MinecraftVersionsType.V1_7_R1)); + assertTrue(MinecraftVersionsType.V1_7.isEqual(MinecraftVersionsType.V1_7_R2)); + assertTrue(MinecraftVersionsType.V1_7.isEqual(MinecraftVersionsType.V1_7_R3)); + assertTrue(MinecraftVersionsType.V1_7.isEqual(MinecraftVersionsType.V1_7_R4)); + assertTrue(MinecraftVersionsType.V1_7_R1.isEqual(MinecraftVersionsType.V1_7_R1)); + assertTrue(MinecraftVersionsType.V1_7_R1.isEqual(MinecraftVersionsType.V1_7)); + assertTrue(MinecraftVersionsType.V1_7_R2.isEqual(MinecraftVersionsType.V1_7_R2)); + assertTrue(MinecraftVersionsType.V1_7_R2.isEqual(MinecraftVersionsType.V1_7)); + assertTrue(MinecraftVersionsType.V1_7_R3.isEqual(MinecraftVersionsType.V1_7_R3)); + assertTrue(MinecraftVersionsType.V1_7_R3.isEqual(MinecraftVersionsType.V1_7)); + assertTrue(MinecraftVersionsType.V1_7_R4.isEqual(MinecraftVersionsType.V1_7_R4)); + assertTrue(MinecraftVersionsType.V1_7_R4.isEqual(MinecraftVersionsType.V1_7)); + + assertTrue(MinecraftVersionsType.V1_8.isEqual(MinecraftVersionsType.V1_8_R1)); + assertTrue(MinecraftVersionsType.V1_8.isEqual(MinecraftVersionsType.V1_8_R2)); + assertTrue(MinecraftVersionsType.V1_8_R1.isEqual(MinecraftVersionsType.V1_8_R1)); + assertTrue(MinecraftVersionsType.V1_8_R1.isEqual(MinecraftVersionsType.V1_8)); + assertTrue(MinecraftVersionsType.V1_8_R2.isEqual(MinecraftVersionsType.V1_8_R2)); + assertTrue(MinecraftVersionsType.V1_8_R2.isEqual(MinecraftVersionsType.V1_8)); + + assertTrue(MinecraftVersionsType.V1_9.isEqual(MinecraftVersionsType.V1_9_R1)); + assertTrue(MinecraftVersionsType.V1_9.isEqual(MinecraftVersionsType.V1_9_R2)); + assertTrue(MinecraftVersionsType.V1_9_R1.isEqual(MinecraftVersionsType.V1_9_R1)); + assertTrue(MinecraftVersionsType.V1_9_R1.isEqual(MinecraftVersionsType.V1_9)); + assertTrue(MinecraftVersionsType.V1_9_R2.isEqual(MinecraftVersionsType.V1_9_R2)); + assertTrue(MinecraftVersionsType.V1_9_R2.isEqual(MinecraftVersionsType.V1_9)); + + assertTrue(MinecraftVersionsType.V1_10.isEqual(MinecraftVersionsType.V1_10_R1)); + assertTrue(MinecraftVersionsType.V1_10_R1.isEqual(MinecraftVersionsType.V1_10_R1)); + assertTrue(MinecraftVersionsType.V1_10_R1.isEqual(MinecraftVersionsType.V1_10)); + + assertTrue(MinecraftVersionsType.Unknown.isEqual(MinecraftVersionsType.Unknown)); + + assertFalse(MinecraftVersionsType.V1_7.isEqual(MinecraftVersionsType.Unknown)); + assertFalse(MinecraftVersionsType.V1_8.isEqual(MinecraftVersionsType.Unknown)); + assertFalse(MinecraftVersionsType.V1_9.isEqual(MinecraftVersionsType.Unknown)); + assertFalse(MinecraftVersionsType.V1_10.isEqual(MinecraftVersionsType.Unknown)); + assertFalse(MinecraftVersionsType.V1_7_R1.isEqual(MinecraftVersionsType.Unknown)); + assertFalse(MinecraftVersionsType.V1_8_R2.isEqual(MinecraftVersionsType.Unknown)); + assertFalse(MinecraftVersionsType.V1_9_R1.isEqual(MinecraftVersionsType.Unknown)); + assertFalse(MinecraftVersionsType.V1_10_R1.isEqual(MinecraftVersionsType.Unknown)); + assertFalse(MinecraftVersionsType.Unknown.isEqual(MinecraftVersionsType.V1_7)); + assertFalse(MinecraftVersionsType.Unknown.isEqual(MinecraftVersionsType.V1_8)); + assertFalse(MinecraftVersionsType.Unknown.isEqual(MinecraftVersionsType.V1_9)); + assertFalse(MinecraftVersionsType.Unknown.isEqual(MinecraftVersionsType.V1_10)); + assertFalse(MinecraftVersionsType.Unknown.isEqual(MinecraftVersionsType.V1_7_R4)); + assertFalse(MinecraftVersionsType.Unknown.isEqual(MinecraftVersionsType.V1_8_R1)); + assertFalse(MinecraftVersionsType.Unknown.isEqual(MinecraftVersionsType.V1_9_R2)); + assertFalse(MinecraftVersionsType.Unknown.isEqual(MinecraftVersionsType.V1_10_R1)); + + assertFalse(MinecraftVersionsType.V1_7.isEqual(MinecraftVersionsType.V1_8)); + assertFalse(MinecraftVersionsType.V1_9.isEqual(MinecraftVersionsType.V1_8)); + assertFalse(MinecraftVersionsType.V1_8.isEqual(MinecraftVersionsType.V1_10)); + assertFalse(MinecraftVersionsType.V1_7_R1.isEqual(MinecraftVersionsType.V1_7_R2)); + assertFalse(MinecraftVersionsType.V1_7_R4.isEqual(MinecraftVersionsType.V1_8_R1)); + assertFalse(MinecraftVersionsType.V1_10_R1.isEqual(MinecraftVersionsType.V1_9_R2)); + } + + /** + * tests the isBelow method + */ + @Test + public void testIsBelow() + { + assertFalse(MinecraftVersionsType.V1_7.isBelow(MinecraftVersionsType.V1_7_R1)); + assertFalse(MinecraftVersionsType.V1_7.isBelow(MinecraftVersionsType.V1_7_R2)); + assertFalse(MinecraftVersionsType.V1_7.isBelow(MinecraftVersionsType.V1_7_R3)); + assertFalse(MinecraftVersionsType.V1_7.isBelow(MinecraftVersionsType.V1_7_R4)); + assertFalse(MinecraftVersionsType.V1_7_R1.isBelow(MinecraftVersionsType.V1_7_R1)); + assertFalse(MinecraftVersionsType.V1_7_R1.isBelow(MinecraftVersionsType.V1_7)); + assertFalse(MinecraftVersionsType.V1_7_R2.isBelow(MinecraftVersionsType.V1_7_R2)); + assertFalse(MinecraftVersionsType.V1_7_R2.isBelow(MinecraftVersionsType.V1_7)); + assertFalse(MinecraftVersionsType.V1_7_R3.isBelow(MinecraftVersionsType.V1_7_R3)); + assertFalse(MinecraftVersionsType.V1_7_R3.isBelow(MinecraftVersionsType.V1_7)); + assertFalse(MinecraftVersionsType.V1_7_R4.isBelow(MinecraftVersionsType.V1_7_R4)); + assertFalse(MinecraftVersionsType.V1_7_R4.isBelow(MinecraftVersionsType.V1_7)); + + assertFalse(MinecraftVersionsType.V1_8.isBelow(MinecraftVersionsType.V1_8_R1)); + assertFalse(MinecraftVersionsType.V1_8.isBelow(MinecraftVersionsType.V1_8_R2)); + assertFalse(MinecraftVersionsType.V1_8_R1.isBelow(MinecraftVersionsType.V1_8_R1)); + assertFalse(MinecraftVersionsType.V1_8_R1.isBelow(MinecraftVersionsType.V1_8)); + assertFalse(MinecraftVersionsType.V1_8_R2.isBelow(MinecraftVersionsType.V1_8_R2)); + assertFalse(MinecraftVersionsType.V1_8_R2.isBelow(MinecraftVersionsType.V1_8)); + + assertFalse(MinecraftVersionsType.V1_9.isBelow(MinecraftVersionsType.V1_9_R1)); + assertFalse(MinecraftVersionsType.V1_9.isBelow(MinecraftVersionsType.V1_9_R2)); + assertFalse(MinecraftVersionsType.V1_9_R1.isBelow(MinecraftVersionsType.V1_9_R1)); + assertFalse(MinecraftVersionsType.V1_9_R1.isBelow(MinecraftVersionsType.V1_9)); + assertFalse(MinecraftVersionsType.V1_9_R2.isBelow(MinecraftVersionsType.V1_9_R2)); + assertFalse(MinecraftVersionsType.V1_9_R2.isBelow(MinecraftVersionsType.V1_9)); + + assertFalse(MinecraftVersionsType.V1_10.isBelow(MinecraftVersionsType.V1_10_R1)); + assertFalse(MinecraftVersionsType.V1_10_R1.isBelow(MinecraftVersionsType.V1_10_R1)); + assertFalse(MinecraftVersionsType.V1_10_R1.isBelow(MinecraftVersionsType.V1_10)); + + assertFalse(MinecraftVersionsType.Unknown.isBelow(MinecraftVersionsType.Unknown)); + + assertFalse(MinecraftVersionsType.V1_7.isBelow(MinecraftVersionsType.Unknown)); + assertFalse(MinecraftVersionsType.V1_8.isBelow(MinecraftVersionsType.Unknown)); + assertFalse(MinecraftVersionsType.V1_9.isBelow(MinecraftVersionsType.Unknown)); + assertFalse(MinecraftVersionsType.V1_10.isBelow(MinecraftVersionsType.Unknown)); + assertFalse(MinecraftVersionsType.V1_7_R1.isBelow(MinecraftVersionsType.Unknown)); + assertFalse(MinecraftVersionsType.V1_8_R2.isBelow(MinecraftVersionsType.Unknown)); + assertFalse(MinecraftVersionsType.V1_9_R1.isBelow(MinecraftVersionsType.Unknown)); + assertFalse(MinecraftVersionsType.V1_10_R1.isBelow(MinecraftVersionsType.Unknown)); + assertTrue(MinecraftVersionsType.Unknown.isBelow(MinecraftVersionsType.V1_7)); + assertTrue(MinecraftVersionsType.Unknown.isBelow(MinecraftVersionsType.V1_8)); + assertTrue(MinecraftVersionsType.Unknown.isBelow(MinecraftVersionsType.V1_9)); + assertTrue(MinecraftVersionsType.Unknown.isBelow(MinecraftVersionsType.V1_10)); + assertTrue(MinecraftVersionsType.Unknown.isBelow(MinecraftVersionsType.V1_7_R4)); + assertTrue(MinecraftVersionsType.Unknown.isBelow(MinecraftVersionsType.V1_8_R1)); + assertTrue(MinecraftVersionsType.Unknown.isBelow(MinecraftVersionsType.V1_9_R2)); + assertTrue(MinecraftVersionsType.Unknown.isBelow(MinecraftVersionsType.V1_10_R1)); + + assertTrue(MinecraftVersionsType.V1_7.isBelow(MinecraftVersionsType.V1_8)); + assertFalse(MinecraftVersionsType.V1_9.isBelow(MinecraftVersionsType.V1_8)); + assertTrue(MinecraftVersionsType.V1_8.isBelow(MinecraftVersionsType.V1_10)); + assertTrue(MinecraftVersionsType.V1_7_R1.isBelow(MinecraftVersionsType.V1_7_R2)); + assertTrue(MinecraftVersionsType.V1_7_R4.isBelow(MinecraftVersionsType.V1_8_R1)); + assertFalse(MinecraftVersionsType.V1_10_R1.isBelow(MinecraftVersionsType.V1_9_R2)); + } + + /** + * tests the isAfter method + */ + @Test + public void testIsAfter() + { + assertFalse(MinecraftVersionsType.V1_7.isAfter(MinecraftVersionsType.V1_7_R1)); + assertFalse(MinecraftVersionsType.V1_7.isAfter(MinecraftVersionsType.V1_7_R2)); + assertFalse(MinecraftVersionsType.V1_7.isAfter(MinecraftVersionsType.V1_7_R3)); + assertFalse(MinecraftVersionsType.V1_7.isAfter(MinecraftVersionsType.V1_7_R4)); + assertFalse(MinecraftVersionsType.V1_7_R1.isAfter(MinecraftVersionsType.V1_7_R1)); + assertFalse(MinecraftVersionsType.V1_7_R1.isAfter(MinecraftVersionsType.V1_7)); + assertFalse(MinecraftVersionsType.V1_7_R2.isAfter(MinecraftVersionsType.V1_7_R2)); + assertFalse(MinecraftVersionsType.V1_7_R2.isAfter(MinecraftVersionsType.V1_7)); + assertFalse(MinecraftVersionsType.V1_7_R3.isAfter(MinecraftVersionsType.V1_7_R3)); + assertFalse(MinecraftVersionsType.V1_7_R3.isAfter(MinecraftVersionsType.V1_7)); + assertFalse(MinecraftVersionsType.V1_7_R4.isAfter(MinecraftVersionsType.V1_7_R4)); + assertFalse(MinecraftVersionsType.V1_7_R4.isAfter(MinecraftVersionsType.V1_7)); + + assertFalse(MinecraftVersionsType.V1_8.isAfter(MinecraftVersionsType.V1_8_R1)); + assertFalse(MinecraftVersionsType.V1_8.isAfter(MinecraftVersionsType.V1_8_R2)); + assertFalse(MinecraftVersionsType.V1_8_R1.isAfter(MinecraftVersionsType.V1_8_R1)); + assertFalse(MinecraftVersionsType.V1_8_R1.isAfter(MinecraftVersionsType.V1_8)); + assertFalse(MinecraftVersionsType.V1_8_R2.isAfter(MinecraftVersionsType.V1_8_R2)); + assertFalse(MinecraftVersionsType.V1_8_R2.isAfter(MinecraftVersionsType.V1_8)); + + assertFalse(MinecraftVersionsType.V1_9.isAfter(MinecraftVersionsType.V1_9_R1)); + assertFalse(MinecraftVersionsType.V1_9.isAfter(MinecraftVersionsType.V1_9_R2)); + assertFalse(MinecraftVersionsType.V1_9_R1.isAfter(MinecraftVersionsType.V1_9_R1)); + assertFalse(MinecraftVersionsType.V1_9_R1.isAfter(MinecraftVersionsType.V1_9)); + assertFalse(MinecraftVersionsType.V1_9_R2.isAfter(MinecraftVersionsType.V1_9_R2)); + assertFalse(MinecraftVersionsType.V1_9_R2.isAfter(MinecraftVersionsType.V1_9)); + + assertFalse(MinecraftVersionsType.V1_10.isAfter(MinecraftVersionsType.V1_10_R1)); + assertFalse(MinecraftVersionsType.V1_10_R1.isAfter(MinecraftVersionsType.V1_10_R1)); + assertFalse(MinecraftVersionsType.V1_10_R1.isAfter(MinecraftVersionsType.V1_10)); + + assertFalse(MinecraftVersionsType.Unknown.isAfter(MinecraftVersionsType.Unknown)); + + assertTrue(MinecraftVersionsType.V1_7.isAfter(MinecraftVersionsType.Unknown)); + assertTrue(MinecraftVersionsType.V1_8.isAfter(MinecraftVersionsType.Unknown)); + assertTrue(MinecraftVersionsType.V1_9.isAfter(MinecraftVersionsType.Unknown)); + assertTrue(MinecraftVersionsType.V1_10.isAfter(MinecraftVersionsType.Unknown)); + assertTrue(MinecraftVersionsType.V1_7_R1.isAfter(MinecraftVersionsType.Unknown)); + assertTrue(MinecraftVersionsType.V1_8_R2.isAfter(MinecraftVersionsType.Unknown)); + assertTrue(MinecraftVersionsType.V1_9_R1.isAfter(MinecraftVersionsType.Unknown)); + assertTrue(MinecraftVersionsType.V1_10_R1.isAfter(MinecraftVersionsType.Unknown)); + assertFalse(MinecraftVersionsType.Unknown.isAfter(MinecraftVersionsType.V1_7)); + assertFalse(MinecraftVersionsType.Unknown.isAfter(MinecraftVersionsType.V1_8)); + assertFalse(MinecraftVersionsType.Unknown.isAfter(MinecraftVersionsType.V1_9)); + assertFalse(MinecraftVersionsType.Unknown.isAfter(MinecraftVersionsType.V1_10)); + assertFalse(MinecraftVersionsType.Unknown.isAfter(MinecraftVersionsType.V1_7_R4)); + assertFalse(MinecraftVersionsType.Unknown.isAfter(MinecraftVersionsType.V1_8_R1)); + assertFalse(MinecraftVersionsType.Unknown.isAfter(MinecraftVersionsType.V1_9_R2)); + assertFalse(MinecraftVersionsType.Unknown.isAfter(MinecraftVersionsType.V1_10_R1)); + + assertFalse(MinecraftVersionsType.V1_7.isAfter(MinecraftVersionsType.V1_8)); + assertTrue(MinecraftVersionsType.V1_9.isAfter(MinecraftVersionsType.V1_8)); + assertFalse(MinecraftVersionsType.V1_8.isAfter(MinecraftVersionsType.V1_10)); + assertFalse(MinecraftVersionsType.V1_7_R1.isAfter(MinecraftVersionsType.V1_7_R2)); + assertFalse(MinecraftVersionsType.V1_7_R4.isAfter(MinecraftVersionsType.V1_8_R1)); + assertTrue(MinecraftVersionsType.V1_10_R1.isAfter(MinecraftVersionsType.V1_9_R2)); + } + + /** + * tests the isAtLeast method + */ + @Test + public void testIsAtLeast() + { + assertTrue(MinecraftVersionsType.V1_7.isAtLeast(MinecraftVersionsType.V1_7_R1)); + assertTrue(MinecraftVersionsType.V1_7.isAtLeast(MinecraftVersionsType.V1_7_R2)); + assertTrue(MinecraftVersionsType.V1_7.isAtLeast(MinecraftVersionsType.V1_7_R3)); + assertTrue(MinecraftVersionsType.V1_7.isAtLeast(MinecraftVersionsType.V1_7_R4)); + assertTrue(MinecraftVersionsType.V1_7_R1.isAtLeast(MinecraftVersionsType.V1_7_R1)); + assertTrue(MinecraftVersionsType.V1_7_R1.isAtLeast(MinecraftVersionsType.V1_7)); + assertTrue(MinecraftVersionsType.V1_7_R2.isAtLeast(MinecraftVersionsType.V1_7_R2)); + assertTrue(MinecraftVersionsType.V1_7_R2.isAtLeast(MinecraftVersionsType.V1_7)); + assertTrue(MinecraftVersionsType.V1_7_R3.isAtLeast(MinecraftVersionsType.V1_7_R3)); + assertTrue(MinecraftVersionsType.V1_7_R3.isAtLeast(MinecraftVersionsType.V1_7)); + assertTrue(MinecraftVersionsType.V1_7_R4.isAtLeast(MinecraftVersionsType.V1_7_R4)); + assertTrue(MinecraftVersionsType.V1_7_R4.isAtLeast(MinecraftVersionsType.V1_7)); + + assertTrue(MinecraftVersionsType.V1_8.isAtLeast(MinecraftVersionsType.V1_8_R1)); + assertTrue(MinecraftVersionsType.V1_8.isAtLeast(MinecraftVersionsType.V1_8_R2)); + assertTrue(MinecraftVersionsType.V1_8_R1.isAtLeast(MinecraftVersionsType.V1_8_R1)); + assertTrue(MinecraftVersionsType.V1_8_R1.isAtLeast(MinecraftVersionsType.V1_8)); + assertTrue(MinecraftVersionsType.V1_8_R2.isAtLeast(MinecraftVersionsType.V1_8_R2)); + assertTrue(MinecraftVersionsType.V1_8_R2.isAtLeast(MinecraftVersionsType.V1_8)); + + assertTrue(MinecraftVersionsType.V1_9.isAtLeast(MinecraftVersionsType.V1_9_R1)); + assertTrue(MinecraftVersionsType.V1_9.isAtLeast(MinecraftVersionsType.V1_9_R2)); + assertTrue(MinecraftVersionsType.V1_9_R1.isAtLeast(MinecraftVersionsType.V1_9_R1)); + assertTrue(MinecraftVersionsType.V1_9_R1.isAtLeast(MinecraftVersionsType.V1_9)); + assertTrue(MinecraftVersionsType.V1_9_R2.isAtLeast(MinecraftVersionsType.V1_9_R2)); + assertTrue(MinecraftVersionsType.V1_9_R2.isAtLeast(MinecraftVersionsType.V1_9)); + + assertTrue(MinecraftVersionsType.V1_10.isAtLeast(MinecraftVersionsType.V1_10_R1)); + assertTrue(MinecraftVersionsType.V1_10_R1.isAtLeast(MinecraftVersionsType.V1_10_R1)); + assertTrue(MinecraftVersionsType.V1_10_R1.isAtLeast(MinecraftVersionsType.V1_10)); + + assertTrue(MinecraftVersionsType.Unknown.isAtLeast(MinecraftVersionsType.Unknown)); + + assertTrue(MinecraftVersionsType.V1_7.isAtLeast(MinecraftVersionsType.Unknown)); + assertTrue(MinecraftVersionsType.V1_8.isAtLeast(MinecraftVersionsType.Unknown)); + assertTrue(MinecraftVersionsType.V1_9.isAtLeast(MinecraftVersionsType.Unknown)); + assertTrue(MinecraftVersionsType.V1_10.isAtLeast(MinecraftVersionsType.Unknown)); + assertTrue(MinecraftVersionsType.V1_7_R1.isAtLeast(MinecraftVersionsType.Unknown)); + assertTrue(MinecraftVersionsType.V1_8_R2.isAtLeast(MinecraftVersionsType.Unknown)); + assertTrue(MinecraftVersionsType.V1_9_R1.isAtLeast(MinecraftVersionsType.Unknown)); + assertTrue(MinecraftVersionsType.V1_10_R1.isAtLeast(MinecraftVersionsType.Unknown)); + assertFalse(MinecraftVersionsType.Unknown.isAtLeast(MinecraftVersionsType.V1_7)); + assertFalse(MinecraftVersionsType.Unknown.isAtLeast(MinecraftVersionsType.V1_8)); + assertFalse(MinecraftVersionsType.Unknown.isAtLeast(MinecraftVersionsType.V1_9)); + assertFalse(MinecraftVersionsType.Unknown.isAtLeast(MinecraftVersionsType.V1_10)); + assertFalse(MinecraftVersionsType.Unknown.isAtLeast(MinecraftVersionsType.V1_7_R4)); + assertFalse(MinecraftVersionsType.Unknown.isAtLeast(MinecraftVersionsType.V1_8_R1)); + assertFalse(MinecraftVersionsType.Unknown.isAtLeast(MinecraftVersionsType.V1_9_R2)); + assertFalse(MinecraftVersionsType.Unknown.isAtLeast(MinecraftVersionsType.V1_10_R1)); + + assertFalse(MinecraftVersionsType.V1_7.isAtLeast(MinecraftVersionsType.V1_8)); + assertTrue(MinecraftVersionsType.V1_9.isAtLeast(MinecraftVersionsType.V1_8)); + assertFalse(MinecraftVersionsType.V1_8.isAtLeast(MinecraftVersionsType.V1_10)); + assertFalse(MinecraftVersionsType.V1_7_R1.isAtLeast(MinecraftVersionsType.V1_7_R2)); + assertFalse(MinecraftVersionsType.V1_7_R4.isAtLeast(MinecraftVersionsType.V1_8_R1)); + assertTrue(MinecraftVersionsType.V1_10_R1.isAtLeast(MinecraftVersionsType.V1_9_R2)); + } + +} diff --git a/API/src/test/java/com/comze_instancelabs/minigamesapi/testutil/TestUtil.java b/API/src/test/java/com/comze_instancelabs/minigamesapi/testutil/TestUtil.java new file mode 100644 index 00000000..c6bc9fd8 --- /dev/null +++ b/API/src/test/java/com/comze_instancelabs/minigamesapi/testutil/TestUtil.java @@ -0,0 +1,234 @@ +/* + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +package com.comze_instancelabs.minigamesapi.testutil; + +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.anyBoolean; +import static org.mockito.Matchers.anyString; +import static org.mockito.Mockito.when; +import static org.powermock.api.mockito.PowerMockito.mockStatic; + +import java.io.File; +import java.lang.reflect.Field; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; +import java.util.function.Consumer; + +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.plugin.java.JavaPlugin; +import org.junit.Before; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.reflect.Whitebox; + +import com.comze_instancelabs.minigamesapi.Arena; +import com.comze_instancelabs.minigamesapi.MinecraftVersionsType; +import com.comze_instancelabs.minigamesapi.MinigamesAPI; +import com.comze_instancelabs.minigamesapi.PluginInstance; +import com.comze_instancelabs.minigamesapi.config.ArenasConfig; +import com.comze_instancelabs.minigamesapi.config.ClassesConfig; +import com.comze_instancelabs.minigamesapi.config.DefaultConfig; +import com.comze_instancelabs.minigamesapi.config.MessagesConfig; +import com.comze_instancelabs.minigamesapi.config.StatsConfig; +import com.comze_instancelabs.minigamesapi.spigottest.SpigotTestSupport; + +/** + * Test tooling for minigames API. + * + * @author mepeisen + */ +@PrepareForTest({ MinigamesAPI.class }) +public abstract class TestUtil extends SpigotTestSupport +{ + + /** test helper. */ + protected MinigameTestHelper minigameTest; + + /** + * Setup the minigame test framework. + * @throws IllegalAccessException + * @throws IllegalArgumentException + */ + @Before + public void setupMinigameTest() throws IllegalArgumentException, IllegalAccessException + { + this.minigameTest = new MinigameTestHelper(); + + final YamlConfiguration config = mockFileConfig(); + final MinigamesAPI api = this.mockPlugin("MinigamesLib", "1.0", config, MinigamesAPI.class, null); + mockStatic(MinigamesAPI.class); + when(MinigamesAPI.getAPI()).thenReturn(api); + when(MinigamesAPI.setupAPI(any(), anyString(), any(), any(), any(), any(), any(), any(), anyBoolean())).thenCallRealMethod(); + when(MinigamesAPI.playerToUUID(any(Player.class))).thenCallRealMethod(); + when(MinigamesAPI.playerToUUID(anyString())).thenCallRealMethod(); + when(MinigamesAPI.uuidToPlayer(any(UUID.class))).thenCallRealMethod(); + + this.minigameTest.api = api; + Whitebox.setInternalState(api, "global_party", new HashMap<>()); + + final Field field = PowerMockito.field(MinigamesAPI.class, "SERVER_VERSION"); + field.setAccessible(true); + field.set(MinigamesAPI.class, MinecraftVersionsType.V1_10_R1); + } + + /** + * Helper class for minigame api access. + * + * @author mepeisen + */ + public final class MinigameTestHelper + { + /** the minigames api. */ + public MinigamesAPI api; + /** hashmap with minigames by internal name. */ + public Map<String, Minigame> minigames = new HashMap<>(); + + /** + * Setup a minigame. + * + * @param name + * minigame plugin name + * @return the minigame data + */ + public Minigame setupMinigame(String name) + { + return setupMinigame(name, null); + } + + /** + * Setup a minigame and perform some setup before loading via minigames api. + * + * @param name + * minigame plugin name + * @param preSetup + * setup function + * @return the minigame data + */ + public Minigame setupMinigame(String name, Consumer<Minigame> preSetup) + { + final Minigame minigame = new Minigame(); + this.minigames.put(name, minigame); + final YamlConfiguration config = mockFileConfig(); + final JavaPlugin plugin = mockPlugin(name, "1.0", config); //$NON-NLS-1$ + minigame.javaPlugin = plugin; + minigame.achievementsYml = setupConfigFile(new File(plugin.getDataFolder(), "achievements.yml")); //$NON-NLS-1$ + minigame.arenasYml = setupConfigFile(new File(plugin.getDataFolder(), "arenas.yml")); //$NON-NLS-1$ + minigame.classesYml = setupConfigFile(new File(plugin.getDataFolder(), "classes.yml")); //$NON-NLS-1$ + minigame.gunsYml = setupConfigFile(new File(plugin.getDataFolder(), "guns.yml")); //$NON-NLS-1$ + minigame.hologramsYml = setupConfigFile(new File(plugin.getDataFolder(), "holograms.yml")); //$NON-NLS-1$ + minigame.messagesYml = setupConfigFile(new File(plugin.getDataFolder(), "messages.yml")); //$NON-NLS-1$ + minigame.shopYml = setupConfigFile(new File(plugin.getDataFolder(), "shop.yml")); //$NON-NLS-1$ + minigame.statsYml = setupConfigFile(new File(plugin.getDataFolder(), "stats.yml")); //$NON-NLS-1$ + if (preSetup != null) + { + preSetup.accept(minigame); + } + MinigamesAPI.setupAPI(plugin, name, Arena.class, new ArenasConfig(plugin), new MessagesConfig(plugin), new ClassesConfig(plugin, true), new StatsConfig(plugin, true), + new DefaultConfig(plugin, true), false); + minigame.pluginInstance = MinigamesAPI.getAPI().getPluginInstance(plugin); + return minigame; + } + } + + /** + * data of a single minigame + * + * @author mepeisen + */ + public static final class Minigame + { + /** stats.yml */ + public YamlConfiguration statsYml; + /** shop.yml */ + public YamlConfiguration shopYml; + /** messages.yml */ + public YamlConfiguration messagesYml; + /** holograms.yml */ + public YamlConfiguration hologramsYml; + /** classes.yml */ + public YamlConfiguration classesYml; + /** guns.yml */ + public YamlConfiguration gunsYml; + /** arenas.yml */ + public YamlConfiguration arenasYml; + /** achievements.yml */ + public YamlConfiguration achievementsYml; + /** this minigame plugin instance. */ + public PluginInstance pluginInstance; + /** the minigame java plugin. */ + public JavaPlugin javaPlugin; + + /** + * Adds a location component to config + * + * @param arenaName + * arena name + * @param component + * component path (f.e. "lobby") + * @param world + * the world + * @param x + * the x coordinate + * @param y + * the y coordinate + * @param z + * the z coordinate + * @param pitch + * the pitch + * @param yaw + * the yaw + */ + public void addArenaComponentToConfig(String arenaName, String component, String world, double x, double y, double z, double pitch, double yaw) + { + this.addComponentToConfig(this.arenasYml, "arenas." + arenaName + "." + component, world, x, y, z, pitch, yaw); //$NON-NLS-1$ //$NON-NLS-2$ + } + + /** + * Adds a location component to config + * + * @param config + * configuration to use + * @param path + * component path (f.e. "arenas.xyz.lobby") + * @param world + * the world + * @param x + * the x coordinate + * @param y + * the y coordinate + * @param z + * the z coordinate + * @param pitch + * the pitch + * @param yaw + * the yaw + */ + public void addComponentToConfig(YamlConfiguration config, String path, String world, double x, double y, double z, double pitch, double yaw) + { + config.set(path + ".world", world); //$NON-NLS-1$ + final Map<String, Object> location = new HashMap<>(); + location.put("x", Double.valueOf(x)); //$NON-NLS-1$ + location.put("y", Double.valueOf(y)); //$NON-NLS-1$ + location.put("z", Double.valueOf(z)); //$NON-NLS-1$ + location.put("pitch", Double.valueOf(pitch)); //$NON-NLS-1$ + location.put("yaw", Double.valueOf(yaw)); //$NON-NLS-1$ + config.createSection(path + ".location", location); //$NON-NLS-1$ + } + } + +} diff --git a/Jenkinsfile b/Jenkinsfile new file mode 100644 index 00000000..3feecabb --- /dev/null +++ b/Jenkinsfile @@ -0,0 +1,61 @@ +pipeline { + agent any + tools { + maven 'maven3.5.0' + jdk 'jdk8' + } + stages { + stage ('Initialization') { + steps { + echo 'Preparing for build' + } + } + + stage ('Build') { + steps { + sh 'mvn clean install' + archiveArtifacts artifacts: '**/target/*.jar', fingerprint: true + } + post { + failure { + mail to: 'mep_eisen@web.de', subject: 'build of MinigamesLib failed', body: 'build of MinigamesLib failed' + } + } + } + + stage ('Upload') { + steps { + script { + env.BUILDTYPE = readPomVersion().endsWith("-SNAPSHOT") ? "snapshots" : "releases"; + } + sh "/srv/hudson/upload_product.sh ${env.BUILDTYPE} API/target 1 minigameslib MinigamesLib" + } + } + + stage ('Deploy') { + when { + expression { + currentBuild.result == null || currentBuild.result == 'SUCCESS' + } + } + steps { + sh 'mvn -Dmce.deployment=true -Dmaven.test.skip=true -DskipTests deploy' + } + post { + failure { + mail to: 'mep_eisen@web.de', subject: 'deploy of MinigamesLib failed', body: 'deploy of MinigamesLib failed' + } + } + } + } +} + +def readPomVersion() { + // Reference: http://stackoverflow.com/a/26514030/1851299 + sh "mvn --quiet --non-recursive -Dexec.executable='echo' -Dexec.args='\${project.version}' org.codehaus.mojo:exec-maven-plugin:1.3.1:exec > pom.project.version.txt" + pomProjectVersion = readFile('pom.project.version.txt').trim() + sh "rm -f pom.project.version.txt" + echo "Current POM version: ${pomProjectVersion}" + return pomProjectVersion +} + diff --git a/README.md b/README.md index ca1e6b5d..fc7c7127 100644 --- a/README.md +++ b/README.md @@ -1,58 +1,94 @@ -MinigamesAPI [![Build Status](https://drone.io/github.com/instance01/MinigamesAPI/status.png?1)](https://drone.io/github.com/instance01/MinigamesAPI/latest) -============ - -Rich MinigamesAPI supporting different types of Minigames. - - -Development Files can be found at https://drone.io/github.com/instance01/MinigamesAPI/files, use the release in the mid. - - -Features --------- - - -- Arenasystem -- Customizable messages -- Different minigame types -- VIP Arenas -- Economy, command and item rewards -- Overall Customization/Attributes like player counts, countdowns, spawns, boundaries etc. -- Signs and corresponding Arena states -- Fast map regeneration mechanism -- Kits/Classes and Classes Gui -- Arcade system -- MySQL/SQLite support -- Guns API (unfinished and only in use in Warlock Tactical right now) -- Bungee support including signs -- Party (/party) -- Achievements -- Additional shops with Gui -- Included effects like blood or dead bodies lying around -- More stuff - - -Oh and of course a bunch of [premade Minigames and examples](https://github.com/MC-Minigames/). - -See the [wiki](https://github.com/instance01/MinigamesAPI/wiki) or the [JavaDocs](http://www.instancedev.com/bukkitdev/MinigamesAPI/javadocs/) for more information on API usage. - - -Maven ------ - -``` - -<repository> - <id>MinigamesAPI-Repo</id> - <name>MinigamesAPI Repository</name> - <url>http://www.instancedev.com/bukkitdev/MinigamesAPI/maven/</url> -</repository> - -<dependency> - <groupId>com.comze_instancelabs</groupId> - <artifactId>MinigamesLib</artifactId> - <version>1.11.0</version> -</dependency> - - -``` - +MinigamesAPI [![Build Status](http://www.minigameslib.de/build.png?app=all&major=1)](http://www.minigameslib.de/buildref.php?app=all&major=1) +============ + +Rich MinigamesAPI supporting different types of Minigames in spigot-minecraft. +Originally written by instancelabs. + +Release builds can be found at (Nexus repository)[http://nexus.xworlds.eu/nexus/content/repositories/mce-releases/] +Development Files can be found at (Nexus repository)[http://nexus.xworlds.eu/nexus/content/repositories/mce-snapshots/] +Complete download package at (Minigameslib.de)[http://www.minigameslib.de/downloads_en.php#all] + +Tested with 1.8.X, 1.9.X, 1.10, 1.11 + + +Features +-------- + +- Arenasystem +- Customizable messages +- Different minigame types +- VIP Arenas +- Economy, command and item rewards +- Overall Customization/Attributes like player counts, countdowns, spawns, boundaries etc. +- Signs and corresponding Arena states +- Fast map regeneration mechanism +- Kits/Classes and Classes Gui +- Arcade system +- MySQL/SQLite support +- Guns API (unfinished and only in use in Warlock Tactical right now) +- Bungee support including signs +- Party (/party) +- Achievements +- Additional shops with Gui +- Included effects like blood or dead bodies lying around +- More stuff + +For details on premium services and for downloads see our [Homepage](http://www.minigameslib.de/index_en.php). + +See the [wiki](https://github.com/MysticCity/MinigamesAPI/wiki) or the JavaDocs for more information on API usage. + + +Games +----- + +- [BedWars](https://github.com/MysticCity/BedWars) +- [BowBash](https://github.com/MysticCity/BowBash) +- [ColorMatch](https://github.com/MysticCity/ColorMatch) +- [Conquer](https://github.com/MysticCity/Conquer) +- [DeathRun](https://github.com/MysticCity/MGDeathRun) +- [FlyingCars](https://github.com/MysticCity/FlyingCars) +- [GunGame](https://github.com/MysticCity/GunGame) +- [HorseRacingPlus](https://github.com/MysticCity/HorseRacingPlus) +- [Jumper](https://github.com/MysticCity/Jumper) +- [MobEscape](https://github.com/MysticCity/MGMobEscape) +- [NoteBlockBlitz](https://github.com/MysticCity/NoteblockBlitz) +- [OneInTheChamber](https://github.com/MysticCity/MGOneInTheChamber) +- [SeaBattle](https://github.com/MysticCity/SeaBattle) +- [SkyWars](https://github.com/MysticCity/MGSkyWars) +- [Snake](https://github.com/MysticCity/Snake) +- [Splegg](https://github.com/MysticCity/MGSplegg) +- [Sudoku](https://github.com/MysticCity/Sudoku) +- [TrapdoorSpleef](https://github.com/MysticCity/TrapdoorSpleef) +- [Warlock](https://github.com/MysticCity/Warlock) +- [WarlockTactical](https://github.com/MysticCity/Warlock-Tactical) + + +Links +----- + +- (Wiki)[https://github.com/MysticCity/MinigamesAPI/wiki] +- (Issues/Support)[https://github.com/MysticCity/MinigamesAPI/issues] +- (Resource@spigotmc)[https://www.spigotmc.org/resources/minigameslib.23844/] +- (Forum@Spigotmc)[https://www.spigotmc.org/threads/minigameslib.150548/] + + +Maven +----- + +``` + +<repository> + <id>MinigamesAPI-Repo</id> + <name>MinigamesAPI Repository</name> + <url>http://nexus.xworlds.eu/nexus/content/groups/mce/</url> +</repository> + +<dependency> + <groupId>com.github.MCE-Plugins</groupId> + <artifactId>MinigamesLib</artifactId> + <version>1.14.16-SNAPSHOT</version> +</dependency> + + +``` + diff --git a/Spigot-Test/.classpath b/Spigot-Test/.classpath new file mode 100644 index 00000000..1945bc02 --- /dev/null +++ b/Spigot-Test/.classpath @@ -0,0 +1,26 @@ +<?xml version="1.0" encoding="UTF-8"?> +<classpath> + <classpathentry including="**/*.java" kind="src" output="target/classes" path="src/main/java"> + <attributes> + <attribute name="optional" value="true"/> + <attribute name="maven.pomderived" value="true"/> + </attributes> + </classpathentry> + <classpathentry kind="src" output="target/test-classes" path="src/test/java"> + <attributes> + <attribute name="optional" value="true"/> + <attribute name="maven.pomderived" value="true"/> + </attributes> + </classpathentry> + <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8"> + <attributes> + <attribute name="maven.pomderived" value="true"/> + </attributes> + </classpathentry> + <classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER"> + <attributes> + <attribute name="maven.pomderived" value="true"/> + </attributes> + </classpathentry> + <classpathentry kind="output" path="target/classes"/> +</classpath> diff --git a/Spigot-Test/.project b/Spigot-Test/.project new file mode 100644 index 00000000..02437c30 --- /dev/null +++ b/Spigot-Test/.project @@ -0,0 +1,23 @@ +<?xml version="1.0" encoding="UTF-8"?> +<projectDescription> + <name>MinigamesLib-Spigot-Test</name> + <comment></comment> + <projects> + </projects> + <buildSpec> + <buildCommand> + <name>org.eclipse.jdt.core.javabuilder</name> + <arguments> + </arguments> + </buildCommand> + <buildCommand> + <name>org.eclipse.m2e.core.maven2Builder</name> + <arguments> + </arguments> + </buildCommand> + </buildSpec> + <natures> + <nature>org.eclipse.jdt.core.javanature</nature> + <nature>org.eclipse.m2e.core.maven2Nature</nature> + </natures> +</projectDescription> diff --git a/Spigot-Test/.settings/org.eclipse.core.resources.prefs b/Spigot-Test/.settings/org.eclipse.core.resources.prefs new file mode 100644 index 00000000..ed7df2b3 --- /dev/null +++ b/Spigot-Test/.settings/org.eclipse.core.resources.prefs @@ -0,0 +1,6 @@ +eclipse.preferences.version=1 +encoding//src/main/java=UTF-8 +encoding//src/main/resources=UTF-8 +encoding//src/test/java=UTF-8 +encoding/<project>=UTF-8 +encoding/src=UTF-8 diff --git a/Spigot-Test/.settings/org.eclipse.jdt.core.prefs b/Spigot-Test/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 00000000..597b1ac6 --- /dev/null +++ b/Spigot-Test/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,433 @@ +eclipse.preferences.version=1 +org.eclipse.jdt.core.codeComplete.argumentPrefixes= +org.eclipse.jdt.core.codeComplete.argumentSuffixes= +org.eclipse.jdt.core.codeComplete.fieldPrefixes= +org.eclipse.jdt.core.codeComplete.fieldSuffixes= +org.eclipse.jdt.core.codeComplete.localPrefixes= +org.eclipse.jdt.core.codeComplete.localSuffixes= +org.eclipse.jdt.core.codeComplete.staticFieldPrefixes= +org.eclipse.jdt.core.codeComplete.staticFieldSuffixes= +org.eclipse.jdt.core.codeComplete.staticFinalFieldPrefixes= +org.eclipse.jdt.core.codeComplete.staticFinalFieldSuffixes= +org.eclipse.jdt.core.compiler.annotation.inheritNullAnnotations=disabled +org.eclipse.jdt.core.compiler.annotation.missingNonNullByDefaultAnnotation=ignore +org.eclipse.jdt.core.compiler.annotation.nonnull=org.eclipse.jdt.annotation.NonNull +org.eclipse.jdt.core.compiler.annotation.nonnull.secondary= +org.eclipse.jdt.core.compiler.annotation.nonnullbydefault=org.eclipse.jdt.annotation.NonNullByDefault +org.eclipse.jdt.core.compiler.annotation.nonnullbydefault.secondary= +org.eclipse.jdt.core.compiler.annotation.nullable=org.eclipse.jdt.annotation.Nullable +org.eclipse.jdt.core.compiler.annotation.nullable.secondary= +org.eclipse.jdt.core.compiler.annotation.nullanalysis=disabled +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.methodParameters=do not generate +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 +org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve +org.eclipse.jdt.core.compiler.compliance=1.8 +org.eclipse.jdt.core.compiler.debug.lineNumber=generate +org.eclipse.jdt.core.compiler.debug.localVariable=generate +org.eclipse.jdt.core.compiler.debug.sourceFile=generate +org.eclipse.jdt.core.compiler.doc.comment.support=enabled +org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.autoboxing=ignore +org.eclipse.jdt.core.compiler.problem.comparingIdentical=warning +org.eclipse.jdt.core.compiler.problem.deadCode=warning +org.eclipse.jdt.core.compiler.problem.deprecation=warning +org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled +org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=disabled +org.eclipse.jdt.core.compiler.problem.discouragedReference=warning +org.eclipse.jdt.core.compiler.problem.emptyStatement=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.problem.explicitlyClosedAutoCloseable=warning +org.eclipse.jdt.core.compiler.problem.fallthroughCase=warning +org.eclipse.jdt.core.compiler.problem.fatalOptionalError=disabled +org.eclipse.jdt.core.compiler.problem.fieldHiding=warning +org.eclipse.jdt.core.compiler.problem.finalParameterBound=warning +org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=warning +org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning +org.eclipse.jdt.core.compiler.problem.hiddenCatchBlock=warning +org.eclipse.jdt.core.compiler.problem.includeNullInfoFromAsserts=enabled +org.eclipse.jdt.core.compiler.problem.incompatibleNonInheritedInterfaceMethod=warning +org.eclipse.jdt.core.compiler.problem.incompleteEnumSwitch=warning +org.eclipse.jdt.core.compiler.problem.indirectStaticAccess=warning +org.eclipse.jdt.core.compiler.problem.invalidJavadoc=warning +org.eclipse.jdt.core.compiler.problem.invalidJavadocTags=enabled +org.eclipse.jdt.core.compiler.problem.invalidJavadocTagsDeprecatedRef=enabled +org.eclipse.jdt.core.compiler.problem.invalidJavadocTagsNotVisibleRef=enabled +org.eclipse.jdt.core.compiler.problem.invalidJavadocTagsVisibility=private +org.eclipse.jdt.core.compiler.problem.localVariableHiding=warning +org.eclipse.jdt.core.compiler.problem.methodWithConstructorName=warning +org.eclipse.jdt.core.compiler.problem.missingDefaultCase=warning +org.eclipse.jdt.core.compiler.problem.missingDeprecatedAnnotation=warning +org.eclipse.jdt.core.compiler.problem.missingEnumCaseDespiteDefault=enabled +org.eclipse.jdt.core.compiler.problem.missingHashCodeMethod=error +org.eclipse.jdt.core.compiler.problem.missingJavadocComments=warning +org.eclipse.jdt.core.compiler.problem.missingJavadocCommentsOverriding=disabled +org.eclipse.jdt.core.compiler.problem.missingJavadocCommentsVisibility=private +org.eclipse.jdt.core.compiler.problem.missingJavadocTagDescription=return_tag +org.eclipse.jdt.core.compiler.problem.missingJavadocTags=warning +org.eclipse.jdt.core.compiler.problem.missingJavadocTagsMethodTypeParameters=disabled +org.eclipse.jdt.core.compiler.problem.missingJavadocTagsOverriding=disabled +org.eclipse.jdt.core.compiler.problem.missingJavadocTagsVisibility=private +org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotation=warning +org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotationForInterfaceMethodImplementation=enabled +org.eclipse.jdt.core.compiler.problem.missingSerialVersion=warning +org.eclipse.jdt.core.compiler.problem.missingSynchronizedOnInheritedMethod=warning +org.eclipse.jdt.core.compiler.problem.noEffectAssignment=warning +org.eclipse.jdt.core.compiler.problem.noImplicitStringConversion=warning +org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral=warning +org.eclipse.jdt.core.compiler.problem.nonnullParameterAnnotationDropped=warning +org.eclipse.jdt.core.compiler.problem.nonnullTypeVariableFromLegacyInvocation=warning +org.eclipse.jdt.core.compiler.problem.nullAnnotationInferenceConflict=error +org.eclipse.jdt.core.compiler.problem.nullReference=warning +org.eclipse.jdt.core.compiler.problem.nullSpecViolation=error +org.eclipse.jdt.core.compiler.problem.nullUncheckedConversion=warning +org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod=warning +org.eclipse.jdt.core.compiler.problem.parameterAssignment=error +org.eclipse.jdt.core.compiler.problem.pessimisticNullAnalysisForFreeTypeVariables=warning +org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment=warning +org.eclipse.jdt.core.compiler.problem.potentialNullReference=warning +org.eclipse.jdt.core.compiler.problem.potentiallyUnclosedCloseable=warning +org.eclipse.jdt.core.compiler.problem.rawTypeReference=warning +org.eclipse.jdt.core.compiler.problem.redundantNullAnnotation=warning +org.eclipse.jdt.core.compiler.problem.redundantNullCheck=warning +org.eclipse.jdt.core.compiler.problem.redundantSpecificationOfTypeArguments=warning +org.eclipse.jdt.core.compiler.problem.redundantSuperinterface=warning +org.eclipse.jdt.core.compiler.problem.reportMethodCanBePotentiallyStatic=ignore +org.eclipse.jdt.core.compiler.problem.reportMethodCanBeStatic=ignore +org.eclipse.jdt.core.compiler.problem.specialParameterHidingField=disabled +org.eclipse.jdt.core.compiler.problem.staticAccessReceiver=warning +org.eclipse.jdt.core.compiler.problem.suppressOptionalErrors=disabled +org.eclipse.jdt.core.compiler.problem.suppressWarnings=enabled +org.eclipse.jdt.core.compiler.problem.syntacticNullAnalysisForFields=disabled +org.eclipse.jdt.core.compiler.problem.syntheticAccessEmulation=warning +org.eclipse.jdt.core.compiler.problem.typeParameterHiding=warning +org.eclipse.jdt.core.compiler.problem.unavoidableGenericTypeProblems=enabled +org.eclipse.jdt.core.compiler.problem.uncheckedTypeOperation=warning +org.eclipse.jdt.core.compiler.problem.unclosedCloseable=warning +org.eclipse.jdt.core.compiler.problem.undocumentedEmptyBlock=error +org.eclipse.jdt.core.compiler.problem.unhandledWarningToken=warning +org.eclipse.jdt.core.compiler.problem.unnecessaryElse=warning +org.eclipse.jdt.core.compiler.problem.unnecessaryTypeCheck=warning +org.eclipse.jdt.core.compiler.problem.unqualifiedFieldAccess=warning +org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownException=warning +org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionExemptExceptionAndThrowable=enabled +org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionIncludeDocCommentReference=enabled +org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionWhenOverriding=disabled +org.eclipse.jdt.core.compiler.problem.unusedExceptionParameter=warning +org.eclipse.jdt.core.compiler.problem.unusedImport=warning +org.eclipse.jdt.core.compiler.problem.unusedLabel=warning +org.eclipse.jdt.core.compiler.problem.unusedLocal=warning +org.eclipse.jdt.core.compiler.problem.unusedObjectAllocation=warning +org.eclipse.jdt.core.compiler.problem.unusedParameter=warning +org.eclipse.jdt.core.compiler.problem.unusedParameterIncludeDocCommentReference=enabled +org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=disabled +org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=disabled +org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=warning +org.eclipse.jdt.core.compiler.problem.unusedTypeParameter=warning +org.eclipse.jdt.core.compiler.problem.unusedWarningToken=warning +org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning +org.eclipse.jdt.core.compiler.source=1.8 +org.eclipse.jdt.core.formatter.align_fields_grouping_blank_lines=2147483647 +org.eclipse.jdt.core.formatter.align_type_members_on_columns=true +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression=16 +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_annotation=0 +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_enum_constant=16 +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_explicit_constructor_call=16 +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_method_invocation=16 +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_qualified_allocation_expression=16 +org.eclipse.jdt.core.formatter.alignment_for_assignment=0 +org.eclipse.jdt.core.formatter.alignment_for_binary_expression=16 +org.eclipse.jdt.core.formatter.alignment_for_compact_if=16 +org.eclipse.jdt.core.formatter.alignment_for_conditional_expression=80 +org.eclipse.jdt.core.formatter.alignment_for_enum_constants=0 +org.eclipse.jdt.core.formatter.alignment_for_expressions_in_array_initializer=16 +org.eclipse.jdt.core.formatter.alignment_for_expressions_in_for_loop_header=0 +org.eclipse.jdt.core.formatter.alignment_for_method_declaration=0 +org.eclipse.jdt.core.formatter.alignment_for_multiple_fields=16 +org.eclipse.jdt.core.formatter.alignment_for_parameterized_type_references=0 +org.eclipse.jdt.core.formatter.alignment_for_parameters_in_constructor_declaration=16 +org.eclipse.jdt.core.formatter.alignment_for_parameters_in_method_declaration=16 +org.eclipse.jdt.core.formatter.alignment_for_resources_in_try=80 +org.eclipse.jdt.core.formatter.alignment_for_selector_in_method_invocation=16 +org.eclipse.jdt.core.formatter.alignment_for_superclass_in_type_declaration=16 +org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_enum_declaration=16 +org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_type_declaration=16 +org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_constructor_declaration=16 +org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_method_declaration=16 +org.eclipse.jdt.core.formatter.alignment_for_type_arguments=0 +org.eclipse.jdt.core.formatter.alignment_for_type_parameters=0 +org.eclipse.jdt.core.formatter.alignment_for_union_type_in_multicatch=16 +org.eclipse.jdt.core.formatter.blank_lines_after_imports=1 +org.eclipse.jdt.core.formatter.blank_lines_after_package=1 +org.eclipse.jdt.core.formatter.blank_lines_before_field=0 +org.eclipse.jdt.core.formatter.blank_lines_before_first_class_body_declaration=0 +org.eclipse.jdt.core.formatter.blank_lines_before_imports=1 +org.eclipse.jdt.core.formatter.blank_lines_before_member_type=1 +org.eclipse.jdt.core.formatter.blank_lines_before_method=1 +org.eclipse.jdt.core.formatter.blank_lines_before_new_chunk=1 +org.eclipse.jdt.core.formatter.blank_lines_before_package=0 +org.eclipse.jdt.core.formatter.blank_lines_between_import_groups=1 +org.eclipse.jdt.core.formatter.blank_lines_between_type_declarations=1 +org.eclipse.jdt.core.formatter.brace_position_for_annotation_type_declaration=next_line +org.eclipse.jdt.core.formatter.brace_position_for_anonymous_type_declaration=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_array_initializer=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_block=next_line +org.eclipse.jdt.core.formatter.brace_position_for_block_in_case=next_line +org.eclipse.jdt.core.formatter.brace_position_for_constructor_declaration=next_line +org.eclipse.jdt.core.formatter.brace_position_for_enum_constant=next_line +org.eclipse.jdt.core.formatter.brace_position_for_enum_declaration=next_line +org.eclipse.jdt.core.formatter.brace_position_for_lambda_body=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_method_declaration=next_line +org.eclipse.jdt.core.formatter.brace_position_for_switch=next_line +org.eclipse.jdt.core.formatter.brace_position_for_type_declaration=next_line +org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_block_comment=false +org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_javadoc_comment=false +org.eclipse.jdt.core.formatter.comment.format_block_comments=true +org.eclipse.jdt.core.formatter.comment.format_header=false +org.eclipse.jdt.core.formatter.comment.format_html=true +org.eclipse.jdt.core.formatter.comment.format_javadoc_comments=true +org.eclipse.jdt.core.formatter.comment.format_line_comments=true +org.eclipse.jdt.core.formatter.comment.format_source_code=true +org.eclipse.jdt.core.formatter.comment.indent_parameter_description=true +org.eclipse.jdt.core.formatter.comment.indent_root_tags=true +org.eclipse.jdt.core.formatter.comment.insert_new_line_before_root_tags=insert +org.eclipse.jdt.core.formatter.comment.insert_new_line_for_parameter=insert +org.eclipse.jdt.core.formatter.comment.line_length=200 +org.eclipse.jdt.core.formatter.comment.new_lines_at_block_boundaries=true +org.eclipse.jdt.core.formatter.comment.new_lines_at_javadoc_boundaries=true +org.eclipse.jdt.core.formatter.comment.preserve_white_space_between_code_and_line_comments=false +org.eclipse.jdt.core.formatter.compact_else_if=true +org.eclipse.jdt.core.formatter.continuation_indentation=2 +org.eclipse.jdt.core.formatter.continuation_indentation_for_array_initializer=2 +org.eclipse.jdt.core.formatter.disabling_tag=@formatter\:off +org.eclipse.jdt.core.formatter.enabling_tag=@formatter\:on +org.eclipse.jdt.core.formatter.format_guardian_clause_on_one_line=false +org.eclipse.jdt.core.formatter.format_line_comment_starting_on_first_column=true +org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_annotation_declaration_header=true +org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_constant_header=true +org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_declaration_header=true +org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_type_header=true +org.eclipse.jdt.core.formatter.indent_breaks_compare_to_cases=true +org.eclipse.jdt.core.formatter.indent_empty_lines=true +org.eclipse.jdt.core.formatter.indent_statements_compare_to_block=true +org.eclipse.jdt.core.formatter.indent_statements_compare_to_body=true +org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_cases=true +org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_switch=true +org.eclipse.jdt.core.formatter.indentation.size=4 +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_enum_constant=insert +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_field=insert +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_local_variable=insert +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_method=insert +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_package=insert +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_parameter=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_type=insert +org.eclipse.jdt.core.formatter.insert_new_line_after_label=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_after_opening_brace_in_array_initializer=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_after_type_annotation=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_at_end_of_file_if_missing=insert +org.eclipse.jdt.core.formatter.insert_new_line_before_catch_in_try_statement=insert +org.eclipse.jdt.core.formatter.insert_new_line_before_closing_brace_in_array_initializer=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_before_else_in_if_statement=insert +org.eclipse.jdt.core.formatter.insert_new_line_before_finally_in_try_statement=insert +org.eclipse.jdt.core.formatter.insert_new_line_before_while_in_do_statement=insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_annotation_declaration=insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_anonymous_type_declaration=insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_block=insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_constant=insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_declaration=insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_method_body=insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_type_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_after_and_in_type_parameter=insert +org.eclipse.jdt.core.formatter.insert_space_after_assignment_operator=insert +org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation_type_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_binary_operator=insert +org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_parameters=insert +org.eclipse.jdt.core.formatter.insert_space_after_closing_brace_in_block=insert +org.eclipse.jdt.core.formatter.insert_space_after_closing_paren_in_cast=insert +org.eclipse.jdt.core.formatter.insert_space_after_colon_in_assert=insert +org.eclipse.jdt.core.formatter.insert_space_after_colon_in_case=insert +org.eclipse.jdt.core.formatter.insert_space_after_colon_in_conditional=insert +org.eclipse.jdt.core.formatter.insert_space_after_colon_in_for=insert +org.eclipse.jdt.core.formatter.insert_space_after_colon_in_labeled_statement=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_allocation_expression=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_annotation=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_array_initializer=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_parameters=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_throws=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_constant_arguments=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_declarations=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_explicitconstructorcall_arguments=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_increments=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_inits=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_parameters=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_throws=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_invocation_arguments=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_field_declarations=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_local_declarations=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_parameterized_type_reference=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_superinterfaces=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_arguments=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_parameters=insert +org.eclipse.jdt.core.formatter.insert_space_after_ellipsis=insert +org.eclipse.jdt.core.formatter.insert_space_after_lambda_arrow=insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_parameterized_type_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_brace_in_array_initializer=insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_allocation_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_annotation=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_cast=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_catch=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_constructor_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_enum_constant=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_for=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_if=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_invocation=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_parenthesized_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_switch=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_synchronized=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_try=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_while=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_postfix_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_prefix_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_question_in_conditional=insert +org.eclipse.jdt.core.formatter.insert_space_after_question_in_wildcard=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_for=insert +org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_try_resources=insert +org.eclipse.jdt.core.formatter.insert_space_after_unary_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_and_in_type_parameter=insert +org.eclipse.jdt.core.formatter.insert_space_before_assignment_operator=insert +org.eclipse.jdt.core.formatter.insert_space_before_at_in_annotation_type_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_binary_operator=insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_parameterized_type_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_brace_in_array_initializer=insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_allocation_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_annotation=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_cast=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_catch=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_constructor_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_enum_constant=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_for=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_if=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_invocation=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_parenthesized_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_switch=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_synchronized=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_try=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_while=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_assert=insert +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_case=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_conditional=insert +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_default=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_for=insert +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_labeled_statement=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_allocation_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_annotation=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_array_initializer=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_throws=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_constant_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_declarations=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_explicitconstructorcall_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_increments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_inits=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_throws=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_invocation_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_field_declarations=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_local_declarations=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_parameterized_type_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_superinterfaces=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_ellipsis=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_lambda_arrow=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_parameterized_type_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_annotation_type_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_anonymous_type_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_array_initializer=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_block=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_constructor_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_constant=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_method_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_switch=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_type_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_allocation_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_type_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation_type_member_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_catch=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_constructor_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_enum_constant=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_for=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_if=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_invocation=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_parenthesized_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_switch=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_synchronized=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_try=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_while=insert +org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_return=insert +org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_throw=insert +org.eclipse.jdt.core.formatter.insert_space_before_postfix_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_prefix_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_question_in_conditional=insert +org.eclipse.jdt.core.formatter.insert_space_before_question_in_wildcard=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_semicolon=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_semicolon_in_for=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_semicolon_in_try_resources=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_unary_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_brackets_in_array_type_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_braces_in_array_initializer=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_brackets_in_array_allocation_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_annotation_type_member_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_constructor_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_enum_constant=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_invocation=do not insert +org.eclipse.jdt.core.formatter.join_lines_in_comments=true +org.eclipse.jdt.core.formatter.join_wrapped_lines=true +org.eclipse.jdt.core.formatter.keep_else_statement_on_same_line=false +org.eclipse.jdt.core.formatter.keep_empty_array_initializer_on_one_line=false +org.eclipse.jdt.core.formatter.keep_imple_if_on_one_line=false +org.eclipse.jdt.core.formatter.keep_then_statement_on_same_line=false +org.eclipse.jdt.core.formatter.lineSplit=200 +org.eclipse.jdt.core.formatter.never_indent_block_comments_on_first_column=false +org.eclipse.jdt.core.formatter.never_indent_line_comments_on_first_column=false +org.eclipse.jdt.core.formatter.number_of_blank_lines_at_beginning_of_method_body=0 +org.eclipse.jdt.core.formatter.number_of_empty_lines_to_preserve=1 +org.eclipse.jdt.core.formatter.parentheses_positions_in_annotation=common_lines +org.eclipse.jdt.core.formatter.parentheses_positions_in_catch_clause=common_lines +org.eclipse.jdt.core.formatter.parentheses_positions_in_enum_constant_declaration=common_lines +org.eclipse.jdt.core.formatter.parentheses_positions_in_for_statment=common_lines +org.eclipse.jdt.core.formatter.parentheses_positions_in_if_while_statement=common_lines +org.eclipse.jdt.core.formatter.parentheses_positions_in_lambda_declaration=common_lines +org.eclipse.jdt.core.formatter.parentheses_positions_in_method_delcaration=common_lines +org.eclipse.jdt.core.formatter.parentheses_positions_in_method_invocation=common_lines +org.eclipse.jdt.core.formatter.parentheses_positions_in_switch_statement=common_lines +org.eclipse.jdt.core.formatter.parentheses_positions_in_try_clause=common_lines +org.eclipse.jdt.core.formatter.put_empty_statement_on_new_line=true +org.eclipse.jdt.core.formatter.tabulation.char=space +org.eclipse.jdt.core.formatter.tabulation.size=4 +org.eclipse.jdt.core.formatter.use_on_off_tags=true +org.eclipse.jdt.core.formatter.use_tabs_only_for_leading_indentations=false +org.eclipse.jdt.core.formatter.wrap_before_assignment_operator=false +org.eclipse.jdt.core.formatter.wrap_before_binary_operator=true +org.eclipse.jdt.core.formatter.wrap_before_conditional_operator=true +org.eclipse.jdt.core.formatter.wrap_before_or_operator_multicatch=true +org.eclipse.jdt.core.formatter.wrap_outer_expressions_when_nested=true +org.eclipse.jdt.core.javaFormatter=org.eclipse.jdt.core.defaultJavaFormatter diff --git a/Spigot-Test/.settings/org.eclipse.jdt.ui.prefs b/Spigot-Test/.settings/org.eclipse.jdt.ui.prefs new file mode 100644 index 00000000..51307816 --- /dev/null +++ b/Spigot-Test/.settings/org.eclipse.jdt.ui.prefs @@ -0,0 +1,67 @@ +cleanup.add_default_serial_version_id=false +cleanup.add_generated_serial_version_id=true +cleanup.add_missing_annotations=true +cleanup.add_missing_deprecated_annotations=true +cleanup.add_missing_methods=false +cleanup.add_missing_nls_tags=false +cleanup.add_missing_override_annotations=true +cleanup.add_missing_override_annotations_interface_methods=true +cleanup.add_serial_version_id=true +cleanup.always_use_blocks=true +cleanup.always_use_parentheses_in_expressions=false +cleanup.always_use_this_for_non_static_field_access=true +cleanup.always_use_this_for_non_static_method_access=true +cleanup.convert_functional_interfaces=true +cleanup.convert_to_enhanced_for_loop=true +cleanup.correct_indentation=true +cleanup.format_source_code=true +cleanup.format_source_code_changes_only=false +cleanup.insert_inferred_type_arguments=false +cleanup.make_local_variable_final=true +cleanup.make_parameters_final=true +cleanup.make_private_fields_final=true +cleanup.make_type_abstract_if_missing_method=false +cleanup.make_variable_declarations_final=true +cleanup.never_use_blocks=false +cleanup.never_use_parentheses_in_expressions=true +cleanup.organize_imports=true +cleanup.qualify_static_field_accesses_with_declaring_class=true +cleanup.qualify_static_member_accesses_through_instances_with_declaring_class=true +cleanup.qualify_static_member_accesses_through_subtypes_with_declaring_class=true +cleanup.qualify_static_member_accesses_with_declaring_class=true +cleanup.qualify_static_method_accesses_with_declaring_class=true +cleanup.remove_private_constructors=true +cleanup.remove_redundant_type_arguments=true +cleanup.remove_trailing_whitespaces=true +cleanup.remove_trailing_whitespaces_all=true +cleanup.remove_trailing_whitespaces_ignore_empty=false +cleanup.remove_unnecessary_casts=true +cleanup.remove_unnecessary_nls_tags=true +cleanup.remove_unused_imports=true +cleanup.remove_unused_local_variables=false +cleanup.remove_unused_private_fields=true +cleanup.remove_unused_private_members=false +cleanup.remove_unused_private_methods=true +cleanup.remove_unused_private_types=true +cleanup.sort_members=false +cleanup.sort_members_all=false +cleanup.use_anonymous_class_creation=false +cleanup.use_blocks=true +cleanup.use_blocks_only_for_return_and_throw=false +cleanup.use_lambda=true +cleanup.use_parentheses_in_expressions=false +cleanup.use_this_for_non_static_field_access=true +cleanup.use_this_for_non_static_field_access_only_if_necessary=false +cleanup.use_this_for_non_static_method_access=true +cleanup.use_this_for_non_static_method_access_only_if_necessary=false +cleanup_profile=_Minigames +cleanup_settings_version=2 +eclipse.preferences.version=1 +formatter_profile=_Minigames +formatter_settings_version=12 +org.eclipse.jdt.ui.exception.name=e +org.eclipse.jdt.ui.gettersetter.use.is=true +org.eclipse.jdt.ui.javadoc=true +org.eclipse.jdt.ui.keywordthis=true +org.eclipse.jdt.ui.overrideannotation=true +org.eclipse.jdt.ui.text.custom_code_templates=<?xml version\="1.0" encoding\="UTF-8" standalone\="no"?><templates><template autoinsert\="true" context\="gettercomment_context" deleted\="false" description\="Comment for getter method" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.gettercomment" name\="gettercomment">/**\r\n * @return the ${bare_field_name}\r\n */</template><template autoinsert\="true" context\="settercomment_context" deleted\="false" description\="Comment for setter method" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.settercomment" name\="settercomment">/**\r\n * @param ${param} the ${bare_field_name} to set\r\n */</template><template autoinsert\="true" context\="constructorcomment_context" deleted\="false" description\="Comment for created constructors" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.constructorcomment" name\="constructorcomment">/**\r\n * ${tags}\r\n */</template><template autoinsert\="false" context\="filecomment_context" deleted\="false" description\="Comment for created Java files" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.filecomment" name\="filecomment">/*\r\n This program is free software\: you can redistribute it and/or modify\r\n it under the terms of the GNU General Public License as published by\r\n the Free Software Foundation, either version 3 of the License, or\r\n (at your option) any later version.\r\n\r\n This program is distributed in the hope that it will be useful,\r\n but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r\n GNU General Public License for more details.\r\n\r\n You should have received a copy of the GNU General Public License\r\n along with this program. If not, see <http\://www.gnu.org/licenses/>.\r\n*/\r\n</template><template autoinsert\="true" context\="typecomment_context" deleted\="false" description\="Comment for created types" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.typecomment" name\="typecomment">/**\r\n * @author ${user}\r\n *\r\n * ${tags}\r\n */</template><template autoinsert\="true" context\="fieldcomment_context" deleted\="false" description\="Comment for fields" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.fieldcomment" name\="fieldcomment">/**\r\n * \r\n */</template><template autoinsert\="true" context\="methodcomment_context" deleted\="false" description\="Comment for non-overriding methods" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.methodcomment" name\="methodcomment">/**\r\n * ${tags}\r\n */</template><template autoinsert\="true" context\="overridecomment_context" deleted\="false" description\="Comment for overriding methods" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.overridecomment" name\="overridecomment">/* (non-Javadoc)\r\n * ${see_to_overridden}\r\n */</template><template autoinsert\="true" context\="delegatecomment_context" deleted\="false" description\="Comment for delegate methods" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.delegatecomment" name\="delegatecomment">/**\r\n * ${tags}\r\n * ${see_to_target}\r\n */</template><template autoinsert\="true" context\="newtype_context" deleted\="false" description\="Newly created files" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.newtype" name\="newtype">${filecomment}\r\n${package_declaration}\r\n\r\n${typecomment}\r\n${type_declaration}</template><template autoinsert\="true" context\="classbody_context" deleted\="false" description\="Code in new class type bodies" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.classbody" name\="classbody">\r\n</template><template autoinsert\="true" context\="interfacebody_context" deleted\="false" description\="Code in new interface type bodies" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.interfacebody" name\="interfacebody">\r\n</template><template autoinsert\="true" context\="enumbody_context" deleted\="false" description\="Code in new enum type bodies" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.enumbody" name\="enumbody">\r\n</template><template autoinsert\="true" context\="annotationbody_context" deleted\="false" description\="Code in new annotation type bodies" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.annotationbody" name\="annotationbody">\r\n</template><template autoinsert\="true" context\="catchblock_context" deleted\="false" description\="Code in new catch blocks" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.catchblock" name\="catchblock">// ${todo} Auto-generated catch block\r\n${exception_var}.printStackTrace();</template><template autoinsert\="true" context\="methodbody_context" deleted\="false" description\="Code in created method stubs" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.methodbody" name\="methodbody">// ${todo} Auto-generated method stub\r\n${body_statement}</template><template autoinsert\="true" context\="constructorbody_context" deleted\="false" description\="Code in created constructor stubs" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.constructorbody" name\="constructorbody">${body_statement}\r\n// ${todo} Auto-generated constructor stub</template><template autoinsert\="true" context\="getterbody_context" deleted\="false" description\="Code in created getters" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.getterbody" name\="getterbody">return ${field};</template><template autoinsert\="true" context\="setterbody_context" deleted\="false" description\="Code in created setters" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.setterbody" name\="setterbody">${field} \= ${param};</template></templates> diff --git a/Spigot-Test/.settings/org.eclipse.m2e.core.prefs b/Spigot-Test/.settings/org.eclipse.m2e.core.prefs new file mode 100644 index 00000000..f897a7f1 --- /dev/null +++ b/Spigot-Test/.settings/org.eclipse.m2e.core.prefs @@ -0,0 +1,4 @@ +activeProfiles= +eclipse.preferences.version=1 +resolveWorkspaceProjects=true +version=1 diff --git a/Spigot-Test/pom.xml b/Spigot-Test/pom.xml new file mode 100644 index 00000000..62dece46 --- /dev/null +++ b/Spigot-Test/pom.xml @@ -0,0 +1,87 @@ +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + <groupId>com.github.MCE-Plugins</groupId> + <artifactId>MinigamesLib-Spigot-Test</artifactId> + <version>1.14.18-SNAPSHOT</version> + <packaging>jar</packaging> + <name>MinigamesLib-Spigot-Test</name> + <description>Spigot-Test-Utilities</description> + + <parent> + <groupId>com.github.MCE-Plugins</groupId> + <artifactId>MinigamesLib-parent</artifactId> + <version>1.14.18-SNAPSHOT</version> + </parent> + + <dependencies> + <!-- <dependency> + <groupId>org.bukkit</groupId> + <artifactId>bukkit</artifactId> + </dependency> --> + <dependency> + <groupId>org.spigotmc</groupId> + <artifactId>spigot</artifactId> + </dependency> + + <dependency> + <groupId>junit</groupId> + <artifactId>junit</artifactId> + <scope>compile</scope> + </dependency> + <dependency> + <groupId>org.powermock</groupId> + <artifactId>powermock-module-junit4</artifactId> + <scope>compile</scope> + </dependency> + <dependency> + <groupId>org.powermock</groupId> + <artifactId>powermock-api-mockito</artifactId> + <scope>compile</scope> + </dependency> + </dependencies> + + <build> + <resources> + <resource> + <directory>src/main/resources</directory> + <filtering>true</filtering> + </resource> + <resource> + <directory>src/main/java</directory> + <includes> + <include>**/*.properties</include> + </includes> + </resource> + </resources> + <plugins> + <plugin> + <version>3.0.0</version> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-source-plugin</artifactId> + <executions> + <execution> + <id>attach-sources</id> + <goals> + <goal>jar</goal> + </goals> + </execution> + </executions> + </plugin> + <plugin> + <version>2.10.3</version> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-javadoc-plugin</artifactId> + <executions> + <execution> + <id>attach-javadoc</id> + <goals> + <goal>jar</goal> + </goals> + </execution> + </executions> + </plugin> + </plugins> + </build> + +</project> \ No newline at end of file diff --git a/Spigot-Test/src/main/java/com/comze_instancelabs/minigamesapi/spigottest/ArgUtil.java b/Spigot-Test/src/main/java/com/comze_instancelabs/minigamesapi/spigottest/ArgUtil.java new file mode 100644 index 00000000..96fbb52d --- /dev/null +++ b/Spigot-Test/src/main/java/com/comze_instancelabs/minigamesapi/spigottest/ArgUtil.java @@ -0,0 +1,71 @@ +/* + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +package com.comze_instancelabs.minigamesapi.spigottest; + +import static org.mockito.Matchers.argThat; + +import java.util.function.Supplier; + +import org.mockito.ArgumentMatcher; + +/** + * @author mepeisen + * + */ +public class ArgUtil +{ + + /** + * Returns a argument matcher that matches a value argument + * @param expected expected value + * @return matcher + */ + public static <T> T argEquals(T expected) + { + return argThat(new ArgumentMatcher<T>() { + + @Override + public boolean matches(Object argument) + { + @SuppressWarnings("unchecked") + final T actual = (T) argument; + return expected.equals(actual); + } + + }); + } + + /** + * Returns a argument matcher that matches a lambda supplier argument + * @param expected expected value returned by supplier + * @return matcher + */ + public static <T> Supplier<T> argSupplier(T expected) + { + return argThat(new ArgumentMatcher<Supplier<T>>() { + + @Override + public boolean matches(Object argument) + { + @SuppressWarnings("unchecked") + final T actual = ((Supplier<T>) argument).get(); + return expected.equals(actual); + } + + }); + } + +} diff --git a/Spigot-Test/src/main/java/com/comze_instancelabs/minigamesapi/spigottest/DummyEnchantments.java b/Spigot-Test/src/main/java/com/comze_instancelabs/minigamesapi/spigottest/DummyEnchantments.java new file mode 100644 index 00000000..36e563ac --- /dev/null +++ b/Spigot-Test/src/main/java/com/comze_instancelabs/minigamesapi/spigottest/DummyEnchantments.java @@ -0,0 +1,17 @@ +package com.comze_instancelabs.minigamesapi.spigottest; + +import net.minecraft.server.v1_12_R1.Enchantments; + +/** + * taken from spigot test sources + */ +class DummyEnchantments { + static { + Enchantments.DAMAGE_ALL.getClass(); + org.bukkit.enchantments.Enchantment.stopAcceptingRegistrations(); + } + + public static void setup() { + // dummy method + } +} diff --git a/Spigot-Test/src/main/java/com/comze_instancelabs/minigamesapi/spigottest/DummyObjective.java b/Spigot-Test/src/main/java/com/comze_instancelabs/minigamesapi/spigottest/DummyObjective.java new file mode 100644 index 00000000..13cdf68b --- /dev/null +++ b/Spigot-Test/src/main/java/com/comze_instancelabs/minigamesapi/spigottest/DummyObjective.java @@ -0,0 +1,140 @@ +/* + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +package com.comze_instancelabs.minigamesapi.spigottest; + +import java.util.HashMap; +import java.util.Map; + +import org.bukkit.OfflinePlayer; +import org.bukkit.scoreboard.DisplaySlot; +import org.bukkit.scoreboard.Objective; +import org.bukkit.scoreboard.Score; +import org.bukkit.scoreboard.Scoreboard; + +/** + * @author mepeisen + * + */ +public class DummyObjective implements Objective +{ + + private final String name; + + private final Map<String, Score> scores = new HashMap<>(); + + /** + * @param name + */ + public DummyObjective(String name) + { + this.name = name; + } + + @Override + public String getName() throws IllegalStateException + { + return this.name; + } + + /* (non-Javadoc) + * @see org.bukkit.scoreboard.Objective#getDisplayName() + */ + @Override + public String getDisplayName() throws IllegalStateException + { + // TODO Auto-generated method stub + return null; + } + + /* (non-Javadoc) + * @see org.bukkit.scoreboard.Objective#setDisplayName(java.lang.String) + */ + @Override + public void setDisplayName(String arg0) throws IllegalStateException, IllegalArgumentException + { + // TODO Auto-generated method stub + + } + + /* (non-Javadoc) + * @see org.bukkit.scoreboard.Objective#getCriteria() + */ + @Override + public String getCriteria() throws IllegalStateException + { + // TODO Auto-generated method stub + return null; + } + + @Override + public boolean isModifiable() throws IllegalStateException + { + return true; + } + + /* (non-Javadoc) + * @see org.bukkit.scoreboard.Objective#getScoreboard() + */ + @Override + public Scoreboard getScoreboard() + { + // TODO Auto-generated method stub + return null; + } + + /* (non-Javadoc) + * @see org.bukkit.scoreboard.Objective#unregister() + */ + @Override + public void unregister() throws IllegalStateException + { + // TODO Auto-generated method stub + + } + + /* (non-Javadoc) + * @see org.bukkit.scoreboard.Objective#setDisplaySlot(org.bukkit.scoreboard.DisplaySlot) + */ + @Override + public void setDisplaySlot(DisplaySlot arg0) throws IllegalStateException + { + // TODO Auto-generated method stub + + } + + /* (non-Javadoc) + * @see org.bukkit.scoreboard.Objective#getDisplaySlot() + */ + @Override + public DisplaySlot getDisplaySlot() throws IllegalStateException + { + // TODO Auto-generated method stub + return null; + } + + @Override + public Score getScore(OfflinePlayer arg0) throws IllegalArgumentException, IllegalStateException + { + return this.getScore(arg0.getName()); + } + + @Override + public Score getScore(String arg0) throws IllegalArgumentException, IllegalStateException + { + return this.scores.computeIfAbsent(arg0, (k) -> new DummyScore()); + } + +} diff --git a/Spigot-Test/src/main/java/com/comze_instancelabs/minigamesapi/spigottest/DummyPlayerInventory.java b/Spigot-Test/src/main/java/com/comze_instancelabs/minigamesapi/spigottest/DummyPlayerInventory.java new file mode 100644 index 00000000..21207bda --- /dev/null +++ b/Spigot-Test/src/main/java/com/comze_instancelabs/minigamesapi/spigottest/DummyPlayerInventory.java @@ -0,0 +1,47 @@ +/* + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +package com.comze_instancelabs.minigamesapi.spigottest; + +import org.bukkit.craftbukkit.v1_12_R1.inventory.CraftInventoryPlayer; +import org.bukkit.inventory.InventoryHolder; + +import net.minecraft.server.v1_12_R1.PlayerInventory; + +/** + * Helper class for player inventories. + * + * @author mepeisen + */ +public class DummyPlayerInventory extends CraftInventoryPlayer +{ + + /** + * Constructor + */ + public DummyPlayerInventory() + { + super(new PlayerInventory(null){ + + @Override + public InventoryHolder getOwner() + { + return null; + } + + }); + } + +} diff --git a/Spigot-Test/src/main/java/com/comze_instancelabs/minigamesapi/spigottest/DummyPluginManager.java b/Spigot-Test/src/main/java/com/comze_instancelabs/minigamesapi/spigottest/DummyPluginManager.java new file mode 100644 index 00000000..70d5f35e --- /dev/null +++ b/Spigot-Test/src/main/java/com/comze_instancelabs/minigamesapi/spigottest/DummyPluginManager.java @@ -0,0 +1,391 @@ +/* + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +package com.comze_instancelabs.minigamesapi.spigottest; + +import java.io.File; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Set; +import java.util.WeakHashMap; + +import org.bukkit.event.Event; +import org.bukkit.event.EventException; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.HandlerList; +import org.bukkit.event.Listener; +import org.bukkit.permissions.Permissible; +import org.bukkit.permissions.Permission; +import org.bukkit.permissions.PermissionDefault; +import org.bukkit.plugin.EventExecutor; +import org.bukkit.plugin.IllegalPluginAccessException; +import org.bukkit.plugin.InvalidDescriptionException; +import org.bukkit.plugin.InvalidPluginException; +import org.bukkit.plugin.Plugin; +import org.bukkit.plugin.PluginLoader; +import org.bukkit.plugin.PluginManager; +import org.bukkit.plugin.RegisteredListener; +import org.bukkit.plugin.UnknownDependencyException; +import org.bukkit.plugin.java.JavaPlugin; + +import com.google.common.collect.ImmutableSet; + +/** + * Simple plugin manager for testing. + * + * @author mepeisen + */ +class DummyPluginManager implements PluginManager +{ + + /** registered plugins per name. */ + private Map<String, JavaPlugin> plugins = new HashMap<>(); + + private final Map<String, Permission> permissions = new HashMap<String, Permission>(); + private final Map<Boolean, Set<Permission>> defaultPerms = new LinkedHashMap<Boolean, Set<Permission>>(); + private final Map<String, Map<Permissible, Boolean>> permSubs = new HashMap<String, Map<Permissible, Boolean>>(); + private final Map<Boolean, Map<Permissible, Boolean>> defSubs = new HashMap<Boolean, Map<Permissible, Boolean>>(); + + /** + * + */ + public DummyPluginManager() + { + this.defaultPerms.put(Boolean.TRUE, new HashSet<>()); + this.defaultPerms.put(Boolean.FALSE, new HashSet<>()); + } + + @Override + public void registerInterface(Class<? extends PluginLoader> loader) throws IllegalArgumentException + { + throw new UnsupportedOperationException(); + } + + /** + * Adds a mocked plugin. + * @param plugin java plugin to be registered. + */ + public void addMockedPlugin(JavaPlugin plugin) + { + this.plugins.put(plugin.getName().replace(' ', '_'), plugin); + } + + @Override + public Plugin getPlugin(String name) + { + return this.plugins.get(name.replace(' ' , '_')); + } + + @Override + public Plugin[] getPlugins() + { + return this.plugins.values().toArray(new Plugin[this.plugins.size()]); + } + + @Override + public boolean isPluginEnabled(String name) + { + return this.getPlugin(name) != null; + } + + @Override + public boolean isPluginEnabled(Plugin plugin) + { + return true; + } + + @Override + public Plugin loadPlugin(File file) throws InvalidPluginException, InvalidDescriptionException, UnknownDependencyException + { + throw new UnsupportedOperationException(); + } + + @Override + public Plugin[] loadPlugins(File directory) + { + throw new UnsupportedOperationException(); + } + + @Override + public void disablePlugins() + { + throw new UnsupportedOperationException(); + } + + @Override + public void clearPlugins() + { + this.plugins.clear(); + permissions.clear(); + if (defaultPerms.get(true) != null) defaultPerms.get(true).clear(); + if (defaultPerms.get(false) != null) defaultPerms.get(false).clear(); + HandlerList.unregisterAll(); + } + + @Override + public void callEvent(Event event) throws IllegalStateException + { + for (final RegisteredListener listener : getEventListeners(getRegistrationClass(event.getClass())).getRegisteredListeners()) + { + try + { + listener.callEvent(event); + } + catch (EventException ex) + { + ex.printStackTrace(); + } + } + } + + @Override + public void registerEvents(Listener listener, Plugin plugin) + { + // code mostly taken from Spigot: JavaPluginLoader.createRegisteredListeners + final Method[] publicMethods = listener.getClass().getMethods(); + final Method[] privateMethods = listener.getClass().getDeclaredMethods(); + final Set<Method> methods = new HashSet<>(publicMethods.length + privateMethods.length, 1.0f); + for (Method method : publicMethods) + { + methods.add(method); + } + for (Method method : privateMethods) + { + methods.add(method); + } + for (final Method method : methods) + { + final EventHandler eh = method.getAnnotation(EventHandler.class); + if (eh == null) continue; + if (method.isBridge() || method.isSynthetic()) + { + continue; + } + final Class<?> checkClass; + if (method.getParameterTypes().length != 1 || !Event.class.isAssignableFrom(checkClass = method.getParameterTypes()[0])) + { + continue; + } + final Class<? extends Event> eventClass = checkClass.asSubclass(Event.class); + method.setAccessible(true); + final EventExecutor executor = new EventExecutor() { + public void execute(Listener listener, Event event) throws EventException { + try { + if (!eventClass.isAssignableFrom(event.getClass())) { + return; + } + method.invoke(listener, event); + } catch (InvocationTargetException ex) { + throw new EventException(ex.getCause()); + } catch (Throwable t) { + throw new EventException(t); + } + } + }; + getEventListeners(getRegistrationClass(eventClass)).register(new RegisteredListener(listener, executor, eh.priority(), plugin, eh.ignoreCancelled())); + } + } + + // taken from Spigot: SimplePluginManager + private Class<? extends Event> getRegistrationClass(Class<? extends Event> clazz) { + try { + clazz.getDeclaredMethod("getHandlerList"); + return clazz; + } catch (NoSuchMethodException e) { + if (clazz.getSuperclass() != null + && !clazz.getSuperclass().equals(Event.class) + && Event.class.isAssignableFrom(clazz.getSuperclass())) { + return getRegistrationClass(clazz.getSuperclass().asSubclass(Event.class)); + } else { + throw new IllegalPluginAccessException("Unable to find handler list for event " + clazz.getName() + ". Static getHandlerList method required!"); + } + } + } + + // taken from Spigot: SimplePluginManager + private HandlerList getEventListeners(Class<? extends Event> type) { + try { + Method method = getRegistrationClass(type).getDeclaredMethod("getHandlerList"); + method.setAccessible(true); + return (HandlerList) method.invoke(null); + } catch (Exception e) { + throw new IllegalPluginAccessException(e.toString()); + } + } + + @Override + public void registerEvent(Class<? extends Event> event, Listener listener, EventPriority priority, EventExecutor executor, Plugin plugin) + { + throw new UnsupportedOperationException(); + } + + @Override + public void registerEvent(Class<? extends Event> event, Listener listener, EventPriority priority, EventExecutor executor, Plugin plugin, boolean ignoreCancelled) + { + throw new UnsupportedOperationException(); + } + + @Override + public void enablePlugin(Plugin plugin) + { + throw new UnsupportedOperationException(); + } + + @Override + public void disablePlugin(Plugin plugin) + { + throw new UnsupportedOperationException(); + } + + public Permission getPermission(String name) { + return permissions.get(name.toLowerCase()); + } + + public void addPermission(Permission perm) { + String name = perm.getName().toLowerCase(); + + if (permissions.containsKey(name)) { + throw new IllegalArgumentException("The permission " + name + " is already defined!"); + } + + permissions.put(name, perm); + calculatePermissionDefault(perm); + } + + public Set<Permission> getDefaultPermissions(boolean op) { + return ImmutableSet.copyOf(defaultPerms.get(op)); + } + + public void removePermission(Permission perm) { + removePermission(perm.getName()); + } + + public void removePermission(String name) { + permissions.remove(name.toLowerCase()); + } + + public void recalculatePermissionDefaults(Permission perm) { + if (perm != null && permissions.containsKey(perm.getName().toLowerCase())) { + defaultPerms.get(true).remove(perm); + defaultPerms.get(false).remove(perm); + + calculatePermissionDefault(perm); + } + } + + private void calculatePermissionDefault(Permission perm) { + if ((perm.getDefault() == PermissionDefault.OP) || (perm.getDefault() == PermissionDefault.TRUE)) { + defaultPerms.get(true).add(perm); + dirtyPermissibles(true); + } + if ((perm.getDefault() == PermissionDefault.NOT_OP) || (perm.getDefault() == PermissionDefault.TRUE)) { + defaultPerms.get(false).add(perm); + dirtyPermissibles(false); + } + } + + private void dirtyPermissibles(boolean op) { + Set<Permissible> permissibles = getDefaultPermSubscriptions(op); + + for (Permissible p : permissibles) { + p.recalculatePermissions(); + } + } + + public void subscribeToPermission(String permission, Permissible permissible) { + String name = permission.toLowerCase(); + Map<Permissible, Boolean> map = permSubs.get(name); + + if (map == null) { + map = new WeakHashMap<Permissible, Boolean>(); + permSubs.put(name, map); + } + + map.put(permissible, true); + } + + public void unsubscribeFromPermission(String permission, Permissible permissible) { + String name = permission.toLowerCase(); + Map<Permissible, Boolean> map = permSubs.get(name); + + if (map != null) { + map.remove(permissible); + + if (map.isEmpty()) { + permSubs.remove(name); + } + } + } + + public Set<Permissible> getPermissionSubscriptions(String permission) { + String name = permission.toLowerCase(); + Map<Permissible, Boolean> map = permSubs.get(name); + + if (map == null) { + return ImmutableSet.of(); + } else { + return ImmutableSet.copyOf(map.keySet()); + } + } + + public void subscribeToDefaultPerms(boolean op, Permissible permissible) { + Map<Permissible, Boolean> map = defSubs.get(op); + + if (map == null) { + map = new WeakHashMap<Permissible, Boolean>(); + defSubs.put(op, map); + } + + map.put(permissible, true); + } + + public void unsubscribeFromDefaultPerms(boolean op, Permissible permissible) { + Map<Permissible, Boolean> map = defSubs.get(op); + + if (map != null) { + map.remove(permissible); + + if (map.isEmpty()) { + defSubs.remove(op); + } + } + } + + public Set<Permissible> getDefaultPermSubscriptions(boolean op) { + Map<Permissible, Boolean> map = defSubs.get(op); + + if (map == null) { + return ImmutableSet.of(); + } else { + return ImmutableSet.copyOf(map.keySet()); + } + } + + public Set<Permission> getPermissions() { + return new HashSet<Permission>(permissions.values()); + } + + @Override + public boolean useTimings() + { + return false; + } + +} diff --git a/Spigot-Test/src/main/java/com/comze_instancelabs/minigamesapi/spigottest/DummyScore.java b/Spigot-Test/src/main/java/com/comze_instancelabs/minigamesapi/spigottest/DummyScore.java new file mode 100644 index 00000000..b1052c6d --- /dev/null +++ b/Spigot-Test/src/main/java/com/comze_instancelabs/minigamesapi/spigottest/DummyScore.java @@ -0,0 +1,100 @@ +/* + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +package com.comze_instancelabs.minigamesapi.spigottest; + +import org.bukkit.OfflinePlayer; +import org.bukkit.scoreboard.Objective; +import org.bukkit.scoreboard.Score; +import org.bukkit.scoreboard.Scoreboard; + +/** + * @author mepeisen + * + */ +public class DummyScore implements Score +{ + + /* (non-Javadoc) + * @see org.bukkit.scoreboard.Score#getEntry() + */ + @Override + public String getEntry() + { + // TODO Auto-generated method stub + return null; + } + + /* (non-Javadoc) + * @see org.bukkit.scoreboard.Score#getObjective() + */ + @Override + public Objective getObjective() + { + // TODO Auto-generated method stub + return null; + } + + /* (non-Javadoc) + * @see org.bukkit.scoreboard.Score#getPlayer() + */ + @Override + public OfflinePlayer getPlayer() + { + // TODO Auto-generated method stub + return null; + } + + /* (non-Javadoc) + * @see org.bukkit.scoreboard.Score#getScore() + */ + @Override + public int getScore() throws IllegalStateException + { + // TODO Auto-generated method stub + return 0; + } + + /* (non-Javadoc) + * @see org.bukkit.scoreboard.Score#getScoreboard() + */ + @Override + public Scoreboard getScoreboard() + { + // TODO Auto-generated method stub + return null; + } + + /* (non-Javadoc) + * @see org.bukkit.scoreboard.Score#isScoreSet() + */ + @Override + public boolean isScoreSet() throws IllegalStateException + { + // TODO Auto-generated method stub + return false; + } + + /* (non-Javadoc) + * @see org.bukkit.scoreboard.Score#setScore(int) + */ + @Override + public void setScore(int arg0) throws IllegalStateException + { + // TODO Auto-generated method stub + + } + +} diff --git a/Spigot-Test/src/main/java/com/comze_instancelabs/minigamesapi/spigottest/DummyScoreboardTeam.java b/Spigot-Test/src/main/java/com/comze_instancelabs/minigamesapi/spigottest/DummyScoreboardTeam.java new file mode 100644 index 00000000..f999340c --- /dev/null +++ b/Spigot-Test/src/main/java/com/comze_instancelabs/minigamesapi/spigottest/DummyScoreboardTeam.java @@ -0,0 +1,314 @@ +/* + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +package com.comze_instancelabs.minigamesapi.spigottest; + +import java.util.HashSet; +import java.util.Set; + +import org.bukkit.ChatColor; +import org.bukkit.OfflinePlayer; +import org.bukkit.scoreboard.NameTagVisibility; +import org.bukkit.scoreboard.Scoreboard; +import org.bukkit.scoreboard.Team; + +/** + * @author mepeisen + * + */ +class DummyScoreboardTeam implements Team +{ + + /* (non-Javadoc) + * @see org.bukkit.scoreboard.Team#getName() + */ + @Override + public String getName() throws IllegalStateException + { + // TODO Auto-generated method stub + return null; + } + + /* (non-Javadoc) + * @see org.bukkit.scoreboard.Team#getDisplayName() + */ + @Override + public String getDisplayName() throws IllegalStateException + { + // TODO Auto-generated method stub + return null; + } + + /* (non-Javadoc) + * @see org.bukkit.scoreboard.Team#setDisplayName(java.lang.String) + */ + @Override + public void setDisplayName(String displayName) throws IllegalStateException, IllegalArgumentException + { + // TODO Auto-generated method stub + + } + + /* (non-Javadoc) + * @see org.bukkit.scoreboard.Team#getPrefix() + */ + @Override + public String getPrefix() throws IllegalStateException + { + // TODO Auto-generated method stub + return null; + } + + /* (non-Javadoc) + * @see org.bukkit.scoreboard.Team#setPrefix(java.lang.String) + */ + @Override + public void setPrefix(String prefix) throws IllegalStateException, IllegalArgumentException + { + // TODO Auto-generated method stub + + } + + /* (non-Javadoc) + * @see org.bukkit.scoreboard.Team#getSuffix() + */ + @Override + public String getSuffix() throws IllegalStateException + { + // TODO Auto-generated method stub + return null; + } + + /* (non-Javadoc) + * @see org.bukkit.scoreboard.Team#setSuffix(java.lang.String) + */ + @Override + public void setSuffix(String suffix) throws IllegalStateException, IllegalArgumentException + { + // TODO Auto-generated method stub + + } + + /* (non-Javadoc) + * @see org.bukkit.scoreboard.Team#allowFriendlyFire() + */ + @Override + public boolean allowFriendlyFire() throws IllegalStateException + { + // TODO Auto-generated method stub + return false; + } + + /* (non-Javadoc) + * @see org.bukkit.scoreboard.Team#setAllowFriendlyFire(boolean) + */ + @Override + public void setAllowFriendlyFire(boolean enabled) throws IllegalStateException + { + // TODO Auto-generated method stub + + } + + /* (non-Javadoc) + * @see org.bukkit.scoreboard.Team#canSeeFriendlyInvisibles() + */ + @Override + public boolean canSeeFriendlyInvisibles() throws IllegalStateException + { + // TODO Auto-generated method stub + return false; + } + + /* (non-Javadoc) + * @see org.bukkit.scoreboard.Team#setCanSeeFriendlyInvisibles(boolean) + */ + @Override + public void setCanSeeFriendlyInvisibles(boolean enabled) throws IllegalStateException + { + // TODO Auto-generated method stub + + } + + /* (non-Javadoc) + * @see org.bukkit.scoreboard.Team#getNameTagVisibility() + */ + @Override + public NameTagVisibility getNameTagVisibility() throws IllegalArgumentException + { + // TODO Auto-generated method stub + return null; + } + + /* (non-Javadoc) + * @see org.bukkit.scoreboard.Team#setNameTagVisibility(org.bukkit.scoreboard.NameTagVisibility) + */ + @Override + public void setNameTagVisibility(NameTagVisibility visibility) throws IllegalArgumentException + { + // TODO Auto-generated method stub + + } + + /* (non-Javadoc) + * @see org.bukkit.scoreboard.Team#getPlayers() + */ + @Override + public Set<OfflinePlayer> getPlayers() throws IllegalStateException + { + // TODO Auto-generated method stub + return new HashSet<>(); + } + + /* (non-Javadoc) + * @see org.bukkit.scoreboard.Team#getEntries() + */ + @Override + public Set<String> getEntries() throws IllegalStateException + { + // TODO Auto-generated method stub + return null; + } + + /* (non-Javadoc) + * @see org.bukkit.scoreboard.Team#getSize() + */ + @Override + public int getSize() throws IllegalStateException + { + // TODO Auto-generated method stub + return 0; + } + + /* (non-Javadoc) + * @see org.bukkit.scoreboard.Team#getScoreboard() + */ + @Override + public Scoreboard getScoreboard() + { + // TODO Auto-generated method stub + return null; + } + + /* (non-Javadoc) + * @see org.bukkit.scoreboard.Team#addPlayer(org.bukkit.OfflinePlayer) + */ + @Override + public void addPlayer(OfflinePlayer player) throws IllegalStateException, IllegalArgumentException + { + // TODO Auto-generated method stub + + } + + /* (non-Javadoc) + * @see org.bukkit.scoreboard.Team#addEntry(java.lang.String) + */ + @Override + public void addEntry(String entry) throws IllegalStateException, IllegalArgumentException + { + // TODO Auto-generated method stub + + } + + /* (non-Javadoc) + * @see org.bukkit.scoreboard.Team#removePlayer(org.bukkit.OfflinePlayer) + */ + @Override + public boolean removePlayer(OfflinePlayer player) throws IllegalStateException, IllegalArgumentException + { + // TODO Auto-generated method stub + return false; + } + + /* (non-Javadoc) + * @see org.bukkit.scoreboard.Team#removeEntry(java.lang.String) + */ + @Override + public boolean removeEntry(String entry) throws IllegalStateException, IllegalArgumentException + { + // TODO Auto-generated method stub + return false; + } + + /* (non-Javadoc) + * @see org.bukkit.scoreboard.Team#unregister() + */ + @Override + public void unregister() throws IllegalStateException + { + // TODO Auto-generated method stub + + } + + /* (non-Javadoc) + * @see org.bukkit.scoreboard.Team#hasPlayer(org.bukkit.OfflinePlayer) + */ + @Override + public boolean hasPlayer(OfflinePlayer player) throws IllegalArgumentException, IllegalStateException + { + // TODO Auto-generated method stub + return false; + } + + /* (non-Javadoc) + * @see org.bukkit.scoreboard.Team#hasEntry(java.lang.String) + */ + @Override + public boolean hasEntry(String entry) throws IllegalArgumentException, IllegalStateException + { + // TODO Auto-generated method stub + return false; + } + + /* (non-Javadoc) + * @see org.bukkit.scoreboard.Team#getOption(org.bukkit.scoreboard.Team.Option) + */ + @Override + public OptionStatus getOption(Option option) throws IllegalStateException + { + // TODO Auto-generated method stub + return null; + } + + /* (non-Javadoc) + * @see org.bukkit.scoreboard.Team#setOption(org.bukkit.scoreboard.Team.Option, org.bukkit.scoreboard.Team.OptionStatus) + */ + @Override + public void setOption(Option option, OptionStatus status) throws IllegalStateException + { + // TODO Auto-generated method stub + + } + + /* (non-Javadoc) + * @see org.bukkit.scoreboard.Team#getColor() + */ + @Override + public ChatColor getColor() throws IllegalStateException + { + // TODO Auto-generated method stub + return null; + } + + /* (non-Javadoc) + * @see org.bukkit.scoreboard.Team#setColor(org.bukkit.ChatColor) + */ + @Override + public void setColor(ChatColor paramChatColor) + { + // TODO Auto-generated method stub + + } + +} diff --git a/Spigot-Test/src/main/java/com/comze_instancelabs/minigamesapi/spigottest/DummyServer.java b/Spigot-Test/src/main/java/com/comze_instancelabs/minigamesapi/spigottest/DummyServer.java new file mode 100644 index 00000000..788a4820 --- /dev/null +++ b/Spigot-Test/src/main/java/com/comze_instancelabs/minigamesapi/spigottest/DummyServer.java @@ -0,0 +1,645 @@ +package com.comze_instancelabs.minigamesapi.spigottest; + +import static org.mockito.Matchers.anyString; +import static org.mockito.Mockito.when; +import static org.powermock.api.mockito.PowerMockito.mock; + +import java.io.File; +import java.io.IOException; +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.logging.Logger; + +import org.bukkit.Bukkit; +import org.bukkit.Server; +import org.bukkit.World; +import org.bukkit.World.Environment; +import org.bukkit.WorldType; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.craftbukkit.v1_12_R1.CraftServer; +import org.bukkit.craftbukkit.v1_12_R1.CraftWorld; +import org.bukkit.craftbukkit.v1_12_R1.inventory.CraftItemFactory; +import org.bukkit.craftbukkit.v1_12_R1.scheduler.CraftScheduler; +import org.bukkit.craftbukkit.v1_12_R1.scoreboard.CraftScoreboard; +import org.bukkit.craftbukkit.v1_12_R1.scoreboard.CraftScoreboardManager; +import org.bukkit.craftbukkit.v1_12_R1.util.Versioning; +import org.bukkit.entity.Player; +import org.bukkit.generator.ChunkGenerator; +import org.bukkit.plugin.Plugin; +import org.bukkit.scoreboard.Objective; +import org.bukkit.scoreboard.Team; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; +import org.spigotmc.SpigotConfig; + +import net.minecraft.server.v1_12_R1.Chunk; +import net.minecraft.server.v1_12_R1.DedicatedPlayerList; +import net.minecraft.server.v1_12_R1.DefinedStructureManager; +import net.minecraft.server.v1_12_R1.EnumGamemode; +import net.minecraft.server.v1_12_R1.ExceptionWorldConflict; +import net.minecraft.server.v1_12_R1.IChunkLoader; +import net.minecraft.server.v1_12_R1.IDataManager; +import net.minecraft.server.v1_12_R1.IPlayerFileData; +import net.minecraft.server.v1_12_R1.MethodProfiler; +import net.minecraft.server.v1_12_R1.MinecraftServer; +import net.minecraft.server.v1_12_R1.NBTTagCompound; +import net.minecraft.server.v1_12_R1.PlayerChunkMap; +import net.minecraft.server.v1_12_R1.WorldData; +import net.minecraft.server.v1_12_R1.WorldProvider; +import net.minecraft.server.v1_12_R1.WorldServer; +import net.minecraft.server.v1_12_R1.WorldSettings; + +/** + * originally taken from spigot test sources + */ +class DummyServer implements InvocationHandler, Answer { + /** + * + */ + static final DummyServer DUMMY_SERVER = new DummyServer(); + + private static interface MethodHandler { + Object handle(DummyServer server, Object[] args); + } + private static final HashMap<Method, MethodHandler> methods = new HashMap<Method, MethodHandler>(); + static { + try { + methods.put( + CraftServer.class.getMethod("addWorld", World.class), + new MethodHandler() { + public Object handle(DummyServer server, Object[] args) { + // silently ignore + return null; + } + }); + methods.put( + CraftServer.class.getMethod("getHandle"), + new MethodHandler() { + public Object handle(DummyServer server, Object[] args) { + return server.playerList; + } + }); + methods.put( + CraftServer.class.getMethod("getServer"), + new MethodHandler() { + public Object handle(DummyServer server, Object[] args) { + return null; + } + }); + methods.put( + Server.class.getMethod("getViewDistance"), + new MethodHandler() { + public Object handle(DummyServer server, Object[] args) { + return 10; + } + }); + methods.put( + Server.class.getMethod("getTicksPerAnimalSpawns"), + new MethodHandler() { + public Object handle(DummyServer server, Object[] args) { + return 50; + } + }); + methods.put( + Server.class.getMethod("getTicksPerMonsterSpawns"), + new MethodHandler() { + public Object handle(DummyServer server, Object[] args) { + return 50; + } + }); + methods.put( + Server.class.getMethod("sendPluginMessage", Plugin.class, String.class, byte[].class), + new MethodHandler() { + public Object handle(DummyServer server, Object[] args) { + server.messages.add(new PluginMessage((Plugin) args[0], (String) args[1], (byte[]) args[2])); + return null; + } + }); + methods.put( + Server.class.getMethod("getPluginManager"), + new MethodHandler() { + public Object handle(DummyServer server, Object[] args) { + return server.pluginManager; + } + }); + methods.put( + Server.class.getMethod("getScoreboardManager"), + new MethodHandler() { + public Object handle(DummyServer server, Object[] args) { + return server.scoreboardManager; + } + }); + methods.put( + Server.class.getMethod("getOnlinePlayers"), + new MethodHandler() { + public Object handle(DummyServer server, Object[] args) { + return Collections.unmodifiableList(server.onlineList); + } + }); + methods.put( + Server.class.getMethod("getScheduler"), + new MethodHandler() { + public Object handle(DummyServer server, Object[] args) { + return server.scheduler; + } + }); + methods.put( + Server.class.getMethod("getWorld", String.class), + new MethodHandler() { + public Object handle(DummyServer server, Object[] args) { + return server.worlds.get((String) args[0]); + } + }); + methods.put( + Server.class.getMethod("getPlayer", String.class), + new MethodHandler() { + public Object handle(DummyServer server, Object[] args) { + for (final Player player : server.onlineList) + { + if (args[0].toString().equalsIgnoreCase(player.getName())) + { + return player; + } + } + return null; + } + }); + methods.put( + Server.class.getMethod("getPlayer", UUID.class), + new MethodHandler() { + public Object handle(DummyServer server, Object[] args) { + for (final Player player : server.onlineList) + { + if (((UUID)args[0]).equals(player.getUniqueId())) + { + return player; + } + } + return null; + } + }); + methods.put( + Server.class.getMethod("getPlayerExact", String.class), + new MethodHandler() { + public Object handle(DummyServer server, Object[] args) { + for (final Player player : server.onlineList) + { + if (args[0].toString().equals(player.getName())) + { + return player; + } + } + return null; + } + }); + methods.put( + Server.class.getMethod("matchPlayer", String.class), + new MethodHandler() { + public Object handle(DummyServer server, Object[] args) { + final List<Player> result = new ArrayList<>(); + for (final Player player : server.onlineList) + { + if (args[0].toString().equals(player.getName())) + { + return Collections.singletonList(player); + } + if (player.getName().toLowerCase().contains(args[0].toString().toLowerCase())) + { + result.add(player); + } + } + return result; + } + }); + methods.put( + Server.class.getMethod("getItemFactory"), + new MethodHandler() { + public Object handle(DummyServer server, Object[] args) { + return CraftItemFactory.instance(); + } + } + ); + methods.put( + Server.class.getMethod("getName"), + new MethodHandler() { + public Object handle(DummyServer server, Object[] args) { + return DummyServer.class.getName(); + } + } + ); + methods.put( + Server.class.getMethod("getVersion"), + new MethodHandler() { + public Object handle(DummyServer server, Object[] args) { + return DummyServer.class.getPackage().getImplementationVersion(); + } + } + ); + methods.put( + Server.class.getMethod("getBukkitVersion"), + new MethodHandler() { + public Object handle(DummyServer server, Object[] args) { + return Versioning.getBukkitVersion(); + } + } + ); + methods.put( + Server.class.getMethod("getLogger"), + new MethodHandler() { + final Logger logger = Logger.getLogger(DummyServer.class.getCanonicalName()); + public Object handle(DummyServer server, Object[] args) { + return logger; + } + } + ); + final CraftServer server = mock(CraftServer.class, DUMMY_SERVER); + Bukkit.setServer(server); + //Bukkit.setServer(Proxy.getProxyClass(Server.class.getClassLoader(), Server.class).asSubclass(Server.class).getConstructor(InvocationHandler.class).newInstance(DUMMY_SERVER)); + } catch (Throwable t) { + throw new Error(t); + } + } + + public static void setup() { + // dummy + } + + private List<Player> onlineList = new ArrayList<>(); + private DummyPluginManager pluginManager = new DummyPluginManager(); + private CraftScoreboardManager scoreboardManager; + private CraftScoreboard mainScoreboard = mock(CraftScoreboard.class); + private CraftScheduler scheduler = new CraftScheduler(); + private Map<String, World> worlds = new HashMap<>(); + private List<PluginMessage> messages = new ArrayList<>(); + private DedicatedPlayerList playerList = mock(DedicatedPlayerList.class); + + private final Map<File, YamlConfiguration> configFiles = new HashMap<>(); + + private int tick = 1; + + private DummyServer() { + when(this.playerList.d()).thenReturn(PlayerChunkMap.getFurthestViewableBlock(10)); + this.mainScoreboard = mockScoreboard(); + this.scoreboardManager = mock(CraftScoreboardManager.class); + when(this.scoreboardManager.getMainScoreboard()).thenReturn(this.mainScoreboard); + when(this.scoreboardManager.getNewScoreboard()).thenAnswer(new Answer() { + + @Override + public Object answer(InvocationOnMock invocation) throws Throwable + { + return mockScoreboard(); + } + }); + } + + CraftScoreboard mockScoreboard() + { + final CraftScoreboard result = mock(CraftScoreboard.class); + final Map<String, Team> teams = new HashMap<>(); + final Map<String, List<Objective>> objetivesByCriteria = new HashMap<>(); + final Map<String, Objective> objectiveByName = new HashMap<>(); + when(result.getTeam(anyString())).thenAnswer(new Answer(){ + + @Override + public Object answer(InvocationOnMock invocation) throws Throwable + { + return teams.get(invocation.getArgumentAt(0, String.class)); + }}); + when(result.getTeams()).thenAnswer(new Answer(){ + + @Override + public Object answer(InvocationOnMock invocation) throws Throwable + { + return new HashSet<>(teams.values()); + }}); + when(result.registerNewTeam(anyString())).thenAnswer(new Answer(){ + + @Override + public Object answer(InvocationOnMock invocation) throws Throwable + { + final Team team = new DummyScoreboardTeam(); + teams.put(invocation.getArgumentAt(0, String.class), team); + return team; + }}); + when(result.registerNewObjective(anyString(), anyString())).thenAnswer(new Answer(){ + + @Override + public Object answer(InvocationOnMock invocation) throws Throwable + { + final String name = invocation.getArgumentAt(0, String.class); + final String criteria = invocation.getArgumentAt(1, String.class); + if (objectiveByName.containsKey(name)) + { + throw new IllegalArgumentException("An objective with the name \'" + name + "\' already exists!"); + } + final Objective obj = new DummyObjective(name); + List<Objective> list = objetivesByCriteria.get(criteria); + if (list == null) + { + list = new ArrayList<>(); + objetivesByCriteria.put(criteria, list); + } + list.add(obj); + objectiveByName.put(name, obj); + return obj; + }}); + when(result.getObjective(anyString())).thenAnswer(new Answer(){ + + @Override + public Object answer(InvocationOnMock invocation) throws Throwable + { + return objectiveByName.get(invocation.getArgumentAt(0, String.class)); + }}); + + when(result.getObjectivesByCriteria(anyString())).thenAnswer(new Answer(){ + + @Override + public Object answer(InvocationOnMock invocation) throws Throwable + { + final String criteria = invocation.getArgumentAt(0, String.class); + if (objetivesByCriteria.containsKey(criteria)) + { + return new HashSet<>(objetivesByCriteria.get(criteria)); + } + return Collections.emptySet(); + }}); + + when(result.getObjectives()).thenAnswer(new Answer(){ + + @Override + public Object answer(InvocationOnMock invocation) throws Throwable + { + return new HashSet<>(objectiveByName.values()); + }}); + return result; + } + + void teardownScoreboards() + { + this.mainScoreboard = mockScoreboard(); + } + + void addMockedPlayer(Player player) + { + this.onlineList.add(player); + } + + void tick() + { + this.scheduler.mainThreadHeartbeat(this.tick); + this.tick++; + } + + @Override + public Object answer(InvocationOnMock invocation) throws Throwable + { + Method method = invocation.getMethod(); + try + { + method = Server.class.getMethod(method.getName(), method.getParameterTypes()); + } + catch (@SuppressWarnings("unused") NoSuchMethodException ex) + { + // silently ignore; use the CraftServer method instead for fetching the handler. + } + MethodHandler handler = methods.get(method); + if (handler != null) { + return handler.handle(this, invocation.getArguments()); + } + throw new UnsupportedOperationException(String.valueOf(method) + " not within methods: " + Arrays.toString(methods.keySet().toArray())); + } + + public Object invoke(Object proxy, Method method, Object[] args) { + MethodHandler handler = methods.get(method); + if (handler != null) { + return handler.handle(this, args); + } + throw new UnsupportedOperationException(String.valueOf(method) + " not within methods: " + Arrays.toString(methods.keySet().toArray())); + } + + /** + * clears all players + */ + public void clearPlayers() + { + this.onlineList.clear(); + } + + public Map<File, YamlConfiguration> getConfigFiles() + { + return this.configFiles; + } + + public void clearWorlds() + { + this.worlds.clear(); + } + + /** + * + */ + public void clearTicks() + { + this.scheduler.cancelAllTasks(); + this.tick = 1; + this.scheduler = new CraftScheduler(); + } + + /** + * + */ + public void clearMessages() + { + this.messages.clear(); + } + + /** + * Returns the plugin messages + * @return plugin messages + */ + public Iterable<PluginMessage> getMessages() + { + return this.messages; + } + + /** + * Initializes a new dummy world. + * @param name + * @return world instance + */ + public World initWorld(String name) + { + return this.worlds.computeIfAbsent(name, (n) -> new DummyWorld()); + } + + /** + * Initializes a new dummy world. + * @param name + * @param type + * @param seed + * @return world instance + */ + public World initWorld(String name, WorldType type, long seed) + { + return this.worlds.computeIfAbsent(name, (n) -> { + final UUID uuid = UUID.randomUUID(); + final ChunkGenerator generator = null; + int dimension = this.worlds.size() + 1; + net.minecraft.server.v1_12_R1.WorldType mctype = null; + switch (type) + { + case AMPLIFIED: + mctype = net.minecraft.server.v1_12_R1.WorldType.AMPLIFIED; + break; + case CUSTOMIZED: + mctype = net.minecraft.server.v1_12_R1.WorldType.CUSTOMIZED; + break; + default: + case FLAT: + mctype = net.minecraft.server.v1_12_R1.WorldType.FLAT; + break; + case LARGE_BIOMES: + mctype = net.minecraft.server.v1_12_R1.WorldType.LARGE_BIOMES; + break; + case NORMAL: + mctype = net.minecraft.server.v1_12_R1.WorldType.NORMAL; + break; + case VERSION_1_1: + mctype = net.minecraft.server.v1_12_R1.WorldType.NORMAL_1_1; + break; + + } + final WorldSettings worldsettings = new WorldSettings(seed, EnumGamemode.SURVIVAL, true, false, mctype); + final WorldData worlddata = new WorldData(worldsettings, name); + final Map<Integer, Map<Integer, Chunk>> chunks = new HashMap<>(); + SpigotConfig.disabledAdvancements = new ArrayList<>(); + + final MinecraftServer mock = mock(MinecraftServer.class); + when(mock.getPlayerList()).thenReturn(playerList); + final WorldServer internal = (WorldServer) (new WorldServer(mock, new IDataManager(){ + + @Override + public WorldData getWorldData() + { + return worlddata; + } + + @Override + public void checkSession() throws ExceptionWorldConflict + { + // ignore + } + + @Override + public IChunkLoader createChunkLoader(WorldProvider arg0) + { + return new IChunkLoader(){ + @Override + public Chunk a(net.minecraft.server.v1_12_R1.World arg0, int arg1, int arg2) throws IOException + { + final Map<Integer, Chunk> map = chunks.get(arg1); + return map == null ? null : map.get(arg2); + } + + @Override + public void a(net.minecraft.server.v1_12_R1.World arg0, Chunk arg1) throws IOException, ExceptionWorldConflict + { + final Map<Integer, Chunk> map = chunks.computeIfAbsent(arg1.locX, (x) -> new HashMap<>()); + map.put(arg1.locZ, arg1); + } + + @Override + public void b(net.minecraft.server.v1_12_R1.World arg0, Chunk arg1) throws IOException + { + // ignore + } + + @Override + public void b() + { + // ignore + } + + @Override + public void c() + { + // TODO Auto-generated method stub + + } + + @Override + public boolean chunkExists(int arg0, int arg1) + { + // TODO Auto-generated method stub + return false; + } + }; + } + + @Override + public void saveWorldData(WorldData arg0, NBTTagCompound arg1) + { + // ignore + } + + @Override + public void saveWorldData(WorldData arg0) + { + // ignore + } + + @Override + public IPlayerFileData getPlayerFileData() + { + // ignore + return null; + } + + @Override + public void a() + { + // ignore + } + + @Override + public File getDirectory() + { + // ignore + return null; + } + + @Override + public File getDataFile(String arg0) + { + // ignore + return null; + } + + @Override + public DefinedStructureManager h() + { + // ignore + return null; + } + + @Override + public UUID getUUID() + { + return uuid; + } + + }, worlddata, dimension, + mock(MethodProfiler.class), Environment.NORMAL, generator)).b(); + return new CraftWorld(internal, generator, Environment.NORMAL); + }); + } + +} diff --git a/Spigot-Test/src/main/java/com/comze_instancelabs/minigamesapi/spigottest/DummyWorld.java b/Spigot-Test/src/main/java/com/comze_instancelabs/minigamesapi/spigottest/DummyWorld.java new file mode 100644 index 00000000..32a107e3 --- /dev/null +++ b/Spigot-Test/src/main/java/com/comze_instancelabs/minigamesapi/spigottest/DummyWorld.java @@ -0,0 +1,1432 @@ +/* + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +package com.comze_instancelabs.minigamesapi.spigottest; + +import static org.powermock.api.mockito.PowerMockito.mock; + +import java.io.File; +import java.util.Collection; +import java.util.List; +import java.util.Set; +import java.util.UUID; + +import org.bukkit.BlockChangeDelegate; +import org.bukkit.Chunk; +import org.bukkit.ChunkSnapshot; +import org.bukkit.Difficulty; +import org.bukkit.Effect; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.Particle; +import org.bukkit.Sound; +import org.bukkit.SoundCategory; +import org.bukkit.TreeType; +import org.bukkit.World; +import org.bukkit.WorldBorder; +import org.bukkit.WorldType; +import org.bukkit.block.Biome; +import org.bukkit.block.Block; +import org.bukkit.entity.Arrow; +import org.bukkit.entity.Entity; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.FallingBlock; +import org.bukkit.entity.Item; +import org.bukkit.entity.LightningStrike; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.generator.BlockPopulator; +import org.bukkit.generator.ChunkGenerator; +import org.bukkit.inventory.ItemStack; +import org.bukkit.material.MaterialData; +import org.bukkit.metadata.MetadataValue; +import org.bukkit.plugin.Plugin; +import org.bukkit.util.Consumer; +import org.bukkit.util.Vector; + +/** + * @author mepeisen + */ +public class DummyWorld implements World +{ + + /* (non-Javadoc) + * @see org.bukkit.plugin.messaging.PluginMessageRecipient#sendPluginMessage(org.bukkit.plugin.Plugin, java.lang.String, byte[]) + */ + @Override + public void sendPluginMessage(Plugin paramPlugin, String paramString, byte[] paramArrayOfByte) + { + // TODO Auto-generated method stub + + } + + /* (non-Javadoc) + * @see org.bukkit.plugin.messaging.PluginMessageRecipient#getListeningPluginChannels() + */ + @Override + public Set<String> getListeningPluginChannels() + { + // TODO Auto-generated method stub + return null; + } + + /* (non-Javadoc) + * @see org.bukkit.metadata.Metadatable#setMetadata(java.lang.String, org.bukkit.metadata.MetadataValue) + */ + @Override + public void setMetadata(String paramString, MetadataValue paramMetadataValue) + { + // TODO Auto-generated method stub + + } + + /* (non-Javadoc) + * @see org.bukkit.metadata.Metadatable#getMetadata(java.lang.String) + */ + @Override + public List<MetadataValue> getMetadata(String paramString) + { + // TODO Auto-generated method stub + return null; + } + + /* (non-Javadoc) + * @see org.bukkit.metadata.Metadatable#hasMetadata(java.lang.String) + */ + @Override + public boolean hasMetadata(String paramString) + { + // TODO Auto-generated method stub + return false; + } + + /* (non-Javadoc) + * @see org.bukkit.metadata.Metadatable#removeMetadata(java.lang.String, org.bukkit.plugin.Plugin) + */ + @Override + public void removeMetadata(String paramString, Plugin paramPlugin) + { + // TODO Auto-generated method stub + + } + + /* (non-Javadoc) + * @see org.bukkit.World#getBlockAt(int, int, int) + */ + @Override + public Block getBlockAt(int paramInt1, int paramInt2, int paramInt3) + { + // TODO Auto-generated method stub + return null; + } + + /* (non-Javadoc) + * @see org.bukkit.World#getBlockAt(org.bukkit.Location) + */ + @Override + public Block getBlockAt(Location paramLocation) + { + // TODO Auto-generated method stub + return null; + } + + /* (non-Javadoc) + * @see org.bukkit.World#getBlockTypeIdAt(int, int, int) + */ + @Override + public int getBlockTypeIdAt(int paramInt1, int paramInt2, int paramInt3) + { + // TODO Auto-generated method stub + return 0; + } + + /* (non-Javadoc) + * @see org.bukkit.World#getBlockTypeIdAt(org.bukkit.Location) + */ + @Override + public int getBlockTypeIdAt(Location paramLocation) + { + // TODO Auto-generated method stub + return 0; + } + + /* (non-Javadoc) + * @see org.bukkit.World#getHighestBlockYAt(int, int) + */ + @Override + public int getHighestBlockYAt(int paramInt1, int paramInt2) + { + // TODO Auto-generated method stub + return 0; + } + + /* (non-Javadoc) + * @see org.bukkit.World#getHighestBlockYAt(org.bukkit.Location) + */ + @Override + public int getHighestBlockYAt(Location paramLocation) + { + // TODO Auto-generated method stub + return 0; + } + + /* (non-Javadoc) + * @see org.bukkit.World#getHighestBlockAt(int, int) + */ + @Override + public Block getHighestBlockAt(int paramInt1, int paramInt2) + { + // TODO Auto-generated method stub + return null; + } + + /* (non-Javadoc) + * @see org.bukkit.World#getHighestBlockAt(org.bukkit.Location) + */ + @Override + public Block getHighestBlockAt(Location paramLocation) + { + // TODO Auto-generated method stub + return null; + } + + @Override + public Chunk getChunkAt(int paramInt1, int paramInt2) + { + return mock(Chunk.class); + } + + @Override + public Chunk getChunkAt(Location paramLocation) + { + return mock(Chunk.class); + } + + @Override + public Chunk getChunkAt(Block paramBlock) + { + return mock(Chunk.class); + } + + @Override + public boolean isChunkLoaded(Chunk paramChunk) + { + return true; + } + + /* (non-Javadoc) + * @see org.bukkit.World#getLoadedChunks() + */ + @Override + public Chunk[] getLoadedChunks() + { + // TODO Auto-generated method stub + return null; + } + + /* (non-Javadoc) + * @see org.bukkit.World#loadChunk(org.bukkit.Chunk) + */ + @Override + public void loadChunk(Chunk paramChunk) + { + // TODO Auto-generated method stub + + } + + /* (non-Javadoc) + * @see org.bukkit.World#isChunkLoaded(int, int) + */ + @Override + public boolean isChunkLoaded(int paramInt1, int paramInt2) + { + // TODO Auto-generated method stub + return false; + } + + /* (non-Javadoc) + * @see org.bukkit.World#isChunkInUse(int, int) + */ + @Override + public boolean isChunkInUse(int paramInt1, int paramInt2) + { + // TODO Auto-generated method stub + return false; + } + + /* (non-Javadoc) + * @see org.bukkit.World#loadChunk(int, int) + */ + @Override + public void loadChunk(int paramInt1, int paramInt2) + { + // TODO Auto-generated method stub + + } + + /* (non-Javadoc) + * @see org.bukkit.World#loadChunk(int, int, boolean) + */ + @Override + public boolean loadChunk(int paramInt1, int paramInt2, boolean paramBoolean) + { + // TODO Auto-generated method stub + return false; + } + + /* (non-Javadoc) + * @see org.bukkit.World#unloadChunk(org.bukkit.Chunk) + */ + @Override + public boolean unloadChunk(Chunk paramChunk) + { + // TODO Auto-generated method stub + return false; + } + + /* (non-Javadoc) + * @see org.bukkit.World#unloadChunk(int, int) + */ + @Override + public boolean unloadChunk(int paramInt1, int paramInt2) + { + // TODO Auto-generated method stub + return false; + } + + /* (non-Javadoc) + * @see org.bukkit.World#unloadChunk(int, int, boolean) + */ + @Override + public boolean unloadChunk(int paramInt1, int paramInt2, boolean paramBoolean) + { + // TODO Auto-generated method stub + return false; + } + + /* (non-Javadoc) + * @see org.bukkit.World#unloadChunk(int, int, boolean, boolean) + */ + @Override + public boolean unloadChunk(int paramInt1, int paramInt2, boolean paramBoolean1, boolean paramBoolean2) + { + // TODO Auto-generated method stub + return false; + } + + /* (non-Javadoc) + * @see org.bukkit.World#unloadChunkRequest(int, int) + */ + @Override + public boolean unloadChunkRequest(int paramInt1, int paramInt2) + { + // TODO Auto-generated method stub + return false; + } + + /* (non-Javadoc) + * @see org.bukkit.World#unloadChunkRequest(int, int, boolean) + */ + @Override + public boolean unloadChunkRequest(int paramInt1, int paramInt2, boolean paramBoolean) + { + // TODO Auto-generated method stub + return false; + } + + /* (non-Javadoc) + * @see org.bukkit.World#regenerateChunk(int, int) + */ + @Override + public boolean regenerateChunk(int paramInt1, int paramInt2) + { + // TODO Auto-generated method stub + return false; + } + + /* (non-Javadoc) + * @see org.bukkit.World#refreshChunk(int, int) + */ + @Override + public boolean refreshChunk(int paramInt1, int paramInt2) + { + // TODO Auto-generated method stub + return false; + } + + /* (non-Javadoc) + * @see org.bukkit.World#dropItem(org.bukkit.Location, org.bukkit.inventory.ItemStack) + */ + @Override + public Item dropItem(Location paramLocation, ItemStack paramItemStack) + { + // TODO Auto-generated method stub + return null; + } + + /* (non-Javadoc) + * @see org.bukkit.World#dropItemNaturally(org.bukkit.Location, org.bukkit.inventory.ItemStack) + */ + @Override + public Item dropItemNaturally(Location paramLocation, ItemStack paramItemStack) + { + // TODO Auto-generated method stub + return null; + } + + /* (non-Javadoc) + * @see org.bukkit.World#spawnArrow(org.bukkit.Location, org.bukkit.util.Vector, float, float) + */ + @Override + public Arrow spawnArrow(Location paramLocation, Vector paramVector, float paramFloat1, float paramFloat2) + { + // TODO Auto-generated method stub + return null; + } + + /* (non-Javadoc) + * @see org.bukkit.World#spawnArrow(org.bukkit.Location, org.bukkit.util.Vector, float, float, java.lang.Class) + */ + @Override + public <T extends Arrow> T spawnArrow(Location paramLocation, Vector paramVector, float paramFloat1, float paramFloat2, Class<T> paramClass) + { + // TODO Auto-generated method stub + return null; + } + + /* (non-Javadoc) + * @see org.bukkit.World#generateTree(org.bukkit.Location, org.bukkit.TreeType) + */ + @Override + public boolean generateTree(Location paramLocation, TreeType paramTreeType) + { + // TODO Auto-generated method stub + return false; + } + + /* (non-Javadoc) + * @see org.bukkit.World#generateTree(org.bukkit.Location, org.bukkit.TreeType, org.bukkit.BlockChangeDelegate) + */ + @Override + public boolean generateTree(Location paramLocation, TreeType paramTreeType, BlockChangeDelegate paramBlockChangeDelegate) + { + // TODO Auto-generated method stub + return false; + } + + /* (non-Javadoc) + * @see org.bukkit.World#spawnEntity(org.bukkit.Location, org.bukkit.entity.EntityType) + */ + @Override + public Entity spawnEntity(Location paramLocation, EntityType paramEntityType) + { + // TODO Auto-generated method stub + return null; + } + + /* (non-Javadoc) + * @see org.bukkit.World#strikeLightning(org.bukkit.Location) + */ + @Override + public LightningStrike strikeLightning(Location paramLocation) + { + // TODO Auto-generated method stub + return null; + } + + /* (non-Javadoc) + * @see org.bukkit.World#strikeLightningEffect(org.bukkit.Location) + */ + @Override + public LightningStrike strikeLightningEffect(Location paramLocation) + { + // TODO Auto-generated method stub + return null; + } + + /* (non-Javadoc) + * @see org.bukkit.World#getEntities() + */ + @Override + public List<Entity> getEntities() + { + // TODO Auto-generated method stub + return null; + } + + /* (non-Javadoc) + * @see org.bukkit.World#getLivingEntities() + */ + @Override + public List<LivingEntity> getLivingEntities() + { + // TODO Auto-generated method stub + return null; + } + + /* (non-Javadoc) + * @see org.bukkit.World#getEntitiesByClass(java.lang.Class[]) + */ + @Override + public <T extends Entity> Collection<T> getEntitiesByClass(Class<T>... paramArrayOfClass) + { + // TODO Auto-generated method stub + return null; + } + + /* (non-Javadoc) + * @see org.bukkit.World#getEntitiesByClass(java.lang.Class) + */ + @Override + public <T extends Entity> Collection<T> getEntitiesByClass(Class<T> paramClass) + { + // TODO Auto-generated method stub + return null; + } + + /* (non-Javadoc) + * @see org.bukkit.World#getEntitiesByClasses(java.lang.Class[]) + */ + @Override + public Collection<Entity> getEntitiesByClasses(Class<?>... paramArrayOfClass) + { + // TODO Auto-generated method stub + return null; + } + + /* (non-Javadoc) + * @see org.bukkit.World#getPlayers() + */ + @Override + public List<Player> getPlayers() + { + // TODO Auto-generated method stub + return null; + } + + /* (non-Javadoc) + * @see org.bukkit.World#getNearbyEntities(org.bukkit.Location, double, double, double) + */ + @Override + public Collection<Entity> getNearbyEntities(Location paramLocation, double paramDouble1, double paramDouble2, double paramDouble3) + { + // TODO Auto-generated method stub + return null; + } + + /* (non-Javadoc) + * @see org.bukkit.World#getName() + */ + @Override + public String getName() + { + // TODO Auto-generated method stub + return null; + } + + /* (non-Javadoc) + * @see org.bukkit.World#getUID() + */ + @Override + public UUID getUID() + { + // TODO Auto-generated method stub + return null; + } + + /* (non-Javadoc) + * @see org.bukkit.World#getSpawnLocation() + */ + @Override + public Location getSpawnLocation() + { + // TODO Auto-generated method stub + return null; + } + + /* (non-Javadoc) + * @see org.bukkit.World#setSpawnLocation(int, int, int) + */ + @Override + public boolean setSpawnLocation(int paramInt1, int paramInt2, int paramInt3) + { + // TODO Auto-generated method stub + return false; + } + + /* (non-Javadoc) + * @see org.bukkit.World#getTime() + */ + @Override + public long getTime() + { + // TODO Auto-generated method stub + return 0; + } + + /* (non-Javadoc) + * @see org.bukkit.World#setTime(long) + */ + @Override + public void setTime(long paramLong) + { + // TODO Auto-generated method stub + + } + + /* (non-Javadoc) + * @see org.bukkit.World#getFullTime() + */ + @Override + public long getFullTime() + { + // TODO Auto-generated method stub + return 0; + } + + /* (non-Javadoc) + * @see org.bukkit.World#setFullTime(long) + */ + @Override + public void setFullTime(long paramLong) + { + // TODO Auto-generated method stub + + } + + /* (non-Javadoc) + * @see org.bukkit.World#hasStorm() + */ + @Override + public boolean hasStorm() + { + // TODO Auto-generated method stub + return false; + } + + /* (non-Javadoc) + * @see org.bukkit.World#setStorm(boolean) + */ + @Override + public void setStorm(boolean paramBoolean) + { + // TODO Auto-generated method stub + + } + + /* (non-Javadoc) + * @see org.bukkit.World#getWeatherDuration() + */ + @Override + public int getWeatherDuration() + { + // TODO Auto-generated method stub + return 0; + } + + /* (non-Javadoc) + * @see org.bukkit.World#setWeatherDuration(int) + */ + @Override + public void setWeatherDuration(int paramInt) + { + // TODO Auto-generated method stub + + } + + /* (non-Javadoc) + * @see org.bukkit.World#isThundering() + */ + @Override + public boolean isThundering() + { + // TODO Auto-generated method stub + return false; + } + + /* (non-Javadoc) + * @see org.bukkit.World#setThundering(boolean) + */ + @Override + public void setThundering(boolean paramBoolean) + { + // TODO Auto-generated method stub + + } + + /* (non-Javadoc) + * @see org.bukkit.World#getThunderDuration() + */ + @Override + public int getThunderDuration() + { + // TODO Auto-generated method stub + return 0; + } + + /* (non-Javadoc) + * @see org.bukkit.World#setThunderDuration(int) + */ + @Override + public void setThunderDuration(int paramInt) + { + // TODO Auto-generated method stub + + } + + /* (non-Javadoc) + * @see org.bukkit.World#createExplosion(double, double, double, float) + */ + @Override + public boolean createExplosion(double paramDouble1, double paramDouble2, double paramDouble3, float paramFloat) + { + // TODO Auto-generated method stub + return false; + } + + /* (non-Javadoc) + * @see org.bukkit.World#createExplosion(double, double, double, float, boolean) + */ + @Override + public boolean createExplosion(double paramDouble1, double paramDouble2, double paramDouble3, float paramFloat, boolean paramBoolean) + { + // TODO Auto-generated method stub + return false; + } + + /* (non-Javadoc) + * @see org.bukkit.World#createExplosion(double, double, double, float, boolean, boolean) + */ + @Override + public boolean createExplosion(double paramDouble1, double paramDouble2, double paramDouble3, float paramFloat, boolean paramBoolean1, boolean paramBoolean2) + { + // TODO Auto-generated method stub + return false; + } + + /* (non-Javadoc) + * @see org.bukkit.World#createExplosion(org.bukkit.Location, float) + */ + @Override + public boolean createExplosion(Location paramLocation, float paramFloat) + { + // TODO Auto-generated method stub + return false; + } + + /* (non-Javadoc) + * @see org.bukkit.World#createExplosion(org.bukkit.Location, float, boolean) + */ + @Override + public boolean createExplosion(Location paramLocation, float paramFloat, boolean paramBoolean) + { + // TODO Auto-generated method stub + return false; + } + + /* (non-Javadoc) + * @see org.bukkit.World#getEnvironment() + */ + @Override + public Environment getEnvironment() + { + // TODO Auto-generated method stub + return null; + } + + /* (non-Javadoc) + * @see org.bukkit.World#getSeed() + */ + @Override + public long getSeed() + { + // TODO Auto-generated method stub + return 0; + } + + /* (non-Javadoc) + * @see org.bukkit.World#getPVP() + */ + @Override + public boolean getPVP() + { + // TODO Auto-generated method stub + return false; + } + + /* (non-Javadoc) + * @see org.bukkit.World#setPVP(boolean) + */ + @Override + public void setPVP(boolean paramBoolean) + { + // TODO Auto-generated method stub + + } + + /* (non-Javadoc) + * @see org.bukkit.World#getGenerator() + */ + @Override + public ChunkGenerator getGenerator() + { + // TODO Auto-generated method stub + return null; + } + + /* (non-Javadoc) + * @see org.bukkit.World#save() + */ + @Override + public void save() + { + // TODO Auto-generated method stub + + } + + /* (non-Javadoc) + * @see org.bukkit.World#getPopulators() + */ + @Override + public List<BlockPopulator> getPopulators() + { + // TODO Auto-generated method stub + return null; + } + + /* (non-Javadoc) + * @see org.bukkit.World#spawn(org.bukkit.Location, java.lang.Class) + */ + @Override + public <T extends Entity> T spawn(Location paramLocation, Class<T> paramClass) throws IllegalArgumentException + { + // TODO Auto-generated method stub + return null; + } + + /* (non-Javadoc) + * @see org.bukkit.World#spawnFallingBlock(org.bukkit.Location, org.bukkit.Material, byte) + */ + @Override + public FallingBlock spawnFallingBlock(Location paramLocation, Material paramMaterial, byte paramByte) throws IllegalArgumentException + { + // TODO Auto-generated method stub + return null; + } + + /* (non-Javadoc) + * @see org.bukkit.World#spawnFallingBlock(org.bukkit.Location, int, byte) + */ + @Override + public FallingBlock spawnFallingBlock(Location paramLocation, int paramInt, byte paramByte) throws IllegalArgumentException + { + // TODO Auto-generated method stub + return null; + } + + /* (non-Javadoc) + * @see org.bukkit.World#playEffect(org.bukkit.Location, org.bukkit.Effect, int) + */ + @Override + public void playEffect(Location paramLocation, Effect paramEffect, int paramInt) + { + // TODO Auto-generated method stub + + } + + /* (non-Javadoc) + * @see org.bukkit.World#playEffect(org.bukkit.Location, org.bukkit.Effect, int, int) + */ + @Override + public void playEffect(Location paramLocation, Effect paramEffect, int paramInt1, int paramInt2) + { + // TODO Auto-generated method stub + + } + + /* (non-Javadoc) + * @see org.bukkit.World#playEffect(org.bukkit.Location, org.bukkit.Effect, java.lang.Object) + */ + @Override + public <T> void playEffect(Location paramLocation, Effect paramEffect, T paramT) + { + // TODO Auto-generated method stub + + } + + /* (non-Javadoc) + * @see org.bukkit.World#playEffect(org.bukkit.Location, org.bukkit.Effect, java.lang.Object, int) + */ + @Override + public <T> void playEffect(Location paramLocation, Effect paramEffect, T paramT, int paramInt) + { + // TODO Auto-generated method stub + + } + + /* (non-Javadoc) + * @see org.bukkit.World#getEmptyChunkSnapshot(int, int, boolean, boolean) + */ + @Override + public ChunkSnapshot getEmptyChunkSnapshot(int paramInt1, int paramInt2, boolean paramBoolean1, boolean paramBoolean2) + { + // TODO Auto-generated method stub + return null; + } + + /* (non-Javadoc) + * @see org.bukkit.World#setSpawnFlags(boolean, boolean) + */ + @Override + public void setSpawnFlags(boolean paramBoolean1, boolean paramBoolean2) + { + // TODO Auto-generated method stub + + } + + /* (non-Javadoc) + * @see org.bukkit.World#getAllowAnimals() + */ + @Override + public boolean getAllowAnimals() + { + // TODO Auto-generated method stub + return false; + } + + /* (non-Javadoc) + * @see org.bukkit.World#getAllowMonsters() + */ + @Override + public boolean getAllowMonsters() + { + // TODO Auto-generated method stub + return false; + } + + /* (non-Javadoc) + * @see org.bukkit.World#getBiome(int, int) + */ + @Override + public Biome getBiome(int paramInt1, int paramInt2) + { + // TODO Auto-generated method stub + return null; + } + + /* (non-Javadoc) + * @see org.bukkit.World#setBiome(int, int, org.bukkit.block.Biome) + */ + @Override + public void setBiome(int paramInt1, int paramInt2, Biome paramBiome) + { + // TODO Auto-generated method stub + + } + + /* (non-Javadoc) + * @see org.bukkit.World#getTemperature(int, int) + */ + @Override + public double getTemperature(int paramInt1, int paramInt2) + { + // TODO Auto-generated method stub + return 0; + } + + /* (non-Javadoc) + * @see org.bukkit.World#getHumidity(int, int) + */ + @Override + public double getHumidity(int paramInt1, int paramInt2) + { + // TODO Auto-generated method stub + return 0; + } + + /* (non-Javadoc) + * @see org.bukkit.World#getMaxHeight() + */ + @Override + public int getMaxHeight() + { + // TODO Auto-generated method stub + return 0; + } + + /* (non-Javadoc) + * @see org.bukkit.World#getSeaLevel() + */ + @Override + public int getSeaLevel() + { + // TODO Auto-generated method stub + return 0; + } + + /* (non-Javadoc) + * @see org.bukkit.World#getKeepSpawnInMemory() + */ + @Override + public boolean getKeepSpawnInMemory() + { + // TODO Auto-generated method stub + return false; + } + + /* (non-Javadoc) + * @see org.bukkit.World#setKeepSpawnInMemory(boolean) + */ + @Override + public void setKeepSpawnInMemory(boolean paramBoolean) + { + // TODO Auto-generated method stub + + } + + /* (non-Javadoc) + * @see org.bukkit.World#isAutoSave() + */ + @Override + public boolean isAutoSave() + { + // TODO Auto-generated method stub + return false; + } + + /* (non-Javadoc) + * @see org.bukkit.World#setAutoSave(boolean) + */ + @Override + public void setAutoSave(boolean paramBoolean) + { + // TODO Auto-generated method stub + + } + + /* (non-Javadoc) + * @see org.bukkit.World#setDifficulty(org.bukkit.Difficulty) + */ + @Override + public void setDifficulty(Difficulty paramDifficulty) + { + // TODO Auto-generated method stub + + } + + /* (non-Javadoc) + * @see org.bukkit.World#getDifficulty() + */ + @Override + public Difficulty getDifficulty() + { + // TODO Auto-generated method stub + return null; + } + + /* (non-Javadoc) + * @see org.bukkit.World#getWorldFolder() + */ + @Override + public File getWorldFolder() + { + // TODO Auto-generated method stub + return null; + } + + /* (non-Javadoc) + * @see org.bukkit.World#getWorldType() + */ + @Override + public WorldType getWorldType() + { + // TODO Auto-generated method stub + return null; + } + + /* (non-Javadoc) + * @see org.bukkit.World#canGenerateStructures() + */ + @Override + public boolean canGenerateStructures() + { + // TODO Auto-generated method stub + return false; + } + + /* (non-Javadoc) + * @see org.bukkit.World#getTicksPerAnimalSpawns() + */ + @Override + public long getTicksPerAnimalSpawns() + { + // TODO Auto-generated method stub + return 0; + } + + /* (non-Javadoc) + * @see org.bukkit.World#setTicksPerAnimalSpawns(int) + */ + @Override + public void setTicksPerAnimalSpawns(int paramInt) + { + // TODO Auto-generated method stub + + } + + /* (non-Javadoc) + * @see org.bukkit.World#getTicksPerMonsterSpawns() + */ + @Override + public long getTicksPerMonsterSpawns() + { + // TODO Auto-generated method stub + return 0; + } + + /* (non-Javadoc) + * @see org.bukkit.World#setTicksPerMonsterSpawns(int) + */ + @Override + public void setTicksPerMonsterSpawns(int paramInt) + { + // TODO Auto-generated method stub + + } + + /* (non-Javadoc) + * @see org.bukkit.World#getMonsterSpawnLimit() + */ + @Override + public int getMonsterSpawnLimit() + { + // TODO Auto-generated method stub + return 0; + } + + /* (non-Javadoc) + * @see org.bukkit.World#setMonsterSpawnLimit(int) + */ + @Override + public void setMonsterSpawnLimit(int paramInt) + { + // TODO Auto-generated method stub + + } + + /* (non-Javadoc) + * @see org.bukkit.World#getAnimalSpawnLimit() + */ + @Override + public int getAnimalSpawnLimit() + { + // TODO Auto-generated method stub + return 0; + } + + /* (non-Javadoc) + * @see org.bukkit.World#setAnimalSpawnLimit(int) + */ + @Override + public void setAnimalSpawnLimit(int paramInt) + { + // TODO Auto-generated method stub + + } + + /* (non-Javadoc) + * @see org.bukkit.World#getWaterAnimalSpawnLimit() + */ + @Override + public int getWaterAnimalSpawnLimit() + { + // TODO Auto-generated method stub + return 0; + } + + /* (non-Javadoc) + * @see org.bukkit.World#setWaterAnimalSpawnLimit(int) + */ + @Override + public void setWaterAnimalSpawnLimit(int paramInt) + { + // TODO Auto-generated method stub + + } + + /* (non-Javadoc) + * @see org.bukkit.World#getAmbientSpawnLimit() + */ + @Override + public int getAmbientSpawnLimit() + { + // TODO Auto-generated method stub + return 0; + } + + /* (non-Javadoc) + * @see org.bukkit.World#setAmbientSpawnLimit(int) + */ + @Override + public void setAmbientSpawnLimit(int paramInt) + { + // TODO Auto-generated method stub + + } + + /* (non-Javadoc) + * @see org.bukkit.World#playSound(org.bukkit.Location, org.bukkit.Sound, float, float) + */ + @Override + public void playSound(Location paramLocation, Sound paramSound, float paramFloat1, float paramFloat2) + { + // TODO Auto-generated method stub + + } + + /* (non-Javadoc) + * @see org.bukkit.World#playSound(org.bukkit.Location, java.lang.String, float, float) + */ + @Override + public void playSound(Location paramLocation, String paramString, float paramFloat1, float paramFloat2) + { + // TODO Auto-generated method stub + + } + + /* (non-Javadoc) + * @see org.bukkit.World#getGameRules() + */ + @Override + public String[] getGameRules() + { + // TODO Auto-generated method stub + return null; + } + + /* (non-Javadoc) + * @see org.bukkit.World#getGameRuleValue(java.lang.String) + */ + @Override + public String getGameRuleValue(String paramString) + { + // TODO Auto-generated method stub + return null; + } + + /* (non-Javadoc) + * @see org.bukkit.World#setGameRuleValue(java.lang.String, java.lang.String) + */ + @Override + public boolean setGameRuleValue(String paramString1, String paramString2) + { + // TODO Auto-generated method stub + return false; + } + + /* (non-Javadoc) + * @see org.bukkit.World#isGameRule(java.lang.String) + */ + @Override + public boolean isGameRule(String paramString) + { + // TODO Auto-generated method stub + return false; + } + + /* (non-Javadoc) + * @see org.bukkit.World#spigot() + */ + @Override + public Spigot spigot() + { + // TODO Auto-generated method stub + return null; + } + + /* (non-Javadoc) + * @see org.bukkit.World#getWorldBorder() + */ + @Override + public WorldBorder getWorldBorder() + { + // TODO Auto-generated method stub + return null; + } + + /* (non-Javadoc) + * @see org.bukkit.World#spawnParticle(org.bukkit.Particle, org.bukkit.Location, int) + */ + @Override + public void spawnParticle(Particle paramParticle, Location paramLocation, int paramInt) + { + // TODO Auto-generated method stub + + } + + /* (non-Javadoc) + * @see org.bukkit.World#spawnParticle(org.bukkit.Particle, double, double, double, int) + */ + @Override + public void spawnParticle(Particle paramParticle, double paramDouble1, double paramDouble2, double paramDouble3, int paramInt) + { + // TODO Auto-generated method stub + + } + + /* (non-Javadoc) + * @see org.bukkit.World#spawnParticle(org.bukkit.Particle, org.bukkit.Location, int, java.lang.Object) + */ + @Override + public <T> void spawnParticle(Particle paramParticle, Location paramLocation, int paramInt, T paramT) + { + // TODO Auto-generated method stub + + } + + /* (non-Javadoc) + * @see org.bukkit.World#spawnParticle(org.bukkit.Particle, double, double, double, int, java.lang.Object) + */ + @Override + public <T> void spawnParticle(Particle paramParticle, double paramDouble1, double paramDouble2, double paramDouble3, int paramInt, T paramT) + { + // TODO Auto-generated method stub + + } + + /* (non-Javadoc) + * @see org.bukkit.World#spawnParticle(org.bukkit.Particle, org.bukkit.Location, int, double, double, double) + */ + @Override + public void spawnParticle(Particle paramParticle, Location paramLocation, int paramInt, double paramDouble1, double paramDouble2, double paramDouble3) + { + // TODO Auto-generated method stub + + } + + /* (non-Javadoc) + * @see org.bukkit.World#spawnParticle(org.bukkit.Particle, double, double, double, int, double, double, double) + */ + @Override + public void spawnParticle(Particle paramParticle, double paramDouble1, double paramDouble2, double paramDouble3, int paramInt, double paramDouble4, double paramDouble5, double paramDouble6) + { + // TODO Auto-generated method stub + + } + + /* (non-Javadoc) + * @see org.bukkit.World#spawnParticle(org.bukkit.Particle, org.bukkit.Location, int, double, double, double, java.lang.Object) + */ + @Override + public <T> void spawnParticle(Particle paramParticle, Location paramLocation, int paramInt, double paramDouble1, double paramDouble2, double paramDouble3, T paramT) + { + // TODO Auto-generated method stub + + } + + /* (non-Javadoc) + * @see org.bukkit.World#spawnParticle(org.bukkit.Particle, double, double, double, int, double, double, double, java.lang.Object) + */ + @Override + public <T> void spawnParticle(Particle paramParticle, double paramDouble1, double paramDouble2, double paramDouble3, int paramInt, double paramDouble4, double paramDouble5, double paramDouble6, + T paramT) + { + // TODO Auto-generated method stub + + } + + /* (non-Javadoc) + * @see org.bukkit.World#spawnParticle(org.bukkit.Particle, org.bukkit.Location, int, double, double, double, double) + */ + @Override + public void spawnParticle(Particle paramParticle, Location paramLocation, int paramInt, double paramDouble1, double paramDouble2, double paramDouble3, double paramDouble4) + { + // TODO Auto-generated method stub + + } + + /* (non-Javadoc) + * @see org.bukkit.World#spawnParticle(org.bukkit.Particle, double, double, double, int, double, double, double, double) + */ + @Override + public void spawnParticle(Particle paramParticle, double paramDouble1, double paramDouble2, double paramDouble3, int paramInt, double paramDouble4, double paramDouble5, double paramDouble6, + double paramDouble7) + { + // TODO Auto-generated method stub + + } + + /* (non-Javadoc) + * @see org.bukkit.World#spawnParticle(org.bukkit.Particle, org.bukkit.Location, int, double, double, double, double, java.lang.Object) + */ + @Override + public <T> void spawnParticle(Particle paramParticle, Location paramLocation, int paramInt, double paramDouble1, double paramDouble2, double paramDouble3, double paramDouble4, T paramT) + { + // TODO Auto-generated method stub + + } + + /* (non-Javadoc) + * @see org.bukkit.World#spawnParticle(org.bukkit.Particle, double, double, double, int, double, double, double, double, java.lang.Object) + */ + @Override + public <T> void spawnParticle(Particle paramParticle, double paramDouble1, double paramDouble2, double paramDouble3, int paramInt, double paramDouble4, double paramDouble5, double paramDouble6, + double paramDouble7, T paramT) + { + // TODO Auto-generated method stub + + } + + /* (non-Javadoc) + * @see org.bukkit.World#playSound(org.bukkit.Location, org.bukkit.Sound, org.bukkit.SoundCategory, float, float) + */ + @Override + public void playSound(Location paramLocation, Sound paramSound, SoundCategory paramSoundCategory, float paramFloat1, float paramFloat2) + { + // TODO Auto-generated method stub + + } + + /* (non-Javadoc) + * @see org.bukkit.World#playSound(org.bukkit.Location, java.lang.String, org.bukkit.SoundCategory, float, float) + */ + @Override + public void playSound(Location paramLocation, String paramString, SoundCategory paramSoundCategory, float paramFloat1, float paramFloat2) + { + // TODO Auto-generated method stub + + } + + /* (non-Javadoc) + * @see org.bukkit.World#spawn(org.bukkit.Location, java.lang.Class, org.bukkit.util.Consumer) + */ + @Override + public <T extends Entity> T spawn(Location paramLocation, Class<T> paramClass, Consumer<T> paramConsumer) throws IllegalArgumentException + { + // TODO Auto-generated method stub + return null; + } + + /* (non-Javadoc) + * @see org.bukkit.World#spawnFallingBlock(org.bukkit.Location, org.bukkit.material.MaterialData) + */ + @Override + public FallingBlock spawnFallingBlock(Location paramLocation, MaterialData paramMaterialData) throws IllegalArgumentException + { + // TODO Auto-generated method stub + return null; + } + +} diff --git a/Spigot-Test/src/main/java/com/comze_instancelabs/minigamesapi/spigottest/PluginMessage.java b/Spigot-Test/src/main/java/com/comze_instancelabs/minigamesapi/spigottest/PluginMessage.java new file mode 100644 index 00000000..c29bf011 --- /dev/null +++ b/Spigot-Test/src/main/java/com/comze_instancelabs/minigamesapi/spigottest/PluginMessage.java @@ -0,0 +1,115 @@ +/* + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +package com.comze_instancelabs.minigamesapi.spigottest; + +import java.util.Arrays; + +import org.bukkit.plugin.Plugin; + +/** + * @author mepeisen + */ +public class PluginMessage +{ + + /** + * the sender plugin. + */ + private Plugin plugin; + /** + * the message channel. + */ + private String channel; + /** + * the data. + */ + private byte[] data; + /** + * @param plugin + * @param channel + * @param data + */ + public PluginMessage(Plugin plugin, String channel, byte[] data) + { + super(); + this.plugin = plugin; + this.channel = channel; + this.data = data; + } + /** + * @return the plugin + */ + public Plugin getPlugin() + { + return this.plugin; + } + /** + * @return the channel + */ + public String getChannel() + { + return this.channel; + } + /** + * @return the data + */ + public byte[] getData() + { + return this.data; + } + /* (non-Javadoc) + * @see java.lang.Object#hashCode() + */ + @Override + public int hashCode() + { + final int prime = 31; + int result = 1; + result = prime * result + ((this.channel == null) ? 0 : this.channel.hashCode()); + result = prime * result + Arrays.hashCode(this.data); + result = prime * result + ((this.plugin == null) ? 0 : this.plugin.hashCode()); + return result; + } + /* (non-Javadoc) + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object obj) + { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + PluginMessage other = (PluginMessage) obj; + if (this.channel == null) + { + if (other.channel != null) + return false; + } + else if (!this.channel.equals(other.channel)) + return false; + if (!Arrays.equals(this.data, other.data)) + return false; + if (this.plugin != other.plugin) + { + return false; + } + return true; + } + +} diff --git a/Spigot-Test/src/main/java/com/comze_instancelabs/minigamesapi/spigottest/SpigotTestSupport.java b/Spigot-Test/src/main/java/com/comze_instancelabs/minigamesapi/spigottest/SpigotTestSupport.java new file mode 100644 index 00000000..f985fdf2 --- /dev/null +++ b/Spigot-Test/src/main/java/com/comze_instancelabs/minigamesapi/spigottest/SpigotTestSupport.java @@ -0,0 +1,418 @@ +/* + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +package com.comze_instancelabs.minigamesapi.spigottest; + +import static org.junit.Assert.fail; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.anyString; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; +import static org.powermock.api.mockito.PowerMockito.mockStatic; + +import java.io.File; +import java.io.InputStream; +import java.io.Reader; +import java.lang.reflect.Method; +import java.util.Arrays; +import java.util.Map; +import java.util.UUID; + +import org.bukkit.Bukkit; +import org.bukkit.World; +import org.bukkit.WorldType; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.craftbukkit.v1_12_R1.CraftServer; +import org.bukkit.craftbukkit.v1_12_R1.scoreboard.CraftScoreboard; +import org.bukkit.craftbukkit.v1_12_R1.scoreboard.CraftScoreboardManager; +import org.bukkit.entity.Player; +import org.bukkit.inventory.PlayerInventory; +import org.bukkit.plugin.PluginDescriptionFile; +import org.bukkit.plugin.PluginLogger; +import org.bukkit.plugin.java.JavaPlugin; +import org.junit.After; +import org.junit.Before; +import org.junit.runner.RunWith; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; +import org.powermock.core.classloader.annotations.PowerMockIgnore; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.powermock.reflect.Whitebox; +import org.spigotmc.SpigotConfig; + +import com.google.common.io.ByteArrayDataOutput; +import com.google.common.io.ByteStreams; + +import net.minecraft.server.v1_12_R1.DispenserRegistry; + +/** + * Test tooling for minigames API. + * + * @author mepeisen + */ +@RunWith(PowerMockRunner.class) +@PrepareForTest({ YamlConfiguration.class, CraftServer.class, CraftScoreboardManager.class, CraftScoreboard.class }) +@PowerMockIgnore({ "org.apache.*", "com.sun.*", "javax.*" }) +public abstract class SpigotTestSupport +{ + + /** + * Initializes the dummy server. + */ + @Before + public void setupServer() + { + DispenserRegistry.c(); + DummyServer.setup(); + DummyEnchantments.setup(); + mockStatic(YamlConfiguration.class); + when(YamlConfiguration.loadConfiguration(any(File.class))).thenAnswer(new Answer<YamlConfiguration>() { + + @Override + public YamlConfiguration answer(InvocationOnMock invocation) throws Throwable + { + final File arg = invocation.getArgumentAt(0, File.class); + return getDummyServer().getConfigFiles().get(arg); + } + + }); + SpigotConfig.config = mockFileConfig(); + } + + /** + * Tear down all plugins and players. + */ + @After + public void teardownMinigamesAndPlayers() + { + this.teardownPlugins(); + this.teardownPlayers(); + this.teardownConfigFiles(); + this.teardownScoreboards(); + this.teardownTasks(); + this.teardownWorlds(); + this.teardownMessages(); + } + + /** + * Initializes a new dummy world. + * + * @param name + * world name + * @return World instance. + */ + public World initWorld(String name) + { + return getDummyServer().initWorld(name); + } + + /** + * Initializes a flat world hold in memory. + * + * @param name + * world name + * @return world instance. + */ + public World initFlatWorld(String name) + { + return getDummyServer().initWorld(name, WorldType.FLAT, 123); + } + + /** + * Returns the dummy server. + * + * @return dummy server + */ + static DummyServer getDummyServer() + { +// final Server server = Bukkit.getServer(); +// return (DummyServer) Proxy.getInvocationHandler(server); + return DummyServer.DUMMY_SERVER; + } + + /** + * Setup a config file for being returned by {@link YamlConfiguration#load(File)} + * + * @param file + * the file path + * @return config file + */ + public static YamlConfiguration setupConfigFile(File file) + { + final YamlConfiguration config = mockFileConfig(); + getDummyServer().getConfigFiles().put(file, config); + file.deleteOnExit(); + return config; + } + + /** + * Tear down all config files. + */ + protected void teardownConfigFiles() + { + getDummyServer().getConfigFiles().clear(); + } + + /** + * Tear down all messages. + */ + protected void teardownMessages() + { + getDummyServer().clearMessages(); + } + + /** + * Removes all plugins. + */ + protected void teardownPlugins() + { + Bukkit.getServer().getPluginManager().clearPlugins(); + } + + /** + * Removes all players. + */ + protected void teardownPlayers() + { + getDummyServer().clearPlayers(); + } + + /** + * Removes all players. + */ + protected void teardownWorlds() + { + getDummyServer().clearWorlds(); + } + + /** + * Teardown the score board support. + */ + protected void teardownScoreboards() + { + getDummyServer().teardownScoreboards(); + } + + /** + * Teardown the server tasks and ticks. + */ + protected void teardownTasks() + { + this.getDummyServer().clearTicks(); + } + + /** + * Mocks a player and adds it to the server. + * + * @param name + * players name + * @param uuid + * unique player id. + * @return mocked player object. + */ + protected Player mockOnlinePlayer(String name, UUID uuid) + { + final DummyServer server = getDummyServer(); + final Player player = mock(Player.class); + final PlayerInventory inv = new DummyPlayerInventory(); + when(player.getName()).thenReturn(name); + when(player.getUniqueId()).thenReturn(uuid); + server.addMockedPlayer(player); + when(player.getInventory()).thenReturn(inv); + return player; + } + + /** + * mocks a file configuration to not load/write from/to disk. + * + * @return yaml file configuration + */ + public static YamlConfiguration mockFileConfig() + { + final YamlConfiguration config = spy(YamlConfiguration.class); + try + { + doNothing().when(config).load(any(File.class)); + doNothing().when(config).load(any(Reader.class)); + doNothing().when(config).load(anyString()); + doNothing().when(config).loadFromString(anyString()); + doNothing().when(config).save(any(File.class)); + doNothing().when(config).save(anyString()); + } + catch (@SuppressWarnings("unused") Exception ex) + { + // silently ignore; should never happen because we config a mock here. + } + return config; + } + + /** + * Mocks a plugin and returns it. + * + * @param name + * plugin name + * @param version + * plugin version + * @param config + * plugin config + * @return mocked java plugin. + */ + public JavaPlugin mockPlugin(String name, String version, FileConfiguration config) + { + return mockPlugin(name, version, config, JavaPlugin.class, null); + } + + /** + * Mocks a plugin and returns it. + * + * @param name + * plugin name + * @param version + * plugin version + * @param config + * plugin config + * @param clazz + * plugin class + * @param answers + * additional answers for mocking + * @return mocked java plugin. + */ + public <T extends JavaPlugin> T mockPlugin(String name, String version, FileConfiguration config, Class<T> clazz, Map<Method, Answer<?>> answers) + { + final T plugin = mock(clazz, (Answer<?>) invocation -> { + if (answers != null && answers.containsKey(invocation.getMethod())) + { + return answers.get(invocation.getMethod()).answer(invocation); + } + if (invocation.getMethod().getName().equals("getResource")) //$NON-NLS-1$ + return null; + return invocation.callRealMethod(); + }); + final PluginLogger logger = mock(PluginLogger.class); + final File dataFolder = new File(".$" + name); //$NON-NLS-1$ + final PluginDescriptionFile description = new PluginDescriptionFile(name, version, "foo"); //$NON-NLS-1$ + Whitebox.setInternalState(plugin, "newConfig", config); //$NON-NLS-1$ + Whitebox.setInternalState(plugin, "logger", logger); //$NON-NLS-1$ + Whitebox.setInternalState(plugin, "dataFolder", dataFolder); //$NON-NLS-1$ + Whitebox.setInternalState(plugin, "description", description); //$NON-NLS-1$ + Whitebox.setInternalState(plugin, "isEnabled", true); //$NON-NLS-1$ + + ((DummyPluginManager) Bukkit.getPluginManager()).addMockedPlugin(plugin); + + return plugin; + } + + /** + * Performs the main tick. + */ + protected void tick() + { + getDummyServer().tick(); + } + + /** + * Assert that a given message was sent. + * + * @param senderPlugin + * @param channel + * @param message + */ + public static void verifyPluginMessage(JavaPlugin senderPlugin, String channel, Object... message) + { + final byte[] bytes = toByteArray(message); + final PluginMessage msg = new PluginMessage(senderPlugin, channel, bytes); + + final StringBuilder builder = new StringBuilder(); + builder.append("Expected plugin message not sent.\nplugin: ").append(senderPlugin.getName()); //$NON-NLS-1$ + builder.append("\nchannel: ").append(channel); //$NON-NLS-1$ + for (Object obj : message) + { + builder.append("\n arg:").append(obj); //$NON-NLS-1$ + } + builder.append("\n bytes: ").append(Arrays.toString(bytes)); //$NON-NLS-1$ + + for (final PluginMessage sent : getDummyServer().getMessages()) + { + if (sent.equals(msg)) + { + // we found the message + return; + } + builder.append("\n candidate: ").append(sent.getPlugin().getName()).append("/").append(sent.getChannel()).append("/").append(Arrays.toString(sent.getData())); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + } + fail(builder.toString()); + } + + private static byte[] toByteArray(Object... message) + { + final ByteArrayDataOutput out = ByteStreams.newDataOutput(); + for (Object obj : message) + { + if (obj instanceof String) + { + out.writeUTF((String) obj); + } + else if (obj instanceof Boolean) + { + out.writeBoolean((Boolean) obj); + } + else if (obj instanceof Byte) + { + out.writeByte((Byte) obj); + } + else if (obj instanceof Character) + { + out.writeChar((Character) obj); + } + else if (obj instanceof Double) + { + out.writeDouble((Double) obj); + } + else if (obj instanceof Float) + { + out.writeFloat((Float) obj); + } + else if (obj instanceof Integer) + { + out.writeInt((Integer) obj); + } + else if (obj instanceof Long) + { + out.writeLong((Long) obj); + } + else if (obj instanceof Short) + { + out.writeShort((Short) obj); + } + else if (obj instanceof Object[]) + { + final byte[] arr = toByteArray((Object[]) obj); + out.writeShort(arr.length); + out.write(arr); + } + else + { + fail("Unknown object type for assert message"); //$NON-NLS-1$ + } + } + final byte[] bytes = out.toByteArray(); + return bytes; + } + +} diff --git a/changelog.md b/changelog.md new file mode 100644 index 00000000..8e5a6ba3 --- /dev/null +++ b/changelog.md @@ -0,0 +1,364 @@ +# Changelog + +#### 1.14.18 + +###### All + +* Merged PullRequest for event class fixes (https://github.com/MysticCity/MinigamesAPI/pull/283) +* (!API change!) Fixed party command for typing player names with wrong case (https://github.com/MysticCity/MinigamesAPI/issues/282) +* MySQL fixed (https://github.com/MysticCity/MinigamesAPI/issues/281) +* Moved "Done: true" for achivements into messages.yml (https://github.com/MysticCity/MinigamesAPI/issues/280) +* Added flag to deactivate smart reset (https://github.com/MysticCity/MinigamesAPI/issues/286) +* Fixed ClassCastException (https://github.com/MysticCity/MinigamesAPI/issues/288) +* Fixed 1.12 deprecated event (https://github.com/MysticCity/MinigamesAPI/issues/295) +* Fixed 1.12 yml file loading + +###### BedWars + +* (1.12) Colored beds (https://github.com/MysticCity/MinigamesAPI/issues/284) + +###### ColorMatch + +* Fixed broken start sound (https://github.com/MysticCity/MinigamesAPI/issues/273) + +###### Conquer + +* Fixed NullPointerException (https://github.com/MysticCity/MinigamesAPI/issues/286) + +###### HorseRacingPlus + +* Fixed NPE if plugin folder does not exist (https://github.com/MysticCity/MinigamesAPI/issues/273) +* Fixed NPE if plugin folder does not exist (https://github.com/MysticCity/MinigamesAPI/issues/273) +* Fixed broken start sound (https://github.com/MysticCity/MinigamesAPI/issues/273) + +###### MobEscape + +* Fixed lags while destroying liquids (https://github.com/MysticCity/MinigamesAPI/issues/291) +* Added block blacklist (https://github.com/MysticCity/MinigamesAPI/issues/291) + +#### 1.14.17 + +###### All + +* Support for minecraft 1.12 (https://github.com/MysticCity/MinigamesAPI/issues/263) +* Fixed chest handling during smart reset (https://github.com/MysticCity/MinigamesAPI/issues/230) +* Fixed bungee support for empty servers (https://github.com/MysticCity/MinigamesAPI/issues/217) + +###### MobEscape + +* fixed detecting of first player waypoint (https://github.com/MysticCity/MinigamesAPI/issues/247) + +###### OITC + +* fixed crushing crops (https://github.com/MysticCity/MinigamesAPI/issues/257) + +###### SkyWars + +* fixed NPE (https://github.com/MysticCity/MinigamesAPI/issues/262) + +#### 1.14.16 + +###### All + +* (Bungeecord) Clicking a join sign will now throw all players of a party to the minigame server (https://github.com/MysticCity/MinigamesAPI/issues/208) +* fixed NullPointerException (https://github.com/MysticCity/MinigamesAPI/issues/243) +* *v2-backport* new chat countdown while reaching max game time (https://github.com/MysticCity/MinigamesAPI/issues/224) +* *v2-backport* api extension for minigames that want to influence the max game time (https://github.com/MysticCity/MinigamesAPI/issues/224) +* *v2-backport* support for unlimited games (max game time set to zero) (https://github.com/MysticCity/MinigamesAPI/issues/224) +* Fixed ArrayIndexOutOfBounds in stop and spectate command +* Fixed exceptions and several bugs related to spectation (https://github.com/MysticCity/MinigamesAPI/issues/230) +* Added SQLite support (https://github.com/MysticCity/MinigamesAPI/issues/220) +* Fixed NullPointerException (https://github.com/MysticCity/MinigamesAPI/issues/249) + +###### BedWars + +* Option to disable GUI for servers that have there own gui implementation (https://github.com/MysticCity/MinigamesAPI/issues/253) + +###### Conquer + +* Team selector gui (https://github.com/MysticCity/MinigamesAPI/issues/216) + +###### MobEscape + +* Fixed runtime error in 1.8.5 to 1.8.9 +* Fixed false positive error: Destroy mode invalid (https://github.com/MysticCity/MinigamesAPI/issues/225) + +###### SkyWars + +* Added new mode 'items' for filling the chests. (https://github.com/MysticCity/MinigamesAPI/issues/254). For details siki wiki at https://github.com/MysticCity/MinigamesAPI/wiki/MGSkyWars + +###### Splegg + +* Fixed exception plaxying projectile sound in 1.7.X/1.8.X (https://github.com/MysticCity/MinigamesAPI/issues/241) + +#### 1.14.15 + +###### All + +* fixed bungeecord signs +* fixed config.yml generation for "old" setupAPI (https://github.com/MysticCity/MinigamesAPI/issues/212) +* fixed specator signs (https://github.com/MysticCity/MinigamesAPI/issues/188) +* fixed hologram removal (https://github.com/MysticCity/MinigamesAPI/issues/191) +* fixed "console spams"/ checking for debug config option (https://github.com/MysticCity/MinigamesAPI/issues/200) +* fixed NPE if main lobby is missing (https://github.com/MysticCity/MinigamesAPI/issues/201) +* some api extension (https://github.com/MysticCity/MinigamesAPI/issues/203) +* compass tracking fixed (https://github.com/MysticCity/MinigamesAPI/issues/206) +* new config flag: "use\_spectator\_scoreboard" (https://github.com/MysticCity/MinigamesAPI/issues/194) + +###### BedWars + +* fixed lags/performance issues (https://github.com/MysticCity/MinigamesAPI/issues/198, https://github.com/MysticCity/MinigamesAPI/issues/207, https://github.com/MysticCity/MinigamesAPI/issues/213) +* fixed unbalanced teams (https://github.com/MysticCity/MinigamesAPI/issues/215) +* fixed localization/ hard coded strings (https://github.com/MysticCity/MinigamesAPI/issues/215) + +###### BowBash + +* fixed lags/performance issues (https://github.com/MysticCity/MinigamesAPI/issues/198, https://github.com/MysticCity/MinigamesAPI/issues/207, https://github.com/MysticCity/MinigamesAPI/issues/213) + +###### ColorMatch + +* fixed lags/performance issues (https://github.com/MysticCity/MinigamesAPI/issues/198, https://github.com/MysticCity/MinigamesAPI/issues/207, https://github.com/MysticCity/MinigamesAPI/issues/213) + +###### Conquer + +* fixed lags/performance issues (https://github.com/MysticCity/MinigamesAPI/issues/198, https://github.com/MysticCity/MinigamesAPI/issues/207, https://github.com/MysticCity/MinigamesAPI/issues/213) + +###### GunGame + +* fixed lags/performance issues (https://github.com/MysticCity/MinigamesAPI/issues/198, https://github.com/MysticCity/MinigamesAPI/issues/207, https://github.com/MysticCity/MinigamesAPI/issues/213) + +###### HorseRacing + +* moved hard coded strings to config (for translation) +* added config option announce\_title (https://github.com/MysticCity/MinigamesAPI/issues/187) + +###### MobEscape + +* fixed lags/performance issues (https://github.com/MysticCity/MinigamesAPI/issues/198, https://github.com/MysticCity/MinigamesAPI/issues/207, https://github.com/MysticCity/MinigamesAPI/issues/213) +* added scoreboard text to messages.yml (https://github.com/MysticCity/MinigamesAPI/issues/218) +* fixed crack particle spawn (https://github.com/MysticCity/MinigamesAPI/issues/146) +* new config: destroy\_mode with possible values "sphere" and "cuboid" (https://github.com/MysticCity/MinigamesAPI/issues/125) + +###### OITC + +* fixed lags/performance issues (https://github.com/MysticCity/MinigamesAPI/issues/198, https://github.com/MysticCity/MinigamesAPI/issues/207, https://github.com/MysticCity/MinigamesAPI/issues/213) + +###### SeaBattle + +* fixed lags/performance issues (https://github.com/MysticCity/MinigamesAPI/issues/198, https://github.com/MysticCity/MinigamesAPI/issues/207, https://github.com/MysticCity/MinigamesAPI/issues/213) +* fixed boat under water (https://github.com/MysticCity/MinigamesAPI/issues/185) + +###### Snake + +* fixed lags/performance issues (https://github.com/MysticCity/MinigamesAPI/issues/198, https://github.com/MysticCity/MinigamesAPI/issues/207, https://github.com/MysticCity/MinigamesAPI/issues/213) + +#### 1.14.14 + +###### All + +* support for Minecraft 1.11 and 1.11.2 +* incompatible change: Players command "<game> spectate <arena>" is now secured by permissions (https://github.com/MysticCity/MinigamesAPI/wiki/Admin-Spectating) +* bugfix by setting spectator bounds: (https://github.com/MysticCity/MinigamesAPI/issues/166) +* improved spectator support (https://github.com/MysticCity/MinigamesAPI/wiki/Admin-Spectating) +* Scoreboards now use display names (https://github.com/MysticCity/MinigamesAPI/issues/178) +* Scoreboards display correct names on multiple arenas of the same game (https://github.com/MysticCity/MinigamesAPI/issues/178) +* Lib now clears up any item on startup/stop, maybe remaining from crashing servers/ games or player interactions + +###### BedWars + +* fixed minor NPE for selecting classes (bedwars has no classes) +* support for 1.11 (https://github.com/MysticCity/MinigamesAPI/issues/182) +* fixed small memory leak + +###### HorseRacingPlus + +* bugfix for 1.11 support (https://github.com/MysticCity/MinigamesAPI/issues/177) + +###### SeaBattle + +* Added config option "die\_below\_bedrock\_level" (fixes arenas where the spawns are over 4 block above the battle sea) +* Really destroys all boats at end (even through disconnects etc.) + +#### 1.14.12/1.14.13 + +###### All + +* No more kill rewards for self-kills (https://github.com/MysticCity/MinigamesAPI/issues/11) +* Fixed NPE using spectator sign outside of arena (https://github.com/MysticCity/MinigamesAPI/issues/154) +* Fixed PlayOutFakeBed (https://github.com/MysticCity/MinigamesAPI/issues/161) +* Migrated to eclipse-plugin (http://minecraft.xworlds.eu/eclipse/) + +###### BedWars + +* Added command "setupbeds" to help page + +###### DeathRun + +* Config option "die\_below\_bedrock\_level" can now be numeric to hold the minimum y coordinate the player can reach + +###### GunGame + +* Config option "die\_below\_bedrock\_level" can now be numeric to hold the minimum y coordinate the player can reach + +###### MobEscape + +* Config option "die\_below\_bedrock\_level" can now be numeric to hold the minimum y coordinate the player can reach + +###### Splegg + +* Config option "die\_below\_bedrock\_level" can now be numeric to hold the minimum y coordinate the player can reach + +###### SkyWars + +* Fixed SmartReset logic for user placed blocks (https://github.com/MysticCity/MinigamesAPI/issues/169) + +###### Sudoku + +* new game sudoku/ migrated to minigames lib + +#### 1.14.11 + +###### All + +* removed system.out.println and printstacktrace + +###### Minigames-API + +* NoSuchMethodError in Effects.playHologram for 1.9 and 1.10 +* Spawns of living entites inside arenas is now forbidden. No more need of worldguard etc (https://github.com/MysticCity/MinigamesAPI/issues/79) +* Players being inside arenas or waiting lobby can no longer be attacked by mobs. +* Effects.playOutTitle fixed (https://github.com/MysticCity/MinigamesAPI/issues/112) +* Feature for displaying arena states in MOTD. See config.yml of Minigames-LIB, enable at config.motd.enabled (https://github.com/MysticCity/MinigamesAPI/issues/54) +* Players in vehicles can not longer leave arena bounds (https://github.com/MysticCity/MinigamesAPI/issues/78) +* Config options to disable xp/inventory/gamemode reset on leave (https://github.com/MysticCity/MinigamesAPI/issues/97) + +###### BedWars + +* Spawning villagers inside BedWars arena is allowed (https://github.com/MysticCity/MinigamesAPI/issues/79) + +###### BowBash + +* fixed console spams of "Cancelled powerup task" +* fixed powerup task error (https://github.com/MysticCity/MinigamesAPI/issues/104) + +###### HorseRacingPlus + +* Spawning horses inside HorseRacingPlus arena is allowed (https://github.com/MysticCity/MinigamesAPI/issues/79) +* Started migration to MinigamesLib (https://github.com/MysticCity/MinigamesAPI/issues/12) + +###### MobEscape + +* Spawning witches and dragons inside MobEscape arena is allowed (https://github.com/MysticCity/MinigamesAPI/issues/79) +* Added new arena config option for falling-block-ratio, see https://github.com/MysticCity/MinigamesAPI/wiki/MGMobEscape for details (https://github.com/MysticCity/MinigamesAPI/issues/64) + +###### SkyWars + +* Players in vehicles can not longer leave arena bounds (https://github.com/MysticCity/MinigamesAPI/issues/78) + +###### Snake + +* fixed powerup task error (https://github.com/MysticCity/MinigamesAPI/issues/104) + +###### Splegg + +* removed arena points, fixes https://github.com/MysticCity/MinigamesAPI/issues/81 +* fixed powerup task error (https://github.com/MysticCity/MinigamesAPI/issues/104) +* Spawning slime and sheeps inside Snake arena is allowed (https://github.com/MysticCity/MinigamesAPI/issues/79) + +###### SeaBattle + +* Workaround for boat under water https://github.com/MysticCity/MinigamesAPI/issues/95 +* Workaround for deny boat movement on startup count down https://github.com/MysticCity/MinigamesAPI/issues/107 +* Players in vehicles can not longer leave arena bounds (https://github.com/MysticCity/MinigamesAPI/issues/78) + +##### TrapdoorSpleef + +* fixed non-generated arena on first arena start (https://github.com/MysticCity/MinigamesAPI/issues/83) + +##### Warlock + +* fixed non-generated arena on first arena start (https://github.com/MysticCity/MinigamesAPI/issues/83) + +##### Warlock-Tactical + +* fixed non-generated arena on first arena start (https://github.com/MysticCity/MinigamesAPI/issues/83) + + + +#### 1.14.10 + +###### All + +* Changed permissions prefix to "ancient." +* Fixed smart + +###### Minigames-API + +* Fixed smart reset on big arenas/ hundreds of blocks + +###### DeathRun + +* Fixed falling blocks animation + + + +#### 1.14.9 + +###### All + +* Using same version numbers (Games and minigamesAPI share same version number to make dependencies more intuitive) +* Support for Spigot 1.10 +* Incompatible change: Reworking the permissions, see https://github.com/MysticCity/MinigamesAPI/wiki/Permissions for details + +###### Minigames-API +* various JUnit-Tests +* refactoring of MinigamesAPI-Bungee (merge to Minigames-API) +* migration to maven and hudson build +* various refactoring and javadoc +* NPE fix (https://github.com/MysticCity/MinigamesAPI/issues/41) +* new leave command invoked on arena leave (https://github.com/MysticCity/MinigamesAPI/issues/29) +* NPE fix (https://github.com/MysticCity/MinigamesAPI/issues/26) +* Upgraded dependencies to vault and crackshot +* Fix for some race conditions while stopping arena +* Fixed some UTF-8 encoding +* sub command "join" with given player name now is protected by permission "adminjoin" +* sub command "reload" is now protected by permission "reload" +* sub command "setkit" with given player name is now protected by permission "adminkit" +* sub command "spectate" with given player name is now protected by permission "adminspectate" +* sub command "setskull" deactivated. Will be reimplemented later on (https://github.com/MysticCity/MinigamesAPI/issues/59) +* NPE fix (https://github.com/MysticCity/MinigamesAPI/issues/57) +* Fixed disappearing objects (villagers, npc etx.) after teleports (https://github.com/MysticCity/MinigamesAPI/issues/37) +* New updater using a nexus query script (https://github.com/MysticCity/MinigamesAPI/issues/23), NOTICE: It does currently only query newer versions with WARNING log level. It does not yet update automatically. +* added config option to disable metrics updates (https://github.com/MysticCity/MinigamesAPI/issues/10) + +###### Minigames-API-Bungee +* removed everything (now part of Minigames-API) + +###### Snake +* wool is back again (see wiki) +* fixed problems with sheeps yaw +* fixed problems with "nervous" sheeps +* added tickCount (see wiki) + +###### BedWars +* do never remove NPCs on map reset +* removed maxuses of trades/ set to 999999 because of some bugs (see https://github.com/MysticCity/MinigamesAPI/issues/61) +* fixed arena reset, now respects all playerblock events +* removed experience on trade (https://github.com/MysticCity/MinigamesAPI/issues/66) + +###### MobEscape +* fixed arena reset, now resetting lower Y levels first (https://github.com/MysticCity/MinigamesAPI/issues/68) +* added jumpFactor configuration value, see wiki for details. + +###### Jumper +* disabled the jumper scoreboard + +###### Conquer +* Command "setcheckpoint" is now protected by permission "setup" + +###### FlyingCars +* NPE fix while leaving minecart + +###### Sudoku +* Sudoku join sign now uses "sudoku.sign" permission instead of "horseracingplus.sign" permission. +* Fixed join sign diff --git a/maven-setup/README.md b/maven-setup/README.md new file mode 100644 index 00000000..21626d6a --- /dev/null +++ b/maven-setup/README.md @@ -0,0 +1,56 @@ +Minigame Maven Setup +==================== + +Install spigot +-------------- + +To be able to compile minigames using maven you need access to the spigot binaries. +After building Spigot with build tools you can use maven to deploy the artifacts to your own maven repository. + +To install spigot in your local repository invoke + +``` + + mvn install + +``` + +To deploy spigot to your web repository invoke + +``` + + mvn deploy -DaltDeploymentRepository=<your-repos-id>::default::http://<your-repos> + +``` + +The minigames lib itself currently only depends on the newest version of spigot. + + + +Install nms builds +------------------ + +As a second goal we require support for nms classes. NMS classes are special variants that highly depend on the minecraft or craftbukkit api. The differ from version to version. + +For a clean support each minigame and the lib decide which version the current server is build on. + +For maven builds to not mess up with this dependencies we decided to use a special shadowed artifact only containing the version specific classes. + +You will find a sub directory called nms-server-poms containing the pom files you need. + +To install the nms builds in your local repository invoke + +``` + + mvn install + +``` + +To deploy the nms builds to your web repository invoke + +``` + + mvn deploy -DaltDeploymentRepository=<your-repos-id>::default::http://<your-repos> + +``` + diff --git a/maven-setup/nms-server-poms/v1_10_R1/pom.xml b/maven-setup/nms-server-poms/v1_10_R1/pom.xml new file mode 100644 index 00000000..2581ca5f --- /dev/null +++ b/maven-setup/nms-server-poms/v1_10_R1/pom.xml @@ -0,0 +1,48 @@ +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + <groupId>net.minecraft.server</groupId> + <artifactId>v1_10_R1</artifactId> + <version>1.10</version> + + <dependencies> + <dependency> + <groupId>org.spigotmc</groupId> + <artifactId>spigot</artifactId> + <version>1.10-R0.1-SNAPSHOT</version> + </dependency> + </dependencies> + + <build> + <plugins> + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-shade-plugin</artifactId> + <version>1.4</version> + <executions> + <execution> + <phase>package</phase> + <goals> + <goal>shade</goal> + </goals> + <configuration> + <artifactSet> + <includes> + <include>org.spigotmc:spigot</include> + </includes> + </artifactSet> + <filters> + <filter> + <artifact>org.spigotmc:spigot</artifact> + <includes> + <include>net/minecraft/server/**</include> + <include>org/bukkit/craftbukkit/v1_10_R1/**</include> + </includes> + </filter> + </filters> + </configuration> + </execution> + </executions> + </plugin> + </plugins> + </build> +</project> \ No newline at end of file diff --git a/maven-setup/nms-server-poms/v1_7_R1/pom.xml b/maven-setup/nms-server-poms/v1_7_R1/pom.xml new file mode 100644 index 00000000..45a81046 --- /dev/null +++ b/maven-setup/nms-server-poms/v1_7_R1/pom.xml @@ -0,0 +1,48 @@ +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + <groupId>net.minecraft.server</groupId> + <artifactId>v1_7_R1</artifactId> + <version>1.7</version> + + <dependencies> + <dependency> + <groupId>org.spigotmc</groupId> + <artifactId>spigot</artifactId> + <version>1.7.2-R0.4-SNAPSHOT</version> + </dependency> + </dependencies> + + <build> + <plugins> + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-shade-plugin</artifactId> + <version>1.4</version> + <executions> + <execution> + <phase>package</phase> + <goals> + <goal>shade</goal> + </goals> + <configuration> + <artifactSet> + <includes> + <include>org.spigotmc:spigot</include> + </includes> + </artifactSet> + <filters> + <filter> + <artifact>org.spigotmc:spigot</artifact> + <includes> + <include>net/minecraft/server/**</include> + <include>org/bukkit/craftbukkit/v1_7_R1/**</include> + </includes> + </filter> + </filters> + </configuration> + </execution> + </executions> + </plugin> + </plugins> + </build> +</project> \ No newline at end of file diff --git a/maven-setup/nms-server-poms/v1_7_R2/pom.xml b/maven-setup/nms-server-poms/v1_7_R2/pom.xml new file mode 100644 index 00000000..4356b809 --- /dev/null +++ b/maven-setup/nms-server-poms/v1_7_R2/pom.xml @@ -0,0 +1,48 @@ +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + <groupId>net.minecraft.server</groupId> + <artifactId>v1_7_R2</artifactId> + <version>1.7</version> + + <dependencies> + <dependency> + <groupId>org.spigotmc</groupId> + <artifactId>spigot</artifactId> + <version>1.7.5-R0.1-SNAPSHOT</version> + </dependency> + </dependencies> + + <build> + <plugins> + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-shade-plugin</artifactId> + <version>1.4</version> + <executions> + <execution> + <phase>package</phase> + <goals> + <goal>shade</goal> + </goals> + <configuration> + <artifactSet> + <includes> + <include>org.spigotmc:spigot</include> + </includes> + </artifactSet> + <filters> + <filter> + <artifact>org.spigotmc:spigot</artifact> + <includes> + <include>net/minecraft/server/**</include> + <include>org/bukkit/craftbukkit/v1_7_R2/**</include> + </includes> + </filter> + </filters> + </configuration> + </execution> + </executions> + </plugin> + </plugins> + </build> +</project> \ No newline at end of file diff --git a/maven-setup/nms-server-poms/v1_7_R3/pom.xml b/maven-setup/nms-server-poms/v1_7_R3/pom.xml new file mode 100644 index 00000000..89d9675d --- /dev/null +++ b/maven-setup/nms-server-poms/v1_7_R3/pom.xml @@ -0,0 +1,48 @@ +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + <groupId>net.minecraft.server</groupId> + <artifactId>v1_7_R3</artifactId> + <version>1.7</version> + + <dependencies> + <dependency> + <groupId>org.spigotmc</groupId> + <artifactId>spigot</artifactId> + <version>1.7.9-R0.2-SNAPSHOT</version> + </dependency> + </dependencies> + + <build> + <plugins> + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-shade-plugin</artifactId> + <version>1.4</version> + <executions> + <execution> + <phase>package</phase> + <goals> + <goal>shade</goal> + </goals> + <configuration> + <artifactSet> + <includes> + <include>org.spigotmc:spigot</include> + </includes> + </artifactSet> + <filters> + <filter> + <artifact>org.spigotmc:spigot</artifact> + <includes> + <include>net/minecraft/server/**</include> + <include>org/bukkit/craftbukkit/v1_7_R3/**</include> + </includes> + </filter> + </filters> + </configuration> + </execution> + </executions> + </plugin> + </plugins> + </build> +</project> \ No newline at end of file diff --git a/maven-setup/nms-server-poms/v1_7_R4/pom.xml b/maven-setup/nms-server-poms/v1_7_R4/pom.xml new file mode 100644 index 00000000..5736deaf --- /dev/null +++ b/maven-setup/nms-server-poms/v1_7_R4/pom.xml @@ -0,0 +1,48 @@ +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + <groupId>net.minecraft.server</groupId> + <artifactId>v1_7_R4</artifactId> + <version>1.7</version> + + <dependencies> + <dependency> + <groupId>org.spigotmc</groupId> + <artifactId>spigot</artifactId> + <version>1.7.10-R0.1-SNAPSHOT</version> + </dependency> + </dependencies> + + <build> + <plugins> + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-shade-plugin</artifactId> + <version>1.4</version> + <executions> + <execution> + <phase>package</phase> + <goals> + <goal>shade</goal> + </goals> + <configuration> + <artifactSet> + <includes> + <include>org.spigotmc:spigot</include> + </includes> + </artifactSet> + <filters> + <filter> + <artifact>org.spigotmc:spigot</artifact> + <includes> + <include>net/minecraft/server/**</include> + <include>org/bukkit/craftbukkit/v1_7_R4/**</include> + </includes> + </filter> + </filters> + </configuration> + </execution> + </executions> + </plugin> + </plugins> + </build> +</project> \ No newline at end of file diff --git a/maven-setup/nms-server-poms/v1_8_R1/pom.xml b/maven-setup/nms-server-poms/v1_8_R1/pom.xml new file mode 100644 index 00000000..c71786e8 --- /dev/null +++ b/maven-setup/nms-server-poms/v1_8_R1/pom.xml @@ -0,0 +1,48 @@ +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + <groupId>net.minecraft.server</groupId> + <artifactId>v1_8_R1</artifactId> + <version>1.8</version> + + <dependencies> + <dependency> + <groupId>org.spigotmc</groupId> + <artifactId>spigot</artifactId> + <version>1.8-R0.1-SNAPSHOT</version> + </dependency> + </dependencies> + + <build> + <plugins> + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-shade-plugin</artifactId> + <version>1.4</version> + <executions> + <execution> + <phase>package</phase> + <goals> + <goal>shade</goal> + </goals> + <configuration> + <artifactSet> + <includes> + <include>org.spigotmc:spigot</include> + </includes> + </artifactSet> + <filters> + <filter> + <artifact>org.spigotmc:spigot</artifact> + <includes> + <include>net/minecraft/server/**</include> + <include>org/bukkit/craftbukkit/v1_8_R1/**</include> + </includes> + </filter> + </filters> + </configuration> + </execution> + </executions> + </plugin> + </plugins> + </build> +</project> \ No newline at end of file diff --git a/maven-setup/nms-server-poms/v1_8_R2/pom.xml b/maven-setup/nms-server-poms/v1_8_R2/pom.xml new file mode 100644 index 00000000..8262efde --- /dev/null +++ b/maven-setup/nms-server-poms/v1_8_R2/pom.xml @@ -0,0 +1,48 @@ +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + <groupId>net.minecraft.server</groupId> + <artifactId>v1_8_R2</artifactId> + <version>1.8</version> + + <dependencies> + <dependency> + <groupId>org.spigotmc</groupId> + <artifactId>spigot</artifactId> + <version>1.8.3-R0.1-SNAPSHOT</version> + </dependency> + </dependencies> + + <build> + <plugins> + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-shade-plugin</artifactId> + <version>1.4</version> + <executions> + <execution> + <phase>package</phase> + <goals> + <goal>shade</goal> + </goals> + <configuration> + <artifactSet> + <includes> + <include>org.spigotmc:spigot</include> + </includes> + </artifactSet> + <filters> + <filter> + <artifact>org.spigotmc:spigot</artifact> + <includes> + <include>net/minecraft/server/**</include> + <include>org/bukkit/craftbukkit/v1_8_R2/**</include> + </includes> + </filter> + </filters> + </configuration> + </execution> + </executions> + </plugin> + </plugins> + </build> +</project> \ No newline at end of file diff --git a/maven-setup/nms-server-poms/v1_8_R3/pom.xml b/maven-setup/nms-server-poms/v1_8_R3/pom.xml new file mode 100644 index 00000000..72b2e0f9 --- /dev/null +++ b/maven-setup/nms-server-poms/v1_8_R3/pom.xml @@ -0,0 +1,48 @@ +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + <groupId>net.minecraft.server</groupId> + <artifactId>v1_8_R3</artifactId> + <version>1.8</version> + + <dependencies> + <dependency> + <groupId>org.spigotmc</groupId> + <artifactId>spigot</artifactId> + <version>1.8.8-R0.1-SNAPSHOT</version> + </dependency> + </dependencies> + + <build> + <plugins> + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-shade-plugin</artifactId> + <version>1.4</version> + <executions> + <execution> + <phase>package</phase> + <goals> + <goal>shade</goal> + </goals> + <configuration> + <artifactSet> + <includes> + <include>org.spigotmc:spigot</include> + </includes> + </artifactSet> + <filters> + <filter> + <artifact>org.spigotmc:spigot</artifact> + <includes> + <include>net/minecraft/server/**</include> + <include>org/bukkit/craftbukkit/v1_8_R3/**</include> + </includes> + </filter> + </filters> + </configuration> + </execution> + </executions> + </plugin> + </plugins> + </build> +</project> \ No newline at end of file diff --git a/maven-setup/nms-server-poms/v1_9_R1/pom.xml b/maven-setup/nms-server-poms/v1_9_R1/pom.xml new file mode 100644 index 00000000..97419ba4 --- /dev/null +++ b/maven-setup/nms-server-poms/v1_9_R1/pom.xml @@ -0,0 +1,48 @@ +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + <groupId>net.minecraft.server</groupId> + <artifactId>v1_9_R1</artifactId> + <version>1.9</version> + + <dependencies> + <dependency> + <groupId>org.spigotmc</groupId> + <artifactId>spigot</artifactId> + <version>1.9-R0.1-SNAPSHOT</version> + </dependency> + </dependencies> + + <build> + <plugins> + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-shade-plugin</artifactId> + <version>1.4</version> + <executions> + <execution> + <phase>package</phase> + <goals> + <goal>shade</goal> + </goals> + <configuration> + <artifactSet> + <includes> + <include>org.spigotmc:spigot</include> + </includes> + </artifactSet> + <filters> + <filter> + <artifact>org.spigotmc:spigot</artifact> + <includes> + <include>net/minecraft/server/**</include> + <include>org/bukkit/craftbukkit/v1_9_R1/**</include> + </includes> + </filter> + </filters> + </configuration> + </execution> + </executions> + </plugin> + </plugins> + </build> +</project> \ No newline at end of file diff --git a/maven-setup/nms-server-poms/v1_9_R2/pom.xml b/maven-setup/nms-server-poms/v1_9_R2/pom.xml new file mode 100644 index 00000000..f3bff99d --- /dev/null +++ b/maven-setup/nms-server-poms/v1_9_R2/pom.xml @@ -0,0 +1,48 @@ +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + <groupId>net.minecraft.server</groupId> + <artifactId>v1_9_R2</artifactId> + <version>1.9</version> + + <dependencies> + <dependency> + <groupId>org.spigotmc</groupId> + <artifactId>spigot</artifactId> + <version>1.9.4-R0.1-SNAPSHOT</version> + </dependency> + </dependencies> + + <build> + <plugins> + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-shade-plugin</artifactId> + <version>1.4</version> + <executions> + <execution> + <phase>package</phase> + <goals> + <goal>shade</goal> + </goals> + <configuration> + <artifactSet> + <includes> + <include>org.spigotmc:spigot</include> + </includes> + </artifactSet> + <filters> + <filter> + <artifact>org.spigotmc:spigot</artifact> + <includes> + <include>net/minecraft/server/**</include> + <include>org/bukkit/craftbukkit/v1_9_R2/**</include> + </includes> + </filter> + </filters> + </configuration> + </execution> + </executions> + </plugin> + </plugins> + </build> +</project> \ No newline at end of file diff --git a/planned.md b/planned.md new file mode 100644 index 00000000..32aecc51 --- /dev/null +++ b/planned.md @@ -0,0 +1,23 @@ +#### upcomming (1.14.10/1.15.0)... +* Dropping some deprecated methods +* Dropping support for Spigot 1.7 +* More JUnit Tests and refactorings +* Minigame tutorials (using/playing the existing games, creating your own game) +* Rework of auto-updater +* Rework of reflection use in Minigames-API +* Rework of metrics +* Migrate Jumper/Sudoku/Destroyer/ColorMatch/HorseRacingPlus to Minigames-API +* Add some kind of "load-balancing"/ server hopping (improve support for bungee) +* Add more sign options +* + +#### known issues... +* https://github.com/MysticCity/MinigamesAPI/issues/37 +* https://github.com/MysticCity/MinigamesAPI/issues/5 +* https://github.com/MysticCity/MinigamesAPI/issues/4 +* + +#### Game Requests +* Undersea battle (Uboot-Kampf) +* + diff --git a/pom.xml b/pom.xml index cb4380f1..3c0433f6 100644 --- a/pom.xml +++ b/pom.xml @@ -1,43 +1,113 @@ -<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> - <modelVersion>4.0.0</modelVersion> - <groupId>com.comze_instancelabs</groupId> - <artifactId>MinigamesLib-parent</artifactId> - <version>parent</version> - <packaging>pom</packaging> - <name>MinigamesLib</name> - <properties> - <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> - <instancedev.global.server>instancedev</instancedev.global.server> - </properties> - <description>Rich Minigames API and base of all of my new minigames.</description> - - <modules> - <module>API</module> - - </modules> - - <repositories> - <repository> - <id>bukkit-repo</id> - <url>http://repo.bukkit.org/content/groups/public</url> - </repository> - </repositories> - - <build> - <sourceDirectory>src</sourceDirectory> - <plugins> - <plugin> - <artifactId>maven-compiler-plugin</artifactId> - <version>3.1</version> - <configuration> - <fork>true</fork> - <!-- <executable>C:\Program Files\Java\jdk1.7.0_45\bin\javac.exe</executable> --> - <source>1.6</source> - <target>1.6</target> - </configuration> - </plugin> - </plugins> - </build> - +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + <groupId>com.github.MCE-Plugins</groupId> + <artifactId>MinigamesLib-parent</artifactId> + <version>1.14.18-SNAPSHOT</version> + <packaging>pom</packaging> + <name>MinigamesLib-parent</name> + <properties> + <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> + <maven.compiler.source>1.8</maven.compiler.source> + <maven.compiler.target>1.8</maven.compiler.target> + <java.version>1.8</java.version> + <powermock.version>1.7.1</powermock.version> + <junit.version>4.12</junit.version> + <minigames.releaseversion>1.14.18</minigames.releaseversion> + <minigames.timestamp>${maven.build.timestamp}</minigames.timestamp> + <spigot.version>1.12-R0.1-SNAPSHOT</spigot.version> + <maven.build.timestamp.format>yyyyMMdd.HHmmss</maven.build.timestamp.format> + </properties> + <description>Rich Minigames API and base of all of my new minigames.</description> + + <modules> + <module>API</module> + <module>Spigot-Test</module> + </modules> + + <repositories> + <repository> + <id>spigot-repo</id> + <url>https://hub.spigotmc.org/nexus/content/repositories/snapshots</url> + </repository> + <repository> + <id>mce-repos</id> + <url>http://nexus.xworlds.eu/nexus/content/groups/mce/</url> + </repository> + <repository> + <id>vault-repo</id> + <url>http://nexus.hc.to/content/repositories/pub_releases</url> + </repository> + </repositories> + + <dependencyManagement> + <dependencies> + <dependency> + <groupId>org.bukkit</groupId> + <artifactId>bukkit</artifactId> + <version>${spigot.version}</version> + <scope>provided</scope> + </dependency> + <dependency> + <groupId>org.spigotmc</groupId> + <artifactId>spigot</artifactId> + <version>${spigot.version}</version> + <scope>provided</scope> + </dependency> + <dependency> + <groupId>com.github.MCE-Plugins</groupId> + <artifactId>MinigamesLib</artifactId> + <version>1.14.18-SNAPSHOT</version> + <scope>provided</scope> + </dependency> + <dependency> + <groupId>net.milkbowl.vault</groupId> + <artifactId>Vault</artifactId> + <version>1.5.6</version> + <scope>provided</scope> + </dependency> + <dependency> + <groupId>com.shampaggon.crackshot</groupId> + <artifactId>Crackshot</artifactId> + <version>0.98.5</version> + <scope>provided</scope> + </dependency> + + <dependency> + <groupId>junit</groupId> + <artifactId>junit</artifactId> + <version>${junit.version}</version> + <scope>test</scope> + </dependency> + <dependency> + <groupId>org.powermock</groupId> + <artifactId>powermock-module-junit4</artifactId> + <version>${powermock.version}</version> + <scope>test</scope> + </dependency> + <dependency> + <groupId>org.powermock</groupId> + <artifactId>powermock-api-mockito</artifactId> + <version>${powermock.version}</version> + <scope>test</scope> + </dependency> + <dependency> + <groupId>com.github.MCE-Plugins</groupId> + <artifactId>MinigamesLib-Spigot-Test</artifactId> + <version>${project.version}</version> + <scope>test</scope> + </dependency> + </dependencies> + </dependencyManagement> + <distributionManagement> + <snapshotRepository> + <id>xworlds-snapshots</id> + <url>${deployUrlSnapshots}</url> + </snapshotRepository> + <repository> + <id>xworlds-releases</id> + <url>${deployUrlReleases}</url> + </repository> + </distributionManagement> + </project> \ No newline at end of file diff --git a/wiki/images/admin-arena-.step1.png b/wiki/images/admin-arena-.step1.png new file mode 100644 index 00000000..a8ceb2ea Binary files /dev/null and b/wiki/images/admin-arena-.step1.png differ diff --git a/wiki/images/admin-arena-.step2.png b/wiki/images/admin-arena-.step2.png new file mode 100644 index 00000000..77f5259a Binary files /dev/null and b/wiki/images/admin-arena-.step2.png differ diff --git a/wiki/images/admin-main-lobby-inside.png b/wiki/images/admin-main-lobby-inside.png new file mode 100644 index 00000000..c664a9a2 Binary files /dev/null and b/wiki/images/admin-main-lobby-inside.png differ diff --git a/wiki/images/admin-main-lobby-outside.png b/wiki/images/admin-main-lobby-outside.png new file mode 100644 index 00000000..8d6dd459 Binary files /dev/null and b/wiki/images/admin-main-lobby-outside.png differ diff --git a/wiki/images/admin-waiting-lobby-higherbounds.png b/wiki/images/admin-waiting-lobby-higherbounds.png new file mode 100644 index 00000000..b553992c Binary files /dev/null and b/wiki/images/admin-waiting-lobby-higherbounds.png differ diff --git a/wiki/images/admin-waiting-lobby-lowerbounds.png b/wiki/images/admin-waiting-lobby-lowerbounds.png new file mode 100644 index 00000000..64030566 Binary files /dev/null and b/wiki/images/admin-waiting-lobby-lowerbounds.png differ diff --git a/wiki/images/admin-waiting-lobby.png b/wiki/images/admin-waiting-lobby.png new file mode 100644 index 00000000..b3798c2b Binary files /dev/null and b/wiki/images/admin-waiting-lobby.png differ diff --git a/wiki/images/game-countdown.png b/wiki/images/game-countdown.png new file mode 100644 index 00000000..7cd6efc2 Binary files /dev/null and b/wiki/images/game-countdown.png differ diff --git a/wiki/images/join-signs.png b/wiki/images/join-signs.png new file mode 100644 index 00000000..7d5b968f Binary files /dev/null and b/wiki/images/join-signs.png differ diff --git a/wiki/images/main-lobby.png b/wiki/images/main-lobby.png new file mode 100644 index 00000000..113dd2d5 Binary files /dev/null and b/wiki/images/main-lobby.png differ diff --git a/wiki/images/playing-snake.png b/wiki/images/playing-snake.png new file mode 100644 index 00000000..cd39b19f Binary files /dev/null and b/wiki/images/playing-snake.png differ diff --git a/wiki/images/waiting-lobby.png b/wiki/images/waiting-lobby.png new file mode 100644 index 00000000..6ec041c5 Binary files /dev/null and b/wiki/images/waiting-lobby.png differ