mirror of
https://github.com/darksaid98/AlathranWars.git
synced 2026-12-01 14:38:55 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
704ca35826 | ||
|
|
6f0c303e62 |
No files matched your search
-435
@@ -1,435 +0,0 @@
|
||||
root = true
|
||||
|
||||
[*]
|
||||
charset = utf-8
|
||||
end_of_line = crlf
|
||||
indent_size = 4
|
||||
indent_style = space
|
||||
insert_final_newline = false
|
||||
max_line_length = 120
|
||||
tab_width = 4
|
||||
ij_continuation_indent_size = 4
|
||||
ij_formatter_off_tag = @formatter:off
|
||||
ij_formatter_on_tag = @formatter:on
|
||||
ij_formatter_tags_enabled = true
|
||||
ij_smart_tabs = false
|
||||
ij_visual_guides =
|
||||
ij_wrap_on_typing = false
|
||||
|
||||
[*.java]
|
||||
ij_continuation_indent_size = 4
|
||||
ij_java_align_consecutive_assignments = false
|
||||
ij_java_align_consecutive_variable_declarations = false
|
||||
ij_java_align_group_field_declarations = false
|
||||
ij_java_align_multiline_annotation_parameters = false
|
||||
ij_java_align_multiline_array_initializer_expression = false
|
||||
ij_java_align_multiline_assignment = false
|
||||
ij_java_align_multiline_binary_operation = false
|
||||
ij_java_align_multiline_chained_methods = false
|
||||
ij_java_align_multiline_deconstruction_list_components = true
|
||||
ij_java_align_multiline_extends_list = false
|
||||
ij_java_align_multiline_for = true
|
||||
ij_java_align_multiline_method_parentheses = false
|
||||
ij_java_align_multiline_parameters = true
|
||||
ij_java_align_multiline_parameters_in_calls = false
|
||||
ij_java_align_multiline_parenthesized_expression = false
|
||||
ij_java_align_multiline_records = true
|
||||
ij_java_align_multiline_resources = true
|
||||
ij_java_align_multiline_ternary_operation = false
|
||||
ij_java_align_multiline_text_blocks = false
|
||||
ij_java_align_multiline_throws_list = false
|
||||
ij_java_align_subsequent_simple_methods = false
|
||||
ij_java_align_throws_keyword = false
|
||||
ij_java_align_types_in_multi_catch = true
|
||||
ij_java_annotation_parameter_wrap = off
|
||||
ij_java_array_initializer_new_line_after_left_brace = false
|
||||
ij_java_array_initializer_right_brace_on_new_line = false
|
||||
ij_java_array_initializer_wrap = off
|
||||
ij_java_assert_statement_colon_on_next_line = false
|
||||
ij_java_assert_statement_wrap = off
|
||||
ij_java_assignment_wrap = off
|
||||
ij_java_binary_operation_sign_on_next_line = false
|
||||
ij_java_binary_operation_wrap = off
|
||||
ij_java_blank_lines_after_anonymous_class_header = 0
|
||||
ij_java_blank_lines_after_class_header = 0
|
||||
ij_java_blank_lines_after_imports = 1
|
||||
ij_java_blank_lines_after_package = 1
|
||||
ij_java_blank_lines_around_class = 1
|
||||
ij_java_blank_lines_around_field = 0
|
||||
ij_java_blank_lines_around_field_in_interface = 0
|
||||
ij_java_blank_lines_around_initializer = 1
|
||||
ij_java_blank_lines_around_method = 1
|
||||
ij_java_blank_lines_around_method_in_interface = 1
|
||||
ij_java_blank_lines_before_class_end = 0
|
||||
ij_java_blank_lines_before_imports = 1
|
||||
ij_java_blank_lines_before_method_body = 0
|
||||
ij_java_blank_lines_before_package = 0
|
||||
ij_java_block_brace_style = end_of_line
|
||||
ij_java_block_comment_add_space = false
|
||||
ij_java_block_comment_at_first_column = true
|
||||
ij_java_builder_methods =
|
||||
ij_java_call_parameters_new_line_after_left_paren = false
|
||||
ij_java_call_parameters_right_paren_on_new_line = false
|
||||
ij_java_call_parameters_wrap = off
|
||||
ij_java_case_statement_on_separate_line = true
|
||||
ij_java_catch_on_new_line = false
|
||||
ij_java_class_annotation_wrap = split_into_lines
|
||||
ij_java_class_brace_style = end_of_line
|
||||
ij_java_class_count_to_use_import_on_demand = 5
|
||||
ij_java_class_names_in_javadoc = 1
|
||||
ij_java_deconstruction_list_wrap = normal
|
||||
ij_java_do_not_indent_top_level_class_members = false
|
||||
ij_java_do_not_wrap_after_single_annotation = false
|
||||
ij_java_do_not_wrap_after_single_annotation_in_parameter = false
|
||||
ij_java_do_while_brace_force = never
|
||||
ij_java_doc_add_blank_line_after_description = true
|
||||
ij_java_doc_add_blank_line_after_param_comments = false
|
||||
ij_java_doc_add_blank_line_after_return = false
|
||||
ij_java_doc_add_p_tag_on_empty_lines = true
|
||||
ij_java_doc_align_exception_comments = true
|
||||
ij_java_doc_align_param_comments = true
|
||||
ij_java_doc_do_not_wrap_if_one_line = false
|
||||
ij_java_doc_enable_formatting = true
|
||||
ij_java_doc_enable_leading_asterisks = true
|
||||
ij_java_doc_indent_on_continuation = false
|
||||
ij_java_doc_keep_empty_lines = true
|
||||
ij_java_doc_keep_empty_parameter_tag = true
|
||||
ij_java_doc_keep_empty_return_tag = true
|
||||
ij_java_doc_keep_empty_throws_tag = true
|
||||
ij_java_doc_keep_invalid_tags = true
|
||||
ij_java_doc_param_description_on_new_line = false
|
||||
ij_java_doc_preserve_line_breaks = false
|
||||
ij_java_doc_use_throws_not_exception_tag = true
|
||||
ij_java_else_on_new_line = false
|
||||
ij_java_enum_constants_wrap = off
|
||||
ij_java_extends_keyword_wrap = off
|
||||
ij_java_extends_list_wrap = off
|
||||
ij_java_field_annotation_wrap = split_into_lines
|
||||
ij_java_field_name_prefix =
|
||||
ij_java_field_name_suffix =
|
||||
ij_java_finally_on_new_line = false
|
||||
ij_java_for_brace_force = never
|
||||
ij_java_for_statement_new_line_after_left_paren = false
|
||||
ij_java_for_statement_right_paren_on_new_line = false
|
||||
ij_java_for_statement_wrap = off
|
||||
ij_java_generate_final_locals = false
|
||||
ij_java_generate_final_parameters = false
|
||||
ij_java_if_brace_force = never
|
||||
ij_java_imports_layout = *, |, javax.**, java.**, |, $*
|
||||
ij_java_indent_case_from_switch = true
|
||||
ij_java_insert_inner_class_imports = false
|
||||
ij_java_insert_override_annotation = true
|
||||
ij_java_keep_blank_lines_before_right_brace = 2
|
||||
ij_java_keep_blank_lines_between_package_declaration_and_header = 2
|
||||
ij_java_keep_blank_lines_in_code = 2
|
||||
ij_java_keep_blank_lines_in_declarations = 2
|
||||
ij_java_keep_builder_methods_indents = false
|
||||
ij_java_keep_control_statement_in_one_line = true
|
||||
ij_java_keep_first_column_comment = true
|
||||
ij_java_keep_indents_on_empty_lines = false
|
||||
ij_java_keep_line_breaks = true
|
||||
ij_java_keep_multiple_expressions_in_one_line = false
|
||||
ij_java_keep_simple_blocks_in_one_line = false
|
||||
ij_java_keep_simple_classes_in_one_line = false
|
||||
ij_java_keep_simple_lambdas_in_one_line = false
|
||||
ij_java_keep_simple_methods_in_one_line = false
|
||||
ij_java_label_indent_absolute = false
|
||||
ij_java_label_indent_size = 0
|
||||
ij_java_lambda_brace_style = end_of_line
|
||||
ij_java_layout_static_imports_separately = true
|
||||
ij_java_line_comment_add_space = false
|
||||
ij_java_line_comment_add_space_on_reformat = false
|
||||
ij_java_line_comment_at_first_column = true
|
||||
ij_java_local_variable_name_prefix =
|
||||
ij_java_local_variable_name_suffix =
|
||||
ij_java_method_annotation_wrap = split_into_lines
|
||||
ij_java_method_brace_style = end_of_line
|
||||
ij_java_method_call_chain_wrap = off
|
||||
ij_java_method_parameters_new_line_after_left_paren = false
|
||||
ij_java_method_parameters_right_paren_on_new_line = false
|
||||
ij_java_method_parameters_wrap = off
|
||||
ij_java_modifier_list_wrap = false
|
||||
ij_java_multi_catch_types_wrap = normal
|
||||
ij_java_names_count_to_use_import_on_demand = 3
|
||||
ij_java_new_line_after_lparen_in_annotation = false
|
||||
ij_java_new_line_after_lparen_in_deconstruction_pattern = true
|
||||
ij_java_new_line_after_lparen_in_record_header = false
|
||||
ij_java_packages_to_use_import_on_demand = java.awt.*, javax.swing.*
|
||||
ij_java_parameter_annotation_wrap = off
|
||||
ij_java_parameter_name_prefix =
|
||||
ij_java_parameter_name_suffix =
|
||||
ij_java_parentheses_expression_new_line_after_left_paren = false
|
||||
ij_java_parentheses_expression_right_paren_on_new_line = false
|
||||
ij_java_place_assignment_sign_on_next_line = false
|
||||
ij_java_prefer_longer_names = true
|
||||
ij_java_prefer_parameters_wrap = false
|
||||
ij_java_record_components_wrap = normal
|
||||
ij_java_repeat_annotations =
|
||||
ij_java_repeat_synchronized = true
|
||||
ij_java_replace_instanceof_and_cast = false
|
||||
ij_java_replace_null_check = true
|
||||
ij_java_replace_sum_lambda_with_method_ref = true
|
||||
ij_java_resource_list_new_line_after_left_paren = false
|
||||
ij_java_resource_list_right_paren_on_new_line = false
|
||||
ij_java_resource_list_wrap = off
|
||||
ij_java_rparen_on_new_line_in_annotation = false
|
||||
ij_java_rparen_on_new_line_in_deconstruction_pattern = true
|
||||
ij_java_rparen_on_new_line_in_record_header = false
|
||||
ij_java_space_after_closing_angle_bracket_in_type_argument = false
|
||||
ij_java_space_after_colon = true
|
||||
ij_java_space_after_comma = true
|
||||
ij_java_space_after_comma_in_type_arguments = true
|
||||
ij_java_space_after_for_semicolon = true
|
||||
ij_java_space_after_quest = true
|
||||
ij_java_space_after_type_cast = true
|
||||
ij_java_space_before_annotation_array_initializer_left_brace = false
|
||||
ij_java_space_before_annotation_parameter_list = false
|
||||
ij_java_space_before_array_initializer_left_brace = false
|
||||
ij_java_space_before_catch_keyword = true
|
||||
ij_java_space_before_catch_left_brace = true
|
||||
ij_java_space_before_catch_parentheses = true
|
||||
ij_java_space_before_class_left_brace = true
|
||||
ij_java_space_before_colon = true
|
||||
ij_java_space_before_colon_in_foreach = true
|
||||
ij_java_space_before_comma = false
|
||||
ij_java_space_before_deconstruction_list = false
|
||||
ij_java_space_before_do_left_brace = true
|
||||
ij_java_space_before_else_keyword = true
|
||||
ij_java_space_before_else_left_brace = true
|
||||
ij_java_space_before_finally_keyword = true
|
||||
ij_java_space_before_finally_left_brace = true
|
||||
ij_java_space_before_for_left_brace = true
|
||||
ij_java_space_before_for_parentheses = true
|
||||
ij_java_space_before_for_semicolon = false
|
||||
ij_java_space_before_if_left_brace = true
|
||||
ij_java_space_before_if_parentheses = true
|
||||
ij_java_space_before_method_call_parentheses = false
|
||||
ij_java_space_before_method_left_brace = true
|
||||
ij_java_space_before_method_parentheses = false
|
||||
ij_java_space_before_opening_angle_bracket_in_type_parameter = false
|
||||
ij_java_space_before_quest = true
|
||||
ij_java_space_before_switch_left_brace = true
|
||||
ij_java_space_before_switch_parentheses = true
|
||||
ij_java_space_before_synchronized_left_brace = true
|
||||
ij_java_space_before_synchronized_parentheses = true
|
||||
ij_java_space_before_try_left_brace = true
|
||||
ij_java_space_before_try_parentheses = true
|
||||
ij_java_space_before_type_parameter_list = false
|
||||
ij_java_space_before_while_keyword = true
|
||||
ij_java_space_before_while_left_brace = true
|
||||
ij_java_space_before_while_parentheses = true
|
||||
ij_java_space_inside_one_line_enum_braces = false
|
||||
ij_java_space_within_empty_array_initializer_braces = false
|
||||
ij_java_space_within_empty_method_call_parentheses = false
|
||||
ij_java_space_within_empty_method_parentheses = false
|
||||
ij_java_spaces_around_additive_operators = true
|
||||
ij_java_spaces_around_annotation_eq = true
|
||||
ij_java_spaces_around_assignment_operators = true
|
||||
ij_java_spaces_around_bitwise_operators = true
|
||||
ij_java_spaces_around_equality_operators = true
|
||||
ij_java_spaces_around_lambda_arrow = true
|
||||
ij_java_spaces_around_logical_operators = true
|
||||
ij_java_spaces_around_method_ref_dbl_colon = false
|
||||
ij_java_spaces_around_multiplicative_operators = true
|
||||
ij_java_spaces_around_relational_operators = true
|
||||
ij_java_spaces_around_shift_operators = true
|
||||
ij_java_spaces_around_type_bounds_in_type_parameters = true
|
||||
ij_java_spaces_around_unary_operator = false
|
||||
ij_java_spaces_within_angle_brackets = false
|
||||
ij_java_spaces_within_annotation_parentheses = false
|
||||
ij_java_spaces_within_array_initializer_braces = false
|
||||
ij_java_spaces_within_braces = false
|
||||
ij_java_spaces_within_brackets = false
|
||||
ij_java_spaces_within_cast_parentheses = false
|
||||
ij_java_spaces_within_catch_parentheses = false
|
||||
ij_java_spaces_within_deconstruction_list = false
|
||||
ij_java_spaces_within_for_parentheses = false
|
||||
ij_java_spaces_within_if_parentheses = false
|
||||
ij_java_spaces_within_method_call_parentheses = false
|
||||
ij_java_spaces_within_method_parentheses = false
|
||||
ij_java_spaces_within_parentheses = false
|
||||
ij_java_spaces_within_record_header = false
|
||||
ij_java_spaces_within_switch_parentheses = false
|
||||
ij_java_spaces_within_synchronized_parentheses = false
|
||||
ij_java_spaces_within_try_parentheses = false
|
||||
ij_java_spaces_within_while_parentheses = false
|
||||
ij_java_special_else_if_treatment = true
|
||||
ij_java_static_field_name_prefix =
|
||||
ij_java_static_field_name_suffix =
|
||||
ij_java_subclass_name_prefix =
|
||||
ij_java_subclass_name_suffix = Impl
|
||||
ij_java_ternary_operation_signs_on_next_line = false
|
||||
ij_java_ternary_operation_wrap = off
|
||||
ij_java_test_name_prefix =
|
||||
ij_java_test_name_suffix = Test
|
||||
ij_java_throws_keyword_wrap = off
|
||||
ij_java_throws_list_wrap = off
|
||||
ij_java_use_external_annotations = false
|
||||
ij_java_use_fq_class_names = false
|
||||
ij_java_use_relative_indents = false
|
||||
ij_java_use_single_class_imports = true
|
||||
ij_java_variable_annotation_wrap = off
|
||||
ij_java_visibility = public
|
||||
ij_java_while_brace_force = never
|
||||
ij_java_while_on_new_line = false
|
||||
ij_java_wrap_comments = false
|
||||
ij_java_wrap_first_method_in_call_chain = false
|
||||
ij_java_wrap_long_lines = false
|
||||
|
||||
[{*.ant,*.fxml,*.jhm,*.jnlp,*.jrxml,*.jspx,*.pom,*.rng,*.tagx,*.tld,*.wsdl,*.xml,*.xsd,*.xsl,*.xslt,*.xul}]
|
||||
ij_continuation_indent_size = 4
|
||||
ij_xml_align_attributes = true
|
||||
ij_xml_align_text = false
|
||||
ij_xml_attribute_wrap = normal
|
||||
ij_xml_block_comment_add_space = false
|
||||
ij_xml_block_comment_at_first_column = true
|
||||
ij_xml_keep_blank_lines = 2
|
||||
ij_xml_keep_indents_on_empty_lines = false
|
||||
ij_xml_keep_line_breaks = true
|
||||
ij_xml_keep_line_breaks_in_text = true
|
||||
ij_xml_keep_whitespaces = false
|
||||
ij_xml_keep_whitespaces_around_cdata = preserve
|
||||
ij_xml_keep_whitespaces_inside_cdata = false
|
||||
ij_xml_line_comment_at_first_column = true
|
||||
ij_xml_space_after_tag_name = false
|
||||
ij_xml_space_around_equals_in_attribute = false
|
||||
ij_xml_space_inside_empty_tag = false
|
||||
ij_xml_text_wrap = normal
|
||||
|
||||
[{*.gradle.kts,*.kt,*.kts,*.main.kts,*.space.kts}]
|
||||
ij_continuation_indent_size = 4
|
||||
ij_kotlin_align_in_columns_case_branch = false
|
||||
ij_kotlin_align_multiline_binary_operation = false
|
||||
ij_kotlin_align_multiline_extends_list = false
|
||||
ij_kotlin_align_multiline_method_parentheses = false
|
||||
ij_kotlin_align_multiline_parameters = true
|
||||
ij_kotlin_align_multiline_parameters_in_calls = false
|
||||
ij_kotlin_allow_trailing_comma = false
|
||||
ij_kotlin_allow_trailing_comma_on_call_site = false
|
||||
ij_kotlin_assignment_wrap = off
|
||||
ij_kotlin_blank_lines_after_class_header = 0
|
||||
ij_kotlin_blank_lines_around_block_when_branches = 0
|
||||
ij_kotlin_blank_lines_before_declaration_with_comment_or_annotation_on_separate_line = 1
|
||||
ij_kotlin_block_comment_add_space = false
|
||||
ij_kotlin_block_comment_at_first_column = true
|
||||
ij_kotlin_call_parameters_new_line_after_left_paren = false
|
||||
ij_kotlin_call_parameters_right_paren_on_new_line = false
|
||||
ij_kotlin_call_parameters_wrap = off
|
||||
ij_kotlin_catch_on_new_line = false
|
||||
ij_kotlin_class_annotation_wrap = split_into_lines
|
||||
ij_kotlin_continuation_indent_for_chained_calls = true
|
||||
ij_kotlin_continuation_indent_for_expression_bodies = true
|
||||
ij_kotlin_continuation_indent_in_argument_lists = true
|
||||
ij_kotlin_continuation_indent_in_elvis = true
|
||||
ij_kotlin_continuation_indent_in_if_conditions = true
|
||||
ij_kotlin_continuation_indent_in_parameter_lists = true
|
||||
ij_kotlin_continuation_indent_in_supertype_lists = true
|
||||
ij_kotlin_else_on_new_line = false
|
||||
ij_kotlin_enum_constants_wrap = off
|
||||
ij_kotlin_extends_list_wrap = off
|
||||
ij_kotlin_field_annotation_wrap = split_into_lines
|
||||
ij_kotlin_finally_on_new_line = false
|
||||
ij_kotlin_if_rparen_on_new_line = false
|
||||
ij_kotlin_import_nested_classes = false
|
||||
ij_kotlin_imports_layout = *, java.**, javax.**, kotlin.**, ^
|
||||
ij_kotlin_insert_whitespaces_in_simple_one_line_method = true
|
||||
ij_kotlin_keep_blank_lines_before_right_brace = 2
|
||||
ij_kotlin_keep_blank_lines_in_code = 2
|
||||
ij_kotlin_keep_blank_lines_in_declarations = 2
|
||||
ij_kotlin_keep_first_column_comment = true
|
||||
ij_kotlin_keep_indents_on_empty_lines = false
|
||||
ij_kotlin_keep_line_breaks = true
|
||||
ij_kotlin_lbrace_on_next_line = false
|
||||
ij_kotlin_line_break_after_multiline_when_entry = true
|
||||
ij_kotlin_line_comment_add_space = false
|
||||
ij_kotlin_line_comment_add_space_on_reformat = false
|
||||
ij_kotlin_line_comment_at_first_column = true
|
||||
ij_kotlin_method_annotation_wrap = split_into_lines
|
||||
ij_kotlin_method_call_chain_wrap = off
|
||||
ij_kotlin_method_parameters_new_line_after_left_paren = false
|
||||
ij_kotlin_method_parameters_right_paren_on_new_line = false
|
||||
ij_kotlin_method_parameters_wrap = off
|
||||
ij_kotlin_name_count_to_use_star_import = 5
|
||||
ij_kotlin_name_count_to_use_star_import_for_members = 3
|
||||
ij_kotlin_packages_to_use_import_on_demand = java.util.*, kotlinx.android.synthetic.**, io.ktor.**
|
||||
ij_kotlin_parameter_annotation_wrap = off
|
||||
ij_kotlin_space_after_comma = true
|
||||
ij_kotlin_space_after_extend_colon = true
|
||||
ij_kotlin_space_after_type_colon = true
|
||||
ij_kotlin_space_before_catch_parentheses = true
|
||||
ij_kotlin_space_before_comma = false
|
||||
ij_kotlin_space_before_extend_colon = true
|
||||
ij_kotlin_space_before_for_parentheses = true
|
||||
ij_kotlin_space_before_if_parentheses = true
|
||||
ij_kotlin_space_before_lambda_arrow = true
|
||||
ij_kotlin_space_before_type_colon = false
|
||||
ij_kotlin_space_before_when_parentheses = true
|
||||
ij_kotlin_space_before_while_parentheses = true
|
||||
ij_kotlin_spaces_around_additive_operators = true
|
||||
ij_kotlin_spaces_around_assignment_operators = true
|
||||
ij_kotlin_spaces_around_equality_operators = true
|
||||
ij_kotlin_spaces_around_function_type_arrow = true
|
||||
ij_kotlin_spaces_around_logical_operators = true
|
||||
ij_kotlin_spaces_around_multiplicative_operators = true
|
||||
ij_kotlin_spaces_around_range = false
|
||||
ij_kotlin_spaces_around_relational_operators = true
|
||||
ij_kotlin_spaces_around_unary_operator = false
|
||||
ij_kotlin_spaces_around_when_arrow = true
|
||||
ij_kotlin_variable_annotation_wrap = off
|
||||
ij_kotlin_while_on_new_line = false
|
||||
ij_kotlin_wrap_elvis_expressions = 1
|
||||
ij_kotlin_wrap_expression_body_functions = 0
|
||||
ij_kotlin_wrap_first_method_in_call_chain = false
|
||||
|
||||
[{*.har,*.json,*.png.mcmeta,mcmod.info,pack.mcmeta}]
|
||||
indent_size = 2
|
||||
ij_continuation_indent_size = 4
|
||||
ij_json_array_wrapping = split_into_lines
|
||||
ij_json_keep_blank_lines_in_code = 0
|
||||
ij_json_keep_indents_on_empty_lines = false
|
||||
ij_json_keep_line_breaks = true
|
||||
ij_json_keep_trailing_comma = false
|
||||
ij_json_object_wrapping = split_into_lines
|
||||
ij_json_property_alignment = do_not_align
|
||||
ij_json_space_after_colon = true
|
||||
ij_json_space_after_comma = true
|
||||
ij_json_space_before_colon = false
|
||||
ij_json_space_before_comma = false
|
||||
ij_json_spaces_within_braces = false
|
||||
ij_json_spaces_within_brackets = false
|
||||
ij_json_wrap_long_lines = false
|
||||
|
||||
[{*.markdown,*.md,*.md }]
|
||||
ij_markdown_force_one_space_after_blockquote_symbol = true
|
||||
ij_markdown_force_one_space_after_header_symbol = true
|
||||
ij_markdown_force_one_space_after_list_bullet = true
|
||||
ij_markdown_force_one_space_between_words = true
|
||||
ij_markdown_format_tables = true
|
||||
ij_markdown_insert_quote_arrows_on_wrap = true
|
||||
ij_markdown_keep_indents_on_empty_lines = false
|
||||
ij_markdown_keep_line_breaks_inside_text_blocks = true
|
||||
ij_markdown_max_lines_around_block_elements = 1
|
||||
ij_markdown_max_lines_around_header = 1
|
||||
ij_markdown_max_lines_between_paragraphs = 1
|
||||
ij_markdown_min_lines_around_block_elements = 1
|
||||
ij_markdown_min_lines_around_header = 1
|
||||
ij_markdown_min_lines_between_paragraphs = 1
|
||||
ij_markdown_wrap_text_if_long = true
|
||||
ij_markdown_wrap_text_inside_blockquotes = true
|
||||
|
||||
[{*.toml,Cargo.lock,Cargo.toml.orig,Gopkg.lock,Pipfile,poetry.lock}]
|
||||
ij_continuation_indent_size = 4
|
||||
ij_toml_keep_indents_on_empty_lines = false
|
||||
|
||||
[{*.yaml,*.yml}]
|
||||
indent_size = 2
|
||||
ij_yaml_align_values_properties = do_not_align
|
||||
ij_yaml_autoinsert_sequence_marker = true
|
||||
ij_yaml_block_mapping_on_new_line = false
|
||||
ij_yaml_indent_sequence_value = true
|
||||
ij_yaml_keep_indents_on_empty_lines = false
|
||||
ij_yaml_keep_line_breaks = true
|
||||
ij_yaml_sequence_on_new_line = false
|
||||
ij_yaml_space_before_colon = false
|
||||
ij_yaml_spaces_within_braces = true
|
||||
ij_yaml_spaces_within_brackets = true
|
||||
@@ -1,2 +0,0 @@
|
||||
# Set the default behavior, in case people don't have core.autocrlf set.
|
||||
* text=auto
|
||||
@@ -1 +0,0 @@
|
||||
* @darksaid98
|
||||
@@ -1,2 +0,0 @@
|
||||
github: darksaid98
|
||||
patreon: alathramc
|
||||
@@ -1,34 +0,0 @@
|
||||
---
|
||||
name: Bug report
|
||||
about: Create a report to help us improve
|
||||
title: ''
|
||||
labels: bug
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
**Describe the bug**
|
||||
A clear and concise description of what the bug is.
|
||||
|
||||
**To Reproduce**
|
||||
Steps to reproduce the behavior:
|
||||
1. Go to '...'
|
||||
2. Click on '....'
|
||||
3. Scroll down to '....'
|
||||
4. See error
|
||||
|
||||
**Expected behavior**
|
||||
A clear and concise description of what you expected to happen.
|
||||
|
||||
**Screenshots**
|
||||
If applicable, add screenshots to help explain your problem.
|
||||
|
||||
**Version information:**
|
||||
- Vanilla version: [e.g. 1.20.2]
|
||||
- Server version: [e.g. paper-123]
|
||||
- Plugin version [e.g. 0.1.0]
|
||||
|
||||
**Additional context**
|
||||
```
|
||||
Add any other context about the problem here including console errors.
|
||||
```
|
||||
@@ -1,20 +0,0 @@
|
||||
---
|
||||
name: Feature request
|
||||
about: Suggest an idea for this project
|
||||
title: ''
|
||||
labels: enhancement
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
**Is your feature request related to a problem? Please describe.**
|
||||
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
|
||||
|
||||
**Describe the solution you'd like**
|
||||
A clear and concise description of what you want to happen.
|
||||
|
||||
**Describe alternatives you've considered**
|
||||
A clear and concise description of any alternative solutions or features you've considered.
|
||||
|
||||
**Additional context**
|
||||
Add any other context or screenshots about the feature request here.
|
||||
@@ -1,15 +0,0 @@
|
||||
name: 'Setup Gradle'
|
||||
description: 'Grant execute permissions and validate Gradle wrapper'
|
||||
|
||||
runs:
|
||||
using: 'composite'
|
||||
steps:
|
||||
- name: Grant execute permissions for Gradle wrapper
|
||||
run: chmod +x gradlew
|
||||
shell: bash
|
||||
|
||||
- name: Validate Gradle Wrapper Authenticity
|
||||
uses: gradle/wrapper-validation-action@v1
|
||||
|
||||
- name: Setup Gradle and Caching
|
||||
uses: gradle/gradle-build-action@v2
|
||||
@@ -1,17 +0,0 @@
|
||||
name: 'Setup JDK'
|
||||
description: 'Set up JDK'
|
||||
|
||||
inputs:
|
||||
java-version:
|
||||
description: 'Java version'
|
||||
required: true
|
||||
default: '17'
|
||||
|
||||
runs:
|
||||
using: 'composite'
|
||||
steps:
|
||||
- name: Setup JDK
|
||||
uses: actions/setup-java@v3
|
||||
with:
|
||||
java-version: ${{ inputs.java-version }}
|
||||
distribution: 'temurin'
|
||||
@@ -1,26 +0,0 @@
|
||||
version: 2
|
||||
updates:
|
||||
- package-ecosystem: "github-actions"
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: "weekly"
|
||||
commit-message:
|
||||
prefix: "ci:"
|
||||
target-branch: "main"
|
||||
- package-ecosystem: "gradle"
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: "weekly"
|
||||
commit-message:
|
||||
prefix: "build:"
|
||||
target-branch: "main"
|
||||
groups:
|
||||
"org.flywaydb":
|
||||
patterns:
|
||||
- "org.flywaydb*"
|
||||
"org.jooq":
|
||||
patterns:
|
||||
- "org.jooq*"
|
||||
"net.kyori":
|
||||
patterns:
|
||||
- "net.kyori*"
|
||||
@@ -1,86 +1,28 @@
|
||||
name: Build & Upload Release jar with Gradle
|
||||
name: Build with Maven
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- 'main'
|
||||
- 'master'
|
||||
tags:
|
||||
- '*'
|
||||
pull_request:
|
||||
branches:
|
||||
- 'main'
|
||||
- 'master'
|
||||
schedule:
|
||||
- cron: '0 0 * * 6'
|
||||
workflow_dispatch:
|
||||
|
||||
concurrency:
|
||||
group: ${{ format('{0}-{1}', github.job, github.ref) }}
|
||||
cancel-in-progress: true
|
||||
release:
|
||||
types: [ published ]
|
||||
branches: [ main ]
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ${{ matrix.os }}
|
||||
strategy:
|
||||
matrix:
|
||||
os: [ ubuntu-latest ]
|
||||
java: [ 17 ]
|
||||
if: github.ref_type != 'tag'
|
||||
steps:
|
||||
- name: Checkout Repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Gradle
|
||||
uses: ./.github/actions/gradle
|
||||
|
||||
- name: Setup JDK
|
||||
uses: ./.github/actions/jdk
|
||||
with:
|
||||
java-version: ${{ matrix.java }}
|
||||
|
||||
- name: Build with Gradle
|
||||
run: ./gradlew clean build --info
|
||||
|
||||
- name: Upload build results
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: ${{ matrix.os }} Java ${{ matrix.java }} Snapshot
|
||||
path: ${{ github.workspace }}/build/libs/
|
||||
|
||||
release:
|
||||
publish_build_files:
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
matrix:
|
||||
java: [ 17 ]
|
||||
if: github.ref_type == 'tag'
|
||||
|
||||
steps:
|
||||
- name: Checkout Repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Gradle
|
||||
uses: ./.github/actions/gradle
|
||||
|
||||
- name: Setup JDK
|
||||
uses: ./.github/actions/jdk
|
||||
- uses: actions/checkout@v2
|
||||
- name: Setup Java
|
||||
uses: actions/setup-java@v3
|
||||
with:
|
||||
java-version: ${{ matrix.java }}
|
||||
distribution: temurin
|
||||
java-version: 17
|
||||
|
||||
- name: Set Release Environment Variable
|
||||
if: github.ref_type == 'tag'
|
||||
run: |
|
||||
echo "CUSTOM_VERSION=${{ github.ref_name }}" >> $GITHUB_ENV
|
||||
- name: Build with Maven
|
||||
run: mvn -B package --file pom.xml
|
||||
|
||||
- name: Build with Gradle
|
||||
run: ./gradlew clean build -PcustomVersion=${{ env.CUSTOM_VERSION }}
|
||||
|
||||
- name: Create Release
|
||||
uses: softprops/action-gh-release@v2
|
||||
id: release
|
||||
- name: Upload Release Assets
|
||||
uses: AButler/[email protected]
|
||||
with:
|
||||
name: ${{ format('Release {0}', github.ref_name) }}
|
||||
files: ${{ github.workspace }}/build/libs/*
|
||||
prerelease: ${{ contains(github.ref_name, '-RC-') }}
|
||||
generate_release_notes: true
|
||||
fail_on_unmatched_files: true
|
||||
draft: false
|
||||
files: 'target/AlathraWar-*.jar'
|
||||
repo-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
release-tag: ${{ github.event.release.tag_name }}
|
||||
@@ -1,26 +0,0 @@
|
||||
name: 'Close Stale Issues & PRs'
|
||||
on:
|
||||
schedule:
|
||||
- cron: '30 1 * * *'
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
issues: write
|
||||
pull-requests: write
|
||||
|
||||
jobs:
|
||||
stale:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/stale@v10
|
||||
with:
|
||||
stale-issue-message: 'This issue has been automatically marked as stale because it has been open for 60 days with no activity.'
|
||||
stale-pr-message: 'This PR has been automatically marked as stale because it has been open for 60 days with no activity.'
|
||||
close-issue-message: 'This issue was closed because it has been stalled for -1 days with no activity.'
|
||||
close-pr-message: 'This PR was closed because it has been stalled for -1 days with no activity.'
|
||||
days-before-issue-stale: 60
|
||||
days-before-pr-stale: 60
|
||||
days-before-issue-close: -1
|
||||
days-before-pr-close: -1
|
||||
stale-issue-label: 'stale'
|
||||
stale-pr-label: 'stale'
|
||||
+6
-84
@@ -1,86 +1,8 @@
|
||||
##############################
|
||||
## Java
|
||||
##############################
|
||||
.mtj.tmp/
|
||||
*.class
|
||||
*.jar
|
||||
*.war
|
||||
*.ear
|
||||
*.nar
|
||||
hs_err_pid*
|
||||
replay_pid*
|
||||
|
||||
##############################
|
||||
## Maven
|
||||
##############################
|
||||
target/
|
||||
pom.xml.tag
|
||||
pom.xml.releaseBackup
|
||||
pom.xml.versionsBackup
|
||||
pom.xml.next
|
||||
pom.xml.bak
|
||||
release.properties
|
||||
dependency-reduced-pom.xml
|
||||
buildNumber.properties
|
||||
.mvn/timing.properties
|
||||
.mvn/wrapper/maven-wrapper.jar
|
||||
|
||||
##############################
|
||||
## Gradle
|
||||
##############################
|
||||
bin/
|
||||
build/
|
||||
.gradle
|
||||
.gradletasknamecache
|
||||
gradle-app.setting
|
||||
!gradle-wrapper.jar
|
||||
|
||||
##############################
|
||||
## IntelliJ
|
||||
##############################
|
||||
out/
|
||||
.idea/
|
||||
.idea_modules/
|
||||
*.iml
|
||||
*.ipr
|
||||
*.iws
|
||||
|
||||
##############################
|
||||
## Eclipse
|
||||
##############################
|
||||
.settings/
|
||||
bin/
|
||||
tmp/
|
||||
.metadata
|
||||
/target/
|
||||
/.settings/
|
||||
/bin/
|
||||
.classpath
|
||||
.project
|
||||
*.tmp
|
||||
*.bak
|
||||
*.swp
|
||||
*~.nib
|
||||
local.properties
|
||||
.loadpath
|
||||
.factorypath
|
||||
|
||||
##############################
|
||||
## NetBeans
|
||||
##############################
|
||||
nbproject/private/
|
||||
build/
|
||||
nbbuild/
|
||||
dist/
|
||||
nbdist/
|
||||
nbactions.xml
|
||||
nb-configuration.xml
|
||||
|
||||
##############################
|
||||
## Visual Studio Code
|
||||
##############################
|
||||
.vscode/
|
||||
.code-workspace
|
||||
|
||||
##############################
|
||||
## OS X
|
||||
##############################
|
||||
.DS_Store
|
||||
/run/
|
||||
/.idea/
|
||||
/.vscode/
|
||||
AlathraWar.iml
|
||||
@@ -1,132 +0,0 @@
|
||||
# Contributor Covenant Code of Conduct
|
||||
|
||||
## Our Pledge
|
||||
|
||||
We as members, contributors, and leaders pledge to make participation in our
|
||||
community a harassment-free experience for everyone, regardless of age, body
|
||||
size, visible or invisible disability, ethnicity, sex characteristics, gender
|
||||
identity and expression, level of experience, education, socio-economic status,
|
||||
nationality, personal appearance, race, caste, color, religion, or sexual
|
||||
identity and orientation.
|
||||
|
||||
We pledge to act and interact in ways that contribute to an open, welcoming,
|
||||
diverse, inclusive, and healthy community.
|
||||
|
||||
## Our Standards
|
||||
|
||||
Examples of behavior that contributes to a positive environment for our
|
||||
community include:
|
||||
|
||||
* Demonstrating empathy and kindness toward other people
|
||||
* Being respectful of differing opinions, viewpoints, and experiences
|
||||
* Giving and gracefully accepting constructive feedback
|
||||
* Accepting responsibility and apologizing to those affected by our mistakes,
|
||||
and learning from the experience
|
||||
* Focusing on what is best not just for us as individuals, but for the overall
|
||||
community
|
||||
|
||||
Examples of unacceptable behavior include:
|
||||
|
||||
* The use of sexualized language or imagery, and sexual attention or advances of
|
||||
any kind
|
||||
* Trolling, insulting or derogatory comments, and personal or political attacks
|
||||
* Public or private harassment
|
||||
* Publishing others' private information, such as a physical or email address,
|
||||
without their explicit permission
|
||||
* Other conduct which could reasonably be considered inappropriate in a
|
||||
professional setting
|
||||
|
||||
## Enforcement Responsibilities
|
||||
|
||||
Community leaders are responsible for clarifying and enforcing our standards of
|
||||
acceptable behavior and will take appropriate and fair corrective action in
|
||||
response to any behavior that they deem inappropriate, threatening, offensive,
|
||||
or harmful.
|
||||
|
||||
Community leaders have the right and responsibility to remove, edit, or reject
|
||||
comments, commits, code, wiki edits, issues, and other contributions that are
|
||||
not aligned to this Code of Conduct, and will communicate reasons for moderation
|
||||
decisions when appropriate.
|
||||
|
||||
## Scope
|
||||
|
||||
This Code of Conduct applies within all community spaces, and also applies when
|
||||
an individual is officially representing the community in public spaces.
|
||||
Examples of representing our community include using an official e-mail address,
|
||||
posting via an official social media account, or acting as an appointed
|
||||
representative at an online or offline event.
|
||||
|
||||
## Enforcement
|
||||
|
||||
Instances of abusive, harassing, or otherwise unacceptable behavior may be
|
||||
reported to the community leaders responsible for enforcement at
|
||||
darksaid9889@gmail.com.
|
||||
All complaints will be reviewed and investigated promptly and fairly.
|
||||
|
||||
All community leaders are obligated to respect the privacy and security of the
|
||||
reporter of any incident.
|
||||
|
||||
## Enforcement Guidelines
|
||||
|
||||
Community leaders will follow these Community Impact Guidelines in determining
|
||||
the consequences for any action they deem in violation of this Code of Conduct:
|
||||
|
||||
### 1. Correction
|
||||
|
||||
**Community Impact**: Use of inappropriate language or other behavior deemed
|
||||
unprofessional or unwelcome in the community.
|
||||
|
||||
**Consequence**: A private, written warning from community leaders, providing
|
||||
clarity around the nature of the violation and an explanation of why the
|
||||
behavior was inappropriate. A public apology may be requested.
|
||||
|
||||
### 2. Warning
|
||||
|
||||
**Community Impact**: A violation through a single incident or series of
|
||||
actions.
|
||||
|
||||
**Consequence**: A warning with consequences for continued behavior. No
|
||||
interaction with the people involved, including unsolicited interaction with
|
||||
those enforcing the Code of Conduct, for a specified period of time. This
|
||||
includes avoiding interactions in community spaces as well as external channels
|
||||
like social media. Violating these terms may lead to a temporary or permanent
|
||||
ban.
|
||||
|
||||
### 3. Temporary Ban
|
||||
|
||||
**Community Impact**: A serious violation of community standards, including
|
||||
sustained inappropriate behavior.
|
||||
|
||||
**Consequence**: A temporary ban from any sort of interaction or public
|
||||
communication with the community for a specified period of time. No public or
|
||||
private interaction with the people involved, including unsolicited interaction
|
||||
with those enforcing the Code of Conduct, is allowed during this period.
|
||||
Violating these terms may lead to a permanent ban.
|
||||
|
||||
### 4. Permanent Ban
|
||||
|
||||
**Community Impact**: Demonstrating a pattern of violation of community
|
||||
standards, including sustained inappropriate behavior, harassment of an
|
||||
individual, or aggression toward or disparagement of classes of individuals.
|
||||
|
||||
**Consequence**: A permanent ban from any sort of public interaction within the
|
||||
community.
|
||||
|
||||
## Attribution
|
||||
|
||||
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
|
||||
version 2.1, available at
|
||||
[https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
|
||||
|
||||
Community Impact Guidelines were inspired by
|
||||
[Mozilla's code of conduct enforcement ladder][Mozilla CoC].
|
||||
|
||||
For answers to common questions about this code of conduct, see the FAQ at
|
||||
[https://www.contributor-covenant.org/faq][FAQ]. Translations are available at
|
||||
[https://www.contributor-covenant.org/translations][translations].
|
||||
|
||||
[homepage]: https://www.contributor-covenant.org
|
||||
[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
|
||||
[Mozilla CoC]: https://github.com/mozilla/diversity
|
||||
[FAQ]: https://www.contributor-covenant.org/faq
|
||||
[translations]: https://www.contributor-covenant.org/translations
|
||||
@@ -1,44 +0,0 @@
|
||||
## Pull Requests
|
||||
|
||||
We use the [GitHub flow](https://guides.github.com/introduction/flow/) for contributions.
|
||||
|
||||
1. Fork the repository.
|
||||
2. Create a new branch for each feature, fix or improvement.
|
||||
3. Send a pull request from each feature branch to the **main** branch.
|
||||
|
||||
It is very important to separate new features or improvements into separate feature branches, and to send a pull request for each branch. This allow us to review and pull in new features or improvements individually.
|
||||
|
||||
## Specifications
|
||||
|
||||
### Commit Messages
|
||||
|
||||
All commit messages should adhere to the [Conventional Commits specification](https://conventionalcommits.org/).
|
||||
|
||||
#### Commit Types
|
||||
|
||||
- API relevant changes
|
||||
* `feat` Commits, that adds a new feature
|
||||
* `fix` Commits, that fixes a bug/issue
|
||||
- `refactor` Commits, that rewrite/restructure your code, however does not change any API behaviour
|
||||
* `perf` Commits are special `refactor` commits, that improve performance
|
||||
- `style` Commits, that do not affect the meaning (white-space, formatting, missing semi-colons, etc)
|
||||
- `test` Commits, that add or correct existing tests
|
||||
- `docs` Commits, that affect documentation only
|
||||
- Tooling relevant changes
|
||||
* `build` Commits, that affect build components like build tool, dependencies, project version, ...
|
||||
* `ci` Commits, that affect CI configuration files and scripts
|
||||
- `revert` Commits, that revert previous commits
|
||||
- `chore` Miscellaneous commits without production code change, e.g. modifying `.gitignore`
|
||||
|
||||
### Versioning
|
||||
|
||||
Our project adheres to the [Semantic Versioning 2.0.0 specification](https://semver.org/) for versioning.
|
||||
|
||||
### Style Guide
|
||||
|
||||
Large refactors breaking the style defined in the `.editorconfig` file are frowned upon.
|
||||
When contributing ensure your code follows existing conventions and styling. (*Any issues that arise will be noted in your pull request.*)
|
||||
|
||||
## Licensing
|
||||
|
||||
You must agree that your patch will be licensed under the main license found in this repository, and if we change the license, we will assume that you agreed with the change unless you object to the changes in time.
|
||||
@@ -1,29 +1,17 @@
|
||||
# AlathranWars Version: 1.3.1
|
||||
|
||||
## A unique Towny oldWar system for the AlathraMC server
|
||||
# AlathraWar Version: 1.3.1
|
||||
## A unique Towny war system for the AlathraMC server
|
||||
|
||||
### Dependencies: Vault, Towny, SiegeWar, TAB
|
||||
|
||||
### Commands
|
||||
|
||||
+ /oldWar - oldWar commands
|
||||
+ /oldSiege - oldSiege commands
|
||||
+ /war - war commands
|
||||
+ /siege - siege commands
|
||||
|
||||
## Siege Point system
|
||||
|
||||
+1 point for every second the homeblock is controlled. Defenders retain control if no one is occupying the homeblock. A
|
||||
contested homeblock yeilds no points. The timer fires every 10 seconds so it's really +10 points every 10 seconds. Kills
|
||||
are worth 20 points each.
|
||||
+1 point for every second the homeblock is controlled. Defenders retain control if no one is occupying the homeblock. A contested homeblock yeilds no points. The timer fires every 10 seconds so it's really +10 points every 10 seconds. Kills are worth 20 points each.
|
||||
|
||||
## Siege Time Limit
|
||||
|
||||
Sieges last 90 minutes. After this time is up the side with the most points wins. A tie goes to the defenders.
|
||||
|
||||
## Siege Cost
|
||||
|
||||
The attackers must put down $20,000 to start a oldSiege. If they win they get this $20,000 back as well as 1/4th the bank
|
||||
of the town OR $20,000, whichever is higher. If the defenders win they sieze the $20,000 initially put down on the oldSiege
|
||||
by the attackers
|
||||
|
||||
## Credits
|
||||
* **SkytAzul** - _The end crystal beam code which can be found [here](https://github.com/SkytAsul/GuardianBeam/). Original license applies._
|
||||
The attackers must put down $20,000 to start a siege. If they win they get this $20,000 back as well as 1/4th the bank of the town OR $20,000, whichever is higher. If the defenders win they sieze the $20,000 initially put down on the siege by the attackers
|
||||
@@ -1,289 +0,0 @@
|
||||
import org.jooq.meta.jaxb.Logging
|
||||
import java.time.Instant
|
||||
|
||||
plugins {
|
||||
`java-library`
|
||||
|
||||
id("io.github.goooler.shadow") version "8.1.8" // Shades and relocates dependencies, See https://imperceptiblethoughts.com/shadow/introduction/
|
||||
id("xyz.jpenilla.run-paper") version "2.3.1" // Adds runServer and runMojangMappedServer tasks for testing
|
||||
id("net.minecrell.plugin-yml.bukkit") version "0.6.0" // Automatic plugin.yml generation
|
||||
id("io.papermc.paperweight.userdev") version "1.7.1" // Used to develop internal plugins using Mojang mappings, See https://github.com/PaperMC/paperweight
|
||||
id("org.flywaydb.flyway") version "10.17.3" // Database migrations
|
||||
id("org.jooq.jooq-codegen-gradle") version "3.19.11"
|
||||
|
||||
eclipse
|
||||
idea
|
||||
}
|
||||
|
||||
val mainPackage = "${project.group}.${project.name.lowercase()}"
|
||||
applyCustomVersion()
|
||||
|
||||
java {
|
||||
toolchain.languageVersion.set(JavaLanguageVersion.of(17)) // Configure the java toolchain. This allows gradle to auto-provision JDK 21 on systems that only have JDK 8 installed for example.
|
||||
withJavadocJar() // Enable javadoc jar generation
|
||||
withSourcesJar() // Enable sources jar generation
|
||||
}
|
||||
|
||||
repositories {
|
||||
mavenCentral()
|
||||
|
||||
maven("https://repo.papermc.io/repository/maven-public/")
|
||||
maven("https://mvn-repo.arim.space/lesser-gpl3/")
|
||||
|
||||
maven("https://maven.athyrium.eu/releases")
|
||||
|
||||
maven("https://repo.glaremasters.me/repository/towny/") {
|
||||
content { includeGroup("com.palmergames.bukkit.towny") }
|
||||
}
|
||||
|
||||
maven("https://jitpack.io/") {
|
||||
content {
|
||||
includeGroup("com.github.MilkBowl") // VaultAPI
|
||||
includeGroup("com.palmergames.bukkit.towny")
|
||||
includeGroup("com.github.Gecolay.GSit")
|
||||
}
|
||||
}
|
||||
|
||||
maven("https://repo.kryptonmc.org/releases") {
|
||||
content { includeGroup("me.neznamy") }
|
||||
}
|
||||
|
||||
maven("https://repo.codemc.org/repository/maven-public/") {
|
||||
content { includeGroup("dev.jorel") }
|
||||
}
|
||||
|
||||
maven("https://repo.extendedclip.com/content/repositories/placeholderapi/") {
|
||||
content { includeGroup("me.clip") }
|
||||
}
|
||||
|
||||
maven("https://repo.dmulloy2.net/repository/public/") // ProtocolLib
|
||||
}
|
||||
|
||||
dependencies {
|
||||
compileOnly("org.jetbrains:annotations:24.1.0")
|
||||
annotationProcessor("org.jetbrains:annotations:24.1.0")
|
||||
|
||||
paperweight.paperDevBundle("1.20.1-R0.1-SNAPSHOT")
|
||||
implementation("space.arim.morepaperlib:morepaperlib:0.4.4")
|
||||
|
||||
// API
|
||||
implementation("com.github.milkdrinkers:crate-api:2.0.0")
|
||||
implementation("com.github.milkdrinkers:crate-yaml:2.0.0")
|
||||
implementation("com.github.milkdrinkers:colorparser:2.0.3") {
|
||||
exclude("net.kyori")
|
||||
}
|
||||
implementation("dev.jorel:commandapi-bukkit-shade:9.3.0")
|
||||
|
||||
// Plugin Dependencies
|
||||
implementation("org.bstats:bstats-bukkit:3.0.3")
|
||||
compileOnly("com.github.MilkBowl:VaultAPI:1.7.1")
|
||||
compileOnly("com.comphenix.protocol:ProtocolLib:5.3.0-SNAPSHOT")
|
||||
compileOnly("me.clip:placeholderapi:2.11.6") {
|
||||
exclude("me.clip.placeholderapi.libs", "kyori")
|
||||
}
|
||||
compileOnly("com.palmergames.bukkit.towny:towny:0.100.2.6") {
|
||||
exclude("com.palmergames.adventure")
|
||||
}
|
||||
compileOnly("me.neznamy:tab-api:4.0.2")
|
||||
compileOnly(files("lib/Graves-4.9.jar"))
|
||||
compileOnly("com.github.Gecolay.GSit:core:1.9.0")
|
||||
compileOnly(files("lib/HeadsPlus-7.0.14.jar"))
|
||||
compileOnly(files("lib/Skulls.jar"))
|
||||
|
||||
// Database Dependencies (Core)
|
||||
implementation("com.zaxxer:HikariCP:5.1.0")
|
||||
library("org.flywaydb:flyway-core:10.17.3")
|
||||
library("org.flywaydb:flyway-mysql:10.17.3")
|
||||
library("org.jooq:jooq:3.19.11")
|
||||
jooqCodegen("com.h2database:h2:2.3.232")
|
||||
|
||||
// Database Dependencies (JDBC Drivers)
|
||||
library("com.h2database:h2:2.3.232")
|
||||
library("org.xerial:sqlite-jdbc:3.46.1.0")
|
||||
library("com.mysql:mysql-connector-j:9.0.0")
|
||||
library("org.mariadb.jdbc:mariadb-java-client:3.4.1")
|
||||
|
||||
// Testing (Core)
|
||||
testImplementation("org.jetbrains:annotations:24.1.0")
|
||||
testImplementation(platform("org.junit:junit-bom:5.11.0"))
|
||||
testImplementation("org.junit.jupiter:junit-jupiter")
|
||||
testRuntimeOnly("org.junit.platform:junit-platform-launcher")
|
||||
testRuntimeOnly("org.slf4j:slf4j-simple:2.1.0-alpha1")
|
||||
testImplementation(platform("org.testcontainers:testcontainers-bom:1.20.1"))
|
||||
testImplementation("org.testcontainers:junit-jupiter")
|
||||
testImplementation("org.testcontainers:mysql")
|
||||
testImplementation("org.testcontainers:mariadb")
|
||||
|
||||
// Testing (Database Dependencies)
|
||||
testImplementation("com.zaxxer:HikariCP:5.1.0")
|
||||
testImplementation("org.flywaydb:flyway-core:10.17.3")
|
||||
testImplementation("org.flywaydb:flyway-mysql:10.17.3")
|
||||
testImplementation("org.jooq:jooq:3.19.11")
|
||||
|
||||
// Testing (JDBC Drivers)
|
||||
testImplementation("com.h2database:h2:2.3.232")
|
||||
testImplementation("org.xerial:sqlite-jdbc:3.46.1.0")
|
||||
testImplementation("com.mysql:mysql-connector-j:9.0.0")
|
||||
testImplementation("org.mariadb.jdbc:mariadb-java-client:3.4.1")
|
||||
}
|
||||
|
||||
tasks {
|
||||
assemble {
|
||||
dependsOn(reobfJar)
|
||||
}
|
||||
|
||||
build {
|
||||
dependsOn(shadowJar)
|
||||
}
|
||||
|
||||
jooqCodegen {
|
||||
dependsOn(flywayMigrate)
|
||||
}
|
||||
|
||||
compileJava {
|
||||
options.encoding = Charsets.UTF_8.name() // We want UTF-8 for everything
|
||||
|
||||
// Set the release flag. This configures what version bytecode the compiler will emit, as well as what JDK APIs are usable.
|
||||
// See https://openjdk.java.net/jeps/247 for more information.
|
||||
options.release.set(17)
|
||||
options.compilerArgs.addAll(arrayListOf("-Xlint:all", "-Xlint:-processing", "-Xdiags:verbose"))
|
||||
|
||||
dependsOn(jooqCodegen) // Generate jOOQ sources before compilation
|
||||
}
|
||||
|
||||
javadoc {
|
||||
isFailOnError = false
|
||||
exclude("**/database/schema/**") // Exclude generated jOOQ sources from javadocs
|
||||
val options = options as StandardJavadocDocletOptions
|
||||
options.encoding = Charsets.UTF_8.name()
|
||||
options.overview = "src/main/javadoc/overview.html"
|
||||
options.windowTitle = "${rootProject.name} Javadoc"
|
||||
options.tags("apiNote:a:API Note:", "implNote:a:Implementation Note:", "implSpec:a:Implementation Requirements:")
|
||||
options.addStringOption("Xdoclint:none", "-quiet")
|
||||
options.use()
|
||||
}
|
||||
|
||||
processResources {
|
||||
filteringCharset = Charsets.UTF_8.name() // We want UTF-8 for everything
|
||||
}
|
||||
|
||||
shadowJar {
|
||||
archiveBaseName.set(project.name)
|
||||
archiveClassifier.set("")
|
||||
|
||||
// Shadow classes
|
||||
fun reloc(originPkg: String, targetPkg: String) = relocate(originPkg, "${mainPackage}.lib.${targetPkg}")
|
||||
|
||||
reloc("space.arim.morepaperlib", "morepaperlib")
|
||||
reloc("com.github.milkdrinkers.crate", "crate")
|
||||
reloc("com.github.milkdrinkers.colorparser", "colorparser")
|
||||
reloc("dev.jorel.commandapi", "commandapi")
|
||||
reloc("com.zaxxer.hikari", "hikaricp")
|
||||
reloc("org.bstats", "bstats")
|
||||
|
||||
mergeServiceFiles {
|
||||
setPath("META-INF/services/org.flywaydb.core.extensibility.Plugin") // Fix Flyway overriding its own files
|
||||
}
|
||||
|
||||
minimize()
|
||||
}
|
||||
|
||||
test {
|
||||
useJUnitPlatform()
|
||||
failFast = false
|
||||
}
|
||||
|
||||
runServer {
|
||||
// Configure the Minecraft version for our task.
|
||||
minecraftVersion("1.20.1")
|
||||
|
||||
// IntelliJ IDEA debugger setup: https://docs.papermc.io/paper/dev/debugging#using-a-remote-debugger
|
||||
jvmArgs("-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:5005", "-DPaper.IgnoreJavaVersion=true", "-Dcom.mojang.eula.agree=true", "-DIReallyKnowWhatIAmDoingISwear", "-Dpaper.playerconnection.keepalive=6000")
|
||||
systemProperty("terminal.jline", false)
|
||||
systemProperty("terminal.ansi", true)
|
||||
|
||||
// Automatically install dependencies
|
||||
downloadPlugins {
|
||||
github("MilkBowl", "Vault", "1.7.3", "Vault.jar")
|
||||
url("https://download.luckperms.net/1521/bukkit/loader/LuckPerms-Bukkit-5.4.108.jar")
|
||||
modrinth("tab-was-taken", "4.1.2")
|
||||
github("PlaceholderAPI", "PlaceholderAPI", "2.11.4", "PlaceholderAPI-2.11.4.jar")
|
||||
url("https://ci.dmulloy2.net/job/ProtocolLib/lastSuccessfulBuild/artifact/build/libs/ProtocolLib.jar")
|
||||
// url("https://www.spigotmc.org/resources/skulls-the-ultimate-head-database.90098/download?version=520217/Skulls.jar")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
tasks.named<Jar>("sourcesJar") { // Required for sources jar generation with jOOQ
|
||||
dependsOn(tasks.jooqCodegen)
|
||||
duplicatesStrategy = DuplicatesStrategy.INCLUDE
|
||||
}
|
||||
|
||||
bukkit { // Options: https://github.com/Minecrell/plugin-yml#bukkit
|
||||
// Plugin main class (required)
|
||||
main = "${mainPackage}.${project.name}"
|
||||
|
||||
// Plugin Information
|
||||
name = project.name
|
||||
prefix = project.name
|
||||
version = "${project.version}"
|
||||
description = "${project.description}"
|
||||
authors = listOf("darksaid98", "ShermansWorld", "NinjaMandalorian", "AubriTheHuman")
|
||||
contributors = listOf()
|
||||
apiVersion = "1.20"
|
||||
|
||||
// Misc properties
|
||||
load = net.minecrell.pluginyml.bukkit.BukkitPluginDescription.PluginLoadOrder.POSTWORLD // STARTUP or POSTWORLD
|
||||
depend = listOf("Vault", "ProtocolLib", "Towny")
|
||||
softDepend = listOf("PlaceholderAPI", "TAB", "Skulls", "HeadsPlus")
|
||||
}
|
||||
|
||||
flyway {
|
||||
url = "jdbc:h2:${project.layout.buildDirectory.get()}/generated/flyway/db;AUTO_SERVER=TRUE;MODE=MYSQL;CASE_INSENSITIVE_IDENTIFIERS=TRUE;IGNORECASE=TRUE"
|
||||
user = "sa"
|
||||
password = ""
|
||||
schemas = listOf("PUBLIC").toTypedArray()
|
||||
placeholders = mapOf( // Substitute placeholders for flyway
|
||||
"tablePrefix" to "",
|
||||
)
|
||||
validateMigrationNaming = true
|
||||
baselineOnMigrate = true
|
||||
cleanDisabled = false
|
||||
locations = arrayOf(
|
||||
"filesystem:src/main/resources/db/migration",
|
||||
"classpath:db/migration"
|
||||
)
|
||||
}
|
||||
|
||||
jooq {
|
||||
configuration {
|
||||
logging = Logging.ERROR
|
||||
jdbc {
|
||||
driver = "org.h2.Driver"
|
||||
url = flyway.url
|
||||
user = flyway.user
|
||||
password = flyway.password
|
||||
}
|
||||
generator {
|
||||
database {
|
||||
name = "org.jooq.meta.h2.H2Database"
|
||||
includes = ".*"
|
||||
excludes = "(flyway_schema_history)|(?i:information_schema\\..*)|(?i:system_lobs\\..*)" // Exclude database specific files
|
||||
inputSchema = "PUBLIC"
|
||||
schemaVersionProvider = "SELECT :schema_name || '_' || MAX(\"version\") FROM \"flyway_schema_history\"" // Grab version from Flyway
|
||||
}
|
||||
target {
|
||||
packageName = "${mainPackage}.database.schema"
|
||||
withClean(true)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun applyCustomVersion() {
|
||||
// Apply custom version arg or append snapshot version
|
||||
val ver = properties["altVer"]?.toString() ?: "${rootProject.version}-SNAPSHOT-${Instant.now().epochSecond}"
|
||||
|
||||
// Strip prefixed "v" from version tag
|
||||
rootProject.version = (if (ver.first().equals('v', true)) ver.substring(1) else ver.uppercase()).uppercase()
|
||||
}
|
||||
@@ -1,3 +0,0 @@
|
||||
files:
|
||||
- source: /src/main/resources/translations/en-US.yml
|
||||
translation: /src/main/resources/translations/%locale%.yml
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,321 +0,0 @@
|
||||
package com.github.alathra.AlathranWars.commands;
|
||||
|
||||
import com.github.alathra.AlathranWars.conflict.Side;
|
||||
import com.github.alathra.AlathranWars.conflict.War;
|
||||
import com.github.alathra.AlathranWars.conflict.battle.siege.Siege;
|
||||
import com.github.alathra.AlathranWars.enums.BattleTeam;
|
||||
import com.github.alathra.AlathranWars.holder.WarManager;
|
||||
import com.github.alathra.AlathranWars.utility.UtilsChat;
|
||||
import com.github.milkdrinkers.colorparser.ColorParser;
|
||||
import com.palmergames.bukkit.towny.TownyAPI;
|
||||
import com.palmergames.bukkit.towny.object.Town;
|
||||
import dev.jorel.commandapi.CommandAPIBukkit;
|
||||
import dev.jorel.commandapi.CommandAPICommand;
|
||||
import dev.jorel.commandapi.arguments.BooleanArgument;
|
||||
import dev.jorel.commandapi.arguments.PlayerArgument;
|
||||
import dev.jorel.commandapi.exceptions.WrapperCommandSyntaxException;
|
||||
import dev.jorel.commandapi.executors.CommandArguments;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.OfflinePlayer;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
public class SiegeCommand {
|
||||
public SiegeCommand() {
|
||||
new CommandAPICommand("siege")
|
||||
.withSubcommands(
|
||||
commandStart(),
|
||||
commandStop(),
|
||||
commandAbandon(),
|
||||
commandList(),
|
||||
commandHelp()
|
||||
)
|
||||
.executesPlayer((sender, args) -> {
|
||||
if (args.count() == 0)
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "Invalid Arguments. /siege help").build());
|
||||
})
|
||||
.register();
|
||||
}
|
||||
|
||||
public static CommandAPICommand commandStart() {
|
||||
return new CommandAPICommand("start")
|
||||
.withPermission("AlathranWars.admin")
|
||||
.withArguments(
|
||||
CommandUtil.warWarArgument(
|
||||
"war",
|
||||
false,
|
||||
false,
|
||||
""
|
||||
),
|
||||
CommandUtil.customSiegeAttackableTownArgument(
|
||||
"town",
|
||||
"war",
|
||||
false,
|
||||
true
|
||||
),
|
||||
new PlayerArgument("leader")
|
||||
.setOptional(true)
|
||||
.withPermission("AlathranWars.admin"),
|
||||
new BooleanArgument("minutemen")
|
||||
.setOptional(true)
|
||||
.withPermission("AlathranWars.admin")
|
||||
)
|
||||
.executesPlayer((Player p, CommandArguments args) -> siegeStart(p, args, false));
|
||||
}
|
||||
|
||||
public static CommandAPICommand commandStop() {
|
||||
return new CommandAPICommand("stop")
|
||||
.withPermission("AlathranWars.admin")
|
||||
.withArguments(
|
||||
CommandUtil.warWarArgument(
|
||||
"war",
|
||||
false,
|
||||
false,
|
||||
""
|
||||
),
|
||||
CommandUtil.customSiegeAttackableTownArgument(
|
||||
"town",
|
||||
"war",
|
||||
false,
|
||||
false
|
||||
)
|
||||
)
|
||||
.executesPlayer(SiegeCommand::siegeStop);
|
||||
}
|
||||
|
||||
public static CommandAPICommand commandAbandon() {
|
||||
return new CommandAPICommand("abandon")
|
||||
.withArguments(
|
||||
CommandUtil.warWarArgument(
|
||||
"war",
|
||||
false,
|
||||
false,
|
||||
""
|
||||
),
|
||||
CommandUtil.customSiegeAttackableTownArgument(
|
||||
"town",
|
||||
"war",
|
||||
false,
|
||||
false
|
||||
)
|
||||
)
|
||||
.executesPlayer(SiegeCommand::siegeAbandon);
|
||||
}
|
||||
|
||||
public static CommandAPICommand commandList() {
|
||||
return new CommandAPICommand("list")
|
||||
.executesPlayer(SiegeCommand::siegeList);
|
||||
}
|
||||
|
||||
public static CommandAPICommand commandHelp() {
|
||||
return new CommandAPICommand("help")
|
||||
.executesPlayer(SiegeCommand::siegeHelp);
|
||||
}
|
||||
|
||||
|
||||
protected static void siegeStart(@NotNull Player sender, @NotNull CommandArguments args, boolean admin) throws WrapperCommandSyntaxException {
|
||||
if (!(args.get("war") instanceof final @NotNull War war))
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>You need to specify a war.").build());
|
||||
|
||||
if (!(args.get("town") instanceof final @NotNull Town town))
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>You need to specify a town.").build());
|
||||
|
||||
//if this is admin mode use the forth arg instad of sender.
|
||||
//if player is null after this then force end
|
||||
final @NotNull Player siegeOwner = (Player) args.getOptional("leader").orElse(sender);
|
||||
|
||||
if (siegeOwner == null)
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("You need to pick a valid leader.").build());
|
||||
|
||||
// Player participance check
|
||||
@Nullable Town leaderTown = TownyAPI.getInstance().getResident(siegeOwner).getTownOrNull();
|
||||
@Nullable Side side = war.getTownSide(leaderTown);
|
||||
|
||||
// TODO DEBUG PRINT
|
||||
// Main.warLogger.log("Leader Town: " + leaderTown.getName());
|
||||
// Main.warLogger.log("Siege Owner: " + siegeOwner.getName());
|
||||
// sender.sendMessage("Leader Town: " + leaderTown.getName());
|
||||
// sender.sendMessage("Siege Owner: " + siegeOwner.getName());
|
||||
|
||||
// TODO DEBUG PRINT
|
||||
/*for (String t : war.getSide1Towns()) {
|
||||
Main.warLogger.log("Side1 town: " + t);
|
||||
sender.sendMessage("Side1 town: " + t);
|
||||
}
|
||||
for (String t : war.getSide2Towns()) {
|
||||
Main.warLogger.log("Side2 town: " + t);
|
||||
sender.sendMessage("Side2 town: " + t);
|
||||
}*/
|
||||
|
||||
if (!war.isTownInWar(leaderTown)) {
|
||||
siegeOwner.sendMessage(ColorParser.of(UtilsChat.getPrefix() + "You are not in this war.").build());
|
||||
if (admin) sender.sendMessage(ColorParser.of(UtilsChat.getPrefix() + "You are not in this war.").build());
|
||||
return;
|
||||
} else if (side.isTownSurrendered(leaderTown)) {
|
||||
siegeOwner.sendMessage(ColorParser.of(UtilsChat.getPrefix() + "You are under occupation.").build());
|
||||
if (admin) sender.sendMessage(ColorParser.of(UtilsChat.getPrefix() + "You are under occupation.").build());
|
||||
return;
|
||||
}
|
||||
|
||||
//Minutemen countermeasures, 86400 * 4 time. 86400 seconds in a day, 4 days min playtime
|
||||
//Minuteman countermeasures
|
||||
/*int minuteman = CommandHelper.isPlayerMinuteman(siegeOwner.getName());
|
||||
boolean minuteManOverride = (boolean) args.getOptional("minutemen").orElse(false);
|
||||
|
||||
if (minuteManOverride) {
|
||||
sender.sendMessage(ChatColor.RED + "Warning! Ignoring Minuteman Countermeasure!");
|
||||
}
|
||||
|
||||
//override?
|
||||
if (!minuteManOverride) {
|
||||
if (minuteman != 0) {
|
||||
if (minuteman == 1) {
|
||||
//player has joined to recently
|
||||
if (admin)
|
||||
sender.sendMessage(ChatColor.RED + "You have joined the server too recently! You can only join a raid after " + Main.getInstance().getConfig().getInt("minimumPlayerAge") + " days from joining.");
|
||||
siegeOwner.sendMessage(ChatColor.RED + "You have joined the server too recently! You can only join a raid after " + Main.getInstance().getConfig().getInt("minimumPlayerAge") + " days from joining.");
|
||||
return;
|
||||
} else if (minuteman == 2) {
|
||||
//player has played too little
|
||||
if (admin)
|
||||
sender.sendMessage(ChatColor.RED + "You have not played enough! You can only join a raid after " + Main.getInstance().getConfig().getInt("minimumPlayTime") + " hours of play.");
|
||||
siegeOwner.sendMessage(ChatColor.RED + "You have not played enough! You can only join a raid after " + Main.getInstance().getConfig().getInt("minimumPlayTime") + " hours of play.");
|
||||
return;
|
||||
}
|
||||
}
|
||||
}*/
|
||||
|
||||
// Is being raided check
|
||||
/*for (OldRaid r : RaidData.getRaids()) {
|
||||
if (r.getRaidedTown().getName().equalsIgnoreCase(town.getName())) {
|
||||
siegeOwner.sendMessage(UtilsChat.getPrefix() + "That town is already currently being raided! Cannot siege at this time!");
|
||||
if (admin)
|
||||
sender.sendMessage(UtilsChat.getPrefix() + "That town is already currently being raided! Cannot siege at this time!");
|
||||
return;
|
||||
}
|
||||
}*/
|
||||
|
||||
// Attacking own side
|
||||
if (side.isTownOnSide(town)) {
|
||||
siegeOwner.sendMessage(ColorParser.of(UtilsChat.getPrefix() + "You cannot attack your own towns.").build());
|
||||
if (admin)
|
||||
sender.sendMessage(ColorParser.of(UtilsChat.getPrefix() + "You cannot attack your own towns.").build());
|
||||
return;
|
||||
}
|
||||
|
||||
@NotNull Siege siege = new Siege(war, town, siegeOwner);
|
||||
war.addSiege(siege);
|
||||
|
||||
Bukkit.broadcast(ColorParser.of(UtilsChat.getPrefix() + siege.getTown() + " has been put to siege by " + siege.getAttackerSide().getName() + "!").build());
|
||||
|
||||
if (admin)
|
||||
sender.sendMessage(ColorParser.of("<red>Forcefully started siege from the console.").build());
|
||||
|
||||
siege.start();
|
||||
// TODO Debug logs...
|
||||
// Main.warLogger.log("Attacked Town: " + town.getName().toLowerCase());
|
||||
// sender.sendMessage("Attacked Town: " + town.getName().toLowerCase());
|
||||
}
|
||||
|
||||
private static void siegeStop(@NotNull Player sender, @NotNull CommandArguments args) throws WrapperCommandSyntaxException {
|
||||
if (!(args.get("war") instanceof final @NotNull War war))
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>You need to specify a war.").build());
|
||||
|
||||
if (!(args.get("town") instanceof final @NotNull Town town))
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>You need to specify a town.").build());
|
||||
|
||||
final @NotNull Set<Siege> sieges = war.getSieges();
|
||||
if (sieges.isEmpty())
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>There are currently no sieges in progress!").build());
|
||||
|
||||
for (@NotNull Siege siege : sieges) {
|
||||
if (siege.getTown().getUUID().equals(town.getUUID()) && siege.getWar().equals(war)) {
|
||||
sender.sendMessage(ColorParser.of(UtilsChat.getPrefix() + "siege cancelled.").build());
|
||||
Bukkit.broadcast(ColorParser.of(UtilsChat.getPrefix() + "The siege at " + siege.getTown().getName() + " has been cancelled by an admin.").build());
|
||||
siege.stop();
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "A siege could not be found with this town name! Type /siege list to view current sieges").build());
|
||||
}
|
||||
|
||||
private static void siegeAbandon(Player p, @NotNull CommandArguments args) throws WrapperCommandSyntaxException {
|
||||
if (!(args.get("war") instanceof final @NotNull War war))
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>You need to specify a war.").build());
|
||||
|
||||
if (!(args.get("town") instanceof final @NotNull Town town))
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>You need to specify a town.").build());
|
||||
|
||||
@Nullable Siege siege = null;
|
||||
|
||||
for (@NotNull Siege siegeVar : war.getSieges()) {
|
||||
if (siegeVar.getTown().getUUID().equals(town.getUUID())) {
|
||||
siege = siegeVar;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (siege == null)
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "Invalid siege").build());
|
||||
|
||||
@NotNull OfflinePlayer oPlayer = siege.getSiegeLeader();
|
||||
if (oPlayer != p) {
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "You are not the leader of this siege.").build());
|
||||
}
|
||||
|
||||
Bukkit.broadcast(ColorParser.of(UtilsChat.getPrefix() + "The siege at " + siege.getTown().getName() + " has been abandoned.").build());
|
||||
// Main.warLogger.log(p.getName() + " abandoned the siege they started at " + siege.getTown().getName());
|
||||
siege.defendersWin();
|
||||
}
|
||||
|
||||
private static void siegeList(@NotNull Player sender, CommandArguments args) throws WrapperCommandSyntaxException {
|
||||
@NotNull Set<War> wars = WarManager.getInstance().getWars();
|
||||
|
||||
@NotNull Set<Siege> sieges = new HashSet<>();
|
||||
|
||||
for (@NotNull War war : wars) {
|
||||
sieges.addAll(war.getSieges());
|
||||
}
|
||||
|
||||
if (sieges.isEmpty())
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>There are currently no sieges in progress.").build());
|
||||
|
||||
sender.sendMessage(ColorParser.of(UtilsChat.getPrefix() + "Sieges currently in progress:").build());
|
||||
|
||||
for (@NotNull Siege siege : sieges) {
|
||||
@NotNull War war = siege.getWar();
|
||||
|
||||
final @NotNull String color = (siege.getSide1AreAttackers() && (war.getTownSide(siege.getTown()).getTeam().equals(BattleTeam.SIDE_1))) ? "<red>" : "<blue>";
|
||||
|
||||
sender.sendMessage(
|
||||
ColorParser.of(
|
||||
color + siege.getTown().getName() + " <gray>- Progress: <progress> - Time: <time>min"
|
||||
)
|
||||
.parseMinimessagePlaceholder("progress", "%.0f%%".formatted(siege.getSiegeProgressPercentage() * 100))
|
||||
.parseMinimessagePlaceholder("time", String.valueOf(Duration.between(Instant.now(), siege.getEndTime()).toMinutes()))
|
||||
.build()
|
||||
);
|
||||
// sender.sendMessage(ColorParser.of(war.getName() + " - " + color + siege.getTown().getName().toLowerCase()).build()); // TODO Fix info
|
||||
// sender.sendMessage(ColorParser.of(war.getSide1() + " - " + (siege.getSide1AreAttackers() ? siege.getAttackerPoints() : siege.getDefenderPoints())).build());
|
||||
// sender.sendMessage(ColorParser.of(war.getSide2() + " - " + (siege.getSide1AreAttackers() ? siege.getDefenderPoints() : siege.getAttackerPoints())).build());
|
||||
// sender.sendMessage(ColorParser.of("Time Left: " + (siege.getMaxSiegeTicks() - siege.getSiegeTicks()) / 1200 + " minutes").build());
|
||||
// sender.sendMessage(ColorParser.of("-=-=-=-=-=-=-=-=-=-=-=-").build());
|
||||
}
|
||||
}
|
||||
|
||||
private static void siegeHelp(@NotNull Player sender, CommandArguments args) {
|
||||
if (sender.hasPermission("AlathranWars.admin")) {
|
||||
sender.sendMessage(ColorParser.of(UtilsChat.getPrefix() + "/siege stop [war] [town]").build());
|
||||
}
|
||||
sender.sendMessage(ColorParser.of(UtilsChat.getPrefix() + "/siege start [war] [town]").build());
|
||||
sender.sendMessage(ColorParser.of(UtilsChat.getPrefix() + "/siege abandon [war] [town]").build());
|
||||
sender.sendMessage(ColorParser.of(UtilsChat.getPrefix() + "/siege list").build());
|
||||
}
|
||||
}
|
||||
@@ -1,404 +0,0 @@
|
||||
package com.github.alathra.AlathranWars.commands;
|
||||
|
||||
import com.github.alathra.AlathranWars.conflict.Side;
|
||||
import com.github.alathra.AlathranWars.conflict.War;
|
||||
import com.github.alathra.AlathranWars.conflict.battle.siege.Siege;
|
||||
import com.github.alathra.AlathranWars.enums.BattleSide;
|
||||
import com.github.alathra.AlathranWars.holder.WarManager;
|
||||
import com.github.alathra.AlathranWars.listeners.war.PlayerJoinListener;
|
||||
import com.github.alathra.AlathranWars.utility.UtilsChat;
|
||||
import com.github.milkdrinkers.colorparser.ColorParser;
|
||||
import com.palmergames.bukkit.towny.TownyAPI;
|
||||
import com.palmergames.bukkit.towny.object.Nation;
|
||||
import com.palmergames.bukkit.towny.object.Resident;
|
||||
import com.palmergames.bukkit.towny.object.Town;
|
||||
import dev.jorel.commandapi.CommandAPIBukkit;
|
||||
import dev.jorel.commandapi.CommandAPICommand;
|
||||
import dev.jorel.commandapi.arguments.ArgumentSuggestions;
|
||||
import dev.jorel.commandapi.arguments.GreedyStringArgument;
|
||||
import dev.jorel.commandapi.arguments.PlayerArgument;
|
||||
import dev.jorel.commandapi.exceptions.WrapperCommandSyntaxException;
|
||||
import dev.jorel.commandapi.executors.CommandArguments;
|
||||
import net.md_5.bungee.api.ChatColor;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
|
||||
public class WarCommand {
|
||||
public WarCommand() {
|
||||
new CommandAPICommand("war")
|
||||
.withSubcommands(
|
||||
commandCreate(),
|
||||
commandDelete(),
|
||||
commandJoin(),
|
||||
commandSurrender(),
|
||||
commandList(),
|
||||
// commandInfo(),
|
||||
commandHelp()
|
||||
)
|
||||
.executesPlayer((sender, args) -> {
|
||||
if (args.count() == 0)
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "Invalid Arguments. /war help").build());
|
||||
})
|
||||
.register();
|
||||
}
|
||||
|
||||
public static CommandAPICommand commandCreate() {
|
||||
return new CommandAPICommand("create")
|
||||
.withPermission("AlathranWars.admin")
|
||||
.withArguments(
|
||||
CommandUtil.customTownAndNationArgument("side1", "war", false),
|
||||
CommandUtil.customTownAndNationArgument("side2", "war", false),
|
||||
new GreedyStringArgument("warlabel")
|
||||
.replaceSuggestions(
|
||||
ArgumentSuggestions.stringCollection(info -> List.of(
|
||||
"Nations War of Conquest",
|
||||
"Nations War for Survival",
|
||||
"Nations War of Liberation"
|
||||
))
|
||||
)
|
||||
)
|
||||
.executesPlayer(WarCommand::warCreate);
|
||||
}
|
||||
|
||||
public static CommandAPICommand commandDelete() {
|
||||
return new CommandAPICommand("delete")
|
||||
.withPermission("AlathranWars.admin")
|
||||
.withArguments(
|
||||
CommandUtil.warWarArgument("war", false, false, "")
|
||||
)
|
||||
.executesPlayer(WarCommand::warDelete);
|
||||
}
|
||||
|
||||
public static CommandAPICommand commandJoin() {
|
||||
return new CommandAPICommand("join")
|
||||
.withArguments(
|
||||
CommandUtil.warWarArgument("war", false, true, ""),
|
||||
CommandUtil.warSideCreateArgument("side", "war", false, true, ""),
|
||||
new PlayerArgument("player").setOptional(true).withPermission("AlathranWars.admin.join")
|
||||
)
|
||||
.executesPlayer((Player p, CommandArguments args) -> warJoinPlayer(p, args, false));
|
||||
}
|
||||
|
||||
public static CommandAPICommand commandSurrender() {
|
||||
return new CommandAPICommand("surrender")
|
||||
.withArguments(
|
||||
CommandUtil.warWarArgument("war", false, false, "player"),
|
||||
new PlayerArgument("player")
|
||||
.setOptional(true)
|
||||
.withPermission("AlathranWars.admin")
|
||||
)
|
||||
.executesPlayer((Player p, CommandArguments args) -> warSurrender(p, args, false));
|
||||
}
|
||||
|
||||
public static CommandAPICommand commandList() {
|
||||
return new CommandAPICommand("list")
|
||||
.executesPlayer(WarCommand::warList);
|
||||
}
|
||||
|
||||
/*public static CommandAPICommand commandInfo() {
|
||||
return new CommandAPICommand("info")
|
||||
.withArguments(
|
||||
new PlayerArgument("player")
|
||||
)
|
||||
.executesPlayer(WarCommand::warInfo);
|
||||
}*/
|
||||
|
||||
public static CommandAPICommand commandHelp() {
|
||||
return new CommandAPICommand("help")
|
||||
.executesPlayer(WarCommand::warHelp);
|
||||
}
|
||||
|
||||
protected static void warCreate(CommandSender p, @NotNull CommandArguments args) throws WrapperCommandSyntaxException {
|
||||
if (!(args.get("warlabel") instanceof final @NotNull String argLabel))
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>You need to specify a war label.").build());
|
||||
|
||||
if (Objects.equals(args.get("side1"), args.get("side2")))
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>Cannot declare war on oneself.").build());
|
||||
|
||||
@Nullable UUID townName1 = (UUID) args.get("side1");
|
||||
@Nullable UUID townName2 = (UUID) args.get("side2");
|
||||
|
||||
// Create new war depending on what argument was specified
|
||||
@Nullable Town town1 = TownyAPI.getInstance().getTown(townName1);
|
||||
@Nullable Town town2 = TownyAPI.getInstance().getTown(townName2);
|
||||
@Nullable Nation nation1 = TownyAPI.getInstance().getNation(townName1);
|
||||
@Nullable Nation nation2 = TownyAPI.getInstance().getNation(townName2);
|
||||
|
||||
// Automatically elevate town wars to nation level if possible (This may be undesirable in terms of allowing civil wars etc)
|
||||
if (town1 != null && town1.getNationOrNull() != null) {
|
||||
nation1 = town1.getNationOrNull();
|
||||
}
|
||||
|
||||
if (town2 != null && town2.getNationOrNull() != null) {
|
||||
nation2 = town2.getNationOrNull();
|
||||
}
|
||||
|
||||
// TODO Ensure side1 valid
|
||||
// TODO Ensure side2 valid
|
||||
// TODO Deep Check if war exists where the same sides are fighting???
|
||||
|
||||
// Create war depending on what args have been passed, attempt to create nation wars first
|
||||
if (nation1 != null) {
|
||||
if (nation2 != null) {
|
||||
new War(argLabel, nation1, nation2);
|
||||
} else if (town2 != null) {
|
||||
new War(argLabel, nation1, town2);
|
||||
}
|
||||
} else if (town1 != null) {
|
||||
if (town2 != null) {
|
||||
new War(argLabel, town1, town2);
|
||||
} else if (nation2 != null) {
|
||||
new War(argLabel, town1, nation2);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/*for (War war1 : WarManager.getInstance().getWars()) {
|
||||
war.
|
||||
}*/
|
||||
|
||||
|
||||
// Check if side1 is nation or town
|
||||
// Check if side2 is nation or town
|
||||
// Check if opposing factions are already at war?
|
||||
|
||||
/*Main.warLogger.log(p.getName() + " created a new war with the name " + argWarName + ", " + argSide1
|
||||
+ " vs. " + argSide2);*/
|
||||
|
||||
}
|
||||
|
||||
private static void warDelete(Player p, @NotNull CommandArguments args) throws WrapperCommandSyntaxException {
|
||||
@Nullable War war = (War) args.get("war");
|
||||
|
||||
war.draw();
|
||||
// Main.warLogger.log(p.getName() + " deleted " + argWarName);
|
||||
}
|
||||
|
||||
protected static void warJoinPlayer(Player p, @NotNull CommandArguments args, boolean admin) throws WrapperCommandSyntaxException {
|
||||
if (!(args.get("war") instanceof final @NotNull War war))
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>You need to specify a war name.").build());
|
||||
|
||||
if (!(args.get("side") instanceof final @NotNull Side side))
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>You need to specify a side.").build());
|
||||
|
||||
if (!(args.getOptional("player").orElse(p) instanceof Player argPlayer))
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>Player not found.").build());
|
||||
|
||||
if (war.isPlayerInWar(argPlayer))
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>You are already in this war.").build());
|
||||
|
||||
argPlayer.sendMessage(ColorParser.of(UtilsChat.getPrefix() + "You have joined the war.").build());
|
||||
side.addPlayer(argPlayer);
|
||||
PlayerJoinListener.checkPlayer(argPlayer);
|
||||
for (@NotNull Siege siege : war.getSieges()) {
|
||||
if (siege.getAttackerSide().equals(side)) {
|
||||
siege.addPlayer(argPlayer, BattleSide.ATTACKER);
|
||||
} else {
|
||||
siege.addPlayer(argPlayer, BattleSide.DEFENDER);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param p - executor
|
||||
* @param args
|
||||
* @param admin - admin behavior
|
||||
*/
|
||||
protected static void warJoin(@NotNull Player p, @NotNull CommandArguments args, boolean admin) throws WrapperCommandSyntaxException {
|
||||
if (!(args.get("war") instanceof final @NotNull War war))
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>You need to specify a war name.").build());
|
||||
|
||||
if (!(args.get("side") instanceof final @NotNull Side side))
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>You need to specify a side.").build());
|
||||
|
||||
if (!(args.getOptional("player").orElse(p) instanceof Player argPlayer))
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>Player not found.").build());
|
||||
|
||||
// Towny Resident Object, if admin then dont use command runner, use declared player
|
||||
@Nullable Resident res = TownyAPI.getInstance().getResident(argPlayer);
|
||||
|
||||
// Town check
|
||||
@Nullable Town town = res.getTownOrNull();
|
||||
if (town == null) {
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of(ChatColor.RED + "You are not in a town.").build());
|
||||
}
|
||||
|
||||
//Minuteman countermeasures
|
||||
// final int minuteman = CommandHelper.isPlayerMinuteman(argPlayer.getName());
|
||||
// final boolean minuteManOverride = (boolean) args.getOptional("minutemen").orElse(false);
|
||||
//
|
||||
// if (minuteManOverride) {
|
||||
// p.sendMessage(ChatColor.RED + "Warning! Ignoring Minuteman Countermeasure!");
|
||||
// }
|
||||
//
|
||||
// //override?
|
||||
// if (!minuteManOverride) {
|
||||
// if (minuteman != 0) {
|
||||
// if (minuteman == 1) {
|
||||
// //player has joined to recently
|
||||
// if (admin)
|
||||
// p.sendMessage(ChatColor.RED + "You have joined the server too recently! You can only join a raid after " + Main.getInstance().getConfig().getInt("minimumPlayerAge") + " days from joining.");
|
||||
// argPlayer.sendMessage(ChatColor.RED + "You have joined the server too recently! You can only join a raid after " + Main.getInstance().getConfig().getInt("minimumPlayerAge") + " days from joining.");
|
||||
// return;
|
||||
// } else if (minuteman == 2) {
|
||||
// //player has played too little
|
||||
// if (admin)
|
||||
// p.sendMessage(ChatColor.RED + "You have not played enough! You can only join a raid after " + Main.getInstance().getConfig().getInt("minimumPlayTime") + " hours of play.");
|
||||
// argPlayer.sendMessage(ChatColor.RED + "You have not played enough! You can only join a raid after " + Main.getInstance().getConfig().getInt("minimumPlayTime") + " hours of play.");
|
||||
// return;
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
|
||||
// Side checks
|
||||
if (war.getSurrenderedTowns().contains(town)) {
|
||||
argPlayer.sendMessage(UtilsChat.getPrefix() + "You've already surrendered!");
|
||||
return;
|
||||
}
|
||||
|
||||
if (res.hasNation()) {
|
||||
if (res.getPlayer().hasPermission("AlathranWars.nationjoin") || res.isKing()) {
|
||||
// Has nation declaration permission
|
||||
side.addNation(res.getNationOrNull());
|
||||
res.getPlayer().sendMessage(UtilsChat.getPrefix() + "You have joined the war for " + res.getNationOrNull().getName());
|
||||
p.sendMessage(UtilsChat.getPrefix() + "You have joined the war for " + res.getNationOrNull().getName());
|
||||
Bukkit.broadcastMessage(UtilsChat.getPrefix() + "The nation of " + res.getNationOrNull().getName() + " has joined the war on the side of " + side.getName() + "!");
|
||||
} else {
|
||||
// Cannot declare nation involvement
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "You cannot declare war for your nation.").build());
|
||||
}
|
||||
} else if (res.hasTown()) {
|
||||
if (res.getPlayer().hasPermission("AlathranWars.townjoin") || res.isMayor()) {
|
||||
// Is in indepdenent town & has declaration perms
|
||||
side.addTown(res.getTownOrNull());
|
||||
res.getPlayer().sendMessage(UtilsChat.getPrefix() + "You have joined the war for " + res.getTownOrNull().getName());
|
||||
p.sendMessage(UtilsChat.getPrefix() + "You have joined the war for " + res.getTownOrNull().getName());
|
||||
Bukkit.broadcastMessage(UtilsChat.getPrefix() + "The town of " + res.getTownOrNull().getName() + " has joined the war on the side of " + side.getName() + "!");
|
||||
} else {
|
||||
// No perms
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "You cannot declare war for your town.").build());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected static void warSurrender(@NotNull Player p, @NotNull CommandArguments args, boolean admin) throws WrapperCommandSyntaxException {
|
||||
@Nullable War war = (War) args.get("war");
|
||||
|
||||
if (!(args.getOptional("player").orElse(p) instanceof Player argPlayer))
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>Player not found.").build());
|
||||
|
||||
// Towny Resident Object
|
||||
@Nullable Resident res = TownyAPI.getInstance().getResident(argPlayer);
|
||||
if (res == null)
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("<red>Resident invalid.").build());
|
||||
|
||||
// Town check
|
||||
@Nullable Town town = res.getTownOrNull();
|
||||
if (town == null)
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("<red>You are not in a town.").build());
|
||||
|
||||
@Nullable Side side = war.getTownSide(town);
|
||||
if (side == null)
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("<red>You are not in the war.").build());
|
||||
|
||||
final @Nullable Nation resNation = res.getNationOrNull();
|
||||
final @Nullable Town resTown = res.getTownOrNull();
|
||||
|
||||
if (resNation != null) {
|
||||
if (p.hasPermission("AlathranWars.nationsurrender") || res.isKing() || admin) {
|
||||
// Has nation surrender permission
|
||||
argPlayer.sendMessage(ColorParser.of(UtilsChat.getPrefix() + "You have surrendered the war for " + resNation.getName() + ".").build());
|
||||
Bukkit.broadcast(ColorParser.of(UtilsChat.getPrefix() + "The nation of " + resNation.getName() + " has surrendered!").build());
|
||||
side.surrenderNation(resNation);
|
||||
side.processSurrenders();
|
||||
} else {
|
||||
// Cannot surrender nation involvement
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "You cannot surrender war for your nation.").build());
|
||||
}
|
||||
} else if (resTown != null) {
|
||||
if (p.hasPermission("AlathranWars.townsurrender") || res.isMayor() || admin) {
|
||||
// Is in indepdenent town & has surrender perms
|
||||
argPlayer.sendMessage(ColorParser.of(UtilsChat.getPrefix() + "You have surrendered the war for " + resTown.getName() + ".").build());
|
||||
Bukkit.broadcast(ColorParser.of(UtilsChat.getPrefix() + "The town of " + resTown.getName() + " has surrendered!").build());
|
||||
side.surrenderTown(resTown);
|
||||
side.processSurrenders();
|
||||
} else {
|
||||
// No perms
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "You cannot surrender war for your town.").build());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private static void warList(@NotNull Player p, CommandArguments args) throws WrapperCommandSyntaxException {
|
||||
@NotNull Set<War> wars = WarManager.getInstance().getWars();
|
||||
|
||||
if (wars.isEmpty()) {
|
||||
p.sendMessage(ColorParser.of("There are no wars at the moment, the world is at peace.").build());
|
||||
} else {
|
||||
p.sendMessage(ColorParser.of(UtilsChat.getPrefix() + "Wars:").build());
|
||||
|
||||
for (@NotNull War war : wars) {
|
||||
p.sendMessage(ColorParser.of(war.getName() + " - " + war.getSide1().getName() + " (" + war.getSide1().getScore() + ") vs. " + war.getSide2().getName() + " (" + war.getSide2().getScore() + ")").build());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/*private static void warInfo(Player p, CommandArguments args) throws WrapperCommandSyntaxException {
|
||||
if (args.count() < 1) {
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "/war info [Player]").build());
|
||||
}
|
||||
|
||||
if (!(args.get("player") instanceof Player argsPlayer))
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("Specify a player.").build());
|
||||
|
||||
Resident res = TownyAPI.getInstance().getResident(argsPlayer);
|
||||
if (res == null || res.getTownOrNull() == null) {
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "Invalid town resident.").build());
|
||||
}
|
||||
|
||||
p.sendMessage(ColorParser.of(UtilsChat.getPrefix() + p.getName() + "'s wars:").build());
|
||||
for (War war : WarManager.getInstance().getWars()) {
|
||||
TownWarState side = war.getState(res.getTownOrNull());
|
||||
if (side != TownWarState.NOT_PARTICIPANT) {
|
||||
if (side == TownWarState.SURRENDERED) {
|
||||
p.sendMessage(war.getName() + " - Surrendered");
|
||||
} else if (side == TownWarState.SIDE1) {
|
||||
p.sendMessage(war.getName() + " - " + war.getSide1());
|
||||
} else if (side == TownWarState.SIDE2) {
|
||||
p.sendMessage(war.getName() + " - " + war.getSide2());
|
||||
}
|
||||
}
|
||||
}
|
||||
}*/
|
||||
|
||||
private static void warHelp(Player p, CommandArguments args) throws WrapperCommandSyntaxException {
|
||||
// TODO
|
||||
}
|
||||
|
||||
/**
|
||||
* Method for console access
|
||||
*
|
||||
* @param sender
|
||||
* @param args
|
||||
*/
|
||||
// private static void consoleCommand(CommandSender sender, CommandArguments args) {
|
||||
// if (args.length < 1) return;
|
||||
// if (args[0].equalsIgnoreCase("list")) {
|
||||
// ArrayList<War> warList = WarManager.getInstance().getWars();
|
||||
// sender.sendMessage("Wars: " + warList.size());
|
||||
// for (War war : WarManager.getInstance().getWars()) {
|
||||
// if (war == null) continue;
|
||||
// sender.sendMessage(war.toString());
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
}
|
||||
@@ -1,603 +0,0 @@
|
||||
package me.ShermansWorld.AlathranWars.deprecated;
|
||||
|
||||
import com.palmergames.bukkit.towny.TownyAPI;
|
||||
import com.palmergames.bukkit.towny.TownyUniverse;
|
||||
import com.palmergames.bukkit.towny.exceptions.NotRegisteredException;
|
||||
import com.palmergames.bukkit.towny.exceptions.TownyException;
|
||||
import com.palmergames.bukkit.towny.object.*;
|
||||
import me.ShermansWorld.AlathranWars.Main;
|
||||
import me.ShermansWorld.AlathranWars.data.SiegeData;
|
||||
import me.ShermansWorld.AlathranWars.enums.TownWarState;
|
||||
import org.bukkit.*;
|
||||
import org.bukkit.boss.BarColor;
|
||||
import org.bukkit.boss.BarStyle;
|
||||
import org.bukkit.boss.BossBar;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
import java.util.ArrayList;
|
||||
|
||||
@Deprecated
|
||||
public class OldSiege {
|
||||
|
||||
public static final int maxSiegeTicks = 72000; // 60 minute tick constant
|
||||
public final NamespacedKey bossBarKey;
|
||||
public ArrayList<String> attackerPlayers;
|
||||
public ArrayList<String> defenderPlayers;
|
||||
public ArrayList<Location> beaconLocs;
|
||||
int[] bukkitId;
|
||||
private OldWar oldWar; // OldWar which siege belongs to
|
||||
private Town town; // Town of the siege
|
||||
private boolean side1AreAttackers; // bool of if side1 being attacker
|
||||
private int attackerPoints;
|
||||
private int defenderPoints;
|
||||
private OfflinePlayer siegeLeader;
|
||||
private int siegeTicks;
|
||||
private TownBlock homeBlock;
|
||||
private Location townSpawn;
|
||||
|
||||
|
||||
public OldSiege(final OldWar oldWar, final Town town, OfflinePlayer siegeLeader) {
|
||||
this.siegeTicks = 0;
|
||||
this.bukkitId = new int[1];
|
||||
this.attackerPlayers = new ArrayList<>();
|
||||
this.defenderPlayers = new ArrayList<>();
|
||||
this.beaconLocs = new ArrayList<>();
|
||||
this.oldWar = oldWar;
|
||||
this.town = town;
|
||||
this.siegeLeader = siegeLeader;
|
||||
|
||||
bossBarKey = new NamespacedKey(Main.getInstance(), "siegeBar." + this.getName());
|
||||
|
||||
side1AreAttackers = oldWar.getState(town.getName()) == TownWarState.SIDE2;
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts a siege
|
||||
*/
|
||||
public void start() {
|
||||
attackerPoints = 0;
|
||||
defenderPoints = 0;
|
||||
this.siegeTicks = 0;
|
||||
homeBlock = town.getHomeBlockOrNull();
|
||||
townSpawn = town.getSpawnOrNull();
|
||||
|
||||
this.bukkitId[0] = Bukkit.getServer().getScheduler().scheduleSyncRepeatingTask(Main.getInstance(), getTickLoop(), 0L, 200L);
|
||||
|
||||
setupDisplayBar();
|
||||
}
|
||||
|
||||
/**
|
||||
* Resumes a siege (after a server restart e.t.c.)
|
||||
*/
|
||||
public void resume(int resumeTick) {
|
||||
|
||||
siegeTicks = resumeTick;
|
||||
|
||||
homeBlock = town.getHomeBlockOrNull();
|
||||
townSpawn = town.getSpawnOrNull();
|
||||
|
||||
this.bukkitId[0] = Bukkit.getServer().getScheduler().scheduleSyncRepeatingTask(Main.getInstance(), getTickLoop(), 0L, 200L);
|
||||
|
||||
setupDisplayBar();
|
||||
}
|
||||
|
||||
/**
|
||||
* Stops a siege
|
||||
*/
|
||||
public void stop() {
|
||||
deleteDisplayBar();
|
||||
Bukkit.getScheduler().cancelTask(this.bukkitId[0]);
|
||||
this.oldWar.getSieges().remove(this);
|
||||
SiegeData.removeSiege(this);
|
||||
|
||||
}
|
||||
|
||||
private Runnable getTickLoop() {
|
||||
return new Runnable() {
|
||||
int homeBlockControl = 0;
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
if (homeBlock != null) {
|
||||
town.setHomeBlock(homeBlock);
|
||||
town.setSpawn(townSpawn);
|
||||
}
|
||||
if (OldSiege.this.side1AreAttackers) {
|
||||
OldSiege.this.attackerPlayers = OldSiege.this.oldWar.getSide1Players();
|
||||
OldSiege.this.defenderPlayers = OldSiege.this.oldWar.getSide2Players();
|
||||
} else {
|
||||
OldSiege.this.attackerPlayers = OldSiege.this.oldWar.getSide2Players();
|
||||
OldSiege.this.defenderPlayers = OldSiege.this.oldWar.getSide1Players();
|
||||
}
|
||||
if (OldSiege.this.siegeTicks >= maxSiegeTicks) {
|
||||
Bukkit.getServer().getScheduler().cancelTask(OldSiege.this.bukkitId[0]);
|
||||
SiegeData.removeSiege(OldSiege.this);
|
||||
if (OldSiege.this.attackerPoints > OldSiege.this.defenderPoints) {
|
||||
OldSiege.this.attackersWin(OldSiege.this.siegeLeader);
|
||||
} else {
|
||||
OldSiege.this.defendersWin();
|
||||
}
|
||||
} else {
|
||||
boolean attackersAreOnHomeBlock = false;
|
||||
boolean defendersAreOnHomeBlock = false;
|
||||
siegeTicks = siegeTicks + 200;
|
||||
for (final String playerName : OldSiege.this.attackerPlayers) {
|
||||
Player pl = Main.getInstance().getServer().getPlayer(playerName);
|
||||
try {
|
||||
if (pl != null) {
|
||||
WorldCoord wc = WorldCoord.parseWorldCoord(pl);
|
||||
if (wc.getTownBlock().getTown().equals(town)) {
|
||||
if (town.getHomeBlockOrNull() != null) {
|
||||
if (town.getHomeBlockOrNull().getWorldCoord().equals(wc)) {
|
||||
if (!pl.isDead()) {
|
||||
if ((Math.abs(pl.getLocation().getBlockY() - townSpawn.getBlockY())) < 10) {
|
||||
attackersAreOnHomeBlock = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (NotRegisteredException ignored) {
|
||||
Main.warLogger.log(UtilsChat.getPrefix() + "Attempting to look for town at " + WorldCoord.parseWorldCoord(pl));
|
||||
}
|
||||
}
|
||||
for (final String playerName : OldSiege.this.defenderPlayers) {
|
||||
Player pl = Main.getInstance().getServer().getPlayer(playerName);
|
||||
try {
|
||||
if (pl != null) {
|
||||
WorldCoord wc = WorldCoord.parseWorldCoord(pl);
|
||||
if (wc.getTownBlock().getTown().equals(town)) {
|
||||
if (town.getHomeBlockOrNull() != null) {
|
||||
if (town.getHomeBlockOrNull().getWorldCoord().equals(wc)) {
|
||||
if (!pl.isDead()) {
|
||||
if ((Math.abs(pl.getLocation().getBlockY() - townSpawn.getBlockY())) <= 10) {
|
||||
defendersAreOnHomeBlock = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (NotRegisteredException ignored) {
|
||||
Main.warLogger.log(UtilsChat.getPrefix() + "Attempting to look for town at " + WorldCoord.parseWorldCoord(pl));
|
||||
}
|
||||
}
|
||||
if (attackersAreOnHomeBlock && defendersAreOnHomeBlock) { // Contested
|
||||
if (this.homeBlockControl != 1) {
|
||||
for (final String playerName : OldSiege.this.attackerPlayers) {
|
||||
try {
|
||||
Bukkit.getPlayer(playerName).sendMessage(UtilsChat.getPrefix()
|
||||
+ "HomeBlock at " + OldSiege.this.town.getName() + " contested!");
|
||||
} catch (NullPointerException ex5) {
|
||||
}
|
||||
}
|
||||
for (final String playerName : OldSiege.this.defenderPlayers) {
|
||||
try {
|
||||
Bukkit.getPlayer(playerName).sendMessage(UtilsChat.getPrefix()
|
||||
+ "HomeBlock at " + OldSiege.this.town.getName() + " contested!");
|
||||
} catch (NullPointerException ex6) {
|
||||
}
|
||||
}
|
||||
}
|
||||
this.homeBlockControl = 1;
|
||||
} else if (attackersAreOnHomeBlock && !defendersAreOnHomeBlock) { // Attackers
|
||||
if (this.homeBlockControl != 2) {
|
||||
for (final String playerName : OldSiege.this.attackerPlayers) {
|
||||
try {
|
||||
Bukkit.getPlayer(playerName).sendMessage(UtilsChat.getPrefix()
|
||||
+ "Attackers have captured the HomeBlock at "
|
||||
+ OldSiege.this.town.getName() + "! +1 Attacker Points per second");
|
||||
} catch (NullPointerException ex7) {
|
||||
}
|
||||
}
|
||||
for (final String playerName : OldSiege.this.defenderPlayers) {
|
||||
try {
|
||||
Bukkit.getPlayer(playerName).sendMessage(UtilsChat.getPrefix()
|
||||
+ "Attackers have captured the HomeBlock at "
|
||||
+ OldSiege.this.town.getName() + "! +1 Attacker Points per second");
|
||||
} catch (NullPointerException ex8) {
|
||||
}
|
||||
}
|
||||
}
|
||||
this.homeBlockControl = 2;
|
||||
OldSiege.this.addPointsToAttackers(10);
|
||||
} else { // Defenders / None
|
||||
if (this.homeBlockControl != 3) {
|
||||
for (final String playerName : OldSiege.this.attackerPlayers) {
|
||||
try {
|
||||
Bukkit.getPlayer(playerName).sendMessage(UtilsChat.getPrefix()
|
||||
+ "Defenders retain control of the HomeBlock at "
|
||||
+ OldSiege.this.town.getName() + "! +1 Defender Points per second");
|
||||
} catch (NullPointerException ex9) {
|
||||
}
|
||||
}
|
||||
for (final String playerName : OldSiege.this.defenderPlayers) {
|
||||
try {
|
||||
Bukkit.getPlayer(playerName).sendMessage(UtilsChat.getPrefix()
|
||||
+ "Defenders retain control of the HomeBlock at "
|
||||
+ OldSiege.this.town.getName() + "! +1 Defender Points per second");
|
||||
} catch (NullPointerException ex10) {
|
||||
}
|
||||
}
|
||||
}
|
||||
OldSiege.this.addPointsToDefenders(10);
|
||||
this.homeBlockControl = 3;
|
||||
}
|
||||
if (OldSiege.this.siegeTicks % 6000 == 0) { // Updates every 5 minutes
|
||||
Bukkit.broadcastMessage(UtilsChat.getPrefix() + "Report on the siege of "
|
||||
+ OldSiege.this.town.getName() + ":");
|
||||
Bukkit.broadcastMessage(
|
||||
"Attacker Points - " + OldSiege.this.attackerPoints);
|
||||
Bukkit.broadcastMessage(
|
||||
"Defender Points - " + OldSiege.this.defenderPoints);
|
||||
}
|
||||
if (siegeTicks % 1200 == 0) { // Saves every minute
|
||||
save();
|
||||
}
|
||||
}
|
||||
|
||||
refreshDisplayBar();
|
||||
}
|
||||
|
||||
|
||||
};
|
||||
}
|
||||
|
||||
public void attackersWin(final OfflinePlayer siegeLeader) {
|
||||
final Resident resident = TownyAPI.getInstance().getResident(siegeLeader.getUniqueId());
|
||||
Nation nation = null;
|
||||
Bukkit.broadcastMessage(UtilsChat.getPrefix() + "The attackers have won the siege of " + this.town.getName() + "!");
|
||||
try {
|
||||
nation = resident.getTown().getNation();
|
||||
} catch (Exception e) {
|
||||
}
|
||||
if (nation != null) {
|
||||
Bukkit.broadcastMessage(UtilsChat.getPrefix() + "The town of " + this.town.getName()
|
||||
+ " has been placed under occupation by " + nation.getName() + "!");
|
||||
}
|
||||
Main.econ.depositPlayer(siegeLeader, 2500.0);
|
||||
double amt = 0.0;
|
||||
if (this.town.getAccount().getHoldingBalance() > 10000.0) {
|
||||
amt = Math.floor(this.town.getAccount().getHoldingBalance()) / 4.0;
|
||||
this.town.getAccount().withdraw(amt, "oldWar loot");
|
||||
} else {
|
||||
if (this.town.getAccount().getHoldingBalance() < 2500.0) {
|
||||
amt = this.town.getAccount().getHoldingBalance();
|
||||
Bukkit.broadcastMessage(UtilsChat.getPrefix() + "The town of " + this.town.getName()
|
||||
+ " has been destroyed by " + this.getAttackerSide() + "!");
|
||||
TownyUniverse.getInstance().getDataSource().deleteTown(this.town);
|
||||
Main.econ.depositPlayer(siegeLeader, amt);
|
||||
return;
|
||||
}
|
||||
this.town.getAccount().withdraw(2500.0, "oldWar loot");
|
||||
amt = 2500.0;
|
||||
}
|
||||
Bukkit.broadcastMessage("The town of " + this.town.getName() + " has been sacked by " + this.getAttackerSide()
|
||||
+ ", valuing $" + amt);
|
||||
Main.warLogger.log("The town of " + this.town.getName() + " has been sacked by " + this.getAttackerSide()
|
||||
+ ", valuing $" + amt);
|
||||
Main.econ.depositPlayer(siegeLeader, amt);
|
||||
|
||||
if (side1AreAttackers) {
|
||||
oldWar.addSide1Points(50);
|
||||
} else {
|
||||
oldWar.addSide2Points(50);
|
||||
}
|
||||
|
||||
stop();
|
||||
clearBeacon();
|
||||
}
|
||||
|
||||
public void defendersWin() {
|
||||
this.town.getAccount().deposit(2500.0, "OldWar chest");
|
||||
Bukkit.broadcastMessage(UtilsChat.getPrefix() + "The defenders have won the siege of " + this.town.getName() + "!");
|
||||
Bukkit.broadcastMessage(UtilsChat.getPrefix() + this.town.getName()
|
||||
+ " has recovered the attackers' oldWar chest, valued at $2,500");
|
||||
Main.warLogger
|
||||
.log(oldWar.getName() + ": The defenders have won the siege of " + this.town.getName() + "!");
|
||||
|
||||
if (side1AreAttackers) {
|
||||
oldWar.addSide2Points(50);
|
||||
} else {
|
||||
oldWar.addSide1Points(50);
|
||||
}
|
||||
|
||||
stop();
|
||||
clearBeacon();
|
||||
}
|
||||
|
||||
/**
|
||||
* No winnder declared
|
||||
*/
|
||||
public void noWinner() {
|
||||
Bukkit.broadcastMessage(UtilsChat.getPrefix() + "The siege of " + this.town.getName() + " was a draw!");
|
||||
Bukkit.broadcastMessage(UtilsChat.getPrefix() + "No money has been recovered.");
|
||||
Main.warLogger
|
||||
.log(oldWar.getName() + ": No one won the siege of " + this.town.getName() + "!");
|
||||
stop();
|
||||
clearBeacon();
|
||||
}
|
||||
|
||||
public void createBeacon() {
|
||||
try {
|
||||
World world = town.getWorld();
|
||||
int homeBlockX = this.town.getHomeBlock().getX() * 16;
|
||||
int homeBlockZ = (this.town.getHomeBlock().getZ() + 1) * 16;
|
||||
if (homeBlockX > 0) {
|
||||
homeBlockX -= 8;
|
||||
}
|
||||
if (homeBlockZ > 0) {
|
||||
homeBlockZ -= 8;
|
||||
}
|
||||
if (homeBlockX < 0) {
|
||||
homeBlockX += 8;
|
||||
}
|
||||
if (homeBlockZ < 0) {
|
||||
homeBlockZ += 8;
|
||||
}
|
||||
int homeBlockY = 253;
|
||||
final Location beaconLoc = new Location(this.town.getWorld(), homeBlockX,
|
||||
homeBlockY - 2, homeBlockZ);
|
||||
while (beaconLoc.getBlock().getType().equals(Material.AIR)) {
|
||||
--homeBlockY;
|
||||
beaconLoc.setY(homeBlockY);
|
||||
}
|
||||
homeBlockY += 2;
|
||||
this.beaconLocs.add(new Location(world, homeBlockX, homeBlockY, homeBlockZ));
|
||||
this.beaconLocs
|
||||
.add(new Location(world, homeBlockX, homeBlockY + 1, homeBlockZ));
|
||||
this.beaconLocs
|
||||
.add(new Location(world, homeBlockX, homeBlockY - 1, homeBlockZ));
|
||||
this.beaconLocs.add(
|
||||
new Location(world, homeBlockX + 1, homeBlockY - 1, homeBlockZ));
|
||||
this.beaconLocs.add(
|
||||
new Location(world, homeBlockX - 1, homeBlockY - 1, homeBlockZ));
|
||||
this.beaconLocs.add(
|
||||
new Location(world, homeBlockX, homeBlockY - 1, homeBlockZ + 1));
|
||||
this.beaconLocs.add(
|
||||
new Location(world, homeBlockX, homeBlockY - 1, homeBlockZ - 1));
|
||||
this.beaconLocs.add(new Location(world, homeBlockX + 1, homeBlockY - 1,
|
||||
homeBlockZ + 1));
|
||||
this.beaconLocs.add(new Location(world, homeBlockX + 1, homeBlockY - 1,
|
||||
homeBlockZ - 1));
|
||||
this.beaconLocs.add(new Location(world, homeBlockX - 1, homeBlockY - 1,
|
||||
homeBlockZ + 1));
|
||||
this.beaconLocs.add(new Location(world, homeBlockX - 1, homeBlockY - 1,
|
||||
homeBlockZ - 1));
|
||||
for (int i = 2; i < this.beaconLocs.size(); ++i) {
|
||||
if (this.beaconLocs.get(i).getBlock().getType() != Material.AIR) {
|
||||
i = 1;
|
||||
homeBlockY++;
|
||||
for (final Location loc : this.beaconLocs) {
|
||||
loc.setY(loc.getY() + 1.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
this.beaconLocs.get(0).getBlock().setType(Material.BEACON);
|
||||
this.beaconLocs.get(1).getBlock().setType(Material.RED_STAINED_GLASS);
|
||||
for (int i = 2; i < this.beaconLocs.size(); ++i) {
|
||||
this.beaconLocs.get(i).getBlock().setType(Material.IRON_BLOCK);
|
||||
}
|
||||
save();
|
||||
} catch (TownyException ex) {
|
||||
}
|
||||
}
|
||||
|
||||
public void resetBeacon(World world, int homeBlockX, int homeBlockY, int homeBlockZ) {
|
||||
this.beaconLocs.add(new Location(world, homeBlockX, homeBlockY, homeBlockZ));
|
||||
this.beaconLocs.add(new Location(world, homeBlockX, homeBlockY + 1, homeBlockZ));
|
||||
this.beaconLocs.add(new Location(world, homeBlockX, homeBlockY - 1, homeBlockZ));
|
||||
this.beaconLocs
|
||||
.add(new Location(world, homeBlockX + 1, homeBlockY - 1, homeBlockZ));
|
||||
this.beaconLocs
|
||||
.add(new Location(world, homeBlockX - 1, homeBlockY - 1, homeBlockZ));
|
||||
this.beaconLocs
|
||||
.add(new Location(world, homeBlockX, homeBlockY - 1, homeBlockZ + 1));
|
||||
this.beaconLocs
|
||||
.add(new Location(world, homeBlockX, homeBlockY - 1, homeBlockZ - 1));
|
||||
this.beaconLocs.add(
|
||||
new Location(world, homeBlockX + 1, homeBlockY - 1, homeBlockZ + 1));
|
||||
this.beaconLocs.add(
|
||||
new Location(world, homeBlockX + 1, homeBlockY - 1, homeBlockZ - 1));
|
||||
this.beaconLocs.add(
|
||||
new Location(world, homeBlockX - 1, homeBlockY - 1, homeBlockZ + 1));
|
||||
this.beaconLocs.add(
|
||||
new Location(world, homeBlockX - 1, homeBlockY - 1, homeBlockZ - 1));
|
||||
}
|
||||
|
||||
public void clearBeacon() {
|
||||
for (final Location loc : this.beaconLocs) {
|
||||
loc.getBlock().setType(Material.AIR);
|
||||
}
|
||||
}
|
||||
|
||||
public void addPointsToAttackers(final int points) {
|
||||
this.attackerPoints += points;
|
||||
}
|
||||
|
||||
public void addPointsToDefenders(final int points) {
|
||||
this.defenderPoints += points;
|
||||
}
|
||||
|
||||
public OldWar getWar() {
|
||||
return this.oldWar;
|
||||
}
|
||||
|
||||
public void setWar(final OldWar oldWar) {
|
||||
this.oldWar = oldWar;
|
||||
}
|
||||
|
||||
public Town getTown() {
|
||||
return this.town;
|
||||
}
|
||||
|
||||
public void setTown(final Town town) {
|
||||
this.town = town;
|
||||
}
|
||||
|
||||
public OfflinePlayer getSiegeOwner() {
|
||||
return siegeLeader;
|
||||
}
|
||||
|
||||
public void setSiegeOwner(OfflinePlayer siegeOwner) {
|
||||
this.siegeLeader = siegeOwner;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets attacker name string
|
||||
*/
|
||||
public String getAttackerSide() {
|
||||
if (side1AreAttackers) {
|
||||
return oldWar.getSide1();
|
||||
} else {
|
||||
return oldWar.getSide2();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets defender name string
|
||||
*/
|
||||
public String getDefenderSide() {
|
||||
if (side1AreAttackers) {
|
||||
return oldWar.getSide2();
|
||||
} else {
|
||||
return oldWar.getSide1();
|
||||
}
|
||||
}
|
||||
|
||||
public void refreshDisplayBar() {
|
||||
BossBar bossBar = Bukkit.getBossBar(bossBarKey);
|
||||
if (bossBar == null) bossBar = createNewDisplayBar();
|
||||
|
||||
bossBar.setTitle(String.format("%d -- Attackers -OldSiege Score- Defenders -- %d", this.attackerPoints, this.defenderPoints));
|
||||
bossBar.setProgress((this.attackerPoints + 0.5D) / ((this.attackerPoints + this.defenderPoints) + 1.0D));
|
||||
|
||||
for (String s : this.getAttackerPlayers()) {
|
||||
Player p = Bukkit.getPlayer(s);
|
||||
if (p != null) {
|
||||
if (!bossBar.getPlayers().contains(p)) bossBar.addPlayer(p);
|
||||
}
|
||||
}
|
||||
|
||||
for (String s : this.getDefenderPlayers()) {
|
||||
Player p = Bukkit.getPlayer(s);
|
||||
if (p != null) {
|
||||
if (!bossBar.getPlayers().contains(p)) bossBar.addPlayer(p);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void setupDisplayBar() {
|
||||
BossBar bossBar = Bukkit.getBossBar(bossBarKey);
|
||||
if (bossBar == null) bossBar = createNewDisplayBar();
|
||||
|
||||
for (String s : this.getAttackerPlayers()) {
|
||||
Player p = Bukkit.getPlayer(s);
|
||||
if (p != null) {
|
||||
bossBar.addPlayer(p);
|
||||
}
|
||||
}
|
||||
|
||||
for (String s : this.getDefenderPlayers()) {
|
||||
Player p = Bukkit.getPlayer(s);
|
||||
if (p != null) bossBar.addPlayer(p);
|
||||
}
|
||||
}
|
||||
|
||||
public void deleteDisplayBar() {
|
||||
BossBar bossBar = Bukkit.getBossBar(bossBarKey);
|
||||
if (bossBar != null) {
|
||||
bossBar.removeAll();
|
||||
}
|
||||
Bukkit.removeBossBar(bossBarKey);
|
||||
|
||||
}
|
||||
|
||||
|
||||
public BossBar createNewDisplayBar() {
|
||||
return Bukkit.createBossBar(bossBarKey, String.format("%d -- Attackers -OldSiege Score- Defenders -- %d", this.attackerPoints, this.defenderPoints), BarColor.YELLOW, BarStyle.SOLID);
|
||||
}
|
||||
|
||||
public int getAttackerPoints() {
|
||||
return this.attackerPoints;
|
||||
}
|
||||
|
||||
public void setAttackerPoints(int points) {
|
||||
this.attackerPoints = points;
|
||||
}
|
||||
|
||||
public int getDefenderPoints() {
|
||||
return this.defenderPoints;
|
||||
}
|
||||
|
||||
public void setDefenderPoints(int points) {
|
||||
this.defenderPoints = points;
|
||||
}
|
||||
|
||||
public int getMaxSiegeTicks() {
|
||||
return maxSiegeTicks;
|
||||
}
|
||||
|
||||
public TownBlock getHomeBlock() {
|
||||
return homeBlock;
|
||||
}
|
||||
|
||||
public void setHomeBlock(TownBlock homeBlock) {
|
||||
this.homeBlock = homeBlock;
|
||||
}
|
||||
|
||||
public Location getTownSpawn() {
|
||||
return townSpawn;
|
||||
}
|
||||
|
||||
public void setTownSpawn(Location townSpawn) {
|
||||
this.townSpawn = townSpawn;
|
||||
}
|
||||
|
||||
public boolean getSide1AreAttackers() {
|
||||
return this.side1AreAttackers;
|
||||
}
|
||||
|
||||
public void setSide1AreAttackers(final boolean side1AreAttackers) {
|
||||
this.side1AreAttackers = side1AreAttackers;
|
||||
}
|
||||
|
||||
public ArrayList<String> getAttackerPlayers() {
|
||||
return this.attackerPlayers;
|
||||
}
|
||||
|
||||
public void setAttackerPlayer(final ArrayList<String> attackerPlayers) {
|
||||
this.attackerPlayers = attackerPlayers;
|
||||
}
|
||||
|
||||
public ArrayList<String> getDefenderPlayers() {
|
||||
return this.defenderPlayers;
|
||||
}
|
||||
|
||||
public void setDefenderPlayer(final ArrayList<String> defenderPlayers) {
|
||||
this.defenderPlayers = this.attackerPlayers;
|
||||
}
|
||||
|
||||
public int getSiegeTicks() {
|
||||
return siegeTicks;
|
||||
}
|
||||
|
||||
public void setSiegeTicks(int siegeTicks) {
|
||||
this.siegeTicks = siegeTicks;
|
||||
}
|
||||
|
||||
public OfflinePlayer getSiegeLeader() {
|
||||
return siegeLeader;
|
||||
}
|
||||
|
||||
public void save() {
|
||||
SiegeData.saveSiege(this);
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return this.getWar().getName() + "-" + this.getTown();
|
||||
}
|
||||
}
|
||||
@@ -1,770 +0,0 @@
|
||||
package me.ShermansWorld.AlathranWars.commands;
|
||||
|
||||
import com.github.milkdrinkers.colorparser.ColorParser;
|
||||
import com.palmergames.bukkit.towny.TownyAPI;
|
||||
import com.palmergames.bukkit.towny.exceptions.NotRegisteredException;
|
||||
import com.palmergames.bukkit.towny.exceptions.TownyException;
|
||||
import com.palmergames.bukkit.towny.object.Town;
|
||||
import com.palmergames.bukkit.towny.object.TownyWorld;
|
||||
import com.palmergames.bukkit.towny.object.WorldCoord;
|
||||
import dev.jorel.commandapi.CommandAPIBukkit;
|
||||
import dev.jorel.commandapi.CommandAPICommand;
|
||||
import dev.jorel.commandapi.arguments.ArgumentSuggestions;
|
||||
import dev.jorel.commandapi.arguments.BooleanArgument;
|
||||
import dev.jorel.commandapi.arguments.PlayerArgument;
|
||||
import dev.jorel.commandapi.arguments.StringArgument;
|
||||
import dev.jorel.commandapi.exceptions.WrapperCommandSyntaxException;
|
||||
import dev.jorel.commandapi.executors.CommandArguments;
|
||||
import me.ShermansWorld.AlathranWars.*;
|
||||
import me.ShermansWorld.AlathranWars.data.RaidData;
|
||||
import me.ShermansWorld.AlathranWars.data.RaidPhase;
|
||||
import me.ShermansWorld.AlathranWars.data.SiegeData;
|
||||
import me.ShermansWorld.AlathranWars.data.WarData;
|
||||
import me.ShermansWorld.AlathranWars.deprecated.CommandHelper;
|
||||
import me.ShermansWorld.AlathranWars.deprecated.OldRaid;
|
||||
import me.ShermansWorld.AlathranWars.deprecated.OldSiege;
|
||||
import me.ShermansWorld.AlathranWars.deprecated.OldWar;
|
||||
import me.ShermansWorld.AlathranWars.enums.TownWarState;
|
||||
import me.ShermansWorld.AlathranWars.utility.Utils;
|
||||
import net.md_5.bungee.api.ChatColor;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.OfflinePlayer;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
public class RaidCommand {
|
||||
|
||||
public RaidCommand() {
|
||||
new CommandAPICommand("raid")
|
||||
.withSubcommands(
|
||||
commandRaid(),
|
||||
commandStop(),
|
||||
commandJoin(),
|
||||
commandLeave(),
|
||||
commandAbandon(),
|
||||
commandList(),
|
||||
commandHelp()
|
||||
)
|
||||
.executesPlayer((sender, args) -> {
|
||||
if (args.count() == 0)
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(new ColorParser(UtilsChat.getPrefix() + "Invalid Arguments. /siege help").build());
|
||||
})
|
||||
.register();
|
||||
}
|
||||
|
||||
public static CommandAPICommand commandRaid() {
|
||||
return new CommandAPICommand("raid")
|
||||
.withArguments(
|
||||
new StringArgument("war")
|
||||
.replaceSuggestions(
|
||||
ArgumentSuggestions.strings(
|
||||
WarData.getWarsNames()
|
||||
)
|
||||
),
|
||||
new StringArgument("town")
|
||||
.replaceSuggestions(
|
||||
ArgumentSuggestions.stringCollection(info -> {
|
||||
final String warname = (String) info.previousArgs().get("war");
|
||||
return CommandHelper.getTownyWarTowns(warname);
|
||||
}
|
||||
)
|
||||
),
|
||||
new StringArgument("gathertown")
|
||||
.setOptional(true)
|
||||
.withPermission("AlathranWars.admin")
|
||||
.replaceSuggestions(
|
||||
ArgumentSuggestions.stringCollection(info -> { // TODO Make getHostileTowns method where we reverse from list
|
||||
final String warname = (String) info.previousArgs().get("war");
|
||||
return CommandHelper.getTownyWarTowns(warname);
|
||||
}
|
||||
)
|
||||
),
|
||||
new PlayerArgument("leader")
|
||||
.setOptional(true)
|
||||
.withPermission("AlathranWars.admin"),
|
||||
new BooleanArgument("minutemen")
|
||||
.setOptional(true)
|
||||
.withPermission("AlathranWars.admin")
|
||||
|
||||
)
|
||||
.executesPlayer((Player p, CommandArguments args) -> raidStart(p, args, false));
|
||||
}
|
||||
|
||||
public static CommandAPICommand commandStop() {
|
||||
return new CommandAPICommand("stop")
|
||||
.withPermission("AlathranWars.admin")
|
||||
.withArguments(
|
||||
new StringArgument("war")
|
||||
.replaceSuggestions(
|
||||
ArgumentSuggestions.stringCollection(info ->
|
||||
WarData.getWarsNames()
|
||||
)
|
||||
),
|
||||
new StringArgument("town")
|
||||
.replaceSuggestions(
|
||||
ArgumentSuggestions.stringCollection(info -> {
|
||||
final String warname = (String) info.previousArgs().get("war");
|
||||
return CommandHelper.getTownyWarTowns(warname);
|
||||
})
|
||||
)
|
||||
)
|
||||
.executesPlayer(RaidCommand::raidStop);
|
||||
}
|
||||
|
||||
public static CommandAPICommand commandJoin() {
|
||||
return new CommandAPICommand("join")
|
||||
.withArguments(
|
||||
new StringArgument("raid")
|
||||
.replaceSuggestions(
|
||||
ArgumentSuggestions.strings(
|
||||
CommandHelper.getRaids()
|
||||
)
|
||||
),
|
||||
new StringArgument("side")
|
||||
.replaceSuggestions(
|
||||
ArgumentSuggestions.stringCollection(info -> {
|
||||
final String raidname = (String) info.previousArgs().get("oldRaid");
|
||||
|
||||
final OldRaid oldRaid = RaidData.getRaid(raidname);
|
||||
|
||||
if (oldRaid == null) return Collections.emptyList();
|
||||
|
||||
return List.of(oldRaid.getRaiderSide(), oldRaid.getDefenderSide());
|
||||
})
|
||||
),
|
||||
new PlayerArgument("player")
|
||||
.setOptional(true)
|
||||
.withPermission("AlathranWars.admin"),
|
||||
new BooleanArgument("minutemen")
|
||||
.setOptional(true)
|
||||
.withPermission("AlathranWars.admin")
|
||||
|
||||
)
|
||||
.executesPlayer((Player p, CommandArguments args) -> raidJoin(p, args, false));
|
||||
}
|
||||
|
||||
public static CommandAPICommand commandLeave() {
|
||||
return new CommandAPICommand("leave")
|
||||
.withArguments(
|
||||
new StringArgument("war")
|
||||
.replaceSuggestions(
|
||||
ArgumentSuggestions.stringCollection(info ->
|
||||
WarData.getWarsNames()
|
||||
)
|
||||
),
|
||||
new StringArgument("town")
|
||||
.replaceSuggestions(
|
||||
ArgumentSuggestions.stringCollection(info -> {
|
||||
final String warname = (String) info.previousArgs().get("war");
|
||||
return CommandHelper.getTownyWarTowns(warname);
|
||||
})
|
||||
),
|
||||
new PlayerArgument("player")
|
||||
.setOptional(true)
|
||||
.withPermission("AlathranWars.admin")
|
||||
)
|
||||
.executesPlayer((Player p, CommandArguments args) -> raidLeave(p, args, false));
|
||||
}
|
||||
|
||||
public static CommandAPICommand commandAbandon() {
|
||||
return new CommandAPICommand("abandon")
|
||||
.withArguments(
|
||||
new StringArgument("war")
|
||||
.replaceSuggestions(
|
||||
ArgumentSuggestions.stringCollection(info ->
|
||||
WarData.getWarsNames()
|
||||
)
|
||||
),
|
||||
new StringArgument("town")
|
||||
.replaceSuggestions(
|
||||
ArgumentSuggestions.stringCollection(info -> {
|
||||
final String warname = (String) info.previousArgs().get("war");
|
||||
return CommandHelper.getTownyWarTowns(warname);
|
||||
})
|
||||
)
|
||||
)
|
||||
.executesPlayer(RaidCommand::raidAbandon);
|
||||
}
|
||||
|
||||
public static CommandAPICommand commandList() {
|
||||
return new CommandAPICommand("list")
|
||||
.executesPlayer(RaidCommand::raidsList);
|
||||
}
|
||||
|
||||
public static CommandAPICommand commandHelp() {
|
||||
return new CommandAPICommand("help")
|
||||
.executesPlayer(RaidCommand::raidHelp);
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts a raid
|
||||
*
|
||||
* @param p
|
||||
* @param args
|
||||
*/
|
||||
protected static void raidStart(Player p, CommandArguments args, boolean admin) throws WrapperCommandSyntaxException {
|
||||
boolean warFound = false;
|
||||
boolean townExists = false;
|
||||
|
||||
if (!(args.get("war") instanceof final String argWarName))
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(new ColorParser(UtilsChat.getPrefix() + "&cUsage: /alathranwarsadmin create raid [war] [raidTown] (gatherTown/\"defaultCode\") (owner) (override)").build());
|
||||
|
||||
for (final OldWar oldWar : WarData.getWars()) {
|
||||
if (oldWar.getName().equalsIgnoreCase(argWarName)) {
|
||||
warFound = true;
|
||||
|
||||
final Player raidOwner = (Player) args.getOptional("leader").orElse(p);
|
||||
|
||||
if (raidOwner == null) {
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(new ColorParser("OldRaid Owner is Null").build());
|
||||
}
|
||||
|
||||
TownyWorld townyWorld;
|
||||
townyWorld = WorldCoord.parseWorldCoord(raidOwner.getLocation()).getTownyWorld();
|
||||
|
||||
String side;
|
||||
if (oldWar.getSide1Players().contains(raidOwner.getName())) {
|
||||
side = oldWar.getSide1();
|
||||
} else if (oldWar.getSide2Players().contains(raidOwner.getName())) {
|
||||
side = oldWar.getSide2();
|
||||
} else {
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(new ColorParser(UtilsChat.getPrefix() + "You are not in this oldWar! Type /oldWar join [oldWar] [side]").build());
|
||||
}
|
||||
|
||||
//Minuteman countermeasures
|
||||
int minuteman = CommandHelper.isPlayerMinuteman(raidOwner.getName());
|
||||
boolean minuteManOverride = (boolean) args.getOptional("minutemen").orElse(false);
|
||||
|
||||
if (minuteManOverride) {
|
||||
p.sendMessage(ChatColor.RED + "Warning! Ignoring Minuteman Countermeasure!");
|
||||
}
|
||||
|
||||
//minuteManOverride?
|
||||
if (!minuteManOverride) {
|
||||
if (minuteman != 0) {
|
||||
if (minuteman == 1) {
|
||||
//player has joined to recently
|
||||
if (admin)
|
||||
p.sendMessage(ChatColor.RED + "You have joined the server too recently! You can only join a raid after " + Main.getInstance().getConfig().getInt("minimumPlayerAge") + " days from joining.");
|
||||
raidOwner.sendMessage(ChatColor.RED + "You have joined the server too recently! You can only join a raid after " + Main.getInstance().getConfig().getInt("minimumPlayerAge") + " days from joining.");
|
||||
return;
|
||||
} else if (minuteman == 2) {
|
||||
//player has played too little
|
||||
if (admin)
|
||||
p.sendMessage(ChatColor.RED + "You have not played enough! You can only join a raid after " + Main.getInstance().getConfig().getInt("minimumPlayTime") + " hours of play.");
|
||||
raidOwner.sendMessage(ChatColor.RED + "You have not played enough! You can only join a raid after " + Main.getInstance().getConfig().getInt("minimumPlayTime") + " hours of play.");
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//check if in a town
|
||||
//takes the command runners town as the gather point
|
||||
Town gatherTown;
|
||||
try {
|
||||
@Nullable String argGatherTown = (String) args.getOptional("gathertown").orElse(null);
|
||||
|
||||
if (admin && argGatherTown != null) {
|
||||
if (argGatherTown.equalsIgnoreCase("defaultCode")) {
|
||||
//use default behavior
|
||||
gatherTown = TownyAPI.getInstance().getTownOrNull(WorldCoord.parseWorldCoord(raidOwner.getLocation()).getTownBlock());
|
||||
} else if (TownyAPI.getInstance().getTown(argGatherTown) != null) {
|
||||
gatherTown = TownyAPI.getInstance().getTown(argGatherTown);
|
||||
} else {
|
||||
if (admin)
|
||||
p.sendMessage(UtilsChat.getPrefix() + "No valid town set for gather town, defaulting to current location");
|
||||
raidOwner.sendMessage(UtilsChat.getPrefix() + "No valid town set for gather town, defaulting to current location");
|
||||
gatherTown = TownyAPI.getInstance().getTownOrNull(WorldCoord.parseWorldCoord(raidOwner.getLocation()).getTownBlock());
|
||||
}
|
||||
} else {
|
||||
gatherTown = TownyAPI.getInstance().getTownOrNull(WorldCoord.parseWorldCoord(raidOwner.getLocation()).getTownBlock());
|
||||
}
|
||||
} catch (NotRegisteredException e2) {
|
||||
if (admin)
|
||||
p.sendMessage(UtilsChat.getPrefix() + "You must be within a town's claim to begin a raid. That town you are in will be the gathering town.");
|
||||
raidOwner.sendMessage(UtilsChat.getPrefix() + "You must be within a town's claim to begin a raid. That town you are in will be the gathering town.");
|
||||
return;
|
||||
}
|
||||
if (gatherTown == null) {
|
||||
if (admin)
|
||||
p.sendMessage(UtilsChat.getPrefix() + "You must be within a town's claim to begin a raid. That town you are in will be the gathering town.");
|
||||
raidOwner.sendMessage(UtilsChat.getPrefix() + "You must be within a town's claim to begin a raid. That town you are in will be the gathering town.");
|
||||
return;
|
||||
}
|
||||
|
||||
//parse the argunment for town
|
||||
for (final String entry : townyWorld.getTowns().keySet()) {
|
||||
final Town raidedTown = townyWorld.getTowns().get(entry);
|
||||
|
||||
//if this is run as admin, shift our check forward a slot
|
||||
if (raidedTown.getName().equalsIgnoreCase((String) args.get("town")) && gatherTown != null) {
|
||||
|
||||
Main.warLogger.log("Raided town: " + raidedTown.getName());
|
||||
Main.warLogger.log("Gather town: " + gatherTown.getName());
|
||||
Main.warLogger.log("OldRaid Owner: " + raidOwner.getName());
|
||||
p.sendMessage("Raided town: " + raidedTown.getName());
|
||||
p.sendMessage("Gather town: " + gatherTown.getName());
|
||||
p.sendMessage("OldRaid Owner: " + raidOwner.getName());
|
||||
//DEBUG PRINT
|
||||
for (String t : oldWar.getSide1Towns()) {
|
||||
Main.warLogger.log("Side1 town: " + t);
|
||||
p.sendMessage("Side1 town: " + t);
|
||||
}
|
||||
for (String t : oldWar.getSide2Towns()) {
|
||||
Main.warLogger.log("Side2 town: " + t);
|
||||
p.sendMessage("Side2 town: " + t);
|
||||
}
|
||||
|
||||
//check if the town were attempting to raid is in the oldWar
|
||||
if (!oldWar.getSide1Towns().contains(raidedTown.getName().toLowerCase()) && !oldWar.getSide2Towns().contains(raidedTown.getName().toLowerCase())) {
|
||||
if (oldWar.getSurrenderedTowns().contains(raidedTown.getName().toLowerCase())) {
|
||||
if (admin)
|
||||
p.sendMessage(UtilsChat.getPrefix() + "The town you are trying to raid has already surrendered!");
|
||||
raidOwner.sendMessage(UtilsChat.getPrefix() + "The town you are trying to raid has already surrendered!");
|
||||
return;
|
||||
}
|
||||
if (admin)
|
||||
p.sendMessage(UtilsChat.getPrefix() + "The town you are trying to raid is not part of the oldWar!");
|
||||
raidOwner.sendMessage(UtilsChat.getPrefix() + "The town you are trying to raid is not part of the oldWar!");
|
||||
return;
|
||||
}
|
||||
|
||||
// Is being sieged check
|
||||
for (OldSiege s : SiegeData.getSieges()) {
|
||||
if (s.getTown().getName().equalsIgnoreCase(raidedTown.getName())) {
|
||||
raidOwner.sendMessage(UtilsChat.getPrefix() + "That town is already currently being sieged! Cannot raid at this time!");
|
||||
if (admin)
|
||||
p.sendMessage(UtilsChat.getPrefix() + "That town is already currently being sieged! Cannot raid at this time!");
|
||||
}
|
||||
}
|
||||
|
||||
townExists = true;
|
||||
|
||||
OldRaid oldRaid2;
|
||||
if (oldWar.getSide1Players().contains(raidOwner.getName())) {
|
||||
//Time and raid activity validity check
|
||||
int c = RaidData.isValidRaid(oldWar, side, raidedTown);
|
||||
if (c == 2) {
|
||||
//if were admin, see if an owner arg exists, and if so then use it
|
||||
oldRaid2 = new OldRaid(oldWar, raidedTown, gatherTown, true, raidOwner);
|
||||
} else if (c == 1) {
|
||||
if (admin)
|
||||
p.sendMessage(UtilsChat.getPrefix() + "This town is already being raided at this time!");
|
||||
raidOwner.sendMessage(UtilsChat.getPrefix() + "This town is already being raided at this time!");
|
||||
return;
|
||||
} else if (c == 0) {
|
||||
if (admin)
|
||||
p.sendMessage(UtilsChat.getPrefix() + "Your side has raided too recently!");
|
||||
raidOwner.sendMessage(UtilsChat.getPrefix() + "Your side has raided too recently!");
|
||||
return;
|
||||
} else if (c == -1) {
|
||||
if (admin)
|
||||
p.sendMessage(UtilsChat.getPrefix() + "This town was raided too recently!");
|
||||
raidOwner.sendMessage(UtilsChat.getPrefix() + "This town was raided too recently!");
|
||||
return;
|
||||
} else if (c == -2) {
|
||||
if (admin)
|
||||
p.sendMessage(UtilsChat.getPrefix() + "At least on member of the raided town must be online to defend it!");
|
||||
raidOwner.sendMessage(UtilsChat.getPrefix() + "At least on member of the raided town must be online to defend it!");
|
||||
return;
|
||||
} else {
|
||||
throw new IllegalArgumentException();
|
||||
}
|
||||
} else {
|
||||
//Something broke if this runs
|
||||
if (!oldWar.getSide2Players().contains(raidOwner.getName())) {
|
||||
Bukkit.getLogger().info("Unable to find player declaring raid in the oldWar");
|
||||
return;
|
||||
}
|
||||
//Time and raid activity validity check
|
||||
int c = RaidData.isValidRaid(oldWar, side, raidedTown);
|
||||
if (c == 2) {
|
||||
oldRaid2 = new OldRaid(oldWar, raidedTown, gatherTown, false, raidOwner);
|
||||
} else if (c == 1) {
|
||||
if (admin)
|
||||
p.sendMessage(UtilsChat.getPrefix() + "This town is already being raided at this time!");
|
||||
raidOwner.sendMessage(UtilsChat.getPrefix() + "This town is already being raided at this time!");
|
||||
return;
|
||||
} else if (c == 0) {
|
||||
if (admin)
|
||||
p.sendMessage(UtilsChat.getPrefix() + "Your side has raided too recently!");
|
||||
raidOwner.sendMessage(UtilsChat.getPrefix() + "Your side has raided too recently!");
|
||||
return;
|
||||
} else if (c == -1) {
|
||||
if (admin)
|
||||
p.sendMessage(UtilsChat.getPrefix() + "This town was raided too recently!");
|
||||
raidOwner.sendMessage(UtilsChat.getPrefix() + "This town was raided too recently!");
|
||||
return;
|
||||
} else if (c == -2) {
|
||||
if (admin)
|
||||
p.sendMessage(UtilsChat.getPrefix() + "At least on member of the raided town must be online to defend it!");
|
||||
raidOwner.sendMessage(UtilsChat.getPrefix() + "At least on member of the raided town must be online to defend it!");
|
||||
return;
|
||||
} else {
|
||||
throw new IllegalArgumentException();
|
||||
}
|
||||
}
|
||||
|
||||
// Player participance check
|
||||
Town leaderTown = TownyAPI.getInstance().getResident(raidOwner).getTownOrNull();
|
||||
TownWarState sideR = oldWar.getState(leaderTown.getName().toLowerCase());
|
||||
if (sideR == TownWarState.NOT_PARTICIPANT) {
|
||||
if (admin) p.sendMessage(UtilsChat.getPrefix() + "You are not in this oldWar.");
|
||||
raidOwner.sendMessage(UtilsChat.getPrefix() + "You are not in this oldWar.");
|
||||
return;
|
||||
} else if (sideR == TownWarState.SURRENDERED) {
|
||||
if (admin) p.sendMessage(UtilsChat.getPrefix() + "You have surrendered.");
|
||||
raidOwner.sendMessage(UtilsChat.getPrefix() + "You have surrendered.");
|
||||
return;
|
||||
}
|
||||
|
||||
// Attacking own side
|
||||
if (oldWar.getState(raidedTown) == sideR) {
|
||||
if (admin) p.sendMessage(UtilsChat.getPrefix() + "You cannot attack your own towns.");
|
||||
raidOwner.sendMessage(UtilsChat.getPrefix() + "You cannot attack your own towns.");
|
||||
return;
|
||||
}
|
||||
|
||||
//check player balance
|
||||
final OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(raidOwner.getUniqueId());
|
||||
if (Main.econ.getBalance(offlinePlayer) <= 1000.0) {
|
||||
if (admin)
|
||||
p.sendMessage(UtilsChat.getPrefix() + "You must have at least $1000 to put up to start a raid.");
|
||||
raidOwner.sendMessage(UtilsChat.getPrefix() + "You must have at least $1000 to put up to start a raid.");
|
||||
return;
|
||||
}
|
||||
|
||||
//publish raid
|
||||
Main.econ.withdrawPlayer(offlinePlayer, 1000);
|
||||
oldRaid2.addActiveRaider(raidOwner.getName());
|
||||
RaidData.addRaid(oldRaid2);
|
||||
oldRaid2.start(); //funny funny method haha
|
||||
WarData.saveWar(oldRaid2.getWar());
|
||||
|
||||
//broadcast
|
||||
Bukkit.broadcastMessage(UtilsChat.getPrefix() + "As part of " + oldWar.getName() + ", forces from " + oldRaid2.getRaiderSide() + " are gathering to raid the town of " + raidedTown.getName() + "!");
|
||||
Bukkit.broadcastMessage(UtilsChat.getPrefix() + "All players from the defending side have been drafted for the town's defense.");
|
||||
Bukkit.broadcastMessage(UtilsChat.getPrefix() + "The raid of "
|
||||
+ raidedTown.getName() + " will begin in " + (RaidPhase.TRAVEL.startTick / 20 / 60) + " minutes!");
|
||||
Bukkit.broadcastMessage(UtilsChat.getPrefix() +
|
||||
"The Raiders are gathering at " + gatherTown.getName() + " before making the journey over!");
|
||||
|
||||
Main.warLogger.log(raidOwner.getName() + " started a raid.");
|
||||
if (admin) {
|
||||
Main.warLogger.log(raidOwner.getName() + " started a raid from admin interference.");
|
||||
p.sendMessage(Helper.color("&cForcefully started raid from the console."));
|
||||
}
|
||||
Main.warLogger.log("As part of " + oldWar.getName() + ", forces from " + oldRaid2.getRaiderSide() + " are raiding the town of " + raidedTown.getName() + "!");
|
||||
Main.warLogger.log("The Raiders are gathering at " + gatherTown.getName() + " before making the journey over!");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!warFound) {
|
||||
p.sendMessage(UtilsChat.getPrefix() + "That war does not exist! /raid start [war] [town]");
|
||||
return;
|
||||
}
|
||||
if (!townExists) {
|
||||
p.sendMessage(UtilsChat.getPrefix() + "That town does not exist! /raid start [war] [town]");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Stops the current raid by admins
|
||||
*
|
||||
* @param p
|
||||
* @param args
|
||||
*/
|
||||
private static void raidStop(Player p, CommandArguments args) throws WrapperCommandSyntaxException {
|
||||
if (!(args.get("war") instanceof final String argWarName))
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(new ColorParser(UtilsChat.getPrefix() + "&cYou need to specify a war name!").build());
|
||||
|
||||
if (!(args.get("town") instanceof final String argTown))
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(new ColorParser(UtilsChat.getPrefix() + "&cYou need to specify a town name!").build());
|
||||
|
||||
|
||||
//are there even any raids
|
||||
if (RaidData.getRaids().isEmpty()) {
|
||||
fail(p, args, "noRaids");
|
||||
}
|
||||
|
||||
//find our desired oldRaid and stop it
|
||||
OldRaid oldRaid = RaidData.getRaid(argWarName + "-" + argTown);
|
||||
|
||||
if (oldRaid != null) {
|
||||
p.sendMessage(UtilsChat.getPrefix() + "oldRaid cancelled");
|
||||
Bukkit.broadcastMessage(UtilsChat.getPrefix() + "The oldRaid of " + oldRaid.getRaidedTown().getName() + " has been cancelled by an admin");
|
||||
oldRaid.stop(); //this purges itself from raids
|
||||
} else {
|
||||
fail(p, args, "badName");
|
||||
}
|
||||
}
|
||||
|
||||
protected static void raidJoin(Player p, CommandArguments args, boolean admin) throws WrapperCommandSyntaxException {
|
||||
if (!(args.get("oldRaid") instanceof final String argRaidName))
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(new ColorParser(UtilsChat.getPrefix() + "&cYou need to specify a oldRaid name!").build());
|
||||
|
||||
if (!(args.get("side") instanceof final String argSide))
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(new ColorParser(UtilsChat.getPrefix() + "&cYou need to specify a side!").build());
|
||||
|
||||
final OldRaid oldRaid = RaidData.getRaid(argRaidName);
|
||||
if (oldRaid == null)
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(new ColorParser(UtilsChat.getPrefix() + "&cThat oldRaid does not exist!").build());
|
||||
|
||||
final OldWar oldWar = oldRaid.getWar();
|
||||
if (oldWar == null)
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(new ColorParser(UtilsChat.getPrefix() + "&cThe oldWar does not exist!").build());
|
||||
|
||||
final Player joiner = (Player) args.getOptional("player").orElse(p);
|
||||
if (joiner == null)
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(new ColorParser("Joiner is Null").build());
|
||||
|
||||
|
||||
if (admin) {
|
||||
if (argSide != null) {
|
||||
if (argSide.equalsIgnoreCase(oldRaid.getDefenderSide())) {
|
||||
if (!oldRaid.getDefenderPlayers().contains(joiner.getName()))
|
||||
oldRaid.getDefenderPlayers().add(joiner.getName());
|
||||
|
||||
p.sendMessage(UtilsChat.getPrefix() + "Player " + joiner.getName() + " added to defender side.");
|
||||
Main.warLogger.log("Player " + joiner.getName() + " added to defender side.");
|
||||
joiner.sendMessage(UtilsChat.getPrefix() + "You were forcefully added to the defender side against the oldRaid party on " + oldRaid.getRaidedTown() + " by an admin.");
|
||||
return;
|
||||
} else {
|
||||
if (!oldRaid.getRaiderPlayers().contains(joiner.getName()))
|
||||
oldRaid.getRaiderPlayers().add(joiner.getName());
|
||||
|
||||
p.sendMessage(UtilsChat.getPrefix() + "Player " + joiner.getName() + " added to raider side.");
|
||||
Main.warLogger.log("Player " + joiner.getName() + " added to raider side.");
|
||||
joiner.sendMessage(UtilsChat.getPrefix() + "You were forcefully added to the oldRaid party on " + oldRaid.getRaidedTown() + " by an admin. Leaving the gather town will remove you from the oldRaid party.");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
if (!oldRaid.getWar().getSide1Players().contains(joiner.getName()) && !oldRaid.getWar().getSide2Players().contains(joiner.getName())) {
|
||||
joiner.sendMessage(UtilsChat.getPrefix() + "You are not in this oldWar! Type /oldWar join [oldWar] [side]");
|
||||
}
|
||||
|
||||
//Minutemen countermeasures, 86400 * 4 time. 86400 seconds in a day, 4 days min playtime
|
||||
//also 12 hours min platim by default
|
||||
int minuteman = CommandHelper.isPlayerMinuteman(joiner.getName());
|
||||
boolean minuteManOverride = (boolean) args.getOptional("minutemen").orElse(false);
|
||||
|
||||
if (minuteManOverride) {
|
||||
p.sendMessage(ChatColor.RED + "Warning! Ignoring Minuteman Countermeasure!");
|
||||
}
|
||||
|
||||
if (!minuteManOverride) {
|
||||
if (minuteman != 0) {
|
||||
if (minuteman == 1) {
|
||||
//player has joined to recently
|
||||
if (admin)
|
||||
p.sendMessage(ChatColor.RED + "You have joined the server too recently! You can only join a oldRaid after " + Main.getInstance().getConfig().getInt("minimumPlayerAge") + " days from joining.");
|
||||
joiner.sendMessage(ChatColor.RED + "You have joined the server too recently! You can only join a oldRaid after " + Main.getInstance().getConfig().getInt("minimumPlayerAge") + " days from joining.");
|
||||
return;
|
||||
} else if (minuteman == 2) {
|
||||
//player has played too little
|
||||
if (admin)
|
||||
p.sendMessage(ChatColor.RED + "You have not played enough! You can only join a oldRaid after " + Main.getInstance().getConfig().getInt("minimumPlayTime") + " hours of play.");
|
||||
joiner.sendMessage(ChatColor.RED + "You have not played enough! You can only join a oldRaid after " + Main.getInstance().getConfig().getInt("minimumPlayTime") + " hours of play.");
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//check if gather phase
|
||||
if (!admin) {
|
||||
if (oldRaid.getPhase() == RaidPhase.GATHER || oldRaid.getPhase() == RaidPhase.START) {
|
||||
try {
|
||||
//check if the player is in the gather town
|
||||
ArrayList<WorldCoord> cluster = Utils.getCluster(oldRaid.getGatherTown().getHomeBlock().getWorldCoord());
|
||||
if (cluster.contains(WorldCoord.parseWorldCoord(joiner))) {
|
||||
oldRaid.addActiveRaider(joiner.getName());
|
||||
joiner.sendMessage(UtilsChat.getPrefix() + "You have joined the oldRaid on " + oldRaid.getRaidedTown().getName() + "!");
|
||||
joiner.sendMessage(UtilsChat.getPrefix() + "Leaving " + oldRaid.getGatherTown().getName() + " will cause you to leave the oldRaid party.");
|
||||
} else {
|
||||
joiner.sendMessage(UtilsChat.getPrefix() + "You must be in the gathering town to join the oldRaid on " + oldRaid.getRaidedTown().getName() + ".");
|
||||
}
|
||||
} catch (TownyException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
} else {
|
||||
joiner.sendMessage(UtilsChat.getPrefix() + "You cannot join the oldRaid on " + oldRaid.getRaidedTown().getName() + "! It has already started!");
|
||||
}
|
||||
} else {
|
||||
try {
|
||||
//check if the player is in the gather town
|
||||
ArrayList<WorldCoord> cluster = Utils.getCluster(oldRaid.getGatherTown().getHomeBlock().getWorldCoord());
|
||||
if (cluster.contains(WorldCoord.parseWorldCoord(joiner))) {
|
||||
oldRaid.addActiveRaider(joiner.getName());
|
||||
joiner.sendMessage(UtilsChat.getPrefix() + "You have joined the oldRaid on " + oldRaid.getRaidedTown().getName() + "!");
|
||||
joiner.sendMessage(UtilsChat.getPrefix() + "Leaving " + oldRaid.getGatherTown().getName() + " will cause you to leave the oldRaid party.");
|
||||
} else {
|
||||
joiner.sendMessage(UtilsChat.getPrefix() + "You must be in the gathering town to join the oldRaid on " + oldRaid.getRaidedTown().getName() + ".");
|
||||
}
|
||||
} catch (TownyException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
oldRaid.save();
|
||||
}
|
||||
|
||||
protected static void raidLeave(Player player, CommandArguments args, boolean admin) throws WrapperCommandSyntaxException {
|
||||
//Get oldRaid!
|
||||
final Player p = (Player) args.getOptional("player").orElse(player);
|
||||
|
||||
if (p == null) {
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(new ColorParser("Raider is Null").build());
|
||||
}
|
||||
|
||||
if (!(args.get("war") instanceof final String argWarName))
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(new ColorParser(UtilsChat.getPrefix() + "&cYou need to specify a war name!").build());
|
||||
|
||||
if (!(args.get("town") instanceof final String argTown))
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(new ColorParser(UtilsChat.getPrefix() + "&cYou need to specify a town name!").build());
|
||||
|
||||
|
||||
OldRaid oldRaid = RaidData.getRaid(argWarName + "-" + argTown);
|
||||
if (oldRaid == null) {
|
||||
p.sendMessage(UtilsChat.getPrefix() + "No oldRaid is gathering in this town or this town does not exist!");
|
||||
if (admin)
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(new ColorParser(UtilsChat.getPrefix() + "No oldRaid is gathering in this town or this town does not exist!").build());
|
||||
}
|
||||
|
||||
if (oldRaid.getWar().getName().equalsIgnoreCase(argWarName)) {
|
||||
if (!oldRaid.getWar().getSide1Players().contains(p.getName()) && !oldRaid.getWar().getSide2Players().contains(p.getName())) {
|
||||
p.sendMessage(UtilsChat.getPrefix() + "You are not in this war! Type /war join [war] [side]");
|
||||
if (admin)
|
||||
player.sendMessage(UtilsChat.getPrefix() + "You are not in this war! Type /war join [war] [side]");
|
||||
}
|
||||
|
||||
//check if gather phase
|
||||
if (oldRaid.getPhase() == RaidPhase.GATHER || oldRaid.getPhase() == RaidPhase.START) {
|
||||
try {
|
||||
//check if player is in gather town
|
||||
ArrayList<WorldCoord> cluster = Utils.getCluster(oldRaid.getGatherTown().getHomeBlock().getWorldCoord());
|
||||
if (cluster.contains(WorldCoord.parseWorldCoord(p))) {
|
||||
oldRaid.removeActiveRaider(p.getName());
|
||||
p.sendMessage(UtilsChat.getPrefix() + "You have left the oldRaid on " + oldRaid.getRaidedTown().getName() + "!");
|
||||
if (admin)
|
||||
player.sendMessage(UtilsChat.getPrefix() + "You have left the oldRaid on " + oldRaid.getRaidedTown().getName() + "!");
|
||||
|
||||
} else {
|
||||
p.sendMessage(UtilsChat.getPrefix() + "You cannot leave the oldRaid on " + oldRaid.getRaidedTown().getName() + "! It has already started!");
|
||||
if (admin)
|
||||
player.sendMessage(UtilsChat.getPrefix() + "You cannot leave the oldRaid on " + oldRaid.getRaidedTown().getName() + "! It has already started!");
|
||||
}
|
||||
} catch (TownyException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
if (admin) {
|
||||
player.sendMessage(UtilsChat.getPrefix() + "Forced player " + p.getName() + " to leave oldRaid on " + oldRaid.getRaidedTown().getName() + " in war " + argWarName);
|
||||
Main.warLogger.log("Forced player " + p.getName() + " to leave oldRaid on " + oldRaid.getRaidedTown().getName() + " in war " + argWarName);
|
||||
}
|
||||
}
|
||||
|
||||
oldRaid.save();
|
||||
}
|
||||
|
||||
/**
|
||||
* Abandons the raid
|
||||
*
|
||||
* @param p
|
||||
* @param args
|
||||
*/
|
||||
private static void raidAbandon(Player p, CommandArguments args) throws WrapperCommandSyntaxException {
|
||||
if (!(args.get("war") instanceof final String argWarName))
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(new ColorParser(UtilsChat.getPrefix() + "&cYou need to specify a war name!").build());
|
||||
|
||||
if (!(args.get("town") instanceof final String argTown))
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(new ColorParser(UtilsChat.getPrefix() + "&cYou need to specify a town name!").build());
|
||||
|
||||
|
||||
//Get oldRaid
|
||||
OldRaid oldRaid = RaidData.getRaid(argWarName + "-" + argTown);
|
||||
|
||||
if (oldRaid == null)
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(new ColorParser(UtilsChat.getPrefix() + "&cThis oldRaid does not exist!").build());
|
||||
|
||||
|
||||
if (oldRaid.getWar().getName().equalsIgnoreCase(argWarName)) {
|
||||
if (!oldRaid.getWar().getSide1Players().contains(p.getName()) && !oldRaid.getWar().getSide2Players().contains(p.getName())) {
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(new ColorParser(UtilsChat.getPrefix() + "&cYou are not in this war! Type /war join [war] [side]").build());
|
||||
}
|
||||
|
||||
if (oldRaid.getOwner().getName().equalsIgnoreCase(p.getName())) {
|
||||
//check if gather phase
|
||||
if (oldRaid.getPhase() == RaidPhase.GATHER || oldRaid.getPhase() == RaidPhase.START || oldRaid.getPhase() == RaidPhase.TRAVEL || oldRaid.getPhase() == RaidPhase.COMBAT) {
|
||||
//force defender victory
|
||||
Bukkit.broadcast(new ColorParser(UtilsChat.getPrefix() + "The oldRaid on " + oldRaid.getRaidedTown().getName() + " has been abandoned by " + oldRaid.getRaiderSide()).build());
|
||||
Main.warLogger.log(p.getName() + " abandoned the oldRaid on " + oldRaid.getRaidedTown().getName() + " they started at " + oldRaid.getGatherTown().getName());
|
||||
oldRaid.defendersWin(oldRaid.getRaiderScore(), oldRaid.getDefenderScore());
|
||||
} else {
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(new ColorParser(UtilsChat.getPrefix() + "&cYou cannot abandon the oldRaid on " + oldRaid.getRaidedTown().getName() + "! It has a problem!").build());
|
||||
}
|
||||
} else {
|
||||
fail(p, args, "owner");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void raidsList(Player p, CommandArguments args) {
|
||||
if (RaidData.getRaids().isEmpty()) {
|
||||
p.sendMessage(new ColorParser(UtilsChat.getPrefix() + "There are currently no Raids in progress").build());
|
||||
return;
|
||||
}
|
||||
|
||||
p.sendMessage(new ColorParser(UtilsChat.getPrefix() + "Raids currently in progress:").build());
|
||||
for (final OldRaid oldRaid : RaidData.getRaids()) {
|
||||
p.sendMessage(new ColorParser("Name: " + oldRaid.getName()).build());
|
||||
p.sendMessage(new ColorParser("OldWar: " + oldRaid.getWar().getName()).build());
|
||||
p.sendMessage(new ColorParser("Owner: " + oldRaid.getOwner().getName()).build());
|
||||
p.sendMessage(new ColorParser("Raiding: " + oldRaid.getRaidedTown().getName().toLowerCase()).build());
|
||||
p.sendMessage(new ColorParser("Gathering In: " + oldRaid.getGatherTown().getName().toLowerCase()).build());
|
||||
p.sendMessage(new ColorParser("Raiders: " + oldRaid.getRaiderSide()).build());
|
||||
p.sendMessage(new ColorParser("Defenders: " + oldRaid.getDefenderSide()).build());
|
||||
p.sendMessage(new ColorParser("Raider Score: " + oldRaid.getRaiderScore()).build());
|
||||
p.sendMessage(new ColorParser("Defender Score: " + oldRaid.getDefenderScore()).build());
|
||||
p.sendMessage(new ColorParser("OldRaid Phase: " + oldRaid.getPhase().name()).build());
|
||||
p.sendMessage(new ColorParser("Time Left: " + (RaidPhase.END.startTick - oldRaid.getRaidTicks()) / 1200 + " minutes").build());
|
||||
p.sendMessage(new ColorParser("-=-=-=-=-=-=-=-=-=-=-=-").build());
|
||||
}
|
||||
}
|
||||
|
||||
private static void raidHelp(Player p, CommandArguments args) {
|
||||
if (p.hasPermission("AlathranWars.admin")) {
|
||||
p.sendMessage(new ColorParser(UtilsChat.getPrefix() + "/raid stop [name]").build());
|
||||
}
|
||||
p.sendMessage(new ColorParser(UtilsChat.getPrefix() + "/raid start [war] [town]").build());
|
||||
p.sendMessage(new ColorParser(UtilsChat.getPrefix() + "/raid join [war] [town]").build());
|
||||
p.sendMessage(new ColorParser(UtilsChat.getPrefix() + "/raid leave [war] [town]").build());
|
||||
p.sendMessage(new ColorParser(UtilsChat.getPrefix() + "/raid abandon [war] [town]").build());
|
||||
p.sendMessage(new ColorParser(UtilsChat.getPrefix() + "/raid list").build());
|
||||
}
|
||||
|
||||
private static void fail(CommandSender p, CommandArguments args, String type) throws WrapperCommandSyntaxException {
|
||||
switch (type) {
|
||||
case "permissions" ->
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(new ColorParser(UtilsChat.getPrefix() + "&cYou do not have permission to do this.").build());
|
||||
case "syntax" ->
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(new ColorParser(UtilsChat.getPrefix() + "&cInvalid Syntax. /raid help").build());
|
||||
case "noRaids" ->
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(new ColorParser(UtilsChat.getPrefix() + "&cThere are currently no Raids in progress.").build());
|
||||
case "badName" ->
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(new ColorParser(UtilsChat.getPrefix() + "&cA raid could not be found with this Name! Type /raid list to view current raids.").build());
|
||||
case "owner" ->
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(new ColorParser(UtilsChat.getPrefix() + "&cOnly the player who started the raid can abandon it.").build());
|
||||
default ->
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(new ColorParser(UtilsChat.getPrefix() + "&cInvalid Arguments. /raid help").build());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,280 +0,0 @@
|
||||
package me.ShermansWorld.AlathranWars.data;
|
||||
|
||||
import com.palmergames.bukkit.towny.TownyAPI;
|
||||
import com.palmergames.bukkit.towny.object.Resident;
|
||||
import com.palmergames.bukkit.towny.object.Town;
|
||||
import com.palmergames.bukkit.towny.object.WorldCoord;
|
||||
import com.palmergames.bukkit.towny.object.metadata.CustomDataField;
|
||||
import com.palmergames.bukkit.towny.object.metadata.LongDataField;
|
||||
import me.ShermansWorld.AlathranWars.Main;
|
||||
import me.ShermansWorld.AlathranWars.deprecated.OldRaid;
|
||||
import me.ShermansWorld.AlathranWars.deprecated.OldWar;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.OfflinePlayer;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import javax.annotation.Nonnull;
|
||||
import java.util.*;
|
||||
|
||||
@Deprecated
|
||||
public class RaidData {
|
||||
// Static OldRaid list for all active OLD_RAIDS
|
||||
private static final ArrayList<OldRaid> OLD_RAIDS = new ArrayList<>();
|
||||
|
||||
|
||||
public static ArrayList<OldRaid> getRaids() {
|
||||
return OLD_RAIDS;
|
||||
}
|
||||
|
||||
public static void setRaids(ArrayList<OldRaid> oldRaids) {
|
||||
for (OldRaid oldRaid : oldRaids) {
|
||||
addRaid(oldRaid);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a raid with a specific name
|
||||
*
|
||||
* @param name - Name to check
|
||||
* @return OldRaid or Null
|
||||
*/
|
||||
public static @Nullable OldRaid getRaid(String name) {
|
||||
for (OldRaid oldRaid : OLD_RAIDS) {
|
||||
if (oldRaid.getName().equalsIgnoreCase(name)) return oldRaid;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static void addRaid(OldRaid oldRaid) {
|
||||
if (oldRaid == null) {
|
||||
Main.warLogger.log("Attempted to add NULL to oldRaid list.");
|
||||
return;
|
||||
}
|
||||
OLD_RAIDS.add(oldRaid);
|
||||
}
|
||||
|
||||
public static void removeRaid(OldRaid oldRaid) {
|
||||
oldRaid.getWar().getRaids().remove(oldRaid);
|
||||
OLD_RAIDS.remove(oldRaid);
|
||||
|
||||
//deleteRaid(oldRaid);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a raid object from a provided HashMap
|
||||
*
|
||||
* @param fileData
|
||||
* @return OldRaid object
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public static OldRaid fromMap(OldWar oldWar, HashMap<String, Object> fileData) {
|
||||
|
||||
if (fileData.get("raidedTown") == null || fileData.get("gatherTown") == null || fileData.get("side1AreRaiders") == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
Town raidedTown = TownyAPI.getInstance().getTown((String) fileData.get("raidedTown"));
|
||||
Town gatherTown = TownyAPI.getInstance().getTown((String) fileData.get("gatherTown"));
|
||||
boolean attackBoolean = Boolean.parseBoolean((String) fileData.get("side1AreRaiders"));
|
||||
//THIS MAY OR MAY NOT WORK
|
||||
OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(UUID.fromString((String) fileData.get("owner")));
|
||||
|
||||
if (raidedTown == null || gatherTown == null) {
|
||||
return null;
|
||||
}
|
||||
OldRaid oldRaid = new OldRaid(oldWar, raidedTown, gatherTown, attackBoolean, offlinePlayer);
|
||||
|
||||
//Extra properties, if any are missing the oldRaid doesnt exist yet
|
||||
if (fileData.get("raiderScore") != null && fileData.get("defenderScore") != null && fileData.get("raidTicks") != null && fileData.get("raidPhase") != null && fileData.get("activeRaiders") != null && fileData.get("lootedChunks") != null && fileData.get("side1AreRaiders") != null) {
|
||||
//active properties
|
||||
oldRaid.setRaidPhase(RaidPhase.getByName((String) fileData.get("raidPhase")));
|
||||
oldRaid.setRaidTicks((int) fileData.get("raidTicks"));
|
||||
oldRaid.setActiveRaiders((ArrayList<String>) fileData.get("activeRaiders"));
|
||||
oldRaid.setRaiderScore((int) fileData.get("raiderScore"));
|
||||
oldRaid.setDefenderScore((int) fileData.get("defenderScore"));
|
||||
oldRaid.setSide1AreRaiders(Boolean.parseBoolean((String) fileData.get("side1AreRaiders")));
|
||||
|
||||
//looted chunks
|
||||
ArrayList<Object> o = (ArrayList<Object>) fileData.get("lootedChunks");
|
||||
for (Object hm : o) {
|
||||
//grab the chunk
|
||||
HashMap<String, Object> chunk = (HashMap<String, Object>) hm;
|
||||
|
||||
//grab data for this chunk
|
||||
//worldcoord is its own map
|
||||
HashMap<String, Object> wc = (HashMap<String, Object>) chunk.get("worldCoord");
|
||||
WorldCoord worldCoordc = WorldCoord.parseWorldCoord((String) wc.get("world"), ((int) wc.get("x")), ((int) wc.get("z")));
|
||||
int ticks = (int) chunk.get("ticks");
|
||||
double value = (double) chunk.get("value");
|
||||
boolean finished = (boolean) chunk.get("finished");
|
||||
|
||||
//put
|
||||
OldRaid.LootBlock lb = new OldRaid.LootBlock(worldCoordc, ticks, value, finished);
|
||||
oldRaid.getLootedChunks().put(worldCoordc, lb);
|
||||
}
|
||||
}
|
||||
|
||||
return oldRaid;
|
||||
}
|
||||
|
||||
public static ArrayList<OldRaid> createRaids(OldWar oldWar, Collection<HashMap<String, Object>> raidMaps) {
|
||||
ArrayList<OldRaid> returnList = new ArrayList<>();
|
||||
for (HashMap<String, Object> map : raidMaps) {
|
||||
Town town = TownyAPI.getInstance().getTown((String) map.get("raidedTown"));
|
||||
if (town == null) continue;
|
||||
|
||||
OldRaid oldRaid = fromMap(oldWar, map);
|
||||
returnList.add(oldRaid);
|
||||
RaidData.addRaid(oldRaid);
|
||||
oldRaid.resume();
|
||||
}
|
||||
return returnList;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Saves the war into files.
|
||||
*
|
||||
* @param oldRaid - OldWar to be saved.
|
||||
*/
|
||||
public static void saveRaid(OldRaid oldRaid) {
|
||||
OldWar oldWar = oldRaid.getWar();
|
||||
oldWar.save();
|
||||
}
|
||||
|
||||
// /**
|
||||
// * deletes raid, unused
|
||||
// */
|
||||
// private static void deleteRaid(OldWar war) {
|
||||
// File[] files = new File(dataFolderPath + File.separator + "wars").listFiles(ymlFilter);
|
||||
//
|
||||
// for (File file : files) {
|
||||
// if (file.getName().startsWith(war.getName())) {
|
||||
// file.delete();
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
|
||||
/**
|
||||
* Turns a oldRaid into a map
|
||||
*
|
||||
* @param oldRaid - OldRaid
|
||||
* @return Map
|
||||
*/
|
||||
public static HashMap<String, Object> raidToMap(OldRaid oldRaid) {
|
||||
HashMap<String, Object> returnMap = new HashMap<>();
|
||||
// Shoves everything into a map.
|
||||
returnMap.put("name", oldRaid.getName());
|
||||
returnMap.put("raidedTown", oldRaid.getRaidedTown().getName());
|
||||
returnMap.put("gatherTown", oldRaid.getGatherTown().getName());
|
||||
returnMap.put("raidTicks", oldRaid.getRaidTicks());
|
||||
returnMap.put("raidPhase", oldRaid.getPhase().name());
|
||||
returnMap.put("raiderScore", oldRaid.getRaiderScore());
|
||||
returnMap.put("defenderScore", oldRaid.getDefenderScore());
|
||||
returnMap.put("side1AreRaiders", Boolean.toString(oldRaid.getSide1AreRaiders()));
|
||||
returnMap.put("activeRaiders", oldRaid.getActiveRaiders());
|
||||
//THIS MAY OR MAY NOT WORK
|
||||
returnMap.put("owner", oldRaid.getOwner().getUniqueId().toString());
|
||||
|
||||
//create a list from the looted chunks
|
||||
final List<Object> chunkList = getChunkList(oldRaid);
|
||||
|
||||
returnMap.put("lootedChunks", chunkList);
|
||||
|
||||
return returnMap;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
private static List<Object> getChunkList(OldRaid oldRaid) {
|
||||
List<Object> chunkList = new ArrayList<>();
|
||||
for (OldRaid.LootBlock b : oldRaid.getLootedChunks().values()) {
|
||||
HashMap<String, Object> blockMap = new HashMap<>();
|
||||
//worldcoord
|
||||
HashMap<String, Object> wcMap = new HashMap<>();
|
||||
wcMap.put("world", b.worldCoord.getWorldName());
|
||||
wcMap.put("x", b.worldCoord.getCoord().getX());
|
||||
wcMap.put("z", b.worldCoord.getCoord().getZ());
|
||||
blockMap.put("worldCoord", wcMap);
|
||||
//properties
|
||||
blockMap.put("ticks", b.ticks);
|
||||
blockMap.put("value", b.value);
|
||||
blockMap.put("finished", b.finished);
|
||||
chunkList.add(blockMap);
|
||||
}
|
||||
return chunkList;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a map of raid maps
|
||||
*
|
||||
* @param oldWar - OldWar to map
|
||||
* @return Map of Maps
|
||||
*/
|
||||
public static HashMap<String, Object> getRaidMap(OldWar oldWar) {
|
||||
HashMap<String, Object> returnMap = new HashMap<>();
|
||||
for (OldRaid oldRaid : oldWar.getRaids()) {
|
||||
returnMap.put(oldRaid.getRaidedTown().getName(), raidToMap(oldRaid));
|
||||
}
|
||||
return returnMap;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return
|
||||
* @Isaac this is for getting when the last raid was on a town
|
||||
*/
|
||||
@SuppressWarnings("rawtypes")
|
||||
public static long whenTownLastRaided(Town town) {
|
||||
if (town.hasMeta("AlathranWars-lastRaided")) {
|
||||
CustomDataField field = town.getMetadata("AlathranWars-lastRaided");
|
||||
if (field != null) {
|
||||
if (field instanceof LongDataField) {
|
||||
return ((LongDataField) field).getValue();
|
||||
}
|
||||
}
|
||||
return -1L;
|
||||
} else {
|
||||
town.addMetaData(new LongDataField("AlathranWars-lastRaided", 0L));
|
||||
}
|
||||
return -1L;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return
|
||||
* @Isaac this is for getting if a town can be raided, return (-2, -1, 0, 1, 2) based on status
|
||||
* (no players online, 24 hours town cooldown, 6 hour oldWar cooldown, town being raided already, valid time to raid)
|
||||
*/
|
||||
public static int isValidRaid(OldWar oldWar, String side, @Nonnull Town town) {
|
||||
long townTime = whenTownLastRaided(town);
|
||||
|
||||
//24 hours town cooldown
|
||||
if ((System.currentTimeMillis() / 1000) - townTime <= 86400) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
//6 hour raid cooldown for oldWar
|
||||
if ((System.currentTimeMillis() / 1000) - (side.equalsIgnoreCase(oldWar.getSide1()) ? oldWar.getLastRaidTimeSide1() : oldWar.getLastRaidTimeSide2()) <= 21600) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
//make sure a player is online in the raided town
|
||||
boolean onlinePlayer = false;
|
||||
for (Resident r : town.getResidents()) {
|
||||
if (r.isOnline()) {
|
||||
onlinePlayer = true;
|
||||
}
|
||||
}
|
||||
if (!onlinePlayer) return -2;
|
||||
|
||||
//check if being raided
|
||||
for (OldRaid oldRaid : oldWar.getRaids()) {
|
||||
if (oldRaid.getRaidedTown().getName().equalsIgnoreCase(town.getName())) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
return 2;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,133 +0,0 @@
|
||||
package me.ShermansWorld.AlathranWars.data;
|
||||
|
||||
import com.palmergames.bukkit.towny.TownyAPI;
|
||||
import com.palmergames.bukkit.towny.object.Town;
|
||||
import me.ShermansWorld.AlathranWars.Main;
|
||||
import me.ShermansWorld.AlathranWars.deprecated.OldSiege;
|
||||
import me.ShermansWorld.AlathranWars.deprecated.OldWar;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.OfflinePlayer;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
@Deprecated
|
||||
public class SiegeData {
|
||||
|
||||
// Static OldSiege list for all active OLD_SIEGES
|
||||
private static final HashSet<OldSiege> OLD_SIEGES = new HashSet<>();
|
||||
|
||||
public static HashSet<OldSiege> getSieges() {
|
||||
return OLD_SIEGES;
|
||||
}
|
||||
|
||||
public static void setSieges(ArrayList<OldSiege> oldSieges) {
|
||||
for (OldSiege oldSiege : oldSieges) {
|
||||
addSiege(oldSiege);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a siege with a specific name
|
||||
*
|
||||
* @param name - Name to check
|
||||
* @return OldSiege or Null
|
||||
*/
|
||||
public static OldSiege getSiege(String name) {
|
||||
for (OldSiege oldSiege : OLD_SIEGES) {
|
||||
if (oldSiege.getTown().getName().equalsIgnoreCase(name)) return oldSiege;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static void addSiege(OldSiege oldSiege) {
|
||||
if (oldSiege == null) {
|
||||
Main.warLogger.log("Attempted to add NULL to oldSiege list.");
|
||||
return;
|
||||
}
|
||||
OLD_SIEGES.add(oldSiege);
|
||||
}
|
||||
|
||||
public static void removeSiege(OldSiege oldSiege) {
|
||||
OLD_SIEGES.remove(oldSiege);
|
||||
//deleteSiege(oldSiege);d
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a siege object from a provided HashMap
|
||||
*
|
||||
* @param fileData data
|
||||
* @return OldSiege object
|
||||
*/
|
||||
private static OldSiege fromMap(OldWar oldWar, HashMap<String, Object> fileData) {
|
||||
|
||||
if (fileData.get("town") == null || fileData.get("side1AreAttackers") == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
Town town = TownyAPI.getInstance().getTown((String) fileData.get("town"));
|
||||
OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(UUID.fromString((String) fileData.get("siegeLeader")));
|
||||
|
||||
return new OldSiege(oldWar, town, offlinePlayer);
|
||||
}
|
||||
|
||||
/**
|
||||
* Saves the war into files.
|
||||
*
|
||||
* @param oldSiege - OldSiege to be saved.
|
||||
*/
|
||||
public static void saveSiege(OldSiege oldSiege) {
|
||||
OldWar oldWar = oldSiege.getWar();
|
||||
oldWar.save();
|
||||
}
|
||||
|
||||
/**
|
||||
* Turns a oldSiege into a map
|
||||
*
|
||||
* @param oldSiege - OldSiege
|
||||
* @return Map
|
||||
*/
|
||||
public static HashMap<String, Object> siegeToMap(OldSiege oldSiege) {
|
||||
HashMap<String, Object> returnMap = new HashMap<>();
|
||||
// Shoves everything into a map.
|
||||
returnMap.put("town", oldSiege.getTown().getName());
|
||||
returnMap.put("siegeTicks", oldSiege.getSiegeTicks());
|
||||
returnMap.put("attackerPoints", oldSiege.getAttackerPoints());
|
||||
returnMap.put("defenderPoints", oldSiege.getDefenderPoints());
|
||||
returnMap.put("side1AreAttackers", Boolean.toString(oldSiege.getSide1AreAttackers()));
|
||||
returnMap.put("siegeLeader", oldSiege.getSiegeLeader().getUniqueId().toString());
|
||||
|
||||
return returnMap;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a map of siege maps
|
||||
*
|
||||
* @param oldWar - OldWar to map
|
||||
* @return Map of Maps
|
||||
*/
|
||||
public static HashMap<String, Object> getSiegeMap(OldWar oldWar) {
|
||||
HashMap<String, Object> returnMap = new HashMap<>();
|
||||
for (OldSiege oldSiege : oldWar.getSieges()) {
|
||||
returnMap.put(oldSiege.getTown().getName(), siegeToMap(oldSiege));
|
||||
}
|
||||
return returnMap;
|
||||
}
|
||||
|
||||
public static ArrayList<OldSiege> createSieges(OldWar oldWar, Collection<HashMap<String, Object>> siegeMaps) {
|
||||
ArrayList<OldSiege> returnList = new ArrayList<>();
|
||||
for (HashMap<String, Object> map : siegeMaps) {
|
||||
Town town = TownyAPI.getInstance().getTown((String) map.get("town"));
|
||||
if (town == null) continue;
|
||||
|
||||
OldSiege oldSiege = fromMap(oldWar, map);
|
||||
oldSiege.addPointsToAttackers((int) map.get("attackerPoints"));
|
||||
oldSiege.addPointsToDefenders((int) map.get("defenderPoints"));
|
||||
oldSiege.resume((int) map.get("siegeTicks"));
|
||||
oldSiege.setWar(oldWar);
|
||||
returnList.add(oldSiege);
|
||||
|
||||
}
|
||||
return returnList;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,185 +0,0 @@
|
||||
package me.ShermansWorld.AlathranWars.data;
|
||||
|
||||
import me.ShermansWorld.AlathranWars.Main;
|
||||
import me.ShermansWorld.AlathranWars.deprecated.OldRaid;
|
||||
import me.ShermansWorld.AlathranWars.deprecated.OldSiege;
|
||||
import me.ShermansWorld.AlathranWars.deprecated.OldWar;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FilenameFilter;
|
||||
import java.util.*;
|
||||
|
||||
@Deprecated
|
||||
public class WarData {
|
||||
|
||||
private final static String dataFolderPath = "plugins" + File.separator + "AlathranWars" + File.separator + "data";
|
||||
// Filter for only accessing yml files
|
||||
private static final FilenameFilter ymlFilter = (dir, name) -> name.endsWith(".yml");
|
||||
// Static OldWar list for all active oldWars
|
||||
private static ArrayList<OldWar> oldWars = new ArrayList<>();
|
||||
|
||||
// Constructor used to initialise folder.
|
||||
public WarData(final Main plugin) {
|
||||
File userDataFolder = new File(dataFolderPath + File.separator + "oldWars");
|
||||
if (!userDataFolder.exists()) {
|
||||
userDataFolder.mkdirs();
|
||||
}
|
||||
}
|
||||
|
||||
public static ArrayList<OldWar> getWars() {
|
||||
return oldWars;
|
||||
}
|
||||
|
||||
public static void setWars(ArrayList<OldWar> oldWars) {
|
||||
WarData.oldWars = oldWars;
|
||||
}
|
||||
|
||||
public static Collection<String> getWarsNames() {
|
||||
List<String> warNames = new ArrayList<>();
|
||||
|
||||
for (OldWar oldWar : getWars()) {
|
||||
warNames.add(oldWar.getName());
|
||||
}
|
||||
|
||||
Collections.sort(warNames);
|
||||
|
||||
return warNames;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a war with a specific name
|
||||
*
|
||||
* @param name - Name to check
|
||||
* @return OldWar or Null
|
||||
*/
|
||||
public static OldWar getWar(String name) {
|
||||
for (OldWar oldWar : oldWars) {
|
||||
if (oldWar.getName().equalsIgnoreCase(name)) return oldWar;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static OldWar getWar(UUID uuid) {
|
||||
for (OldWar oldWar : oldWars) {
|
||||
if (oldWar.getUUID().equals(uuid)) return oldWar;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static void addWar(OldWar oldWar) {
|
||||
if (oldWar == null) {
|
||||
Main.warLogger.log("Attempted to add NULL to oldWar list.");
|
||||
return;
|
||||
}
|
||||
oldWars.add(oldWar);
|
||||
}
|
||||
|
||||
public static void removeWar(OldWar oldWar) {
|
||||
oldWars.remove(oldWar);
|
||||
deleteWar(oldWar);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the oldWars currently saved in files as an ArrayList of OldWar Objects
|
||||
*
|
||||
* @return OldWar Object ArrayList
|
||||
*/
|
||||
public static ArrayList<OldWar> createWars() {
|
||||
File[] files = new File(dataFolderPath + File.separator + "oldWars").listFiles(ymlFilter);
|
||||
|
||||
ArrayList<OldWar> returnList = new ArrayList<>();
|
||||
for (File file : files) {
|
||||
try {
|
||||
HashMap<String, Object> fileData = DataManager.getData(file);
|
||||
OldWar fileOldWar = fromMap(fileData);
|
||||
returnList.add(fileOldWar);
|
||||
} catch (Exception e) {
|
||||
Main.warLogger.log("Failed to load " + file.getName());
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
return returnList;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a war object from a provided HashMap
|
||||
*
|
||||
* @param fileData
|
||||
* @return OldWar object
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public static OldWar fromMap(HashMap<String, Object> fileData) {
|
||||
|
||||
OldWar oldWar = new OldWar((String) fileData.get("name"),
|
||||
(String) fileData.get("side1"),
|
||||
(String) fileData.get("side2")
|
||||
);
|
||||
|
||||
oldWar.setSide1Towns((ArrayList<String>) fileData.get("side1Towns"));
|
||||
oldWar.setSide2Towns((ArrayList<String>) fileData.get("side2Towns"));
|
||||
oldWar.setSurrenderedTowns((ArrayList<String>) fileData.get("surrenderedTowns"));
|
||||
|
||||
oldWar.addSide1Points((int) fileData.get("side1Points"));
|
||||
oldWar.addSide2Points((int) fileData.get("side2Points"));
|
||||
|
||||
if (fileData.get("lastRaidTimeSide1") != null && fileData.get("lastRaidTimeSide2") != null) {
|
||||
oldWar.setLastRaidTimeSide1((int) fileData.get("lastRaidTimeSide1"));
|
||||
oldWar.setLastRaidTimeSide2((int) fileData.get("lastRaidTimeSide2"));
|
||||
}
|
||||
|
||||
|
||||
// OldSiege adding from map.
|
||||
Collection<HashMap<String, Object>> siegeMaps = ((HashMap<String, HashMap<String, Object>>) fileData.get("oldSieges")).values();
|
||||
ArrayList<OldSiege> oldSieges = SiegeData.createSieges(oldWar, siegeMaps);
|
||||
for (OldSiege oldSiege : oldSieges) {
|
||||
oldWar.addSiege(oldSiege);
|
||||
SiegeData.addSiege(oldSiege);
|
||||
}
|
||||
|
||||
// OldRaid adding from map.
|
||||
Collection<HashMap<String, Object>> raidMaps = ((HashMap<String, HashMap<String, Object>>) fileData.get("oldRaids")).values();
|
||||
ArrayList<OldRaid> oldRaids = RaidData.createRaids(oldWar, raidMaps);
|
||||
for (OldRaid oldRaid : oldRaids) {
|
||||
oldWar.addRaid(oldRaid);
|
||||
}
|
||||
|
||||
return oldWar;
|
||||
}
|
||||
|
||||
/**
|
||||
* Saves the oldWar into files.
|
||||
*
|
||||
* @param oldWar - OldWar to be saved.
|
||||
*/
|
||||
public static void saveWar(OldWar oldWar) {
|
||||
HashMap<String, Object> sHashMap = new HashMap<>();
|
||||
|
||||
// Shoves everything into a map.
|
||||
sHashMap.put("name", oldWar.getName());
|
||||
sHashMap.put("side1", oldWar.getSide1());
|
||||
sHashMap.put("side2", oldWar.getSide2());
|
||||
sHashMap.put("side1Towns", oldWar.getSide1Towns());
|
||||
sHashMap.put("side2Towns", oldWar.getSide2Towns());
|
||||
sHashMap.put("surrenderedTowns", oldWar.getSurrenderedTowns());
|
||||
sHashMap.put("side1Points", oldWar.getSide1Points());
|
||||
sHashMap.put("side2Points", oldWar.getSide2Points());
|
||||
|
||||
sHashMap.put("sieges", SiegeData.getSiegeMap(oldWar));
|
||||
sHashMap.put("raids", RaidData.getRaidMap(oldWar));
|
||||
sHashMap.put("lastRaidTimeSide1", oldWar.getLastRaidTimeSide1());
|
||||
sHashMap.put("lastRaidTimeSide2", oldWar.getLastRaidTimeSide2());
|
||||
|
||||
DataManager.saveData("oldWars" + File.separator + oldWar.getName() + ".yml", sHashMap);
|
||||
}
|
||||
|
||||
private static void deleteWar(OldWar oldWar) {
|
||||
File[] files = new File(dataFolderPath + File.separator + "oldWars").listFiles(ymlFilter);
|
||||
for (File file : files) {
|
||||
if (file.getName().startsWith(oldWar.getName())) {
|
||||
file.delete();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
org.gradle.caching=true
|
||||
org.gradle.parallel=true
|
||||
org.gradle.daemon=true
|
||||
org.gradle.jvmargs=-Xmx2048M
|
||||
group=com.github.alathra
|
||||
version=3.0.0
|
||||
description=
|
||||
Vendored
BIN
Binary file not shown.
-7
@@ -1,7 +0,0 @@
|
||||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-8.10.1-bin.zip
|
||||
networkTimeout=10000
|
||||
validateDistributionUrl=true
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
zipStorePath=wrapper/dists
|
||||
@@ -1,252 +0,0 @@
|
||||
#!/bin/sh
|
||||
|
||||
#
|
||||
# Copyright © 2015-2021 the original authors.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# https://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
#
|
||||
|
||||
##############################################################################
|
||||
#
|
||||
# Gradle start up script for POSIX generated by Gradle.
|
||||
#
|
||||
# Important for running:
|
||||
#
|
||||
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
|
||||
# noncompliant, but you have some other compliant shell such as ksh or
|
||||
# bash, then to run this script, type that shell name before the whole
|
||||
# command line, like:
|
||||
#
|
||||
# ksh Gradle
|
||||
#
|
||||
# Busybox and similar reduced shells will NOT work, because this script
|
||||
# requires all of these POSIX shell features:
|
||||
# * functions;
|
||||
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
|
||||
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
|
||||
# * compound commands having a testable exit status, especially «case»;
|
||||
# * various built-in commands including «command», «set», and «ulimit».
|
||||
#
|
||||
# Important for patching:
|
||||
#
|
||||
# (2) This script targets any POSIX shell, so it avoids extensions provided
|
||||
# by Bash, Ksh, etc; in particular arrays are avoided.
|
||||
#
|
||||
# The "traditional" practice of packing multiple parameters into a
|
||||
# space-separated string is a well documented source of bugs and security
|
||||
# problems, so this is (mostly) avoided, by progressively accumulating
|
||||
# options in "$@", and eventually passing that to Java.
|
||||
#
|
||||
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
|
||||
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
|
||||
# see the in-line comments for details.
|
||||
#
|
||||
# There are tweaks for specific operating systems such as AIX, CygWin,
|
||||
# Darwin, MinGW, and NonStop.
|
||||
#
|
||||
# (3) This script is generated from the Groovy template
|
||||
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
|
||||
# within the Gradle project.
|
||||
#
|
||||
# You can find Gradle at https://github.com/gradle/gradle/.
|
||||
#
|
||||
##############################################################################
|
||||
|
||||
# Attempt to set APP_HOME
|
||||
|
||||
# Resolve links: $0 may be a link
|
||||
app_path=$0
|
||||
|
||||
# Need this for daisy-chained symlinks.
|
||||
while
|
||||
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
|
||||
[ -h "$app_path" ]
|
||||
do
|
||||
ls=$( ls -ld "$app_path" )
|
||||
link=${ls#*' -> '}
|
||||
case $link in #(
|
||||
/*) app_path=$link ;; #(
|
||||
*) app_path=$APP_HOME$link ;;
|
||||
esac
|
||||
done
|
||||
|
||||
# This is normally unused
|
||||
# shellcheck disable=SC2034
|
||||
APP_BASE_NAME=${0##*/}
|
||||
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
|
||||
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s
|
||||
' "$PWD" ) || exit
|
||||
|
||||
# Use the maximum available, or set MAX_FD != -1 to use that value.
|
||||
MAX_FD=maximum
|
||||
|
||||
warn () {
|
||||
echo "$*"
|
||||
} >&2
|
||||
|
||||
die () {
|
||||
echo
|
||||
echo "$*"
|
||||
echo
|
||||
exit 1
|
||||
} >&2
|
||||
|
||||
# OS specific support (must be 'true' or 'false').
|
||||
cygwin=false
|
||||
msys=false
|
||||
darwin=false
|
||||
nonstop=false
|
||||
case "$( uname )" in #(
|
||||
CYGWIN* ) cygwin=true ;; #(
|
||||
Darwin* ) darwin=true ;; #(
|
||||
MSYS* | MINGW* ) msys=true ;; #(
|
||||
NONSTOP* ) nonstop=true ;;
|
||||
esac
|
||||
|
||||
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
|
||||
|
||||
|
||||
# Determine the Java command to use to start the JVM.
|
||||
if [ -n "$JAVA_HOME" ] ; then
|
||||
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
|
||||
# IBM's JDK on AIX uses strange locations for the executables
|
||||
JAVACMD=$JAVA_HOME/jre/sh/java
|
||||
else
|
||||
JAVACMD=$JAVA_HOME/bin/java
|
||||
fi
|
||||
if [ ! -x "$JAVACMD" ] ; then
|
||||
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
else
|
||||
JAVACMD=java
|
||||
if ! command -v java >/dev/null 2>&1
|
||||
then
|
||||
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
fi
|
||||
|
||||
# Increase the maximum file descriptors if we can.
|
||||
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
|
||||
case $MAX_FD in #(
|
||||
max*)
|
||||
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
|
||||
# shellcheck disable=SC2039,SC3045
|
||||
MAX_FD=$( ulimit -H -n ) ||
|
||||
warn "Could not query maximum file descriptor limit"
|
||||
esac
|
||||
case $MAX_FD in #(
|
||||
'' | soft) :;; #(
|
||||
*)
|
||||
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
|
||||
# shellcheck disable=SC2039,SC3045
|
||||
ulimit -n "$MAX_FD" ||
|
||||
warn "Could not set maximum file descriptor limit to $MAX_FD"
|
||||
esac
|
||||
fi
|
||||
|
||||
# Collect all arguments for the java command, stacking in reverse order:
|
||||
# * args from the command line
|
||||
# * the main class name
|
||||
# * -classpath
|
||||
# * -D...appname settings
|
||||
# * --module-path (only if needed)
|
||||
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
|
||||
|
||||
# For Cygwin or MSYS, switch paths to Windows format before running java
|
||||
if "$cygwin" || "$msys" ; then
|
||||
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
|
||||
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
|
||||
|
||||
JAVACMD=$( cygpath --unix "$JAVACMD" )
|
||||
|
||||
# Now convert the arguments - kludge to limit ourselves to /bin/sh
|
||||
for arg do
|
||||
if
|
||||
case $arg in #(
|
||||
-*) false ;; # don't mess with options #(
|
||||
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
|
||||
[ -e "$t" ] ;; #(
|
||||
*) false ;;
|
||||
esac
|
||||
then
|
||||
arg=$( cygpath --path --ignore --mixed "$arg" )
|
||||
fi
|
||||
# Roll the args list around exactly as many times as the number of
|
||||
# args, so each arg winds up back in the position where it started, but
|
||||
# possibly modified.
|
||||
#
|
||||
# NB: a `for` loop captures its iteration list before it begins, so
|
||||
# changing the positional parameters here affects neither the number of
|
||||
# iterations, nor the values presented in `arg`.
|
||||
shift # remove old arg
|
||||
set -- "$@" "$arg" # push replacement arg
|
||||
done
|
||||
fi
|
||||
|
||||
|
||||
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
|
||||
|
||||
# Collect all arguments for the java command:
|
||||
# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
|
||||
# and any embedded shellness will be escaped.
|
||||
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
|
||||
# treated as '${Hostname}' itself on the command line.
|
||||
|
||||
set -- \
|
||||
"-Dorg.gradle.appname=$APP_BASE_NAME" \
|
||||
-classpath "$CLASSPATH" \
|
||||
org.gradle.wrapper.GradleWrapperMain \
|
||||
"$@"
|
||||
|
||||
# Stop when "xargs" is not available.
|
||||
if ! command -v xargs >/dev/null 2>&1
|
||||
then
|
||||
die "xargs is not available"
|
||||
fi
|
||||
|
||||
# Use "xargs" to parse quoted args.
|
||||
#
|
||||
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
|
||||
#
|
||||
# In Bash we could simply go:
|
||||
#
|
||||
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
|
||||
# set -- "${ARGS[@]}" "$@"
|
||||
#
|
||||
# but POSIX shell has neither arrays nor command substitution, so instead we
|
||||
# post-process each arg (as a line of input to sed) to backslash-escape any
|
||||
# character that might be a shell metacharacter, then use eval to reverse
|
||||
# that process (while maintaining the separation between arguments), and wrap
|
||||
# the whole thing up as a single "set" statement.
|
||||
#
|
||||
# This will of course break if any of these variables contains a newline or
|
||||
# an unmatched quote.
|
||||
#
|
||||
|
||||
eval "set -- $(
|
||||
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
|
||||
xargs -n1 |
|
||||
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
|
||||
tr '\n' ' '
|
||||
)" '"$@"'
|
||||
|
||||
exec "$JAVACMD" "$@"
|
||||
Vendored
-94
@@ -1,94 +0,0 @@
|
||||
@rem
|
||||
@rem Copyright 2015 the original author or authors.
|
||||
@rem
|
||||
@rem Licensed under the Apache License, Version 2.0 (the "License");
|
||||
@rem you may not use this file except in compliance with the License.
|
||||
@rem You may obtain a copy of the License at
|
||||
@rem
|
||||
@rem https://www.apache.org/licenses/LICENSE-2.0
|
||||
@rem
|
||||
@rem Unless required by applicable law or agreed to in writing, software
|
||||
@rem distributed under the License is distributed on an "AS IS" BASIS,
|
||||
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
@rem See the License for the specific language governing permissions and
|
||||
@rem limitations under the License.
|
||||
@rem
|
||||
@rem SPDX-License-Identifier: Apache-2.0
|
||||
@rem
|
||||
|
||||
@if "%DEBUG%"=="" @echo off
|
||||
@rem ##########################################################################
|
||||
@rem
|
||||
@rem Gradle startup script for Windows
|
||||
@rem
|
||||
@rem ##########################################################################
|
||||
|
||||
@rem Set local scope for the variables with windows NT shell
|
||||
if "%OS%"=="Windows_NT" setlocal
|
||||
|
||||
set DIRNAME=%~dp0
|
||||
if "%DIRNAME%"=="" set DIRNAME=.
|
||||
@rem This is normally unused
|
||||
set APP_BASE_NAME=%~n0
|
||||
set APP_HOME=%DIRNAME%
|
||||
|
||||
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
|
||||
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
|
||||
|
||||
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
|
||||
|
||||
@rem Find java.exe
|
||||
if defined JAVA_HOME goto findJavaFromJavaHome
|
||||
|
||||
set JAVA_EXE=java.exe
|
||||
%JAVA_EXE% -version >NUL 2>&1
|
||||
if %ERRORLEVEL% equ 0 goto execute
|
||||
|
||||
echo. 1>&2
|
||||
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
|
||||
echo. 1>&2
|
||||
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
|
||||
echo location of your Java installation. 1>&2
|
||||
|
||||
goto fail
|
||||
|
||||
:findJavaFromJavaHome
|
||||
set JAVA_HOME=%JAVA_HOME:"=%
|
||||
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
|
||||
|
||||
if exist "%JAVA_EXE%" goto execute
|
||||
|
||||
echo. 1>&2
|
||||
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
|
||||
echo. 1>&2
|
||||
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
|
||||
echo location of your Java installation. 1>&2
|
||||
|
||||
goto fail
|
||||
|
||||
:execute
|
||||
@rem Setup the command line
|
||||
|
||||
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
|
||||
|
||||
|
||||
@rem Execute Gradle
|
||||
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
|
||||
|
||||
:end
|
||||
@rem End local scope for the variables with windows NT shell
|
||||
if %ERRORLEVEL% equ 0 goto mainEnd
|
||||
|
||||
:fail
|
||||
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
|
||||
rem the _cmd.exe /c_ return code!
|
||||
set EXIT_CODE=%ERRORLEVEL%
|
||||
if %EXIT_CODE% equ 0 set EXIT_CODE=1
|
||||
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
|
||||
exit /b %EXIT_CODE%
|
||||
|
||||
:mainEnd
|
||||
if "%OS%"=="Windows_NT" endlocal
|
||||
|
||||
:omega
|
||||
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,70 @@
|
||||
<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>me.ShermansWorld</groupId>
|
||||
<artifactId>AlathraWar</artifactId>
|
||||
<version>2.1.0-Event</version>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<name>AlathraWar</name>
|
||||
<url>http://maven.apache.org</url>
|
||||
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<maven.compiler.source>17</maven.compiler.source>
|
||||
<maven.compiler.target>17</maven.compiler.target>
|
||||
</properties>
|
||||
|
||||
<build>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
</build>
|
||||
|
||||
<repositories>
|
||||
<!-- This adds the Spigot Maven repository to the build -->
|
||||
<repository>
|
||||
<id>papermc</id>
|
||||
<url>https://papermc.io/repo/repository/maven-public/</url>
|
||||
</repository>
|
||||
<repository>
|
||||
<id>jitpack.io</id>
|
||||
<url>https://jitpack.io</url>
|
||||
</repository>
|
||||
<repository>
|
||||
<id>krypton</id>
|
||||
<url>https://repo.kryptonmc.org/releases</url>
|
||||
</repository>
|
||||
</repositories>
|
||||
|
||||
<dependencies>
|
||||
<!--This adds the Spigot API artifact to the build -->
|
||||
<dependency>
|
||||
<groupId>org.spigotmc</groupId>
|
||||
<artifactId>spigot-api</artifactId>
|
||||
<version>1.19-R0.1-SNAPSHOT</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.github.MilkBowl</groupId>
|
||||
<artifactId>VaultAPI</artifactId>
|
||||
<version>1.7</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.github.LlmDl</groupId>
|
||||
<artifactId>Towny</artifactId>
|
||||
<version>0.98.3.3</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>me.neznamy</groupId>
|
||||
<artifactId>tab-api</artifactId>
|
||||
<version>3.2.4</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>
|
||||
@@ -0,0 +1,8 @@
|
||||
#Minimum time in days a player must have joined ago to join any war or event.
|
||||
#Set to 0 to disable check
|
||||
minimumPlayerAge: 4
|
||||
#Minimum playtime in hours a player must have in hours to join a war/siege/raid
|
||||
#Set to 0 to disable check
|
||||
minimumPlayTime: 12
|
||||
#How long should a bettering ram open a door (in seconds)
|
||||
batteringRamEffectiveness: 10
|
||||
@@ -0,0 +1,25 @@
|
||||
name: AlathraWar
|
||||
version: ${project.version}
|
||||
api-version: 1.19
|
||||
author: ShermansWorld
|
||||
main: me.ShermansWorld.AlathraWar.Main
|
||||
depend: [Vault, Towny, TAB]
|
||||
|
||||
commands:
|
||||
war:
|
||||
description: used to create, delete, join and leave wars
|
||||
softdepend: [Vault, Towny, TAB]
|
||||
usage: /war
|
||||
siege:
|
||||
description: used to start, end, and view sieges
|
||||
softdepend: [Vault, Towny]
|
||||
usage: /siege
|
||||
raid:
|
||||
description: used to start, end, and view raids
|
||||
softdepend: [Vault, Towny]
|
||||
usage: /raid
|
||||
alathrawaradmin:
|
||||
description: used to administrate wars and modify existing events
|
||||
softdepend: [Vault, Towny, TAB]
|
||||
usage: /alathrawaradmin
|
||||
aliases: [awa]
|
||||
@@ -1,12 +0,0 @@
|
||||
pluginManagement {
|
||||
repositories {
|
||||
gradlePluginPortal()
|
||||
mavenCentral()
|
||||
}
|
||||
}
|
||||
|
||||
plugins {
|
||||
id("org.gradle.toolchains.foojay-resolver-convention") version "0.8.0" // allow automatic download of JDKs
|
||||
}
|
||||
|
||||
rootProject.name = "AlathranWars"
|
||||
@@ -1,197 +0,0 @@
|
||||
package com.github.alathra.alathranwars;
|
||||
|
||||
import com.github.alathra.alathranwars.commands.CommandHandler;
|
||||
import com.github.alathra.alathranwars.config.ConfigHandler;
|
||||
import com.github.alathra.alathranwars.conflict.war.WarController;
|
||||
import com.github.alathra.alathranwars.database.DatabaseQueries;
|
||||
import com.github.alathra.alathranwars.database.handler.DatabaseHandler;
|
||||
import com.github.alathra.alathranwars.hook.*;
|
||||
import com.github.alathra.alathranwars.listeners.ListenerHandler;
|
||||
import com.github.alathra.alathranwars.translation.TranslationManager;
|
||||
import com.github.alathra.alathranwars.updatechecker.UpdateChecker;
|
||||
import com.github.alathra.alathranwars.utility.Logger;
|
||||
import com.github.milkdrinkers.colorparser.ColorParser;
|
||||
import org.bukkit.plugin.java.JavaPlugin;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import space.arim.morepaperlib.MorePaperLib;
|
||||
|
||||
public class AlathranWars extends JavaPlugin {
|
||||
private static MorePaperLib paperLib;
|
||||
|
||||
private static AlathranWars instance;
|
||||
private ConfigHandler configHandler;
|
||||
private TranslationManager translationManager;
|
||||
private DatabaseHandler databaseHandler;
|
||||
private CommandHandler commandHandler;
|
||||
private ListenerHandler listenerHandler;
|
||||
private UpdateChecker updateChecker;
|
||||
|
||||
// Hooks
|
||||
private static BStatsHook bStatsHook;
|
||||
private static VaultHook vaultHook;
|
||||
private static ProtocolLibHook protocolLibHook;
|
||||
private static PAPIHook papiHook;
|
||||
|
||||
public void onLoad() {
|
||||
instance = this;
|
||||
paperLib = new MorePaperLib(instance);
|
||||
WarController.getInstance();
|
||||
configHandler = new ConfigHandler(instance);
|
||||
translationManager = new TranslationManager(instance);
|
||||
databaseHandler = new DatabaseHandler(configHandler, getComponentLogger());
|
||||
commandHandler = new CommandHandler(instance);
|
||||
listenerHandler = new ListenerHandler(instance);
|
||||
updateChecker = new UpdateChecker();
|
||||
bStatsHook = new BStatsHook(instance);
|
||||
vaultHook = new VaultHook(instance);
|
||||
protocolLibHook = new ProtocolLibHook(instance);
|
||||
papiHook = new PAPIHook(instance);
|
||||
|
||||
configHandler.onLoad();
|
||||
translationManager.onLoad();
|
||||
databaseHandler.onLoad();
|
||||
commandHandler.onLoad();
|
||||
listenerHandler.onLoad();
|
||||
updateChecker.onLoad();
|
||||
bStatsHook.onLoad();
|
||||
vaultHook.onLoad();
|
||||
protocolLibHook.onLoad();
|
||||
papiHook.onLoad();
|
||||
}
|
||||
|
||||
public void onEnable() {
|
||||
configHandler.onEnable();
|
||||
translationManager.onEnable();
|
||||
databaseHandler.onEnable();
|
||||
commandHandler.onEnable();
|
||||
listenerHandler.onEnable();
|
||||
updateChecker.onEnable();
|
||||
bStatsHook.onEnable();
|
||||
vaultHook.onEnable();
|
||||
protocolLibHook.onEnable();
|
||||
papiHook.onEnable();
|
||||
|
||||
if (!databaseHandler.isRunning()) {
|
||||
Logger.get().warn(ColorParser.of("<yellow>Database handler failed to start. Database support has been disabled.").build());
|
||||
}
|
||||
|
||||
if (vaultHook.isVaultLoaded()) {
|
||||
Logger.get().info(ColorParser.of("<green>Vault has been found on this server. Vault support enabled.").build());
|
||||
} else {
|
||||
Logger.get().warn(ColorParser.of("<yellow>Vault is not installed on this server. Vault support has been disabled.").build());
|
||||
}
|
||||
|
||||
if (protocolLibHook.isHookLoaded()) {
|
||||
Logger.get().info(ColorParser.of("<green>ProtocolLib has been found on this server. ProtocolLib support enabled.").build());
|
||||
} else {
|
||||
Logger.get().warn(ColorParser.of("<yellow>ProtocolLib is not installed on this server. ProtocolLib support has been disabled.").build());
|
||||
}
|
||||
|
||||
WarController.getInstance().loadAll();
|
||||
}
|
||||
|
||||
public void onDisable() {
|
||||
getPaperLib().scheduling().cancelGlobalTasks();
|
||||
DatabaseQueries.saveAll();
|
||||
|
||||
configHandler.onDisable();
|
||||
translationManager.onDisable();
|
||||
databaseHandler.onDisable();
|
||||
commandHandler.onDisable();
|
||||
listenerHandler.onDisable();
|
||||
updateChecker.onDisable();
|
||||
bStatsHook.onDisable();
|
||||
vaultHook.onDisable();
|
||||
protocolLibHook.onDisable();
|
||||
papiHook.onDisable();
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets plugin instance.
|
||||
*
|
||||
* @return the plugin instance
|
||||
*/
|
||||
@NotNull
|
||||
public static AlathranWars getInstance() {
|
||||
return instance;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets more paper lib instance.
|
||||
*
|
||||
* @return the more paper lib instance
|
||||
*/
|
||||
public static MorePaperLib getPaperLib() {
|
||||
return paperLib;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets data handler.
|
||||
*
|
||||
* @return the data handler
|
||||
*/
|
||||
@NotNull
|
||||
public DatabaseHandler getDataHandler() {
|
||||
return databaseHandler;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets config handler.
|
||||
*
|
||||
* @return the config handler
|
||||
*/
|
||||
@NotNull
|
||||
public ConfigHandler getConfigHandler() {
|
||||
return configHandler;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets config handler.
|
||||
*
|
||||
* @return the translation handler
|
||||
*/
|
||||
@NotNull
|
||||
public TranslationManager getTranslationManager() {
|
||||
return translationManager;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets update checker.
|
||||
*
|
||||
* @return the update checker
|
||||
*/
|
||||
@NotNull
|
||||
public UpdateChecker getUpdateChecker() {
|
||||
return updateChecker;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets bStats hook.
|
||||
*
|
||||
* @return the bStats hook
|
||||
*/
|
||||
@NotNull
|
||||
public static BStatsHook getBStatsHook() {
|
||||
return bStatsHook;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets vault hook.
|
||||
*
|
||||
* @return the vault hook
|
||||
*/
|
||||
@NotNull
|
||||
public static VaultHook getVaultHook() {
|
||||
return vaultHook;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets ProtocolLib hook.
|
||||
*
|
||||
* @return the ProtocolLib hook
|
||||
*/
|
||||
@NotNull
|
||||
public static ProtocolLibHook getProtocolLibHook() {
|
||||
return protocolLibHook;
|
||||
}
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
package com.github.alathra.alathranwars;
|
||||
|
||||
/**
|
||||
* Implemented in classes that should support being reloaded IE executing the methods during runtime after startup.
|
||||
*/
|
||||
public interface Reloadable {
|
||||
/**
|
||||
* On plugin load.
|
||||
*/
|
||||
void onLoad();
|
||||
|
||||
/**
|
||||
* On plugin enable.
|
||||
*/
|
||||
void onEnable();
|
||||
|
||||
/**
|
||||
* On plugin disable.
|
||||
*/
|
||||
void onDisable();
|
||||
}
|
||||
@@ -1,127 +0,0 @@
|
||||
package com.github.alathra.alathranwars.commands;
|
||||
|
||||
import com.github.alathra.alathranwars.AlathranWars;
|
||||
import com.github.alathra.alathranwars.hook.NameColorHandler;
|
||||
import com.github.alathra.alathranwars.items.WarItemRegistry;
|
||||
import com.github.alathra.alathranwars.utility.UtilsChat;
|
||||
import com.github.milkdrinkers.colorparser.ColorParser;
|
||||
import dev.jorel.commandapi.CommandAPIBukkit;
|
||||
import dev.jorel.commandapi.CommandAPICommand;
|
||||
import dev.jorel.commandapi.arguments.ArgumentSuggestions;
|
||||
import dev.jorel.commandapi.arguments.IntegerArgument;
|
||||
import dev.jorel.commandapi.arguments.PlayerArgument;
|
||||
import dev.jorel.commandapi.arguments.StringArgument;
|
||||
import dev.jorel.commandapi.executors.CommandArguments;
|
||||
import net.kyori.adventure.text.Component;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
public class AdminCommands {
|
||||
public AdminCommands() {
|
||||
new CommandAPICommand("alathranwarsadmin")
|
||||
.withAliases("awa", "wa", "waradmin")
|
||||
.withPermission("AlathranWars.admin")
|
||||
.withSubcommands(
|
||||
commandItem(),
|
||||
commandWar(),
|
||||
commandSiege(),
|
||||
commandNames()
|
||||
)
|
||||
.executes((sender, args) -> {
|
||||
if (args.count() == 0)
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "Invalid Arguments.").build());
|
||||
})
|
||||
.register();
|
||||
}
|
||||
|
||||
private CommandAPICommand commandItem() {
|
||||
return new CommandAPICommand("item")
|
||||
.withArguments(
|
||||
new StringArgument("item")
|
||||
.replaceSuggestions(
|
||||
ArgumentSuggestions.strings(
|
||||
CommandUtil.getWarItems()
|
||||
)
|
||||
),
|
||||
new IntegerArgument("amount").setOptional(true),
|
||||
new PlayerArgument("player").setOptional(true)
|
||||
)
|
||||
.executesPlayer((Player sender, CommandArguments args) -> {
|
||||
// Parse item
|
||||
if (!(args.get("item") instanceof String argItem))
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>Invalid item argument.").build());
|
||||
|
||||
@Nullable ItemStack stack;
|
||||
if (argItem.contains(AlathranWars.getInstance().getName().toLowerCase())) {
|
||||
stack = WarItemRegistry.getInstance().getOrNullNamespace(argItem);
|
||||
} else {
|
||||
stack = WarItemRegistry.getInstance().getOrNull(argItem);
|
||||
}
|
||||
|
||||
if (stack == null)
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>The item is not an AlathranWars item.").build());
|
||||
|
||||
// Parse amount
|
||||
int argAmount = (int) args.getOptional("amount").orElse(1);
|
||||
|
||||
if (argAmount > 64)
|
||||
argAmount = 64;
|
||||
else if (argAmount < 1) {
|
||||
argAmount = 1;
|
||||
}
|
||||
stack.setAmount(argAmount);
|
||||
|
||||
// Determine who gets the item
|
||||
Player argPlayer = (Player) args.getOptional("player").orElse(sender);
|
||||
|
||||
// Give
|
||||
argPlayer.getInventory().addItem(stack);
|
||||
|
||||
final @Nullable Component itemName = stack.getItemMeta() == null ? ColorParser.of(stack.toString()).build() : stack.getItemMeta().displayName();
|
||||
sender.sendMessage(
|
||||
ColorParser.of(
|
||||
"<prefix>Gave <amount>x <item> to <player>."
|
||||
)
|
||||
.parseMinimessagePlaceholder("prefix", UtilsChat.getPrefix())
|
||||
.parseMinimessagePlaceholder("amount", String.valueOf(stack.getAmount()))
|
||||
.parseMinimessagePlaceholder("item", itemName)
|
||||
.parseMinimessagePlaceholder("player", argPlayer.getName())
|
||||
.build()
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
private CommandAPICommand commandWar() {
|
||||
return new CommandAPICommand("war")
|
||||
.withSubcommands(
|
||||
WarCommands.commandCreate(true),
|
||||
WarCommands.commandDelete(true),
|
||||
WarCommands.commandJoin(true),
|
||||
WarCommands.commandJoinNear(),
|
||||
WarCommands.commandSurrender(true),
|
||||
WarCommands.commandList(),
|
||||
WarCommands.commandInfo(),
|
||||
WarCommands.commandKick()
|
||||
);
|
||||
}
|
||||
|
||||
private CommandAPICommand commandSiege() {
|
||||
return new CommandAPICommand("siege")
|
||||
.withSubcommands(
|
||||
SiegeCommands.commandStart(true),
|
||||
SiegeCommands.commandStop(true),
|
||||
SiegeCommands.commandAbandon(true),
|
||||
SiegeCommands.commandSurrender(true),
|
||||
SiegeCommands.commandList()
|
||||
);
|
||||
}
|
||||
|
||||
private CommandAPICommand commandNames() {
|
||||
return new CommandAPICommand("updatenames")
|
||||
.executesPlayer((player, commandArguments) -> {
|
||||
Bukkit.getOnlinePlayers().forEach(p -> NameColorHandler.getInstance().calculatePlayerColors(p));
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
package com.github.alathra.alathranwars.commands;
|
||||
|
||||
import com.github.alathra.alathranwars.AlathranWars;
|
||||
import dev.jorel.commandapi.CommandAPI;
|
||||
import dev.jorel.commandapi.CommandAPIBukkitConfig;
|
||||
|
||||
public class CommandHandler {
|
||||
private final AlathranWars plugin;
|
||||
|
||||
/**
|
||||
* Instantiates the Command handler.
|
||||
*
|
||||
* @param plugin the plugin
|
||||
*/
|
||||
public CommandHandler(AlathranWars plugin) {
|
||||
this.plugin = plugin;
|
||||
}
|
||||
|
||||
public void onLoad() {
|
||||
CommandAPI.onLoad(new CommandAPIBukkitConfig(plugin).shouldHookPaperReload(true).silentLogs(true));
|
||||
}
|
||||
|
||||
public void onEnable() {
|
||||
CommandAPI.onEnable();
|
||||
|
||||
// Register commands
|
||||
new WarCommands();
|
||||
new SiegeCommands();
|
||||
new AdminCommands();
|
||||
}
|
||||
|
||||
public void onDisable() {
|
||||
CommandAPI.onDisable();
|
||||
}
|
||||
}
|
||||
@@ -1,725 +0,0 @@
|
||||
package com.github.alathra.alathranwars.commands;
|
||||
|
||||
import com.github.alathra.alathranwars.AlathranWars;
|
||||
import com.github.alathra.alathranwars.conflict.battle.siege.Siege;
|
||||
import com.github.alathra.alathranwars.conflict.war.War;
|
||||
import com.github.alathra.alathranwars.conflict.war.WarController;
|
||||
import com.github.alathra.alathranwars.conflict.war.side.Side;
|
||||
import com.github.alathra.alathranwars.enums.CommandArgsSiege;
|
||||
import com.github.alathra.alathranwars.enums.CommandArgsWar;
|
||||
import com.github.alathra.alathranwars.items.WarItemRegistry;
|
||||
import com.github.alathra.alathranwars.utility.UtilsChat;
|
||||
import com.github.milkdrinkers.colorparser.ColorParser;
|
||||
import com.palmergames.bukkit.towny.TownyAPI;
|
||||
import com.palmergames.bukkit.towny.object.Nation;
|
||||
import com.palmergames.bukkit.towny.object.Resident;
|
||||
import com.palmergames.bukkit.towny.object.Town;
|
||||
import com.palmergames.bukkit.towny.object.TownyObject;
|
||||
import dev.jorel.commandapi.SuggestionInfo;
|
||||
import dev.jorel.commandapi.arguments.Argument;
|
||||
import dev.jorel.commandapi.arguments.ArgumentSuggestions;
|
||||
import dev.jorel.commandapi.arguments.CustomArgument;
|
||||
import dev.jorel.commandapi.arguments.StringArgument;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.OfflinePlayer;
|
||||
import org.bukkit.Statistic;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
public class CommandUtil {
|
||||
/*public Argument<World> customWorldArgument(String nodeName) {
|
||||
|
||||
// Construct our CustomArgument that takes in a String input and returns a World object
|
||||
return new CustomArgument<World, String>(new StringArgument(nodeName), info -> {
|
||||
// Parse the world from our input
|
||||
World world = Bukkit.getWorld(info.input());
|
||||
|
||||
if (world == null) {
|
||||
throw CustomArgumentException.fromMessageBuilder(new MessageBuilder("Unknown world: ").appendArgInput());
|
||||
} else {
|
||||
return world;
|
||||
}
|
||||
}).replaceSuggestions(ArgumentSuggestions.strings(info ->
|
||||
// List of world names on the server
|
||||
Bukkit.getWorlds().stream().map(World::getName).toArray(String[]::new))
|
||||
);
|
||||
}*/
|
||||
|
||||
static public Argument<Nation> customNationArgument(String nodeName) {
|
||||
return new CustomArgument<>(new StringArgument(nodeName), info -> {
|
||||
final String argNationName = info.input();
|
||||
|
||||
if (TownyAPI.getInstance().getNation(argNationName) == null)
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>The nation does not exist!").parseLegacy().build());
|
||||
|
||||
return TownyAPI.getInstance().getNation(argNationName);
|
||||
}).replaceSuggestions(ArgumentSuggestions.stringCollection(info -> {
|
||||
final @NotNull List<String> nationNames = TownyAPI.getInstance().getNations()
|
||||
.stream()
|
||||
.map(Nation::getName)
|
||||
.sorted()
|
||||
.collect(Collectors.toList());
|
||||
|
||||
return nationNames;
|
||||
}));
|
||||
}
|
||||
|
||||
static public Argument<Town> customTownArgument(String nodeName) {
|
||||
return new CustomArgument<>(new StringArgument(nodeName), info -> {
|
||||
final String argTownName = info.input();
|
||||
|
||||
if (TownyAPI.getInstance().getTown(argTownName) == null)
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>The town does not exist!").parseLegacy().build());
|
||||
|
||||
return TownyAPI.getInstance().getTown(argTownName);
|
||||
}).replaceSuggestions(ArgumentSuggestions.stringCollection(info -> {
|
||||
final @NotNull List<String> townNames = TownyAPI.getInstance().getTowns()
|
||||
.stream()
|
||||
.map(Town::getName)
|
||||
.sorted()
|
||||
.collect(Collectors.toList());
|
||||
|
||||
return townNames;
|
||||
}));
|
||||
}
|
||||
|
||||
static public Argument<Nation> customNationNotInWarArgument(String nodeName, String warNodeName, boolean hideNationsInWar) {
|
||||
return new CustomArgument<>(new StringArgument(nodeName), info -> {
|
||||
final String argNationName = info.input();
|
||||
|
||||
if (TownyAPI.getInstance().getNation(argNationName) == null)
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>The nation does not exist!").parseLegacy().build());
|
||||
|
||||
if (!hideNationsInWar || !(info.previousArgs().get(warNodeName) instanceof War war))
|
||||
return TownyAPI.getInstance().getNation(argNationName);
|
||||
|
||||
@Nullable Nation nation = TownyAPI.getInstance().getNation(argNationName);
|
||||
|
||||
if (war.getNations().contains(nation) || war.getNationsSurrendered().contains(nation))
|
||||
return nation;
|
||||
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>The nation is already at war!").parseLegacy().build());
|
||||
}).replaceSuggestions(ArgumentSuggestions.stringCollection(info -> {
|
||||
final @NotNull List<String> nationNames = TownyAPI.getInstance().getNations()
|
||||
.stream()
|
||||
.map(Nation::getName)
|
||||
.sorted()
|
||||
.collect(Collectors.toList());
|
||||
final @NotNull List<String> townNames = TownyAPI.getInstance().getTowns()
|
||||
.stream()
|
||||
.map(Town::getName)
|
||||
.sorted()
|
||||
.toList();
|
||||
|
||||
nationNames.addAll(townNames);
|
||||
|
||||
// Only proceed after this if we want to remove town already in the specified war
|
||||
if (!hideNationsInWar || !(info.previousArgs().get(warNodeName) instanceof War war))
|
||||
return nationNames;
|
||||
|
||||
final @NotNull List<String> removeNames = Stream.concat( // Create a list of all nations in war
|
||||
war.getNations().stream().map(Nation::getName),
|
||||
war.getNationsSurrendered().stream().map(Nation::getName)
|
||||
).toList();
|
||||
|
||||
nationNames.removeAll(removeNames);
|
||||
|
||||
return nationNames;
|
||||
}));
|
||||
}
|
||||
|
||||
static public Argument<Town> customTownNotInWarArgument(String nodeName, String warNodeName, boolean hideTownsInWar) {
|
||||
return new CustomArgument<>(new StringArgument(nodeName), info -> {
|
||||
final String argTownName = info.input();
|
||||
|
||||
if (TownyAPI.getInstance().getTown(argTownName) == null)
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>The town does not exist!").parseLegacy().build());
|
||||
|
||||
if (!hideTownsInWar || !(info.previousArgs().get(warNodeName) instanceof War war))
|
||||
return TownyAPI.getInstance().getTown(argTownName);
|
||||
|
||||
@Nullable Town town = TownyAPI.getInstance().getTown(argTownName);
|
||||
|
||||
if (war.getTowns().contains(town) || war.getTownsSurrendered().contains(town))
|
||||
return town;
|
||||
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>The town is already at war!").parseLegacy().build());
|
||||
}).replaceSuggestions(ArgumentSuggestions.stringCollection(info -> {
|
||||
final @NotNull List<String> townNames = TownyAPI.getInstance().getTowns()
|
||||
.stream()
|
||||
.map(Town::getName)
|
||||
.sorted()
|
||||
.collect(Collectors.toList());
|
||||
|
||||
// Only proceed after this if we want to remove town already in the specified war
|
||||
if (!hideTownsInWar || !(info.previousArgs().get(warNodeName) instanceof War war))
|
||||
return townNames;
|
||||
|
||||
final @NotNull List<String> removeNames = Stream.concat( // Create a list of all nations & towns in war
|
||||
war.getTowns().stream().map(Town::getName),
|
||||
war.getTownsSurrendered().stream().map(Town::getName)
|
||||
).toList();
|
||||
|
||||
townNames.removeAll(removeNames);
|
||||
|
||||
return townNames;
|
||||
}));
|
||||
}
|
||||
|
||||
static public Argument<Nation> customNationInWarArgument(String nodeName, String warNodeName) {
|
||||
return new CustomArgument<>(new StringArgument(nodeName), info -> {
|
||||
if (!(info.previousArgs().get(warNodeName) instanceof War war))
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>The war does not exist!").parseLegacy().build());
|
||||
|
||||
@Nullable Nation nation = TownyAPI.getInstance().getNation(info.input());
|
||||
|
||||
if (nation == null)
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>The nation does not exist!").parseLegacy().build());
|
||||
|
||||
if (!war.isInWar(nation))
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>The nation is not in that war!").parseLegacy().build());
|
||||
|
||||
return nation;
|
||||
}).replaceSuggestions(ArgumentSuggestions.stringCollection(info -> {
|
||||
if (!(info.previousArgs().get(warNodeName) instanceof War war))
|
||||
return Collections.emptyList();
|
||||
|
||||
return Stream.concat( // Create a list of all nations & towns in war
|
||||
war.getNations().stream().map(Nation::getName),
|
||||
war.getNationsSurrendered().stream().map(Nation::getName)
|
||||
).sorted().toList();
|
||||
}));
|
||||
}
|
||||
|
||||
static public Argument<Town> customTownInWarArgument(String nodeName, String warNodeName) {
|
||||
return new CustomArgument<>(new StringArgument(nodeName), info -> {
|
||||
if (!(info.previousArgs().get(warNodeName) instanceof War war))
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>The war does not exist!").parseLegacy().build());
|
||||
|
||||
@Nullable Town town = TownyAPI.getInstance().getTown(info.input());
|
||||
|
||||
if (town == null)
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>The town does not exist!").parseLegacy().build());
|
||||
|
||||
if (!war.isInWar(town))
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>The town is not in that war!").parseLegacy().build());
|
||||
|
||||
return town;
|
||||
}).replaceSuggestions(ArgumentSuggestions.stringCollection(info -> {
|
||||
if (!(info.previousArgs().get(warNodeName) instanceof War war))
|
||||
return Collections.emptyList();
|
||||
|
||||
return Stream.concat( // Create a list of all nations & towns in war
|
||||
war.getTowns().stream().map(Town::getName),
|
||||
war.getTownsSurrendered().stream().map(Town::getName)
|
||||
).sorted().toList();
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* Accepts all towns and nations as argument. Returns a string.
|
||||
*
|
||||
* @param nodeName the node name
|
||||
* @param warNodeName the war node name
|
||||
* @param hideTownsInWar the hide towns in war
|
||||
* @return the town or nation UUID
|
||||
*/
|
||||
static public Argument<UUID> customTownAndNationArgument(String nodeName, String warNodeName, boolean hideTownsInWar) {
|
||||
return new CustomArgument<>(new StringArgument(nodeName), info -> {
|
||||
final String argTownOrNationName = info.input();
|
||||
|
||||
@Nullable Town town = TownyAPI.getInstance().getTown(argTownOrNationName);
|
||||
|
||||
if (town != null)
|
||||
return town.getUUID();
|
||||
|
||||
@Nullable Nation nation = TownyAPI.getInstance().getNation(argTownOrNationName);
|
||||
|
||||
if (nation != null)
|
||||
return nation.getUUID();
|
||||
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(
|
||||
ColorParser.of(UtilsChat.getPrefix() + "<red>The town or nation <name> does not exist!")
|
||||
.parseMinimessagePlaceholder("name", argTownOrNationName)
|
||||
.build()
|
||||
);
|
||||
}).replaceSuggestions(ArgumentSuggestions.stringCollection(info -> {
|
||||
final @NotNull List<String> nationNames = TownyAPI.getInstance().getNations()
|
||||
.stream()
|
||||
.map(Nation::getName)
|
||||
.sorted()
|
||||
.collect(Collectors.toList());
|
||||
final @NotNull List<String> townNames = TownyAPI.getInstance().getTowns()
|
||||
.stream()
|
||||
.map(Town::getName)
|
||||
.sorted()
|
||||
.toList();
|
||||
|
||||
nationNames.addAll(townNames);
|
||||
|
||||
// Only proceed after this if we want to remove town already in the specified war
|
||||
if (!hideTownsInWar || !(info.previousArgs().get(warNodeName) instanceof War war))
|
||||
return nationNames;
|
||||
|
||||
final @NotNull List<String> removeNames = Stream.concat( // Create a list of all nations & towns in war
|
||||
war.getNations().stream().map(Nation::getName),
|
||||
Stream.concat(
|
||||
war.getNationsSurrendered().stream().map(Nation::getName),
|
||||
Stream.concat(
|
||||
war.getTowns().stream().map(Town::getName),
|
||||
war.getTownsSurrendered().stream().map(Town::getName)
|
||||
)
|
||||
)
|
||||
).toList();
|
||||
|
||||
nationNames.removeAll(removeNames);
|
||||
|
||||
return nationNames;
|
||||
}));
|
||||
}
|
||||
|
||||
static public Argument<UUID> playerOrTownOrNationInWar(String nodeName, String warNodeName) {
|
||||
return new CustomArgument<>(new StringArgument(nodeName), info -> {
|
||||
final String argPlayerOrTownOrNationName = info.input();
|
||||
|
||||
if (!(info.previousArgs().get(warNodeName) instanceof War war)) {
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(
|
||||
ColorParser.of(UtilsChat.getPrefix() + "<red>The war does not exist!")
|
||||
.build()
|
||||
);
|
||||
}
|
||||
|
||||
final List<String> townNames = war.getTownsAll().stream().map(Town::getName).sorted().toList();
|
||||
final List<String> nationNames = war.getNationsAll().stream().map(Nation::getName).sorted().toList();
|
||||
final List<String> playerNames = war.getPlayersAll().stream()
|
||||
.filter(offlinePlayer -> Instant.ofEpochMilli(offlinePlayer.getLastSeen()).isAfter(Instant.now().minus(Duration.ofDays(60)))) // Remove players that haven't been on in 60 days
|
||||
.filter(p -> p.getName() != null)
|
||||
.map(OfflinePlayer::getName)
|
||||
.sorted()
|
||||
.toList();
|
||||
|
||||
|
||||
if (townNames.contains(argPlayerOrTownOrNationName) && TownyAPI.getInstance().getTown(argPlayerOrTownOrNationName) != null)
|
||||
return TownyAPI.getInstance().getTown(argPlayerOrTownOrNationName).getUUID();
|
||||
|
||||
if (nationNames.contains(argPlayerOrTownOrNationName) && TownyAPI.getInstance().getNation(argPlayerOrTownOrNationName) != null)
|
||||
return TownyAPI.getInstance().getNation(argPlayerOrTownOrNationName).getUUID();
|
||||
|
||||
if (playerNames.contains(argPlayerOrTownOrNationName))
|
||||
return Bukkit.getOfflinePlayer(argPlayerOrTownOrNationName).getUniqueId();
|
||||
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(
|
||||
ColorParser.of(UtilsChat.getPrefix() + "<red>The player, town or nation <name> is not in the war!")
|
||||
.parseMinimessagePlaceholder("name", argPlayerOrTownOrNationName)
|
||||
.build()
|
||||
);
|
||||
}).replaceSuggestions(ArgumentSuggestions.stringCollection(info -> {
|
||||
if (!(info.previousArgs().get(warNodeName) instanceof War war)) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
|
||||
final List<String> nationNames = war.getNationsAll().stream().map(Nation::getName).sorted().toList();
|
||||
final List<String> townNames = war.getTownsAll().stream().map(Town::getName).sorted().toList();
|
||||
final List<String> playerNames = war.getPlayersAll().stream()
|
||||
.filter(offlinePlayer -> Instant.ofEpochMilli(offlinePlayer.getLastSeen()).isAfter(Instant.now().minus(Duration.ofDays(60)))) // Remove players that haven't been on in 60 days
|
||||
.map(OfflinePlayer::getName)
|
||||
.filter(Objects::nonNull)
|
||||
.sorted()
|
||||
.toList();
|
||||
|
||||
final List<String> recommendations = new ArrayList<>();
|
||||
recommendations.addAll(nationNames);
|
||||
recommendations.addAll(townNames);
|
||||
recommendations.addAll(playerNames);
|
||||
|
||||
return recommendations;
|
||||
}));
|
||||
}
|
||||
|
||||
public static Argument<Town> customSiegeAttackableTownArgument(String nodeName, String warNodeName, final boolean checkIfIn, final boolean checkIfSieged) {
|
||||
return new CustomArgument<>(new StringArgument(nodeName), info -> {
|
||||
if (!(info.previousArgs().get(warNodeName) instanceof War war))
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>The war does not exist!").parseLegacy().build());
|
||||
|
||||
@Nullable Town town = TownyAPI.getInstance().getTown(info.input());
|
||||
|
||||
if (town == null)
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>The town does not exist!").parseLegacy().build());
|
||||
|
||||
if (!war.isInWar(town))
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>The town is not in that war!").parseLegacy().build());
|
||||
|
||||
if (checkIfSieged) {
|
||||
for (@NotNull Siege siege : WarController.getInstance().getSieges()) {
|
||||
if (siege.getTown().getUUID() == town.getUUID())
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>The town is already under siege!").parseLegacy().build());
|
||||
}
|
||||
}
|
||||
|
||||
return town;
|
||||
}).replaceSuggestions(ArgumentSuggestions.stringCollection(info -> {
|
||||
if (!(info.previousArgs().get(warNodeName) instanceof War war))
|
||||
return Collections.emptyList();
|
||||
|
||||
final @NotNull List<String> townNames = new ArrayList<>();
|
||||
|
||||
if (info.sender() instanceof Player p) {
|
||||
if (war.getSide1().isOnSide(p)) {
|
||||
townNames.addAll(war.getSide2().getTowns()
|
||||
.stream()
|
||||
.map(TownyObject::getName)
|
||||
.sorted()
|
||||
.toList()
|
||||
);
|
||||
} else if (war.getSide2().isOnSide(p)) {
|
||||
townNames.addAll(war.getSide1().getTowns()
|
||||
.stream()
|
||||
.map(TownyObject::getName)
|
||||
.sorted()
|
||||
.toList()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return townNames;
|
||||
}));
|
||||
}
|
||||
|
||||
public static Argument<Siege> siegeSiegeArgument(String nodeName, final boolean isAdmin, final CommandArgsSiege checkSiege, final String playerNodeName) {
|
||||
return new CustomArgument<>(new StringArgument(nodeName), info -> {
|
||||
final String argSiegeName = info.input();
|
||||
|
||||
@Nullable UUID siegeUUID = null;
|
||||
for (Siege siege : WarController.getInstance().getSieges()) {
|
||||
if (siege.getName().equals(argSiegeName)) {
|
||||
siegeUUID = siege.getUUID();
|
||||
}
|
||||
}
|
||||
|
||||
final @Nullable Siege siege = WarController.getInstance().getSiege(siegeUUID);
|
||||
if (siege == null)
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>The siege <siege> does not exist!").parseMinimessagePlaceholder("siege", argSiegeName).build());
|
||||
|
||||
switch (checkSiege) {
|
||||
case IN_SIEGE -> {
|
||||
if (isAdmin) {
|
||||
if (!(info.previousArgs().get(playerNodeName) instanceof Player player))
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>The player does not exist!").build());
|
||||
|
||||
if (!siege.isPlayerParticipating(player))
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>The player is already in that war.").build());
|
||||
} else {
|
||||
if (!(info.sender() instanceof Player player))
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>Only players can execute this command!").build());
|
||||
|
||||
if (!siege.isPlayerParticipating(player))
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>You are already in this war.").build());
|
||||
}
|
||||
}
|
||||
case OUT_SIEGE -> {
|
||||
if (isAdmin) {
|
||||
if (!(info.previousArgs().get(playerNodeName) instanceof Player player))
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>The player does not exist!").build());
|
||||
|
||||
if (siege.isPlayerParticipating(player))
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>The player is not in that war.").build());
|
||||
} else {
|
||||
if (!(info.sender() instanceof Player player))
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>Only players can execute this command!").build());
|
||||
|
||||
if (siege.isPlayerParticipating(player))
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>You are not in that war.").build());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return siege;
|
||||
}).replaceSuggestions(ArgumentSuggestions.stringCollection(info -> switch (checkSiege) {
|
||||
case ALL_SIEGES -> siegeAll(info, isAdmin);
|
||||
case IN_SIEGE -> siegeInside(info, isAdmin, playerNodeName);
|
||||
case OUT_SIEGE -> siegeOutside(info, isAdmin, playerNodeName);
|
||||
}));
|
||||
}
|
||||
|
||||
private static List<String> siegeAll(SuggestionInfo<CommandSender> info, final boolean isAdmin) {
|
||||
return WarController.getInstance().getSieges().stream().map(Siege::getName).toList();
|
||||
}
|
||||
|
||||
private static List<String> siegeOutside(SuggestionInfo<CommandSender> info, final boolean isAdmin, final String playerNodeName) {
|
||||
List<String> siegeNames = new ArrayList<>();
|
||||
|
||||
if (isAdmin) {
|
||||
if (info.previousArgs().get(playerNodeName) instanceof Player player) {
|
||||
siegeNames = WarController.getInstance().getSieges().stream().filter(siege -> !siege.isPlayerParticipating(player)).map(Siege::getName).toList();
|
||||
}
|
||||
} else {
|
||||
if (info.sender() instanceof Player player) {
|
||||
siegeNames = WarController.getInstance().getSieges().stream().filter(siege -> !siege.isPlayerParticipating(player)).map(Siege::getName).toList();
|
||||
}
|
||||
}
|
||||
|
||||
return siegeNames;
|
||||
}
|
||||
|
||||
private static List<String> siegeInside(SuggestionInfo<CommandSender> info, final boolean isAdmin, final String playerNodeName) {
|
||||
List<String> siegeNames = new ArrayList<>();
|
||||
|
||||
if (isAdmin) {
|
||||
if (info.previousArgs().get(playerNodeName) instanceof Player player) {
|
||||
siegeNames = WarController.getInstance().getSieges().stream().filter(siege -> siege.isPlayerParticipating(player)).map(Siege::getName).toList();
|
||||
}
|
||||
} else {
|
||||
if (info.sender() instanceof Player player) {
|
||||
siegeNames = WarController.getInstance().getSieges().stream().filter(siege -> siege.isPlayerParticipating(player)).map(Siege::getName).toList();
|
||||
}
|
||||
}
|
||||
|
||||
return siegeNames;
|
||||
}
|
||||
|
||||
public static Argument<War> warWarArgument(String nodeName, final boolean isAdmin, final CommandArgsWar checkWar, final String playerNodeName) {
|
||||
return new CustomArgument<>(new StringArgument(nodeName), info -> {
|
||||
final String argWarName = info.input();
|
||||
|
||||
final @Nullable War war = WarController.getInstance().getWar(argWarName);
|
||||
if (war == null)
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>The war <war> does not exist!").parseMinimessagePlaceholder("war", argWarName).build());
|
||||
|
||||
switch (checkWar) {
|
||||
case IN_WAR -> {
|
||||
if (isAdmin) {
|
||||
if (!(info.previousArgs().get(playerNodeName) instanceof Player player))
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>The player does not exist!").parseLegacy().build());
|
||||
|
||||
if (!war.isInWar(player))
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>The player is already in that war.").parseLegacy().build());
|
||||
} else {
|
||||
if (!(info.sender() instanceof Player player))
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>Only players can execute this command!").parseLegacy().build());
|
||||
|
||||
if (!war.isInWar(player))
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>You are already in this war.").parseLegacy().build());
|
||||
}
|
||||
}
|
||||
case OUT_WAR -> {
|
||||
if (isAdmin) {
|
||||
if (!(info.previousArgs().get(playerNodeName) instanceof Player player))
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>The player does not exist!").parseLegacy().build());
|
||||
|
||||
if (war.isInWar(player))
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>The player is not in that war.").parseLegacy().build());
|
||||
} else {
|
||||
if (!(info.sender() instanceof Player player))
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>Only players can execute this command!").parseLegacy().build());
|
||||
|
||||
if (war.isInWar(player))
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>You are not in that war.").parseLegacy().build());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return war;
|
||||
}).replaceSuggestions(ArgumentSuggestions.stringCollection(info -> switch (checkWar) {
|
||||
case ALL_WARS -> warsAll(info, isAdmin);
|
||||
case IN_WAR -> warsInside(info, isAdmin, playerNodeName);
|
||||
case OUT_WAR -> warsOutside(info, isAdmin, playerNodeName);
|
||||
}));
|
||||
}
|
||||
|
||||
private static List<String> warsAll(SuggestionInfo<CommandSender> info, final boolean isAdmin) {
|
||||
return WarController.getInstance().getWarNames();
|
||||
}
|
||||
|
||||
private static List<String> warsOutside(SuggestionInfo<CommandSender> info, final boolean isAdmin, final String playerNodeName) {
|
||||
List<String> warNames = new ArrayList<>();
|
||||
|
||||
if (isAdmin) {
|
||||
if (info.previousArgs().get(playerNodeName) instanceof Player player) {
|
||||
warNames = WarController.getInstance().getWars().stream().filter(war -> !war.isInWar(player)).map(War::getName).toList();
|
||||
}
|
||||
} else {
|
||||
if (info.sender() instanceof Player player) {
|
||||
warNames = WarController.getInstance().getWars().stream().filter(war -> !war.isInWar(player)).map(War::getName).toList();
|
||||
}
|
||||
}
|
||||
|
||||
return warNames;
|
||||
}
|
||||
|
||||
private static List<String> warsInside(SuggestionInfo<CommandSender> info, final boolean isAdmin, final String playerNodeName) {
|
||||
List<String> warNames = new ArrayList<>();
|
||||
|
||||
if (isAdmin) {
|
||||
if (info.previousArgs().get(playerNodeName) instanceof Player player) {
|
||||
warNames = WarController.getInstance().getWars().stream().filter(war -> war.isInWar(player)).map(War::getName).toList();
|
||||
}
|
||||
} else {
|
||||
if (info.sender() instanceof Player player) {
|
||||
warNames = WarController.getInstance().getWars().stream().filter(war -> war.isInWar(player)).map(War::getName).toList();
|
||||
}
|
||||
}
|
||||
|
||||
return warNames;
|
||||
}
|
||||
|
||||
public static Argument<Side> warSideCreateArgument(final String nodeName, final String warNodeName, final boolean isAdmin, final boolean checkIfIn, final String playerNodeName) {
|
||||
return new CustomArgument<>(new StringArgument(nodeName), info -> {
|
||||
if (!(info.previousArgs().get(warNodeName) instanceof War war))
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>You need to specify a war.").parseLegacy().build());
|
||||
|
||||
final String argSideName = info.input();
|
||||
|
||||
if (!war.isSideValid(argSideName))
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>The side does not exist.").parseLegacy().build());
|
||||
|
||||
final @Nullable Side side = war.getSide(argSideName);
|
||||
|
||||
if (side == null)
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>The side is invalid.").parseLegacy().build());
|
||||
|
||||
if (checkIfIn) {
|
||||
if (isAdmin) {
|
||||
if (!(info.previousArgs().get(playerNodeName) instanceof Player player))
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>The player does not exist!").parseLegacy().build());
|
||||
|
||||
if (side.getPlayersOnline().contains(player))
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>The player is already on that side.").parseLegacy().build());
|
||||
} else {
|
||||
if (!(info.sender() instanceof Player player))
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>Only players can execute this command!").parseLegacy().build());
|
||||
|
||||
if (side.getPlayersOnline().contains(player))
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>You are already on that side.").parseLegacy().build());
|
||||
}
|
||||
}
|
||||
|
||||
return side;
|
||||
}).replaceSuggestions(ArgumentSuggestions.stringCollection(info -> {
|
||||
if (!(info.previousArgs().get(warNodeName) instanceof War war))
|
||||
return Collections.emptyList();
|
||||
|
||||
final @NotNull List<String> sideNames = new ArrayList<>();
|
||||
|
||||
if (checkIfIn) {
|
||||
if (isAdmin) {
|
||||
if (info.previousArgs().get(playerNodeName) instanceof Player player) {
|
||||
for (@NotNull Side side : war.getSides()) {
|
||||
if (!side.getPlayersOnline().contains(player))
|
||||
sideNames.add(side.getName());
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (info.sender() instanceof Player player) {
|
||||
for (@NotNull Side side : war.getSides()) {
|
||||
if (!side.getPlayersOnline().contains(player))
|
||||
sideNames.add(side.getName());
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
sideNames.add(war.getSide1().getName());
|
||||
sideNames.add(war.getSide2().getName());
|
||||
}
|
||||
|
||||
return sideNames;
|
||||
}
|
||||
));
|
||||
}
|
||||
|
||||
public static Argument<String> warTargetCreateArgument(final String nodeName, final String warNodeName, final boolean isAdmin) {
|
||||
return new CustomArgument<>(new StringArgument(nodeName), info -> {
|
||||
final String argTargetName = info.input();
|
||||
|
||||
if (!(info.previousArgs().get(warNodeName) instanceof War war))
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>You need to specify a war.").parseLegacy().build());
|
||||
|
||||
final boolean isNation = TownyAPI.getInstance().getNation(argTargetName) != null;
|
||||
final boolean isTown = TownyAPI.getInstance().getTown(argTargetName) != null;
|
||||
final boolean isPlayer = Bukkit.getPlayer(argTargetName) != null;
|
||||
|
||||
if (isNation && !war.getNations().stream().map(Nation::getName).toList().contains(argTargetName))
|
||||
return argTargetName;
|
||||
|
||||
if (isTown && !war.getTowns().stream().map(Town::getName).toList().contains(argTargetName))
|
||||
return argTargetName;
|
||||
|
||||
if (isPlayer && !war.getPlayersOnline().stream().map(Player::getName).toList().contains(argTargetName))
|
||||
return argTargetName;
|
||||
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>Invalid target.").build());
|
||||
}).replaceSuggestions(ArgumentSuggestions.stringCollection(info -> { // Returns list of every nation, town and player not in the war
|
||||
if (!(info.previousArgs().get(warNodeName) instanceof War war))
|
||||
return Collections.emptyList();
|
||||
|
||||
// Get all participants in war into list
|
||||
final List<String> inWar = Stream.concat(
|
||||
war.getPlayersOnline().stream().map(Player::getName),
|
||||
Stream.concat(
|
||||
war.getNations().stream().map(Nation::getName),
|
||||
war.getTowns().stream().map(Town::getName)
|
||||
)
|
||||
).toList();
|
||||
|
||||
// Make list of all nations, towns and player
|
||||
final List<String> players = Bukkit.getOnlinePlayers().stream().map(Player::getName).toList();
|
||||
final List<String> towns = TownyAPI.getInstance().getTowns().stream().map(Town::getName).toList();
|
||||
final List<String> nations = TownyAPI.getInstance().getNations().stream().map(Nation::getName).toList();
|
||||
|
||||
return Stream.concat(
|
||||
nations.stream(),
|
||||
Stream.concat(
|
||||
towns.stream(),
|
||||
players.stream()
|
||||
)
|
||||
)
|
||||
.filter(string -> !inWar.contains(string)) // Remove participants in te war
|
||||
.toList();
|
||||
}
|
||||
));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param player player to check
|
||||
* @return 0, 1, 2 (good to go, insufficient join, insufficient playtime)
|
||||
*/
|
||||
public static int isPlayerMinuteman(String player) {
|
||||
@Nullable Resident res = TownyAPI.getInstance().getResident(player);
|
||||
if (res != null) {
|
||||
//getInstance registration time
|
||||
long regTime = res.getRegistered();
|
||||
int playTicks = Bukkit.getPlayer(res.getUUID()).getStatistic(Statistic.PLAY_ONE_MINUTE);
|
||||
int out = 0;
|
||||
if (AlathranWars.getInstance().getConfig().getInt("minimumPlayerAge") > 0) {
|
||||
//compare the join date, if they joined less that min age ago it is true
|
||||
if ((System.currentTimeMillis() - regTime) < 86400000L * AlathranWars.getInstance().getConfig().getInt("minimumPlayerAge"))
|
||||
out = 1;
|
||||
}
|
||||
if (AlathranWars.getInstance().getConfig().getInt("minimumPlayTime") > 0) {
|
||||
//check playtime, if its less than min its true
|
||||
if (playTicks < (AlathranWars.getInstance().getConfig().getInt("minimumPlayTime") * (60 * 60 * 20)))
|
||||
out = 2;
|
||||
}
|
||||
|
||||
return out;
|
||||
}
|
||||
//if the player doesnt exist just return true
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* return list of all alathranwars items with namespace
|
||||
*
|
||||
* @return list of all alathranwars items namespaced
|
||||
*/
|
||||
public static @NotNull List<String> getWarItems() {
|
||||
return new ArrayList<>(WarItemRegistry.getInstance().getItemRegistry().keySet());
|
||||
}
|
||||
}
|
||||
@@ -1,236 +0,0 @@
|
||||
package com.github.alathra.alathranwars.commands;
|
||||
|
||||
import com.github.alathra.alathranwars.AlathranWars;
|
||||
import com.github.alathra.alathranwars.conflict.battle.siege.Siege;
|
||||
import com.github.alathra.alathranwars.conflict.war.War;
|
||||
import com.github.alathra.alathranwars.conflict.war.WarController;
|
||||
import com.github.alathra.alathranwars.conflict.war.side.Side;
|
||||
import com.github.alathra.alathranwars.enums.battle.BattleVictoryReason;
|
||||
import com.github.alathra.alathranwars.utility.UtilsChat;
|
||||
import com.github.milkdrinkers.colorparser.ColorParser;
|
||||
import com.palmergames.bukkit.towny.TownyAPI;
|
||||
import com.palmergames.bukkit.towny.object.Resident;
|
||||
import com.palmergames.bukkit.towny.object.Town;
|
||||
import dev.jorel.commandapi.CommandAPIBukkit;
|
||||
import dev.jorel.commandapi.CommandAPICommand;
|
||||
import dev.jorel.commandapi.arguments.PlayerArgument;
|
||||
import dev.jorel.commandapi.exceptions.WrapperCommandSyntaxException;
|
||||
import dev.jorel.commandapi.executors.CommandArguments;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.OfflinePlayer;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.Set;
|
||||
|
||||
import static com.github.alathra.alathranwars.enums.CommandArgsSiege.ALL_SIEGES;
|
||||
import static com.github.alathra.alathranwars.enums.CommandArgsSiege.IN_SIEGE;
|
||||
import static com.github.alathra.alathranwars.enums.CommandArgsWar.ALL_WARS;
|
||||
import static com.github.alathra.alathranwars.enums.CommandArgsWar.IN_WAR;
|
||||
|
||||
public class SiegeCommands {
|
||||
public SiegeCommands() {
|
||||
new CommandAPICommand("siege")
|
||||
.withSubcommands(
|
||||
commandStart(false),
|
||||
commandStop(false),
|
||||
commandAbandon(false),
|
||||
commandSurrender(false),
|
||||
commandList()
|
||||
)
|
||||
.executesPlayer((sender, args) -> {
|
||||
if (args.count() == 0)
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "Invalid Arguments. /siege help").build());
|
||||
})
|
||||
.register();
|
||||
}
|
||||
|
||||
public static CommandAPICommand commandStart(boolean asAdmin) {
|
||||
return new CommandAPICommand("start")
|
||||
// .withPermission("AlathranWars.admin")
|
||||
.withArguments(
|
||||
CommandUtil.warWarArgument(
|
||||
"war",
|
||||
asAdmin,
|
||||
asAdmin ? ALL_WARS : IN_WAR,
|
||||
""
|
||||
),
|
||||
CommandUtil.customSiegeAttackableTownArgument(
|
||||
"town",
|
||||
"war",
|
||||
false,
|
||||
true
|
||||
),
|
||||
new PlayerArgument("leader")
|
||||
.setOptional(!asAdmin)
|
||||
.withPermission("AlathranWars.admin")/*,
|
||||
new BooleanArgument("minutemen")
|
||||
.setOptional(true)
|
||||
.withPermission("AlathranWars.admin")*/
|
||||
)
|
||||
.executesPlayer((Player p, CommandArguments args) -> siegeStart(p, args, asAdmin));
|
||||
}
|
||||
|
||||
public static CommandAPICommand commandStop(boolean asAdmin) {
|
||||
return new CommandAPICommand("stop")
|
||||
.withPermission("AlathranWars.admin")
|
||||
.withArguments(
|
||||
CommandUtil.siegeSiegeArgument("siege", asAdmin, asAdmin ? ALL_SIEGES : IN_SIEGE, "player")
|
||||
)
|
||||
.executesPlayer((Player p, CommandArguments args) -> siegeStop(p, args, asAdmin));
|
||||
}
|
||||
|
||||
public static CommandAPICommand commandAbandon(boolean asAdmin) {
|
||||
return new CommandAPICommand("abandon")
|
||||
.withArguments(
|
||||
CommandUtil.siegeSiegeArgument("siege", asAdmin, asAdmin ? ALL_SIEGES : IN_SIEGE, "player")
|
||||
)
|
||||
.executesPlayer((Player p, CommandArguments args) -> siegeAbandon(p, args, asAdmin));
|
||||
}
|
||||
|
||||
public static CommandAPICommand commandSurrender(boolean asAdmin) {
|
||||
return new CommandAPICommand("surrender")
|
||||
.withArguments(
|
||||
CommandUtil.siegeSiegeArgument("siege", asAdmin, asAdmin ? ALL_SIEGES : IN_SIEGE, "player")
|
||||
)
|
||||
.executesPlayer((Player p, CommandArguments args) -> siegeSurrender(p, args, asAdmin));
|
||||
}
|
||||
|
||||
public static CommandAPICommand commandList() {
|
||||
return new CommandAPICommand("list")
|
||||
.executesPlayer(SiegeCommands::siegeList);
|
||||
}
|
||||
|
||||
protected static void siegeStart(@NotNull Player sender, @NotNull CommandArguments args, boolean asAdmin) throws WrapperCommandSyntaxException {
|
||||
if (!(args.get("war") instanceof final @NotNull War war))
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("<red>You need to specify a war.").build());
|
||||
|
||||
if (!(args.get("town") instanceof final @NotNull Town town))
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("<red>You need to specify a town.").build());
|
||||
|
||||
final @NotNull Player siegeLeader = (Player) args.getOptional("leader").orElse(sender);
|
||||
|
||||
// Player participance check
|
||||
@Nullable Side side = war.getPlayerSide(siegeLeader);
|
||||
if (side == null)
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("<red>You are not in this war.").build());
|
||||
|
||||
if (side.isSurrendered(siegeLeader))
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("<red>You have surrendered and cannot participate in this war.").build());
|
||||
|
||||
if (side.isSiegeGraceActive() && !asAdmin)
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(
|
||||
ColorParser.of("<red>Your side needs to wait <time> minutes before starting another siege.")
|
||||
.parseMinimessagePlaceholder("time", String.valueOf(side.getSiegeGraceCooldown().toMinutes()))
|
||||
.build()
|
||||
);
|
||||
|
||||
// Attacking own side
|
||||
if (side.isOnSide(town) && !side.isSurrendered(town)) {
|
||||
if (asAdmin)
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("<red>You cannot attack your own side.").build());
|
||||
else
|
||||
siegeLeader.sendMessage(ColorParser.of("<red>You cannot attack your own towns.").build());
|
||||
return;
|
||||
}
|
||||
|
||||
final Location location = siegeLeader.getLocation();
|
||||
final Location townLocation = town.getSpawnOrNull();
|
||||
if (townLocation == null)
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("<red>The town you are attacking doesn't have a spawn point set. Contact admin.").build());
|
||||
|
||||
if (!location.getWorld().equals(townLocation.getWorld()))
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("<red>You need to be in the same world as the town you're attacking!").build());
|
||||
|
||||
if (location.distance(townLocation) >= Siege.BATTLEFIELD_START_MAX_RANGE && !asAdmin)
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("<red>You need to be within <range> blocks of the town to start a siege!").parseMinimessagePlaceholder("range", String.valueOf(Siege.BATTLEFIELD_START_MAX_RANGE)).build());
|
||||
|
||||
if (location.distance(townLocation) <= Siege.BATTLEFIELD_START_MIN_RANGE && !asAdmin)
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("<red>You need to be further than <range> blocks away from the town to start a siege!").parseMinimessagePlaceholder("range", String.valueOf(Siege.BATTLEFIELD_START_MIN_RANGE)).build());
|
||||
|
||||
if ((AlathranWars.getVaultHook().isEconomyLoaded() && AlathranWars.getVaultHook().getEconomy().getBalance(siegeLeader) < Siege.SIEGE_VICTORY_MONEY) && !asAdmin)
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("<red>You need to have $<amount> to start a siege!").parseMinimessagePlaceholder("amount", String.valueOf(Siege.SIEGE_VICTORY_MONEY)).build());
|
||||
|
||||
side.setSiegeGrace();
|
||||
Siege siege = new Siege(war, town, siegeLeader);
|
||||
|
||||
war.addSiege(siege);
|
||||
|
||||
Bukkit.broadcast(
|
||||
ColorParser.of(
|
||||
"<prefix>The town of <town> has been put to siege by <side>!"
|
||||
)
|
||||
.parseMinimessagePlaceholder("prefix", UtilsChat.getPrefix())
|
||||
.parseMinimessagePlaceholder("town", town.getName())
|
||||
.parseMinimessagePlaceholder("side", siege.getAttackerSide().getName())
|
||||
.build()
|
||||
);
|
||||
|
||||
siege.start();
|
||||
}
|
||||
|
||||
private static void siegeStop(@NotNull Player sender, @NotNull CommandArguments args, boolean asAdmin) throws WrapperCommandSyntaxException {
|
||||
if (!(args.get("siege") instanceof final @NotNull Siege siege))
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("<red>Invalid siege.").build());
|
||||
|
||||
siege.equalWin(BattleVictoryReason.ADMIN_COMMAND);
|
||||
}
|
||||
|
||||
private static void siegeAbandon(Player p, @NotNull CommandArguments args, boolean asAdmin) throws WrapperCommandSyntaxException {
|
||||
if (!(args.get("siege") instanceof final @NotNull Siege siege))
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("<red>Invalid siege.").build());
|
||||
|
||||
@NotNull OfflinePlayer siegeLeader = siege.getSiegeLeader();
|
||||
if (siegeLeader != p && !asAdmin)
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("<red>You are not the leader of this siege.").build());
|
||||
|
||||
siege.defendersWin(BattleVictoryReason.OPPONENT_RETREAT);
|
||||
}
|
||||
|
||||
private static void siegeSurrender(Player p, @NotNull CommandArguments args, boolean asAdmin) throws WrapperCommandSyntaxException {
|
||||
if (!(args.get("siege") instanceof final @NotNull Siege siege))
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("<red>Invalid siege.").build());
|
||||
|
||||
Town town = siege.getTown();
|
||||
|
||||
@Nullable Resident res = TownyAPI.getInstance().getResident(p);
|
||||
if (res == null)
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("<red>Resident invalid.").build());
|
||||
|
||||
final boolean canKingSurrender = (res.hasNation() && town.hasNation() && res.getNationOrNull().equals(town.getNationOrNull()) && res.isKing());
|
||||
final boolean canMayorSurrender = (res.hasTown() && res.getTownOrNull().equals(town) && res.isMayor());
|
||||
|
||||
if (!asAdmin && !canKingSurrender && !canMayorSurrender)
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("<red>You cannot surrender this town.").build());
|
||||
|
||||
siege.attackersWin(BattleVictoryReason.OPPONENT_RETREAT);
|
||||
}
|
||||
|
||||
private static void siegeList(@NotNull Player sender, CommandArguments args) throws WrapperCommandSyntaxException {
|
||||
Set<Siege> sieges = WarController.getInstance().getSieges();
|
||||
|
||||
if (sieges.isEmpty()) {
|
||||
sender.sendMessage(ColorParser.of("<red>There are no sieges at the moment.").build());
|
||||
return;
|
||||
}
|
||||
|
||||
final StringBuilder msg = new StringBuilder();
|
||||
|
||||
for (Siege siege : sieges) {
|
||||
msg.append("\n<white><bold>%s<reset>".formatted(siege.getName()));
|
||||
msg.append("\n <grey>Progress: <white>%.0f%%".formatted(siege.getSiegeProgressPercentage() * 100));
|
||||
msg.append("\n <grey>Remaining: <white>%s minutes".formatted(String.valueOf(Duration.between(Instant.now(), siege.getEndTime()).toMinutesPart())));
|
||||
msg.append("\n");
|
||||
}
|
||||
|
||||
sender.sendMessage(
|
||||
ColorParser.of(
|
||||
msg.toString()
|
||||
).build()
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,524 +0,0 @@
|
||||
package com.github.alathra.alathranwars.commands;
|
||||
|
||||
import com.github.alathra.alathranwars.conflict.war.War;
|
||||
import com.github.alathra.alathranwars.conflict.war.WarBuilder;
|
||||
import com.github.alathra.alathranwars.conflict.war.WarController;
|
||||
import com.github.alathra.alathranwars.conflict.war.side.Side;
|
||||
import com.github.alathra.alathranwars.conflict.war.side.SideCreationException;
|
||||
import com.github.alathra.alathranwars.hook.NameColorHandler;
|
||||
import com.github.alathra.alathranwars.utility.UtilsChat;
|
||||
import com.github.milkdrinkers.colorparser.ColorParser;
|
||||
import com.palmergames.bukkit.towny.TownyAPI;
|
||||
import com.palmergames.bukkit.towny.object.Nation;
|
||||
import com.palmergames.bukkit.towny.object.Resident;
|
||||
import com.palmergames.bukkit.towny.object.Town;
|
||||
import dev.jorel.commandapi.CommandAPIBukkit;
|
||||
import dev.jorel.commandapi.CommandAPICommand;
|
||||
import dev.jorel.commandapi.arguments.ArgumentSuggestions;
|
||||
import dev.jorel.commandapi.arguments.BooleanArgument;
|
||||
import dev.jorel.commandapi.arguments.GreedyStringArgument;
|
||||
import dev.jorel.commandapi.arguments.PlayerArgument;
|
||||
import dev.jorel.commandapi.exceptions.WrapperCommandSyntaxException;
|
||||
import dev.jorel.commandapi.executors.CommandArguments;
|
||||
import net.kyori.adventure.key.Key;
|
||||
import net.kyori.adventure.sound.Sound;
|
||||
import net.kyori.adventure.title.Title;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.OfflinePlayer;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
|
||||
import static com.github.alathra.alathranwars.enums.CommandArgsWar.*;
|
||||
|
||||
public class WarCommands {
|
||||
public WarCommands() {
|
||||
new CommandAPICommand("war")
|
||||
.withSubcommands(
|
||||
commandCreate(false),
|
||||
commandDelete(false),
|
||||
commandJoin(false),
|
||||
commandSurrender(false),
|
||||
commandList(),
|
||||
commandInfo()
|
||||
)
|
||||
.executesPlayer((sender, args) -> {
|
||||
if (args.count() == 0)
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "Invalid Arguments. /war help").build());
|
||||
})
|
||||
.register();
|
||||
}
|
||||
|
||||
public static CommandAPICommand commandCreate(boolean asAdmin) {
|
||||
return new CommandAPICommand("create")
|
||||
.withPermission("AlathranWars.admin")
|
||||
.withArguments(
|
||||
CommandUtil.customTownAndNationArgument("side1", "war", false),
|
||||
CommandUtil.customTownAndNationArgument("side2", "war", false),
|
||||
new BooleanArgument("event"),
|
||||
new GreedyStringArgument("warlabel")
|
||||
.replaceSuggestions(
|
||||
ArgumentSuggestions.stringCollection(info -> List.of(
|
||||
"Nations War of Conquest",
|
||||
"Nations War for Survival",
|
||||
"Nations War of Liberation"
|
||||
))
|
||||
)
|
||||
)
|
||||
.executesPlayer(WarCommands::warCreate);
|
||||
}
|
||||
|
||||
public static CommandAPICommand commandDelete(boolean asAdmin) {
|
||||
return new CommandAPICommand("delete")
|
||||
.withPermission("AlathranWars.admin")
|
||||
.withArguments(
|
||||
CommandUtil.warWarArgument("war", asAdmin, ALL_WARS, "")
|
||||
)
|
||||
.executesPlayer(WarCommands::warDelete);
|
||||
}
|
||||
|
||||
public static CommandAPICommand commandJoin(boolean asAdmin) {
|
||||
return new CommandAPICommand("join")
|
||||
.withPermission("AlathranWars.war.join")
|
||||
.withArguments(
|
||||
CommandUtil.warWarArgument("war", asAdmin, asAdmin ? ALL_WARS : OUT_WAR, ""),
|
||||
CommandUtil.warSideCreateArgument("side", "war", asAdmin, !asAdmin, ""),
|
||||
CommandUtil.warTargetCreateArgument("target", "war", asAdmin).setOptional(!asAdmin)
|
||||
// new PlayerArgument("player").setOptional(true).withPermission("AlathranWars.admin.join"),
|
||||
// new PlayerArgument("nation").setOptional(true).withPermission("AlathranWars.admin.join"),
|
||||
// new PlayerArgument("town").setOptional(true).withPermission("AlathranWars.admin.join")
|
||||
)
|
||||
.executesPlayer((Player p, CommandArguments args) -> warJoin(p, args, asAdmin));
|
||||
}
|
||||
|
||||
public static CommandAPICommand commandJoinNear() {
|
||||
return new CommandAPICommand("joinnear")
|
||||
.withPermission("AlathranWars.admin")
|
||||
.withArguments(
|
||||
CommandUtil.warWarArgument("war", true, ALL_WARS, ""),
|
||||
CommandUtil.warSideCreateArgument("side", "war", true, false, "")
|
||||
)
|
||||
.executesPlayer((Player p, CommandArguments args) -> warJoinNear(p, args, true));
|
||||
}
|
||||
|
||||
public static CommandAPICommand commandSurrender(boolean asAdmin) {
|
||||
return new CommandAPICommand("surrender")
|
||||
.withArguments(
|
||||
CommandUtil.warWarArgument("war", asAdmin, asAdmin ? ALL_WARS : IN_WAR, "player"),
|
||||
new PlayerArgument("player")
|
||||
.setOptional(true)
|
||||
.withPermission("AlathranWars.admin")
|
||||
)
|
||||
.executesPlayer((Player p, CommandArguments args) -> warSurrender(p, args, false));
|
||||
}
|
||||
|
||||
public static CommandAPICommand commandList() {
|
||||
return new CommandAPICommand("list")
|
||||
.executesPlayer(WarCommands::warList);
|
||||
}
|
||||
|
||||
public static CommandAPICommand commandInfo() {
|
||||
return new CommandAPICommand("info")
|
||||
.withArguments(
|
||||
CommandUtil.warWarArgument("war", false, ALL_WARS, "player")
|
||||
)
|
||||
.executesPlayer(WarCommands::warInfo);
|
||||
}
|
||||
|
||||
public static CommandAPICommand commandKick() {
|
||||
return new CommandAPICommand("kick")
|
||||
.withArguments(
|
||||
CommandUtil.warWarArgument("war", true, ALL_WARS, "player"),
|
||||
CommandUtil.playerOrTownOrNationInWar("target", "war")
|
||||
.withPermission("AlathranWars.admin")
|
||||
)
|
||||
.executesPlayer(WarCommands::warKick);
|
||||
}
|
||||
|
||||
protected static void warCreate(CommandSender p, @NotNull CommandArguments args) throws WrapperCommandSyntaxException {
|
||||
if (!(args.get("warlabel") instanceof final String argLabel))
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>You need to specify a war label.").build());
|
||||
|
||||
if (Objects.equals(args.get("side1"), args.get("side2")))
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>Cannot declare war on oneself.").build());
|
||||
|
||||
final boolean event = (boolean) args.getOrDefault("event", false);
|
||||
|
||||
final UUID uuid1 = (UUID) args.get("side1");
|
||||
final UUID uuid2 = (UUID) args.get("side2");
|
||||
|
||||
// Create new war depending on what argument was specified
|
||||
@Nullable Town town1 = TownyAPI.getInstance().getTown(uuid1);
|
||||
@Nullable Town town2 = TownyAPI.getInstance().getTown(uuid2);
|
||||
|
||||
// Automatically escalate to nation level if possible
|
||||
@Nullable Nation nation1 = town1 == null ? TownyAPI.getInstance().getNation(uuid1) : town1.getNationOrNull();
|
||||
@Nullable Nation nation2 = town2 == null ? TownyAPI.getInstance().getNation(uuid2) : town2.getNationOrNull();
|
||||
|
||||
// Implement permission checking here if this is ever going to be exposed to players
|
||||
|
||||
// Create war depending on what args have been passed, attempt to create nation wars first
|
||||
WarBuilder builder = new WarBuilder()
|
||||
.setUuid(UUID.randomUUID())
|
||||
.setLabel(argLabel)
|
||||
.setEvent(event);
|
||||
if (nation1 != null) {
|
||||
if (nation2 != null) { // Nation vs Nation
|
||||
// Allow civil wars
|
||||
if (nation2.getUUID() != nation1.getUUID()) {
|
||||
builder
|
||||
.setAggressor(nation1)
|
||||
.setVictim(nation2);
|
||||
} else {
|
||||
builder
|
||||
.setAggressor(town1)
|
||||
.setVictim(town2);
|
||||
}
|
||||
} else if (town2 != null) { // Nation vs Town
|
||||
builder
|
||||
.setAggressor(nation1)
|
||||
.setVictim(town2);
|
||||
}
|
||||
} else if (town1 != null) {
|
||||
if (town2 != null) { // Town vs Town
|
||||
builder
|
||||
.setAggressor(town1)
|
||||
.setVictim(town2);
|
||||
} else if (nation2 != null) { // Nation vs Town
|
||||
builder
|
||||
.setAggressor(town1)
|
||||
.setVictim(nation2);
|
||||
}
|
||||
}
|
||||
try {
|
||||
builder.create(); // TODO Add war to list
|
||||
} catch (SideCreationException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
private static void warDelete(Player p, @NotNull CommandArguments args) throws WrapperCommandSyntaxException {
|
||||
War war = (War) args.get("war");
|
||||
if (war == null) return;
|
||||
|
||||
war.draw();
|
||||
}
|
||||
|
||||
protected static void warJoin(Player p, @NotNull CommandArguments args, boolean asAdmin) throws WrapperCommandSyntaxException {
|
||||
War war = (War) args.get("war");
|
||||
if (war == null) return;
|
||||
|
||||
if (!(args.get("side") instanceof final Side side))
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>You need to specify a side.").build());
|
||||
|
||||
// The target or empty string
|
||||
if (!(args.getOptional("target").orElse("") instanceof String targetString))
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>Invalid target name.").build());
|
||||
|
||||
// The target player or sender of the command
|
||||
Player targetPlayer = args.getOptional("target").map(o -> Bukkit.getPlayer((String) o)).orElse(p);
|
||||
|
||||
// Get the player resident
|
||||
@Nullable Resident res = TownyAPI.getInstance().getResident(targetPlayer);
|
||||
if (res == null)
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("<red>Resident invalid.").build());
|
||||
|
||||
// Get nations and towns
|
||||
@Nullable Nation nation = asAdmin ? TownyAPI.getInstance().getNation(targetString) : res.hasNation() ? res.getNationOrNull() : TownyAPI.getInstance().getNation(targetString);
|
||||
@Nullable Town town = asAdmin ? TownyAPI.getInstance().getTown(targetString) : res.hasTown() ? res.getTownOrNull() : TownyAPI.getInstance().getTown(targetString);
|
||||
|
||||
final boolean isArgNation = nation != null;
|
||||
final boolean isArgTown = town != null;
|
||||
final boolean isArgPlayer = targetPlayer != null;
|
||||
|
||||
// If no valid targets
|
||||
if ((!isArgNation && !isArgTown && !isArgPlayer))
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("<red>Invalid target.").build());
|
||||
|
||||
// Check if player can validly join or not
|
||||
final boolean canKingJoin = (res.hasNation() && res.getNationOrNull().equals(nation) && res.isKing() && nation.isKing(res));
|
||||
final boolean canMayorJoin = (res.hasTown() && res.getTownOrNull().equals(town) && res.isMayor() && town.isMayor(res));
|
||||
|
||||
if (!war.isEventWar()) {
|
||||
// Join nation into war
|
||||
if (isArgNation && nation != null && !war.isInWar(nation) && (asAdmin || canKingJoin)) {
|
||||
side.add(nation);
|
||||
nation.getResidents().stream().filter(Resident::isOnline).map(Resident::getPlayer).toList().forEach(player -> NameColorHandler.getInstance().calculatePlayerColors(player));
|
||||
Bukkit.broadcast(
|
||||
ColorParser.of(
|
||||
"<prefix>The nation of <nation> joined the war of <war> on the side of <side>."
|
||||
)
|
||||
.parseMinimessagePlaceholder("prefix", UtilsChat.getPrefix())
|
||||
.parseMinimessagePlaceholder("nation", nation.getName())
|
||||
.parseMinimessagePlaceholder("war", war.getLabel())
|
||||
.parseMinimessagePlaceholder("side", side.getName())
|
||||
.build()
|
||||
);
|
||||
final Title warTitle = Title.title(
|
||||
ColorParser.of("<gradient:#D72A09:#B01F03><u><b>War")
|
||||
.build(),
|
||||
ColorParser.of("<gray><i>You entered the war of <war>!")
|
||||
.parseMinimessagePlaceholder("war", war.getLabel())
|
||||
.build(),
|
||||
Title.Times.times(Duration.ofMillis(500), Duration.ofMillis(3500), Duration.ofMillis(500))
|
||||
);
|
||||
final Sound warSound = Sound.sound(Key.key("entity.wither.spawn"), Sound.Source.VOICE, 0.5f, 1.0F);
|
||||
|
||||
nation.getResidents().stream().filter(Resident::isOnline).map(Resident::getPlayer).toList().forEach(player -> {
|
||||
player.showTitle(warTitle);
|
||||
player.playSound(warSound);
|
||||
});
|
||||
return;
|
||||
} else if (town == null && nation != null && (!canKingJoin || !asAdmin)) {
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("<red>Nation is already in that war.").build());
|
||||
}
|
||||
|
||||
// Join town into war
|
||||
if (isArgTown && town != null && !war.isInWar(town) && (asAdmin || canMayorJoin)) {
|
||||
side.add(town);
|
||||
town.getResidents().stream().filter(Resident::isOnline).map(Resident::getPlayer).toList().forEach(player -> NameColorHandler.getInstance().getPlayerNameColor(player));
|
||||
Bukkit.broadcast(
|
||||
ColorParser.of(
|
||||
"<prefix>The town of <town> joined the war of <war> on the side of <side>."
|
||||
)
|
||||
.parseMinimessagePlaceholder("prefix", UtilsChat.getPrefix())
|
||||
.parseMinimessagePlaceholder("town", town.getName())
|
||||
.parseMinimessagePlaceholder("war", war.getLabel())
|
||||
.parseMinimessagePlaceholder("side", side.getName())
|
||||
.build()
|
||||
);
|
||||
final Title warTitle = Title.title(
|
||||
ColorParser.of("<gradient:#D72A09:#B01F03><u><b>War")
|
||||
.build(),
|
||||
ColorParser.of("<gray><i>You entered the war of <war>!")
|
||||
.parseMinimessagePlaceholder("war", war.getLabel())
|
||||
.build(),
|
||||
Title.Times.times(Duration.ofMillis(500), Duration.ofMillis(3500), Duration.ofMillis(500))
|
||||
);
|
||||
final Sound warSound = Sound.sound(Key.key("entity.wither.spawn"), Sound.Source.VOICE, 0.5f, 1.0F);
|
||||
|
||||
town.getResidents().stream().filter(Resident::isOnline).map(Resident::getPlayer).toList().forEach(player -> {
|
||||
player.showTitle(warTitle);
|
||||
player.playSound(warSound);
|
||||
});
|
||||
return;
|
||||
} else if (targetPlayer == null && town != null && !canMayorJoin) {
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("<red>Town is already in that war.").build());
|
||||
}
|
||||
}
|
||||
|
||||
// Join player into war
|
||||
if (isArgPlayer && targetPlayer != null && !war.isInWar(targetPlayer) && asAdmin) {
|
||||
targetPlayer.sendMessage(ColorParser.of(UtilsChat.getPrefix() + "You have joined the war.").build());
|
||||
side.add(targetPlayer);
|
||||
NameColorHandler.getInstance().calculatePlayerColors(targetPlayer);
|
||||
final Title warTitle = Title.title(
|
||||
ColorParser.of("<gradient:#D72A09:#B01F03><u><b>War")
|
||||
.build(),
|
||||
ColorParser.of("<gray><i>You entered the war of <war>!")
|
||||
.parseMinimessagePlaceholder("war", war.getLabel())
|
||||
.build(),
|
||||
Title.Times.times(Duration.ofMillis(500), Duration.ofMillis(3500), Duration.ofMillis(500))
|
||||
);
|
||||
final Sound warSound = Sound.sound(Key.key("entity.wither.spawn"), Sound.Source.VOICE, 0.5f, 1.0F);
|
||||
|
||||
targetPlayer.showTitle(warTitle);
|
||||
targetPlayer.playSound(warSound);
|
||||
return;
|
||||
} else if (!asAdmin) {
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("<red>Players cannot individually join wars.").build());
|
||||
} else {
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("<red>Player is already in that war.").build());
|
||||
}
|
||||
|
||||
// Join player into war
|
||||
// if (war.isPlayerInWar(player))
|
||||
// throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("<red>You are already in this war.").build());
|
||||
|
||||
|
||||
/*for (@NotNull Siege siege : war.getSieges()) {
|
||||
if (siege.getAttackerSide().equals(side)) {
|
||||
siege.addPlayer(argPlayer, BattleSide.ATTACKER);
|
||||
} else {
|
||||
siege.addPlayer(argPlayer, BattleSide.DEFENDER);
|
||||
}
|
||||
}*/
|
||||
}
|
||||
|
||||
protected static void warJoinNear(@NotNull Player p, @NotNull CommandArguments args, boolean asAdmin) throws WrapperCommandSyntaxException {
|
||||
War war = (War) args.get("war");
|
||||
if (war == null) return;
|
||||
|
||||
if (!(args.get("side") instanceof final Side side))
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>You need to specify a side.").build());
|
||||
|
||||
final Location location = p.getLocation();
|
||||
|
||||
for (Player targetPlayer : Bukkit.getOnlinePlayers()) {
|
||||
if (p.equals(targetPlayer)) continue;
|
||||
final Location targetLocation = targetPlayer.getLocation();
|
||||
if (!location.getWorld().equals(targetLocation.getWorld())) continue;
|
||||
if (location.distance(targetLocation) > 25D) continue;
|
||||
if (war.isInWar(targetPlayer)) continue;
|
||||
|
||||
targetPlayer.sendMessage(ColorParser.of(UtilsChat.getPrefix() + "You have joined the war.").build());
|
||||
side.add(targetPlayer);
|
||||
NameColorHandler.getInstance().calculatePlayerColors(targetPlayer);
|
||||
final Title warTitle = Title.title(
|
||||
ColorParser.of("<gradient:#D72A09:#B01F03><u><b>War")
|
||||
.build(),
|
||||
ColorParser.of("<gray><i>You entered the war of <war>!")
|
||||
.parseMinimessagePlaceholder("war", war.getLabel())
|
||||
.build(),
|
||||
Title.Times.times(Duration.ofMillis(500), Duration.ofMillis(3500), Duration.ofMillis(500))
|
||||
);
|
||||
final Sound warSound = Sound.sound(Key.key("entity.wither.spawn"), Sound.Source.VOICE, 0.5f, 1.0F);
|
||||
|
||||
targetPlayer.showTitle(warTitle);
|
||||
targetPlayer.playSound(warSound);
|
||||
}
|
||||
}
|
||||
|
||||
protected static void warSurrender(@NotNull Player p, @NotNull CommandArguments args, boolean asAdmin) throws WrapperCommandSyntaxException {
|
||||
War war = (War) args.get("war");
|
||||
if (war == null) return;
|
||||
|
||||
if (!(args.getOptional("player").orElse(p) instanceof Player argPlayer))
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("<red>Player not found.").build());
|
||||
|
||||
// Towny Resident Object
|
||||
@Nullable Resident res = TownyAPI.getInstance().getResident(argPlayer);
|
||||
if (res == null)
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("<red>Resident invalid.").build());
|
||||
|
||||
// Town check
|
||||
@Nullable Town town = res.getTownOrNull();
|
||||
if (town == null)
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("<red>You are not in a town.").build());
|
||||
|
||||
@Nullable Side side = war.getSide(town);
|
||||
if (side == null)
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("<red>You are not in that war.").build());
|
||||
|
||||
final @Nullable Nation resNation = res.getNationOrNull();
|
||||
final @Nullable Town resTown = res.getTownOrNull();
|
||||
|
||||
if (resNation != null && (p.hasPermission("AlathranWars.nationsurrender") || res.isKing() || asAdmin)) {
|
||||
// Has nation surrender permission
|
||||
argPlayer.sendMessage(ColorParser.of(UtilsChat.getPrefix() + "You have surrendered the war for " + resNation.getName() + ".").build());
|
||||
Bukkit.broadcast(ColorParser.of(UtilsChat.getPrefix() + "The nation of " + resNation.getName() + " has surrendered!").build());
|
||||
war.surrender(resNation);
|
||||
} else if (resTown == null) {
|
||||
// Cannot surrender nation involvement
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("<red>You cannot surrender for your nation.").build());
|
||||
}
|
||||
|
||||
if (resTown != null && (p.hasPermission("AlathranWars.townsurrender") || res.isMayor() || asAdmin)) {
|
||||
// Is in indepdenent town & has surrender perms
|
||||
argPlayer.sendMessage(ColorParser.of(UtilsChat.getPrefix() + "You have surrendered the war for " + resTown.getName() + ".").build());
|
||||
Bukkit.broadcast(ColorParser.of(UtilsChat.getPrefix() + "The town of " + resTown.getName() + " has surrendered!").build());
|
||||
war.cancelSieges(resTown);
|
||||
war.surrender(resTown);
|
||||
} else {
|
||||
// No perms
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("<red>You cannot surrender war for your town.").build());
|
||||
}
|
||||
}
|
||||
|
||||
protected static void warKick(@NotNull Player p, @NotNull CommandArguments args) throws WrapperCommandSyntaxException {
|
||||
War war = (War) args.get("war");
|
||||
if (war == null) return;
|
||||
|
||||
UUID uuid = (UUID) args.get("target");
|
||||
|
||||
boolean isNation = TownyAPI.getInstance().getNation(uuid) != null;
|
||||
boolean isTown = TownyAPI.getInstance().getTown(uuid) != null;
|
||||
boolean isPlayer = Bukkit.getOfflinePlayer(uuid) != null;
|
||||
|
||||
Nation nation = TownyAPI.getInstance().getNation(uuid);
|
||||
Town town = TownyAPI.getInstance().getTown(uuid);
|
||||
OfflinePlayer player = Bukkit.getOfflinePlayer(uuid);
|
||||
|
||||
Side sideNation = war.getSide(nation);
|
||||
Side sideTown = war.getSide(town);
|
||||
Side sidePlayer = war.getPlayerSide(uuid);
|
||||
|
||||
if (isNation && sideNation != null) {
|
||||
sideNation.kick(nation);
|
||||
p.sendMessage(ColorParser.of("Target yeeted.").build());
|
||||
nation.getResidents().stream().filter(Resident::isOnline).map(Resident::getPlayer).forEach(player1 -> NameColorHandler.getInstance().calculatePlayerColors(player1));
|
||||
return;
|
||||
}
|
||||
|
||||
if (isTown && sideTown != null) {
|
||||
sideTown.kick(town);
|
||||
p.sendMessage(ColorParser.of("Target yeeted.").build());
|
||||
town.getResidents().stream().filter(Resident::isOnline).map(Resident::getPlayer).forEach(player1 -> NameColorHandler.getInstance().calculatePlayerColors(player1));
|
||||
return;
|
||||
}
|
||||
|
||||
if (isPlayer && sidePlayer != null) {
|
||||
sidePlayer.kick(player.getUniqueId());
|
||||
p.sendMessage(ColorParser.of("Target yeeted.").build());
|
||||
if (player.getPlayer() != null)
|
||||
NameColorHandler.getInstance().calculatePlayerColors(player.getPlayer());
|
||||
return;
|
||||
}
|
||||
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("<red>Failed to yeet from the war because the target is not in it.").build());
|
||||
}
|
||||
|
||||
private static void warList(@NotNull Player p, CommandArguments args) throws WrapperCommandSyntaxException {
|
||||
Set<War> wars = WarController.getInstance().getWars();
|
||||
|
||||
if (wars.isEmpty()) {
|
||||
p.sendMessage(ColorParser.of("<red>There are no wars at the moment, the world is at peace.").build());
|
||||
return;
|
||||
}
|
||||
|
||||
final StringBuilder msg = new StringBuilder();
|
||||
|
||||
for (War war : wars) {
|
||||
msg.append("\n<white><bold>%s<reset>".formatted(war.getLabel()));
|
||||
msg.append("\n <grey>Sides: <white>%s <grey>vs <white>%s".formatted(war.getSide1().getName(), war.getSide2().getName()));
|
||||
msg.append("\n <grey>Score: <white>%s <grey>vs <white>%s".formatted(war.getSide1().getScore(), war.getSide2().getScore()));
|
||||
msg.append("\n");
|
||||
}
|
||||
|
||||
p.sendMessage(
|
||||
ColorParser.of(
|
||||
msg.toString()
|
||||
).build()
|
||||
);
|
||||
}
|
||||
|
||||
private static void warInfo(Player p, CommandArguments args) throws WrapperCommandSyntaxException {
|
||||
War war = (War) args.get("war");
|
||||
if (war == null) return;
|
||||
|
||||
final StringBuilder msg = new StringBuilder();
|
||||
|
||||
for (Side side : war.getSides()) {
|
||||
msg.append("\n<white><bold>%s<reset>".formatted(side.getName()));
|
||||
msg.append("\n <grey>Score: <green>%s".formatted(side.getScore()));
|
||||
msg.append("\n <grey>Nations: <green>%s<grey>/<red>%s".formatted(side.getNations().size(), side.getNations().size() + side.getNationsSurrendered().size()));
|
||||
msg.append("\n <grey>Towns: <green>%s<grey>/<red>%s".formatted(side.getTowns().size(), side.getTowns().size() + side.getTownsSurrendered().size()));
|
||||
msg.append("\n <grey>Players: <green>%s<grey>/<red>%s".formatted(side.getPlayersAll().size(), side.getPlayersAll().size() + side.getPlayersSurrendered().size()));
|
||||
msg.append("\n");
|
||||
}
|
||||
|
||||
p.sendMessage(
|
||||
ColorParser.of(
|
||||
msg.toString()
|
||||
).build()
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,58 +0,0 @@
|
||||
package com.github.alathra.alathranwars.config;
|
||||
|
||||
import com.github.alathra.alathranwars.AlathranWars;
|
||||
import com.github.alathra.alathranwars.Reloadable;
|
||||
import com.github.milkdrinkers.crate.Config;
|
||||
|
||||
import javax.inject.Singleton;
|
||||
|
||||
/**
|
||||
* A class that generates/loads {@literal &} provides access to a configuration file.
|
||||
*/
|
||||
@Singleton
|
||||
public class ConfigHandler implements Reloadable {
|
||||
private final AlathranWars plugin;
|
||||
private Config cfg;
|
||||
private Config databaseCfg;
|
||||
|
||||
/**
|
||||
* Instantiates a new Config handler.
|
||||
*
|
||||
* @param plugin the plugin instance
|
||||
*/
|
||||
public ConfigHandler(AlathranWars plugin) {
|
||||
this.plugin = plugin;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onLoad() {
|
||||
cfg = new Config("config", plugin.getDataFolder().getPath(), plugin.getResource("config.yml")); // Create a config file from the template in our resources folder
|
||||
databaseCfg = new Config("database", plugin.getDataFolder().getPath(), plugin.getResource("database.yml"));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onEnable() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDisable() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets main config object.
|
||||
*
|
||||
* @return the config object
|
||||
*/
|
||||
public Config getConfig() {
|
||||
return cfg;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets database config object.
|
||||
*
|
||||
* @return the config object
|
||||
*/
|
||||
public Config getDatabaseConfig() {
|
||||
return databaseCfg;
|
||||
}
|
||||
}
|
||||
@@ -1,43 +0,0 @@
|
||||
package com.github.alathra.alathranwars.conflict;
|
||||
|
||||
import com.github.alathra.alathranwars.enums.ConflictType;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
public abstract class Conflict implements IUnique<Conflict> {
|
||||
private ConflictType conflictType;
|
||||
private final UUID uuid;
|
||||
|
||||
public Conflict(UUID uuid) {
|
||||
this.uuid = uuid;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return conflict uuid
|
||||
*/
|
||||
@Override
|
||||
public UUID getUUID() {
|
||||
return uuid;
|
||||
}
|
||||
|
||||
/**
|
||||
* Equals boolean.
|
||||
*
|
||||
* @param uuid the uuid
|
||||
* @return the boolean
|
||||
*/
|
||||
@Override
|
||||
public boolean equals(UUID uuid) {
|
||||
return getUUID().equals(uuid);
|
||||
}
|
||||
|
||||
/**
|
||||
* Equals boolean.
|
||||
*
|
||||
* @param conflict the conflict
|
||||
* @return the boolean
|
||||
*/
|
||||
public boolean equals(Conflict conflict) {
|
||||
return conflict.getUUID().equals(uuid);
|
||||
}
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
package com.github.alathra.alathranwars.conflict;
|
||||
|
||||
import com.github.alathra.alathranwars.conflict.war.War;
|
||||
|
||||
public interface IAssociatedWar {
|
||||
/**
|
||||
* Gets the associated war with this object from the war uuid
|
||||
* @return the associated war
|
||||
*/
|
||||
War getWar();
|
||||
|
||||
/**
|
||||
* Check whether a war is associated with this class
|
||||
* @param war the war to compare with
|
||||
* @return if the war is the one associated with this object
|
||||
*/
|
||||
boolean equals(War war);
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
package com.github.alathra.alathranwars.conflict;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
public interface IUnique<T extends IUnique<T>> {
|
||||
UUID getUUID();
|
||||
|
||||
/**
|
||||
* Equals boolean.
|
||||
*
|
||||
* @param uuid the uuid
|
||||
* @return the boolean
|
||||
*/
|
||||
default boolean equals(UUID uuid) {
|
||||
return getUUID().equals(uuid);
|
||||
}
|
||||
|
||||
/**
|
||||
* Equals boolean.
|
||||
*
|
||||
* @param obj the object implementing IUnique
|
||||
* @return the boolean
|
||||
*/
|
||||
default boolean equals(T obj) {
|
||||
return getUUID().equals(obj.getUUID());
|
||||
}
|
||||
}
|
||||
@@ -1,62 +0,0 @@
|
||||
package com.github.alathra.alathranwars.conflict;
|
||||
|
||||
import com.palmergames.bukkit.towny.exceptions.AlreadyRegisteredException;
|
||||
import com.palmergames.bukkit.towny.object.Nation;
|
||||
import com.palmergames.bukkit.towny.object.Town;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
public class Occupation {
|
||||
public static boolean isOccupied(Town town) {
|
||||
return town.isConquered();
|
||||
}
|
||||
|
||||
public static void removeOccupied(Town town) {
|
||||
if (!isOccupied(town)) return;
|
||||
|
||||
// final boolean hasPreviousNation = town.hasNation();
|
||||
// final Nation previousNation = town.getNationOrNull();
|
||||
// if (hasPreviousNation) {
|
||||
// town.removeNation();
|
||||
// }
|
||||
|
||||
town.setConquered(false);
|
||||
|
||||
town.save();
|
||||
// if (hasPreviousNation) {
|
||||
// previousNation.save();
|
||||
// }
|
||||
}
|
||||
|
||||
public static void setOccupied(Nation occupied, @Nullable Nation occupier) {
|
||||
for (Town town : occupied.getTowns())
|
||||
setOccupied(town, occupier);
|
||||
}
|
||||
|
||||
public static void setOccupied(Town town, @Nullable Nation occupier) {
|
||||
if (isOccupied(town)) return;
|
||||
|
||||
// Remove from current nation
|
||||
// final boolean hasPreviousNation = town.hasNation();
|
||||
// final boolean hasNewNation = occupier != null;
|
||||
// final Nation previousNation = town.getNationOrNull();
|
||||
// if (hasPreviousNation && hasNewNation && previousNation != occupier)
|
||||
// town.removeNation();
|
||||
|
||||
// // Put town into occupiers nation
|
||||
// try {
|
||||
// if (hasNewNation)
|
||||
// town.setNation(occupier);
|
||||
// } catch (AlreadyRegisteredException e) {
|
||||
// e.printStackTrace();
|
||||
// return;
|
||||
// }
|
||||
town.setConquered(true);
|
||||
|
||||
town.save();
|
||||
// if (hasNewNation)
|
||||
// occupier.save();
|
||||
//
|
||||
// if (hasPreviousNation && previousNation != occupier)
|
||||
// previousNation.save();
|
||||
}
|
||||
}
|
||||
-213
@@ -1,213 +0,0 @@
|
||||
package com.github.alathra.alathranwars.conflict.battle;
|
||||
|
||||
import com.github.alathra.alathranwars.conflict.war.War;
|
||||
import com.github.alathra.alathranwars.enums.battle.BattleSide;
|
||||
import com.github.alathra.alathranwars.events.battle.PlayerEnteredBattlefieldEvent;
|
||||
import com.github.alathra.alathranwars.events.battle.PlayerLeftBattlefieldEvent;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.OfflinePlayer;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* Provides methods for handling all members of a Battle
|
||||
*/
|
||||
public abstract class AbstractBattleTeamManagement {
|
||||
// SECTION Player management
|
||||
|
||||
private final List<OfflinePlayer> attackers = new ArrayList<>(); // A list of all players who are in the attackers team
|
||||
private final List<OfflinePlayer> defenders = new ArrayList<>(); // A list of all players who are in the attackers team
|
||||
|
||||
/**
|
||||
* Get all online players eligible to fight in the battle
|
||||
* @param side battle side
|
||||
* @return list of players
|
||||
*/
|
||||
public List<Player> getPlayersOnline(BattleSide side) {
|
||||
return switch (side) {
|
||||
case ATTACKER -> attackers.stream()
|
||||
.filter(OfflinePlayer::isOnline)
|
||||
.map(OfflinePlayer::getPlayer)
|
||||
.toList();
|
||||
case DEFENDER -> defenders.stream()
|
||||
.filter(OfflinePlayer::isOnline)
|
||||
.map(OfflinePlayer::getPlayer)
|
||||
.toList();
|
||||
case SPECTATOR -> Bukkit.getOnlinePlayers().stream()
|
||||
.map(OfflinePlayer::getPlayer)
|
||||
.filter(p -> !attackers.contains(p) && !defenders.contains(p))
|
||||
.toList();
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all players eligible to fight in the battle
|
||||
* @param side battle side
|
||||
* @return list of players
|
||||
*/
|
||||
public List<OfflinePlayer> getPlayers(BattleSide side) {
|
||||
return switch (side) {
|
||||
case ATTACKER -> attackers;
|
||||
case DEFENDER -> defenders;
|
||||
default -> List.of();
|
||||
};
|
||||
}
|
||||
|
||||
public void addPlayer(OfflinePlayer p, BattleSide side) {
|
||||
switch (side) {
|
||||
case ATTACKER -> attackers.add(p);
|
||||
case DEFENDER -> defenders.add(p);
|
||||
}
|
||||
}
|
||||
|
||||
public void addPlayer(Player p, BattleSide side) { addPlayer(Bukkit.getOfflinePlayer(p.getUniqueId()), side); }
|
||||
|
||||
public void addPlayer(UUID uuid, BattleSide side) { addPlayer(Bukkit.getOfflinePlayer(uuid), side); }
|
||||
|
||||
public void removePlayer(OfflinePlayer p, BattleSide side) {
|
||||
switch (side) {
|
||||
case ATTACKER -> attackers.remove(p);
|
||||
case DEFENDER -> defenders.remove(p);
|
||||
}
|
||||
}
|
||||
|
||||
public void removePlayer(Player p, BattleSide side) { removePlayer(p.getUniqueId(), side); }
|
||||
|
||||
public void removePlayer(UUID uuid, BattleSide side) { removePlayer(Bukkit.getOfflinePlayer(uuid), side); }
|
||||
|
||||
// Player info methods
|
||||
|
||||
public BattleSide getPlayerBattleSide(OfflinePlayer p) {
|
||||
if (getPlayers(BattleSide.ATTACKER).contains(p))
|
||||
return BattleSide.ATTACKER;
|
||||
|
||||
if (getPlayers(BattleSide.DEFENDER).contains(p))
|
||||
return BattleSide.DEFENDER;
|
||||
|
||||
return BattleSide.SPECTATOR;
|
||||
}
|
||||
|
||||
public BattleSide getPlayerBattleSide(Player p) {
|
||||
return getPlayerBattleSide(p.getUniqueId());
|
||||
}
|
||||
|
||||
public BattleSide getPlayerBattleSide(UUID uuid) {
|
||||
return getPlayerBattleSide(Bukkit.getOfflinePlayer(uuid));
|
||||
}
|
||||
|
||||
// Misc
|
||||
|
||||
/**
|
||||
* Checks if the player is considered part of this battle
|
||||
* @param p the player
|
||||
* @return yes if they have joined the battle
|
||||
*/
|
||||
public boolean isPlayerParticipating(OfflinePlayer p) {
|
||||
return getPlayers(BattleSide.ATTACKER).contains(p) || getPlayers(BattleSide.DEFENDER).contains(p);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the player is considered part of this battle
|
||||
* @param p the player
|
||||
* @return yes if they have joined the battle
|
||||
*/
|
||||
public boolean isPlayerParticipating(Player p) {
|
||||
return isPlayerParticipating(p.getUniqueId());
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the player is considered part of this battle
|
||||
* @param uuid the player uuid
|
||||
* @return yes if they have joined the battle
|
||||
*/
|
||||
public boolean isPlayerParticipating(UUID uuid) {
|
||||
return isPlayerParticipating(Bukkit.getOfflinePlayer(uuid));
|
||||
}
|
||||
|
||||
// SECTION Active player management
|
||||
|
||||
private final List<Player> activeAttackers = new ArrayList<>(); // Players in the battle zone
|
||||
private final List<Player> activeDefenders = new ArrayList<>(); // Players in the battle zone
|
||||
private final List<Player> activeSpectators = new ArrayList<>(); // Players in the battle zone
|
||||
|
||||
/**
|
||||
* Get all online players within the battlefield.
|
||||
* @param side battle side
|
||||
* @return list of players
|
||||
*/
|
||||
public List<Player> getActivePlayers(BattleSide side) {
|
||||
return switch (side) {
|
||||
case ATTACKER -> activeAttackers;
|
||||
case DEFENDER -> activeDefenders;
|
||||
case SPECTATOR -> activeSpectators;
|
||||
};
|
||||
}
|
||||
|
||||
private void addActivePlayer(Player p, BattleSide side) {
|
||||
switch (side) {
|
||||
case ATTACKER -> activeAttackers.add(p);
|
||||
case DEFENDER -> activeDefenders.add(p);
|
||||
case SPECTATOR -> activeSpectators.add(p);
|
||||
};
|
||||
}
|
||||
|
||||
private void removeActivePlayer(Player p, BattleSide side) {
|
||||
switch (side) {
|
||||
case ATTACKER -> activeAttackers.remove(p);
|
||||
case DEFENDER -> activeDefenders.remove(p);
|
||||
case SPECTATOR -> activeSpectators.remove(p);
|
||||
};
|
||||
}
|
||||
|
||||
public void calculateBattlefieldPlayers(Location location, int range, War war, Battle battle) {
|
||||
final List<Player> previousAttackersOnBattlefield = new ArrayList<>(getActivePlayers(BattleSide.ATTACKER));
|
||||
final List<Player> previousDefendersOnBattlefield = new ArrayList<>(getActivePlayers(BattleSide.DEFENDER));
|
||||
final List<Player> previousSpectatorsOnBattlefield = new ArrayList<>(getActivePlayers(BattleSide.SPECTATOR));
|
||||
|
||||
activeAttackers.clear();
|
||||
activeSpectators.addAll(getPlayersWithinRange(BattleSide.ATTACKER, location, range));
|
||||
|
||||
activeDefenders.clear();
|
||||
activeSpectators.addAll(getPlayersWithinRange(BattleSide.DEFENDER, location, range));
|
||||
|
||||
activeSpectators.clear();
|
||||
activeSpectators.addAll(getPlayersWithinRange(BattleSide.SPECTATOR, location, range));
|
||||
|
||||
// Attackers
|
||||
emitLeaving(BattleSide.ATTACKER, previousAttackersOnBattlefield, war, battle); // Emit Leaving attackers events
|
||||
emitEntering(BattleSide.ATTACKER, previousAttackersOnBattlefield, war, battle); // Emit Entering attackers events
|
||||
|
||||
// Defenders
|
||||
emitLeaving(BattleSide.DEFENDER, previousDefendersOnBattlefield, war, battle); // Emit Leaving defenders events
|
||||
emitEntering(BattleSide.DEFENDER, previousDefendersOnBattlefield, war, battle); // Emit Entering defenders events
|
||||
|
||||
// Spectators
|
||||
emitLeaving(BattleSide.SPECTATOR, previousSpectatorsOnBattlefield, war, battle); // Emit Leaving spectators events
|
||||
emitEntering(BattleSide.SPECTATOR, previousSpectatorsOnBattlefield, war, battle); // Emit Entering spectators events
|
||||
}
|
||||
|
||||
private List<Player> getPlayersWithinRange(BattleSide battleSide, Location location, int range) {
|
||||
return getPlayersOnline(battleSide).stream()
|
||||
.filter(OfflinePlayer::isOnline)
|
||||
.filter(p -> location.getWorld().equals(p.getLocation().getWorld()))
|
||||
.filter(p -> location.distance(p.getLocation()) < range)
|
||||
.toList();
|
||||
}
|
||||
|
||||
private void emitEntering(BattleSide battleSide, List<Player> previousPlayers, War war, Battle battle) {
|
||||
getActivePlayers(battleSide).stream()
|
||||
.filter(p -> p.isConnected() && !previousPlayers.contains(p))
|
||||
.collect(Collectors.toSet())
|
||||
.forEach(p -> new PlayerEnteredBattlefieldEvent(p, war, battle, battleSide).callEvent());
|
||||
}
|
||||
|
||||
private void emitLeaving(BattleSide battleSide, List<Player> previousPlayers, War war, Battle battle) {
|
||||
previousPlayers.stream()
|
||||
.filter(p -> p.isConnected() && !getActivePlayers(battleSide).contains(p))
|
||||
.collect(Collectors.toSet())
|
||||
.forEach(p -> new PlayerLeftBattlefieldEvent(p, war, battle, battleSide).callEvent());
|
||||
}
|
||||
}
|
||||
@@ -1,72 +0,0 @@
|
||||
package com.github.alathra.alathranwars.conflict.battle;
|
||||
|
||||
import com.github.alathra.alathranwars.conflict.IUnique;
|
||||
import com.github.alathra.alathranwars.conflict.war.War;
|
||||
import com.github.alathra.alathranwars.enums.battle.BattleType;
|
||||
import com.github.alathra.alathranwars.enums.battle.BattleVictoryReason;
|
||||
import org.jetbrains.annotations.ApiStatus;
|
||||
|
||||
public interface Battle extends IUnique<Battle> {
|
||||
War war = null;
|
||||
|
||||
default War getWar() {
|
||||
return war;
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts the battle
|
||||
*/
|
||||
@ApiStatus.Internal
|
||||
void start();
|
||||
|
||||
/**
|
||||
* Resumes the battle (after a server restart e.t.c.)
|
||||
*/
|
||||
@ApiStatus.Internal
|
||||
void resume();
|
||||
|
||||
/**
|
||||
* Stops the battle
|
||||
* </p>
|
||||
* Internal stop method for battles which triggers cleanup methods
|
||||
*/
|
||||
@ApiStatus.Internal
|
||||
void stop(); // Ends battle
|
||||
|
||||
/**
|
||||
* Stop a battle in favor of the attackers
|
||||
*
|
||||
* @param reason what triggered the end
|
||||
*/
|
||||
void attackersWin(BattleVictoryReason reason); // A Attacker victory
|
||||
|
||||
/**
|
||||
* Stop a battle in favor of the defenders
|
||||
*
|
||||
* @param reason what triggered the end
|
||||
*/
|
||||
void defendersWin(BattleVictoryReason reason); // A Defender victory
|
||||
|
||||
/**
|
||||
* End a battle in favor of no one
|
||||
*
|
||||
* @param reason what triggered the end
|
||||
*/
|
||||
void equalWin(BattleVictoryReason reason); // A Draw
|
||||
|
||||
/**
|
||||
* Equals boolean.
|
||||
*
|
||||
* @param battle the battle
|
||||
* @return the boolean
|
||||
*/
|
||||
default boolean equals(Battle battle) {
|
||||
return getUUID().equals(battle.getUUID());
|
||||
}
|
||||
|
||||
BattleType battleType = null;
|
||||
|
||||
default BattleType getBattleType() {
|
||||
return battleType;
|
||||
}
|
||||
}
|
||||
@@ -1,94 +0,0 @@
|
||||
/*
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2021 SkytAsul
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
*/
|
||||
|
||||
package com.github.alathra.alathranwars.conflict.battle.beam;
|
||||
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.plugin.Plugin;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
public class CrystalLaser extends Laser {
|
||||
private final Object crystal;
|
||||
private final int crystalID = Packets.generateEID();
|
||||
private Object createCrystalPacket;
|
||||
private Object metadataPacketCrystal;
|
||||
private final Object[] destroyPackets;
|
||||
private final Object fakeCrystalDataWatcher;
|
||||
|
||||
/**
|
||||
* Creates a new Ender Crystal Laser instance
|
||||
*
|
||||
* @param start Location where laser will starts. The Crystal laser do not handle decimal number, it will be rounded to blocks.
|
||||
* @param end Location where laser will ends. The Crystal laser do not handle decimal number, it will be rounded to blocks.
|
||||
* @param duration Duration of laser in seconds (<i>-1 if infinite</i>)
|
||||
* @param distance Distance where laser will be visible (<i>-1 if infinite</i>)
|
||||
* @throws ReflectiveOperationException if a reflection exception occurred during Laser creation
|
||||
* @see #start(Plugin) to start the laser
|
||||
* @see #durationInTicks() to make the duration in ticks
|
||||
* @see #executeEnd(Runnable) to add Runnable-s to execute when the laser will stop
|
||||
*/
|
||||
public CrystalLaser(Location start, Location end, int duration, int distance) throws ReflectiveOperationException {
|
||||
super(start, new Location(end.getWorld(), end.getBlockX(), end.getBlockY(), end.getBlockZ()), duration, distance);
|
||||
|
||||
fakeCrystalDataWatcher = Packets.createFakeDataWatcher();
|
||||
Packets.setCrystalWatcher(fakeCrystalDataWatcher, end);
|
||||
if (Packets.version < 17) {
|
||||
crystal = null;
|
||||
} else {
|
||||
crystal = Packets.createCrystal(start, UUID.randomUUID(), crystalID);
|
||||
}
|
||||
metadataPacketCrystal = Packets.createPacketMetadata(crystalID, fakeCrystalDataWatcher);
|
||||
|
||||
destroyPackets = Packets.createPacketsRemoveEntities(crystalID);
|
||||
}
|
||||
|
||||
private Object getCrystalSpawnPacket() throws ReflectiveOperationException {
|
||||
if (createCrystalPacket == null) {
|
||||
if (Packets.version < 17) {
|
||||
createCrystalPacket = Packets.createPacketEntitySpawnNormal(start, Packets.crystalID, Packets.crystalType, crystalID);
|
||||
} else {
|
||||
createCrystalPacket = Packets.createPacketEntitySpawnNormal(crystal);
|
||||
}
|
||||
}
|
||||
return createCrystalPacket;
|
||||
}
|
||||
|
||||
@Override
|
||||
public LaserType getLaserType() {
|
||||
return LaserType.ENDER_CRYSTAL;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void sendStartPackets(Player p, boolean hasSeen) throws ReflectiveOperationException {
|
||||
Packets.sendPackets(p, getCrystalSpawnPacket());
|
||||
Packets.sendPackets(p, metadataPacketCrystal);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void sendDestroyPackets(Player p) throws ReflectiveOperationException {
|
||||
Packets.sendPackets(p, destroyPackets);
|
||||
}
|
||||
}
|
||||
@@ -1,213 +0,0 @@
|
||||
/*
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2021 SkytAsul
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
*/
|
||||
|
||||
package com.github.alathra.alathranwars.conflict.battle.beam;
|
||||
|
||||
import com.github.alathra.alathranwars.AlathranWars;
|
||||
import com.github.alathra.alathranwars.utility.Logger;
|
||||
import com.github.milkdrinkers.colorparser.ColorParser;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.plugin.Plugin;
|
||||
import org.bukkit.scheduler.BukkitRunnable;
|
||||
import space.arim.morepaperlib.scheduling.ScheduledTask;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
/**
|
||||
* A whole class to create Guardian Lasers and Ender Crystal Beams using packets and reflection.<br>
|
||||
* Inspired by the API
|
||||
* <a href="https://www.spigotmc.org/resources/guardianbeamapi.18329">GuardianBeamAPI</a><br>
|
||||
* <b>1.9 -> 1.20</b>
|
||||
*
|
||||
* @author SkytAsul
|
||||
* @version 2.3.3
|
||||
* @see <a href="https://github.com/SkytAsul/GuardianBeam">GitHub repository</a>
|
||||
*/
|
||||
public abstract class Laser {
|
||||
protected final int distanceSquared;
|
||||
protected final int duration;
|
||||
protected boolean durationInTicks = false;
|
||||
protected Location start;
|
||||
protected Location end;
|
||||
|
||||
protected Plugin plugin;
|
||||
protected ScheduledTask task;
|
||||
|
||||
protected Set<Player> show = ConcurrentHashMap.newKeySet();
|
||||
private final Set<Player> seen = new HashSet<>();
|
||||
|
||||
private final List<Runnable> executeEnd = new ArrayList<>(1);
|
||||
|
||||
protected Laser(Location start, Location end, int duration, int distance) {
|
||||
if (!Packets.enabled)
|
||||
throw new IllegalStateException("The Laser Beam API is disabled. An error has occured during initialization.");
|
||||
if (start.getWorld() != end.getWorld())
|
||||
throw new IllegalArgumentException("Locations do not belong to the same worlds.");
|
||||
this.start = start.clone();
|
||||
this.end = end.clone();
|
||||
this.duration = duration;
|
||||
distanceSquared = distance < 0 ? -1 : distance * distance;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a runnable to execute when the laser reaches its final duration
|
||||
*
|
||||
* @param runnable action to execute
|
||||
* @return this {@link Laser} instance
|
||||
*/
|
||||
public Laser executeEnd(Runnable runnable) {
|
||||
executeEnd.add(runnable);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Makes the duration provided in the constructor passed as ticks and not seconds
|
||||
*
|
||||
* @return this {@link Laser} instance
|
||||
*/
|
||||
public Laser durationInTicks() {
|
||||
durationInTicks = true;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts this laser.
|
||||
* <p>
|
||||
* It will make the laser visible for nearby players and start the countdown to the final duration.
|
||||
* <p>
|
||||
* Once finished, it will destroy the laser and execute all runnables passed with {@link Laser#executeEnd}.
|
||||
*
|
||||
* @param plugin plugin used to start the task
|
||||
*/
|
||||
public void start(Plugin plugin) {
|
||||
if (task != null) throw new IllegalStateException("Task already started");
|
||||
this.plugin = plugin;
|
||||
Runnable runnable = new BukkitRunnable() {
|
||||
int time = 0;
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
if (time == duration) {
|
||||
stop();
|
||||
return;
|
||||
}
|
||||
if (!durationInTicks || time % 20 == 0) {
|
||||
for (Player p : start.getWorld().getPlayers()) {
|
||||
if (isCloseEnough(p)) {
|
||||
if (show.add(p)) {
|
||||
sendStartPackets(p, !seen.add(p));
|
||||
}
|
||||
} else if (show.remove(p)) {
|
||||
sendDestroyPackets(p);
|
||||
}
|
||||
}
|
||||
}
|
||||
time++;
|
||||
} catch (ReflectiveOperationException e) {
|
||||
Logger.get().error(ColorParser.of("<red>Laser packer exception: ").build(), e);
|
||||
}
|
||||
}
|
||||
};
|
||||
task = AlathranWars.getPaperLib().scheduling().asyncScheduler().runAtFixedRate(runnable, Duration.ZERO, Duration.ofMillis(durationInTicks ? 50L : 1000L));
|
||||
}
|
||||
|
||||
/**
|
||||
* Stops this laser.
|
||||
* <p>
|
||||
* This will destroy the laser for every player and start execute all runnables passed with {@link Laser#executeEnd}
|
||||
*/
|
||||
public synchronized void stop() {
|
||||
if (task == null || task.isCancelled()) throw new IllegalStateException("Task not started");
|
||||
task.cancel();
|
||||
|
||||
try {
|
||||
try {
|
||||
for (Player p : show) {
|
||||
sendDestroyPackets(p);
|
||||
}
|
||||
show.clear();
|
||||
executeEnd.forEach(Runnable::run);
|
||||
} catch (ReflectiveOperationException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
} catch (IllegalStateException ignored) {
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets laser status.
|
||||
*
|
||||
* @return <code>true</code> if the laser is currently running
|
||||
* (i.e. {@link #start} has been called and the duration is not over)
|
||||
*/
|
||||
public boolean isStarted() {
|
||||
return task != null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets laser type.
|
||||
*
|
||||
* @return LaserType enum constant of this laser
|
||||
*/
|
||||
public abstract LaserType getLaserType();
|
||||
|
||||
/**
|
||||
* Gets the start location of the laser.
|
||||
*
|
||||
* @return where exactly is the start position of the laser located
|
||||
*/
|
||||
public Location getStart() {
|
||||
return start.clone();
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the end location of the laser.
|
||||
*
|
||||
* @return where exactly is the end position of the laser located
|
||||
*/
|
||||
public Location getEnd() {
|
||||
return end.clone();
|
||||
}
|
||||
|
||||
protected abstract void sendStartPackets(Player p, boolean hasSeen) throws ReflectiveOperationException;
|
||||
|
||||
protected abstract void sendDestroyPackets(Player p) throws ReflectiveOperationException;
|
||||
|
||||
protected boolean isCloseEnough(Player player) {
|
||||
if (distanceSquared == -1) return true;
|
||||
Location location = player.getLocation();
|
||||
return getStart().distanceSquared(location) <= distanceSquared ||
|
||||
getEnd().distanceSquared(location) <= distanceSquared;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,56 +0,0 @@
|
||||
/*
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2021 SkytAsul
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
*/
|
||||
|
||||
package com.github.alathra.alathranwars.conflict.battle.beam;
|
||||
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.plugin.Plugin;
|
||||
|
||||
public enum LaserType {
|
||||
/**
|
||||
* Represents a laser from an Ender Crystal entity.
|
||||
* <p>
|
||||
* Start and end locations are automatically rounded to integers (block locations).
|
||||
*/
|
||||
ENDER_CRYSTAL;
|
||||
|
||||
/**
|
||||
* Creates a new Laser instance, {@link CrystalLaser} depending on this enum value.
|
||||
*
|
||||
* @param start Location where laser will starts
|
||||
* @param end Location where laser will ends
|
||||
* @param duration Duration of laser in seconds (<i>-1 if infinite</i>)
|
||||
* @param distance Distance where laser will be visible
|
||||
* @throws ReflectiveOperationException if a reflection exception occurred during Laser creation
|
||||
* @see Laser#start(Plugin) to start the laser
|
||||
* @see Laser#durationInTicks() to make the duration in ticks
|
||||
* @see Laser#executeEnd(Runnable) to add Runnable-s to execute when the laser will stop
|
||||
*/
|
||||
public Laser create(Location start, Location end, int duration, int distance) throws ReflectiveOperationException {
|
||||
if (this == LaserType.ENDER_CRYSTAL) {
|
||||
return new CrystalLaser(start, end, duration, distance);
|
||||
}
|
||||
throw new IllegalStateException();
|
||||
}
|
||||
}
|
||||
@@ -1,396 +0,0 @@
|
||||
/*
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2021 SkytAsul
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
*/
|
||||
|
||||
package com.github.alathra.alathranwars.conflict.battle.beam;
|
||||
|
||||
import com.github.alathra.alathranwars.utility.Logger;
|
||||
import com.github.milkdrinkers.colorparser.ColorParser;
|
||||
import net.minecraft.world.entity.Entity;
|
||||
import net.minecraft.world.entity.animal.Squid;
|
||||
import net.minecraft.world.entity.boss.enderdragon.EndCrystal;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
import java.lang.reflect.Constructor;
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
class Packets {
|
||||
public static boolean enabled = false;
|
||||
static int version;
|
||||
private static int versionMinor;
|
||||
private static final String npack = "net.minecraft.server." + Bukkit.getServer().getClass().getPackage().getName().replace(".", ",").split(",")[3];
|
||||
private static final String cpack = Bukkit.getServer().getClass().getPackage().getName() + ".";
|
||||
|
||||
static final int crystalID = 51; // pre-1.13
|
||||
|
||||
static Object crystalType;
|
||||
|
||||
private static Constructor<?> crystalConstructor;
|
||||
|
||||
private static Object watcherObject4; // crystal target
|
||||
private static Object watcherObject5; // crystal base plate
|
||||
|
||||
private static Constructor<?> watcherConstructor;
|
||||
private static Method watcherSet;
|
||||
private static Method watcherRegister;
|
||||
private static Method watcherDirty;
|
||||
private static Method watcherPack;
|
||||
|
||||
private static Constructor<?> blockPositionConstructor;
|
||||
|
||||
private static Constructor<?> packetSpawnNormal;
|
||||
private static Constructor<?> packetRemove;
|
||||
private static Constructor<?> packetMetadata;
|
||||
|
||||
private static Method getHandle;
|
||||
private static Field playerConnection;
|
||||
private static Method sendPacket;
|
||||
private static Method setUUID;
|
||||
private static Method setID;
|
||||
|
||||
private static Object fakeSquid;
|
||||
|
||||
private static Object nmsWorld;
|
||||
|
||||
static {
|
||||
try {
|
||||
// e.g. Bukkit.getServer().getClass().getPackage().getName() -> org.bukkit.craftbukkit.v1_17_R1
|
||||
String[] versions = Bukkit.getServer().getClass().getPackage().getName().split("\\.")[3].substring(1).split("_");
|
||||
version = Integer.parseInt(versions[1]); // 1.X
|
||||
if (version >= 17) {
|
||||
// e.g. Bukkit.getBukkitVersion() -> 1.17.1-R0.1-SNAPSHOT
|
||||
versions = Bukkit.getBukkitVersion().split("-R")[0].split("\\.");
|
||||
versionMinor = versions.length <= 2 ? 0 : Integer.parseInt(versions[2]);
|
||||
} else versionMinor = Integer.parseInt(versions[2].substring(1)); // 1.X.Y
|
||||
|
||||
ProtocolMappings mappings = ProtocolMappings.getMappings(version);
|
||||
if (mappings == null) {
|
||||
mappings = ProtocolMappings.values()[ProtocolMappings.values().length - 1];
|
||||
}
|
||||
|
||||
Class<?> entityTypesClass = getNMSClass("world.entity", "EntityTypes");
|
||||
Class<Entity> entityClass = Entity.class;
|
||||
Class<EndCrystal> crystalClass = EndCrystal.class;
|
||||
Class<?> squidClass = Squid.class;
|
||||
// invisilibity
|
||||
Object watcherObject1 = getField(entityClass, mappings.getWatcherFlags(), null);
|
||||
watcherObject4 = getField(crystalClass, mappings.getWatcherTargetLocation(), null);
|
||||
watcherObject5 = getField(crystalClass, mappings.getWatcherBasePlate(), null);
|
||||
|
||||
if (version >= 13) {
|
||||
crystalType = entityTypesClass.getDeclaredField(mappings.getCrystalTypeName()).get(null);
|
||||
}
|
||||
|
||||
Class<?> dataWatcherClass = getNMSClass("network.syncher", "DataWatcher");
|
||||
watcherConstructor = dataWatcherClass.getDeclaredConstructor(entityClass);
|
||||
if (version >= 18) {
|
||||
watcherSet = dataWatcherClass.getDeclaredMethod("b", watcherObject1.getClass(), Object.class);
|
||||
watcherRegister = dataWatcherClass.getDeclaredMethod("a", watcherObject1.getClass(), Object.class);
|
||||
} else {
|
||||
watcherSet = getMethod(dataWatcherClass, "set");
|
||||
watcherRegister = getMethod(dataWatcherClass, "register");
|
||||
}
|
||||
if (version >= 15) watcherDirty = getMethod(dataWatcherClass, "markDirty");
|
||||
if (version > 19 || (version == 19 && versionMinor >= 3))
|
||||
watcherPack = dataWatcherClass.getDeclaredMethod("b");
|
||||
packetSpawnNormal = getNMSClass("network.protocol.game", "PacketPlayOutSpawnEntity").getDeclaredConstructor(version < 17 ? new Class<?>[0] : new Class<?>[]{getNMSClass("world.entity", "Entity")});
|
||||
packetRemove = getNMSClass("network.protocol.game", "PacketPlayOutEntityDestroy").getDeclaredConstructor(version == 17 && versionMinor == 0 ? int.class : int[].class);
|
||||
packetMetadata = getNMSClass("network.protocol.game", "PacketPlayOutEntityMetadata")
|
||||
.getDeclaredConstructor(version < 19 || (version == 19 && versionMinor < 3)
|
||||
? new Class<?>[]{int.class, dataWatcherClass, boolean.class}
|
||||
: new Class<?>[]{int.class, List.class});
|
||||
|
||||
blockPositionConstructor =
|
||||
getNMSClass("core", "BlockPosition").getConstructor(int.class, int.class, int.class);
|
||||
|
||||
nmsWorld = Class.forName(cpack + "CraftWorld").getDeclaredMethod("getHandle").invoke(Bukkit.getWorlds().get(0));
|
||||
|
||||
Constructor<?> squidConstructor = squidClass.getDeclaredConstructors()[0];
|
||||
if (version >= 17) {
|
||||
crystalConstructor = crystalClass.getDeclaredConstructor(nmsWorld.getClass().getSuperclass(), double.class, double.class, double.class);
|
||||
}
|
||||
|
||||
Object[] entityConstructorParams = version < 14 ? new Object[]{nmsWorld} : new Object[]{entityTypesClass.getDeclaredField(mappings.getSquidTypeName()).get(null), nmsWorld};
|
||||
fakeSquid = squidConstructor.newInstance(entityConstructorParams);
|
||||
Object fakeSquidWatcher = createFakeDataWatcher();
|
||||
tryWatcherSet(fakeSquidWatcher, watcherObject1, (byte) 32);
|
||||
|
||||
getHandle = Class.forName(cpack + "entity.CraftPlayer").getDeclaredMethod("getHandle");
|
||||
playerConnection = getNMSClass("server.level", "EntityPlayer")
|
||||
.getDeclaredField(version < 17 ? "playerConnection" : (version < 20 ? "b" : "c"));
|
||||
playerConnection.setAccessible(true);
|
||||
sendPacket = getNMSClass("server.network", "PlayerConnection").getMethod(
|
||||
version < 18 ? "sendPacket" : (version >= 20 && versionMinor >= 2 ? "b" : "a"),
|
||||
getNMSClass("network.protocol", "Packet"));
|
||||
|
||||
if (version >= 17) {
|
||||
setUUID = entityClass.getDeclaredMethod("a_", UUID.class);
|
||||
setID = entityClass.getDeclaredMethod("e", int.class);
|
||||
}
|
||||
|
||||
enabled = true;
|
||||
} catch (Exception e) {
|
||||
Logger.get().error(
|
||||
ColorParser.of("Laser reflection failed to initialize. The utility is disabled. Please ensure your version (<version>) is supported.")
|
||||
.parseMinimessagePlaceholder("version", Bukkit.getServer().getClass().getPackage().getName())
|
||||
.build()
|
||||
, e);
|
||||
}
|
||||
}
|
||||
|
||||
static int generateEID() {
|
||||
return Entity.nextEntityId();
|
||||
}
|
||||
|
||||
public static void sendPackets(Player p, Object... packets) throws ReflectiveOperationException {
|
||||
Object connection = playerConnection.get(getHandle.invoke(p));
|
||||
for (Object packet : packets) {
|
||||
if (packet == null) continue;
|
||||
sendPacket.invoke(connection, packet);
|
||||
}
|
||||
}
|
||||
|
||||
public static Object createFakeDataWatcher() throws ReflectiveOperationException {
|
||||
Object watcher = watcherConstructor.newInstance(fakeSquid);
|
||||
if (version > 13) setField(watcher, "registrationLocked", false);
|
||||
return watcher;
|
||||
}
|
||||
|
||||
public static Object createCrystal(Location location, UUID uuid, int id) throws ReflectiveOperationException {
|
||||
Object entity = crystalConstructor.newInstance(nmsWorld, location.getX(), location.getY(), location.getZ());
|
||||
setEntityIDs(entity, uuid, id);
|
||||
return entity;
|
||||
}
|
||||
|
||||
public static Object createPacketEntitySpawnNormal(Location location, int typeID, Object type, int id) throws ReflectiveOperationException {
|
||||
Object packet = packetSpawnNormal.newInstance();
|
||||
setField(packet, "a", id);
|
||||
setField(packet, "b", UUID.randomUUID());
|
||||
setField(packet, "c", location.getX());
|
||||
setField(packet, "d", location.getY());
|
||||
setField(packet, "e", location.getZ());
|
||||
setField(packet, "i", (int) (location.getYaw() * 256.0F / 360.0F));
|
||||
setField(packet, "j", (int) (location.getPitch() * 256.0F / 360.0F));
|
||||
setField(packet, "k", version < 13 ? typeID : type);
|
||||
return packet;
|
||||
}
|
||||
|
||||
public static Object createPacketEntitySpawnNormal(Object entity) throws ReflectiveOperationException {
|
||||
return packetSpawnNormal.newInstance(entity);
|
||||
}
|
||||
|
||||
public static void setCrystalWatcher(Object watcher, Location target) throws ReflectiveOperationException {
|
||||
Object blockPosition =
|
||||
blockPositionConstructor.newInstance(target.getBlockX(), target.getBlockY(), target.getBlockZ());
|
||||
tryWatcherSet(watcher, watcherObject4, Optional.of(blockPosition));
|
||||
tryWatcherSet(watcher, watcherObject5, Boolean.FALSE);
|
||||
}
|
||||
|
||||
public static Object[] createPacketsRemoveEntities(int... entitiesId) throws ReflectiveOperationException {
|
||||
Object[] packets;
|
||||
if (version == 17 && versionMinor == 0) {
|
||||
packets = new Object[entitiesId.length];
|
||||
for (int i = 0; i < entitiesId.length; i++) {
|
||||
packets[i] = packetRemove.newInstance(entitiesId[i]);
|
||||
}
|
||||
} else {
|
||||
packets = new Object[]{packetRemove.newInstance(entitiesId)};
|
||||
}
|
||||
return packets;
|
||||
}
|
||||
|
||||
public static void setEntityIDs(Object entity, UUID uuid, int id) throws ReflectiveOperationException {
|
||||
setUUID.invoke(entity, uuid);
|
||||
setID.invoke(entity, id);
|
||||
}
|
||||
|
||||
static Object createPacketMetadata(int entityId, Object watcher) throws ReflectiveOperationException {
|
||||
if (version < 19 || (version == 19 && versionMinor < 3)) {
|
||||
return packetMetadata.newInstance(entityId, watcher, false);
|
||||
} else {
|
||||
return packetMetadata.newInstance(entityId, watcherPack.invoke(watcher));
|
||||
}
|
||||
}
|
||||
|
||||
private static void tryWatcherSet(Object watcher, Object watcherObject, Object watcherData) throws ReflectiveOperationException {
|
||||
try {
|
||||
watcherSet.invoke(watcher, watcherObject, watcherData);
|
||||
} catch (InvocationTargetException ex) {
|
||||
watcherRegister.invoke(watcher, watcherObject, watcherData);
|
||||
if (version >= 15) watcherDirty.invoke(watcher, watcherObject);
|
||||
}
|
||||
}
|
||||
|
||||
/* Reflection utils */
|
||||
private static Method getMethod(Class<?> clazz, String name) throws NoSuchMethodException {
|
||||
for (Method m : clazz.getDeclaredMethods()) {
|
||||
if (m.getName().equals(name)) return m;
|
||||
}
|
||||
throw new NoSuchMethodException(name + " in " + clazz.getName());
|
||||
}
|
||||
|
||||
private static void setField(Object instance, String name, Object value) throws ReflectiveOperationException {
|
||||
Field field = instance.getClass().getDeclaredField(name);
|
||||
field.setAccessible(true);
|
||||
field.set(instance, value);
|
||||
}
|
||||
|
||||
private static Object getField(Class<?> clazz, String name, Object instance) throws ReflectiveOperationException {
|
||||
Field field = clazz.getDeclaredField(name);
|
||||
field.setAccessible(true);
|
||||
return field.get(instance);
|
||||
}
|
||||
|
||||
private static Class<?> getNMSClass(String package17, String className) throws ClassNotFoundException {
|
||||
return Class.forName((version < 17 ? npack : "net.minecraft." + package17) + "." + className);
|
||||
}
|
||||
|
||||
private enum ProtocolMappings {
|
||||
V1_9(9, "Z", "bA", "bB", "b", "c", 94, 68),
|
||||
V1_10(10, V1_9),
|
||||
V1_11(11, V1_10),
|
||||
V1_12(12, V1_11),
|
||||
V1_13(13, "ac", "bF", "bG", "b", "c", 70, 28),
|
||||
V1_14(14, "W", "b", "bD", "c", "d", 73, 30),
|
||||
V1_15(15, "T", "b", "bA", "c", "d", 74, 31),
|
||||
V1_16(16, null, "b", "d", "c", "d", -1, 31) {
|
||||
@Override
|
||||
public String getWatcherFlags() {
|
||||
return Packets.versionMinor < 2 ? "T" : "S";
|
||||
}
|
||||
},
|
||||
V1_17(17, "Z", "b", "e", "c", "d", 86, 35, "K", "aJ", "u", "setCollisionRule", "getPlayerNameSet"),
|
||||
V1_18(18, null, "b", "e", "c", "d", 86, 35, "K", "aJ", "u", "a", "g") {
|
||||
@Override
|
||||
public String getWatcherFlags() {
|
||||
return Packets.versionMinor < 2 ? "aa" : "Z";
|
||||
}
|
||||
},
|
||||
V1_19(19, null, "b", "e", "c", "d", 89, 38, null, null, "w", "a", "g") {
|
||||
@Override
|
||||
public String getWatcherFlags() {
|
||||
return versionMinor < 4 ? "Z" : "an";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getSquidTypeName() {
|
||||
if (versionMinor < 3)
|
||||
return "aM";
|
||||
else if (versionMinor == 3)
|
||||
return "aN";
|
||||
else
|
||||
return "aT";
|
||||
}
|
||||
|
||||
},
|
||||
V1_20(20, null, "b", "e", "c", "d", 89, 38, "V", "aT", "B", "a", "g") {
|
||||
@Override
|
||||
public String getWatcherFlags() {
|
||||
return versionMinor < 2 ? "an" : "ao";
|
||||
}
|
||||
},
|
||||
;
|
||||
|
||||
private final int major;
|
||||
private final String watcherFlags;
|
||||
private final String watcherSpikes;
|
||||
private final String watcherTargetEntity;
|
||||
private final String watcherTargetLocation;
|
||||
private final String watcherBasePlate;
|
||||
private final int squidID;
|
||||
private final int guardianID;
|
||||
private final String guardianTypeName;
|
||||
private final String squidTypeName;
|
||||
private final String crystalTypeName;
|
||||
private final String teamSetCollision;
|
||||
private final String teamGetPlayers;
|
||||
|
||||
ProtocolMappings(int major, ProtocolMappings parent) {
|
||||
this(major, parent.watcherFlags, parent.watcherSpikes, parent.watcherTargetEntity, parent.watcherTargetLocation, parent.watcherBasePlate, parent.squidID, parent.guardianID, parent.guardianTypeName, parent.squidTypeName, parent.crystalTypeName, parent.teamSetCollision, parent.teamGetPlayers);
|
||||
}
|
||||
|
||||
ProtocolMappings(int major,
|
||||
String watcherFlags, String watcherSpikes, String watcherTargetEntity, String watcherTargetLocation, String watcherBasePlate,
|
||||
int squidID, int guardianID) {
|
||||
this(major, watcherFlags, watcherSpikes, watcherTargetEntity, watcherTargetLocation, watcherBasePlate, squidID, guardianID, null, "SQUID", "END_CRYSTAL", null, null);
|
||||
}
|
||||
|
||||
ProtocolMappings(int major,
|
||||
String watcherFlags, String watcherSpikes, String watcherTargetEntity, String watcherTargetLocation, String watcherBasePlate,
|
||||
int squidID, int guardianID,
|
||||
String guardianTypeName, String squidTypeName, String crystalTypeName, String teamSetCollision, String teamGetPlayers) {
|
||||
this.major = major;
|
||||
this.watcherFlags = watcherFlags;
|
||||
this.watcherSpikes = watcherSpikes;
|
||||
this.watcherTargetEntity = watcherTargetEntity;
|
||||
this.watcherTargetLocation = watcherTargetLocation;
|
||||
this.watcherBasePlate = watcherBasePlate;
|
||||
this.squidID = squidID;
|
||||
this.guardianID = guardianID;
|
||||
this.guardianTypeName = guardianTypeName;
|
||||
this.squidTypeName = squidTypeName;
|
||||
this.crystalTypeName = crystalTypeName;
|
||||
this.teamSetCollision = teamSetCollision;
|
||||
this.teamGetPlayers = teamGetPlayers;
|
||||
}
|
||||
|
||||
public static ProtocolMappings getMappings(int major) {
|
||||
for (ProtocolMappings map : values()) {
|
||||
if (major == map.getMajor()) return map;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public int getMajor() {
|
||||
return major;
|
||||
}
|
||||
|
||||
public String getWatcherFlags() {
|
||||
return watcherFlags;
|
||||
}
|
||||
|
||||
public String getWatcherTargetLocation() {
|
||||
return watcherTargetLocation;
|
||||
}
|
||||
|
||||
public String getWatcherBasePlate() {
|
||||
return watcherBasePlate;
|
||||
}
|
||||
|
||||
public String getSquidTypeName() {
|
||||
return squidTypeName;
|
||||
}
|
||||
|
||||
public String getCrystalTypeName() {
|
||||
return crystalTypeName;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
-98
@@ -1,98 +0,0 @@
|
||||
package com.github.alathra.alathranwars.conflict.battle.beam.betterbeam;
|
||||
|
||||
public class BetterBeam {
|
||||
/*BetterBeam() {
|
||||
PacketContainer spawnPacket = new PacketContainer(PacketType.Play.Server.SPAWN_ENTITY);
|
||||
PacketContainer metadataPacket = new PacketContainer(PacketType.Play.Server.ENTITY_METADATA);
|
||||
PacketContainer destroyPacket = new PacketContainer(PacketType.Play.Server.ENTITY_DESTROY);
|
||||
|
||||
// Required fields
|
||||
// EndCrystal entity
|
||||
// Squid entity (Made invisible)
|
||||
AlathranWars.getProtocolLibHook().getProtocolManager()
|
||||
|
||||
PacketContainer spawnCrystalPacket = new PacketContainer(PacketType.Play.Server.ENTITY_METADATA);
|
||||
PacketContainer spawnCrystalPacket = new PacketContainer(PacketType.Play.Server.ENTITY_METADATA);
|
||||
|
||||
ProtocolManager manager = AlathranWars.getProtocolLibHook().getProtocolManager();
|
||||
|
||||
Entity endcrystal;
|
||||
|
||||
endcrystal.getI
|
||||
spawnPacket.getStructures()
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
private void spawnEntity(Location location, Vector vector, EntityType type) {
|
||||
int entityId = 10000;
|
||||
|
||||
PacketContainer packet = new PacketContainer(PacketType.Play.Server.SPAWN_ENTITY);
|
||||
|
||||
// Crucial data, do not remove
|
||||
packet.getIntegers().write(0, entityId);
|
||||
packet.getUUIDs().write(0, UUID.randomUUID());
|
||||
packet.getEntityTypeModifier().write(0, type);
|
||||
|
||||
packet.getDoubles()
|
||||
.write(0, location.getX())
|
||||
.write(1, location.getY())
|
||||
.write(2, location.getZ());
|
||||
// -- section end --
|
||||
|
||||
// Pitch and yaw, remove this code section if you want to default to 0
|
||||
|
||||
packet.
|
||||
packet.getIntegers()
|
||||
.write(4, (int) (location.getPitch() * 256.0F / 360.0F))
|
||||
.write(5, (int) (location.getYaw() * 256.0F / 360.0F));
|
||||
|
||||
// -- section end --
|
||||
|
||||
// Send the packet to all players
|
||||
try {
|
||||
for(Player player : Bukkit.getOnlinePlayers()) {
|
||||
ProtocolLibrary.getProtocolManager().sendServerPacket(player, packet);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private void spawnLivingEntity(Location location, Vector vector, EntityType type) {
|
||||
int entityId = 10000;
|
||||
|
||||
PacketContainer packet = new PacketContainer(PacketType.Play.Server.SPAWN_ENTITY);
|
||||
|
||||
// Crucial data, do not remove
|
||||
packet.getIntegers().write(0, entityId);
|
||||
packet.getUUIDs().write(0, UUID.randomUUID());
|
||||
packet.getIntegers().write(1, (int) type.getTypeId()); // getTypeId is deprecated, you can find the actual IDs on wiki.vg/Protocol
|
||||
|
||||
packet.getDoubles()
|
||||
.write(0, location.getX())
|
||||
.write(1, location.getY())
|
||||
.write(2, location.getZ());
|
||||
// -- section end --
|
||||
|
||||
// Pitch and yaw, remove this code section if you want to default to 0
|
||||
packet.getBytes()
|
||||
.write(4, (byte) (location.getYaw() * 256.0F / 360.0F)) // yaw
|
||||
.write(5, (byte) (location.getPitch() * 256.0F / 360.0F)) // pitch
|
||||
.write(5, (byte) (location.getYaw() * 256.0F / 360.0F)); // head yaw
|
||||
|
||||
// -- section end --
|
||||
|
||||
// Send the packet to all players
|
||||
try {
|
||||
for(Player player : Bukkit.getOnlinePlayers()) {
|
||||
ProtocolLibrary.getProtocolManager().sendServerPacket(player, packet);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
}*/
|
||||
}
|
||||
-9
@@ -1,9 +0,0 @@
|
||||
package com.github.alathra.alathranwars.conflict.battle.phase;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
public class BattlePhaseManager<T extends Enum<T> & IBattlePhase<T>> extends BattlePhaseManagerImpl<T> {
|
||||
public BattlePhaseManager(T phase, int progress, Instant startTime) {
|
||||
super(phase, progress, startTime);
|
||||
}
|
||||
}
|
||||
-57
@@ -1,57 +0,0 @@
|
||||
package com.github.alathra.alathranwars.conflict.battle.phase;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
|
||||
public abstract class BattlePhaseManagerImpl<T extends Enum<T> & IBattlePhase<T>> implements IBattlePhaseManager<T> {
|
||||
private T phase;
|
||||
private int progress;
|
||||
private Instant startTime;
|
||||
|
||||
public BattlePhaseManagerImpl(T phase, int progress, Instant startTime) {
|
||||
this.phase = phase;
|
||||
this.progress = progress;
|
||||
this.startTime = startTime;
|
||||
}
|
||||
|
||||
@Override
|
||||
public T get() {
|
||||
return phase;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void set(T phase) throws BattlePhaseSwitchException {
|
||||
this.phase = phase;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getProgress() {
|
||||
return progress;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setProgress(int val) {
|
||||
if (val > 100) { // TODO Use phase progress max here
|
||||
val = 100;
|
||||
} else if (val < 0) {
|
||||
val = 0;
|
||||
}
|
||||
|
||||
progress = val;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Instant getStartTime() {
|
||||
return startTime;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setStartTime(Instant instant) {
|
||||
startTime = instant;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Duration getElapsedTime() {
|
||||
return Duration.between(Instant.now(), getStartTime());
|
||||
}
|
||||
}
|
||||
-7
@@ -1,7 +0,0 @@
|
||||
package com.github.alathra.alathranwars.conflict.battle.phase;
|
||||
|
||||
public class BattlePhaseSwitchException extends RuntimeException {
|
||||
public BattlePhaseSwitchException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
-100
@@ -1,100 +0,0 @@
|
||||
package com.github.alathra.alathranwars.conflict.battle.phase;
|
||||
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
/**
|
||||
* Used to implement common methods in battle phase enums
|
||||
* @param <T> the Enum
|
||||
*/
|
||||
public interface IBattlePhase<T extends Enum<T> & IBattlePhase<T>> {
|
||||
int getPhaseIdentifier();
|
||||
|
||||
/**
|
||||
* Uses {@link #next(Enum)} to get the next phase
|
||||
* @return a phase enum value
|
||||
* @throws BattlePhaseSwitchException Thrown if no next phase can be found
|
||||
*/
|
||||
T next() throws BattlePhaseSwitchException;
|
||||
|
||||
/**
|
||||
* Uses {@link #previous(Enum)} to get the previous phase
|
||||
* @return a phase enum value
|
||||
* @throws BattlePhaseSwitchException Thrown if no previous phase can be found
|
||||
*/
|
||||
T previous() throws BattlePhaseSwitchException;
|
||||
|
||||
/**
|
||||
* Get the next phase after the provided one
|
||||
* @param phase a phase enum value
|
||||
* @return a phase enum value
|
||||
* @throws BattlePhaseSwitchException Thrown if no next phase can be found
|
||||
*/
|
||||
default T next(T phase) throws BattlePhaseSwitchException {
|
||||
final int currentPhase = phase.getPhaseIdentifier();
|
||||
|
||||
// Find the next enum constant by incrementing until a valid enum constant is found
|
||||
int increment = 0;
|
||||
for (int i = 1; i < 6; i++) {
|
||||
if (fromIdentifier(currentPhase + i) != null) {
|
||||
increment = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Failed to find new phase
|
||||
if (increment == 0)
|
||||
throw new BattlePhaseSwitchException("No later phase could be found.");
|
||||
|
||||
return fromIdentifier(currentPhase + increment);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the previous phase to the provided one
|
||||
* @param phase a phase enum value
|
||||
* @return a phase enum value
|
||||
* @throws BattlePhaseSwitchException Thrown if no previous phase can be found
|
||||
*/
|
||||
default T previous(T phase) throws BattlePhaseSwitchException {
|
||||
final int currentPhase = phase.getPhaseIdentifier();
|
||||
if (currentPhase - 1 < 1)
|
||||
throw new BattlePhaseSwitchException("No previous phase could be found.");
|
||||
|
||||
// Find the previous enum constant by decrementing until a valid enum constant is found
|
||||
int decrement = 0;
|
||||
for (int i = 1; i < 6; i++) {
|
||||
if (fromIdentifier(currentPhase - i) != null) {
|
||||
decrement = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Failed to find new phase
|
||||
if (decrement == 0)
|
||||
throw new BattlePhaseSwitchException("No previous phase could be found.");
|
||||
|
||||
return fromIdentifier(currentPhase - decrement);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a phase from the phase identifier
|
||||
* @param identifier the phase identifier
|
||||
* @return a phase enum value or null if none was found
|
||||
*/
|
||||
@Nullable
|
||||
default T fromIdentifier(final int identifier) {
|
||||
if (identifier < 1)
|
||||
return null;
|
||||
|
||||
return Arrays.stream(getDeclaringClass().getEnumConstants())
|
||||
.filter(phase -> phase.getPhaseIdentifier() == identifier)
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Don't override this method, it is implemented in all enums by default.
|
||||
*/
|
||||
Class<T> getDeclaringClass();
|
||||
}
|
||||
-70
@@ -1,70 +0,0 @@
|
||||
package com.github.alathra.alathranwars.conflict.battle.phase;
|
||||
|
||||
import org.jetbrains.annotations.ApiStatus;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
|
||||
public interface IBattlePhaseManager<T extends Enum<T> & IBattlePhase<T>> {
|
||||
/**
|
||||
* Get the current battle phase
|
||||
* @return the phase
|
||||
*/
|
||||
T get();
|
||||
|
||||
/**
|
||||
* Set the current battle phase
|
||||
* @param phase the phase
|
||||
* @throws BattlePhaseSwitchException Thrown if unable to switch phase
|
||||
*/
|
||||
@ApiStatus.Internal
|
||||
void set(T phase) throws BattlePhaseSwitchException;
|
||||
|
||||
/**
|
||||
* Goes to the next battle phase if possible
|
||||
* @throws BattlePhaseSwitchException Thrown if unable to switch phase
|
||||
*/
|
||||
default T next() throws BattlePhaseSwitchException {
|
||||
return get().next();
|
||||
};
|
||||
|
||||
/**
|
||||
* Goes to the previous battle phase if possible
|
||||
* @throws BattlePhaseSwitchException Thrown if unable to switch phase
|
||||
*/
|
||||
default T previous() throws BattlePhaseSwitchException {
|
||||
return get().previous();
|
||||
};
|
||||
|
||||
/**
|
||||
* Get the current phase progress
|
||||
* @return integer from 0 to 100
|
||||
*/
|
||||
int getProgress();
|
||||
|
||||
/**
|
||||
* Set the current phase progress
|
||||
* @param val integer from 0 to 100
|
||||
*/
|
||||
@ApiStatus.Internal
|
||||
void setProgress(int val);
|
||||
|
||||
/**
|
||||
* Get the time at which this phase started
|
||||
* @return the instant at which this phase started
|
||||
*/
|
||||
Instant getStartTime();
|
||||
|
||||
/**
|
||||
* Set the time of when this phase started
|
||||
* @param instant the instant at which this phase started
|
||||
*/
|
||||
@ApiStatus.Internal
|
||||
void setStartTime(Instant instant);
|
||||
|
||||
/**
|
||||
* Get the duration between now and when phase started
|
||||
* @return duration between now and start time
|
||||
*/
|
||||
Duration getElapsedTime();
|
||||
}
|
||||
-36
@@ -1,36 +0,0 @@
|
||||
package com.github.alathra.alathranwars.conflict.battle.phase;
|
||||
|
||||
public enum TestBattlePhase implements IBattlePhase<TestBattlePhase> {
|
||||
INITIAL(1),
|
||||
FIGHTING(2),
|
||||
END(3);
|
||||
|
||||
// Identifiers start at 1, used to traverse between stages
|
||||
private final int phaseIdentifier;
|
||||
|
||||
TestBattlePhase(int phaseIdentifier) {
|
||||
this.phaseIdentifier = phaseIdentifier;
|
||||
}
|
||||
|
||||
public int getPhaseIdentifier() {
|
||||
return phaseIdentifier;
|
||||
}
|
||||
|
||||
public TestBattlePhase next() throws BattlePhaseSwitchException {
|
||||
return next(fromIdentifier(getPhaseIdentifier()));
|
||||
}
|
||||
|
||||
public TestBattlePhase previous() throws BattlePhaseSwitchException {
|
||||
return previous(fromIdentifier(getPhaseIdentifier()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public TestBattlePhase next(TestBattlePhase phase) throws BattlePhaseSwitchException {
|
||||
return IBattlePhase.super.next(phase);
|
||||
}
|
||||
|
||||
@Override
|
||||
public TestBattlePhase previous(TestBattlePhase phase) throws BattlePhaseSwitchException {
|
||||
return IBattlePhase.super.previous(phase);
|
||||
}
|
||||
}
|
||||
-7
@@ -1,7 +0,0 @@
|
||||
package com.github.alathra.alathranwars.conflict.battle.progress;
|
||||
|
||||
public class BattleProgressManager extends BattleProgressManagerImpl {
|
||||
public BattleProgressManager(int progress, int maxProgress) {
|
||||
super(progress, maxProgress);
|
||||
}
|
||||
}
|
||||
-32
@@ -1,32 +0,0 @@
|
||||
package com.github.alathra.alathranwars.conflict.battle.progress;
|
||||
|
||||
public abstract class BattleProgressManagerImpl implements IBattleProgressManager {
|
||||
private int progress;
|
||||
private final int maxProgress;
|
||||
|
||||
public BattleProgressManagerImpl(int progress, int maxProgress) {
|
||||
this.progress = progress;
|
||||
this.maxProgress = maxProgress;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int get() {
|
||||
return progress;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void set(int val) {
|
||||
if (val > getMax()) {
|
||||
val = getMax();
|
||||
} else if (val < 0) {
|
||||
val = 0;
|
||||
}
|
||||
|
||||
progress = val;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getMax() {
|
||||
return maxProgress;
|
||||
}
|
||||
}
|
||||
-24
@@ -1,24 +0,0 @@
|
||||
package com.github.alathra.alathranwars.conflict.battle.progress;
|
||||
|
||||
import org.jetbrains.annotations.ApiStatus;
|
||||
|
||||
public interface IBattleProgressManager {
|
||||
/**
|
||||
* Get the current battle progress
|
||||
* @return the current progress
|
||||
*/
|
||||
int get();
|
||||
|
||||
/**
|
||||
* Set the current battle progress
|
||||
* @param val the new progress (Cannot be higher than max or lower than 0)
|
||||
*/
|
||||
@ApiStatus.Internal
|
||||
void set(int val);
|
||||
|
||||
/**
|
||||
* Get the current battles maximum progress
|
||||
* @return the maximum progress this battle can reach
|
||||
*/
|
||||
int getMax();
|
||||
}
|
||||
@@ -1,645 +0,0 @@
|
||||
package com.github.alathra.alathranwars.conflict.battle.raid;
|
||||
|
||||
import com.github.alathra.alathranwars.AlathranWars;
|
||||
import com.github.alathra.alathranwars.conflict.battle.Battle;
|
||||
import com.github.alathra.alathranwars.conflict.war.War;
|
||||
import com.github.alathra.alathranwars.conflict.war.side.Side;
|
||||
import com.github.alathra.alathranwars.enums.CaptureProgressDirection;
|
||||
import com.github.alathra.alathranwars.enums.battle.*;
|
||||
import com.github.alathra.alathranwars.events.battle.BattleResultEvent;
|
||||
import com.github.alathra.alathranwars.events.battle.PreBattleResultEvent;
|
||||
import com.github.milkdrinkers.colorparser.ColorParser;
|
||||
import com.palmergames.bukkit.towny.object.Town;
|
||||
import com.palmergames.bukkit.towny.object.TownBlock;
|
||||
import net.kyori.adventure.bossbar.BossBar;
|
||||
import net.kyori.adventure.key.Key;
|
||||
import net.kyori.adventure.sound.Sound;
|
||||
import net.kyori.adventure.text.Component;
|
||||
import net.kyori.adventure.title.Title;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.OfflinePlayer;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
/**
|
||||
* Credits to the original authors for their implementation which greatly inspired the new one.
|
||||
*
|
||||
* @author darksaid98
|
||||
*
|
||||
* @author AubriTheHuman
|
||||
* @author NinjaMandalorian
|
||||
* @author ShermansWorld
|
||||
*/
|
||||
public class Raid {
|
||||
// public static final Duration RAID_DURATION = Duration.ofMinutes(60);
|
||||
// public static final int MAX_RAID_PROGRESS_MINUTES = 8; // How many minutes attackers will need to be on point uncontested for to reach 100%
|
||||
// public static final int MAX_RAID_PROGRESS = 60 * 10 * MAX_RAID_PROGRESS_MINUTES; // On reaching this, the attackers win. 10 points is added per second
|
||||
// public static final Duration ATTACKERS_MUST_TOUCH_END = Duration.ofMinutes(40); // If point is not touched in this much time, defenders win
|
||||
// public static final Duration ATTACKERS_MUST_TOUCH_REVERT = Duration.ofSeconds(60); // If point is not touched in this much time, raid progress begins reverting
|
||||
// public static final int BATTLEFIELD_RANGE = 500;
|
||||
// public static final int BATTLEFIELD_START_MAX_RANGE = BATTLEFIELD_RANGE * 2;
|
||||
// public static final int BATTLEFIELD_START_MIN_RANGE = 75;
|
||||
// public static final double SIEGE_VICTORY_MONEY = 2500.0;
|
||||
//
|
||||
// private final @NotNull UUID uuid;
|
||||
// private final Set<Player> attackers = new HashSet<>(); // Players inside battlefield
|
||||
// private final Set<Player> defenders = new HashSet<>(); // Players inside battlefield
|
||||
// private final Set<Player> attackerPlayers = new HashSet<>();
|
||||
// private final Set<Player> defenderPlayers = new HashSet<>();
|
||||
// private final Set<UUID> attackerPlayersIncludingOffline = new HashSet<>();
|
||||
// private final Set<UUID> defenderPlayersIncludingOffline = new HashSet<>();
|
||||
// private @NotNull War war; // War which raid belongs to
|
||||
// private Instant endTime;
|
||||
// private int raidProgress = 0;
|
||||
// private Instant lastTouched;
|
||||
// private RaidRunnable raidRunnable;
|
||||
// private Town town; // Town of the raid
|
||||
// private boolean side1AreAttackers; // bool of if side1 being attacker
|
||||
// private OfflinePlayer raidLeader;
|
||||
// private @Nullable TownBlock homeBlock = null;
|
||||
// private @Nullable Location townSpawn = null;
|
||||
// private @Nullable BossBar activeBossBar = null;
|
||||
// private boolean stopped = false; // Used to track if the raid has been already deleted
|
||||
//
|
||||
// public Raid(final @NotNull War war, final Town town, Player raidLeader) {
|
||||
// uuid = UUID.randomUUID();
|
||||
//
|
||||
// endTime = Instant.now().plus(RAID_DURATION);
|
||||
// lastTouched = Instant.now();
|
||||
//
|
||||
// this.war = war;
|
||||
// this.town = town;
|
||||
// this.raidLeader = raidLeader;
|
||||
//
|
||||
// side1AreAttackers = war.getSide(town).getTeam().equals(BattleTeam.SIDE_2);
|
||||
//
|
||||
// if (getSide1AreAttackers()) {
|
||||
// attackerPlayersIncludingOffline.addAll(getWar().getSide1().getPlayersAll());
|
||||
// defenderPlayersIncludingOffline.addAll(getWar().getSide2().getPlayersAll());
|
||||
// } else {
|
||||
// attackerPlayersIncludingOffline.addAll(getWar().getSide2().getPlayersAll());
|
||||
// defenderPlayersIncludingOffline.addAll(getWar().getSide1().getPlayersAll());
|
||||
// }
|
||||
// calculateOnlinePlayers();
|
||||
// }
|
||||
//
|
||||
// // Construct when loading from DB
|
||||
// public Raid(War war, @NotNull UUID uuid, Town town, OfflinePlayer raidLeader, Instant endTime, Instant lastTouched, int raidProgress, Set<UUID> attackerPlayersIncludingOffline, Set<UUID> defenderPlayersIncludingOffline) {
|
||||
// this.war = war;
|
||||
// this.uuid = uuid;
|
||||
// this.town = town;
|
||||
// this.raidLeader = raidLeader;
|
||||
// this.endTime = endTime;
|
||||
// this.lastTouched = lastTouched;
|
||||
// this.raidProgress = raidProgress;
|
||||
// this.attackerPlayersIncludingOffline.addAll(attackerPlayersIncludingOffline);
|
||||
// this.defenderPlayersIncludingOffline.addAll(defenderPlayersIncludingOffline);
|
||||
//
|
||||
// side1AreAttackers = war.getSide(town).getTeam().equals(BattleTeam.SIDE_2);
|
||||
//
|
||||
// calculateOnlinePlayers();
|
||||
// }
|
||||
//
|
||||
// /**
|
||||
// * Starts a raid
|
||||
// */
|
||||
// public void start() {
|
||||
// raidRunnable = new RaidRunnable(this);
|
||||
// if (!war.isEventWar())
|
||||
// AlathranWars.econ.withdrawPlayer(raidLeader, SIEGE_VICTORY_MONEY);
|
||||
//
|
||||
// final Title.Times times = Title.Times.times(Duration.ofMillis(500), Duration.ofMillis(3500), Duration.ofMillis(500));
|
||||
// final Title defTitle = Title.title(
|
||||
// ColorParser.of("<red><u><b><town>")
|
||||
// .parseMinimessagePlaceholder("town", town.getName())
|
||||
// .build(),
|
||||
// ColorParser.of("<gray><i>Is under raid, defend!")
|
||||
// .build(),
|
||||
// times
|
||||
// );
|
||||
// final Title attTitle = Title.title(
|
||||
// ColorParser.of("<red><u><b><town>")
|
||||
// .parseMinimessagePlaceholder("town", town.getName())
|
||||
// .build(),
|
||||
// ColorParser.of("<gray><i>Has been put to raid, attack!")
|
||||
// .build(),
|
||||
// times
|
||||
// );
|
||||
//
|
||||
// final List<Sound> soundList = List.of(
|
||||
// Sound.sound(Key.key("item.goat_horn.sound.0"), Sound.Source.VOICE, 0.5f, new Random().nextFloat(0.9F, 1.0F)),
|
||||
// Sound.sound(Key.key("item.goat_horn.sound.2"), Sound.Source.VOICE, 0.5f, new Random().nextFloat(0.9F, 1.0F)),
|
||||
// Sound.sound(Key.key("item.goat_horn.sound.3"), Sound.Source.VOICE, 0.5f, new Random().nextFloat(0.9F, 1.0F)),
|
||||
// Sound.sound(Key.key("item.goat_horn.sound.7"), Sound.Source.VOICE, 0.5f, new Random().nextFloat(0.9F, 1.0F))
|
||||
// );
|
||||
//
|
||||
// getDefenderPlayers().forEach(player -> {
|
||||
// player.showTitle(defTitle);
|
||||
// player.playSound(soundList.get(new Random().nextInt(1, soundList.size())));
|
||||
// });
|
||||
//
|
||||
// getAttackerPlayers().forEach(player -> {
|
||||
// player.showTitle(attTitle);
|
||||
// player.playSound(soundList.get(new Random().nextInt(1, soundList.size())));
|
||||
// });
|
||||
// }
|
||||
//
|
||||
// /**
|
||||
// * Resumes a raid (after a server restart e.t.c.)
|
||||
// */
|
||||
// public void resume() {
|
||||
// raidRunnable = new RaidRunnable(this, getRaidProgress());
|
||||
// }
|
||||
//
|
||||
// /**
|
||||
// * Stops a raid
|
||||
// */
|
||||
// public void stop() {
|
||||
// if (stopped) return;
|
||||
// stopped = true;
|
||||
// raidRunnable.cancel();
|
||||
//// DatabaseQueries.deleteRaid(this); // TODO Delete raid
|
||||
// war.removeRaid(this);
|
||||
// }
|
||||
//
|
||||
// public void attackersWin(BattleVictoryReason reason) {
|
||||
// if (!new PreBattleResultEvent(war, this, BattleType.SIEGE, BattleVictor.ATTACKER, reason).callEvent()) return;
|
||||
//
|
||||
// if (!war.isEventWar()) {
|
||||
// AlathranWars.econ.depositPlayer(raidLeader, SIEGE_VICTORY_MONEY);
|
||||
// double amt;
|
||||
//
|
||||
// if (town.getAccount().getHoldingBalance() > 10000.0) {
|
||||
// amt = Math.floor(town.getAccount().getHoldingBalance()) / 4.0;
|
||||
// town.getAccount().withdraw(amt, "Raid Defeat");
|
||||
// } else {
|
||||
// town.getAccount().withdraw(SIEGE_VICTORY_MONEY, "Raid Defeat");
|
||||
// amt = SIEGE_VICTORY_MONEY;
|
||||
// }
|
||||
//
|
||||
// AlathranWars.econ.depositPlayer(raidLeader, amt);
|
||||
// }
|
||||
//
|
||||
// if (side1AreAttackers) {
|
||||
// war.getSide1().addScore(50);
|
||||
// war.getSide2().addScore(5);
|
||||
// } else {
|
||||
// war.getSide1().addScore(5);
|
||||
// war.getSide2().addScore(50);
|
||||
// }
|
||||
//
|
||||
// new BattleResultEvent(war, this, BattleVictor.ATTACKER, reason).callEvent();
|
||||
//
|
||||
// stop();
|
||||
//
|
||||
// if (!war.isEventWar()) {
|
||||
// Side townSide = getWar().getSide(town);
|
||||
// Side attackerSide = getAttackerSide();
|
||||
//
|
||||
// if (attackerSide.equals(townSide)) {
|
||||
// if (townSide.isSurrendered(town))
|
||||
// war.unsurrender(town);
|
||||
// } else {
|
||||
// if (!townSide.isSurrendered(town))
|
||||
// war.surrender(town);
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// public void defendersWin(BattleVictoryReason reason) {
|
||||
// if (!new PreBattleResultEvent(war, this, BattleType.SIEGE, BattleVictor.DEFENDER, reason).callEvent()) return;
|
||||
//
|
||||
// if (!war.isEventWar())
|
||||
// town.getAccount().deposit(SIEGE_VICTORY_MONEY, "Raid Victory");
|
||||
//
|
||||
// if (side1AreAttackers) {
|
||||
// war.getSide2().addScore(10);
|
||||
// } else {
|
||||
// war.getSide1().addScore(10);
|
||||
// }
|
||||
//
|
||||
// new BattleResultEvent(war, this, BattleVictor.DEFENDER, reason).callEvent();
|
||||
//
|
||||
// stop();
|
||||
// }
|
||||
//
|
||||
// /**
|
||||
// * No winner declared
|
||||
// */
|
||||
// public void equalWin(BattleVictoryReason reason) {
|
||||
// if (!new PreBattleResultEvent(war, this, BattleType.SIEGE, BattleVictor.DRAW, reason).callEvent()) return;
|
||||
//
|
||||
// new BattleResultEvent(war, this, BattleVictor.DRAW, reason).callEvent();
|
||||
//
|
||||
// stop();
|
||||
// }
|
||||
//
|
||||
// @NotNull
|
||||
// public Instant getLastTouched() {
|
||||
// return lastTouched;
|
||||
// }
|
||||
//
|
||||
// public void setLastTouched(Instant lastTouched) {
|
||||
// this.lastTouched = lastTouched;
|
||||
// }
|
||||
//
|
||||
// public int getRaidProgress() {
|
||||
// return raidProgress;
|
||||
// }
|
||||
//
|
||||
// public void setRaidProgress(int raidProgress) {
|
||||
// if (raidProgress < 0) {
|
||||
// raidProgress = 0;
|
||||
// } else if (raidProgress > MAX_RAID_PROGRESS) {
|
||||
// raidProgress = MAX_RAID_PROGRESS;
|
||||
// }
|
||||
// this.raidProgress = raidProgress;
|
||||
// }
|
||||
//
|
||||
// public float getRaidProgressPercentage() {
|
||||
// return (getRaidProgress() * 1.0f) / MAX_RAID_PROGRESS;
|
||||
// }
|
||||
//
|
||||
// @NotNull
|
||||
// public War getWar() {
|
||||
// return war;
|
||||
// }
|
||||
//
|
||||
// public void setWar(final War war) {
|
||||
// this.war = war;
|
||||
// }
|
||||
//
|
||||
// @NotNull
|
||||
// public Town getTown() {
|
||||
// return town;
|
||||
// }
|
||||
//
|
||||
// public void setTown(final Town town) {
|
||||
// this.town = town;
|
||||
// }
|
||||
//
|
||||
// /**
|
||||
// * Gets attacker name string
|
||||
// */
|
||||
// @NotNull
|
||||
// public Side getAttackerSide() {
|
||||
// return side1AreAttackers ? war.getSide1() : war.getSide2();
|
||||
// }
|
||||
//
|
||||
// /**
|
||||
// * Gets defender name string
|
||||
// */
|
||||
// @NotNull
|
||||
// public Side getDefenderSide() {
|
||||
// return side1AreAttackers ? war.getSide2() : war.getSide1();
|
||||
// }
|
||||
//
|
||||
// // SECTION Display Bar
|
||||
//
|
||||
// public void updateDisplayBar(@NotNull CaptureProgressDirection progressDirection) {
|
||||
// if (activeBossBar == null)
|
||||
// createNewDisplayBar();
|
||||
//
|
||||
// for (@NotNull Player p : Bukkit.getOnlinePlayers()) {
|
||||
// p.hideBossBar(activeBossBar);
|
||||
// }
|
||||
//
|
||||
// for (@Nullable Player p : this.getPlayersOnBattlefield()) {
|
||||
// if (p != null)
|
||||
// p.showBossBar(activeBossBar);
|
||||
// }
|
||||
//
|
||||
// final String color = switch (progressDirection) {
|
||||
// case UP -> {
|
||||
// if (getAttackerSide().getSide().equals(BattleSide.ATTACKER)) {
|
||||
// activeBossBar.color(BossBar.Color.RED);
|
||||
// yield "<red>";
|
||||
// } else {
|
||||
// activeBossBar.color(BossBar.Color.BLUE);
|
||||
// yield "<blue>";
|
||||
// }
|
||||
// }
|
||||
// case CONTESTED -> {
|
||||
// activeBossBar.color(BossBar.Color.YELLOW);
|
||||
// yield "<yellow>";
|
||||
// }
|
||||
// case UNCONTESTED -> {
|
||||
// activeBossBar.color(BossBar.Color.WHITE);
|
||||
// yield "<white>";
|
||||
// }
|
||||
// case DOWN -> {
|
||||
// if (getAttackerSide().getSide().equals(BattleSide.ATTACKER)) {
|
||||
// activeBossBar.color(BossBar.Color.BLUE);
|
||||
// yield "<blue>";
|
||||
// } else {
|
||||
// activeBossBar.color(BossBar.Color.RED);
|
||||
// yield "<red>";
|
||||
// }
|
||||
// }
|
||||
// };
|
||||
//
|
||||
// if (Instant.now().isBefore(getEndTime())) {
|
||||
// activeBossBar.name(
|
||||
// ColorParser.of("<gray>Capture Progress: %s<progress> <gray>Time: %s<time>min".formatted(color, color))
|
||||
// .parseMinimessagePlaceholder("progress", "%.0f%%".formatted(getRaidProgressPercentage() * 100))
|
||||
// .parseMinimessagePlaceholder("time", String.valueOf(Duration.between(Instant.now(), getEndTime()).toMinutes()))
|
||||
// .build()
|
||||
// );
|
||||
// } else {
|
||||
// activeBossBar.name(
|
||||
// ColorParser.of("%sOVERTIME".formatted(color)).build()
|
||||
// );
|
||||
// }
|
||||
// activeBossBar.progress(getRaidProgressPercentage());
|
||||
// }
|
||||
//
|
||||
// public void createNewDisplayBar() {
|
||||
// final @NotNull Component text = ColorParser.of("<gray>Capture Progress: <yellow><progress> <gray>Time: <yellow><time>min")
|
||||
// .parseMinimessagePlaceholder("progress", "%.0f%%".formatted(getRaidProgressPercentage() * 100))
|
||||
// .parseMinimessagePlaceholder("time", String.valueOf(Duration.between(Instant.now(), getEndTime()).toMinutesPart()))
|
||||
// .build();
|
||||
//
|
||||
// this.activeBossBar = BossBar.bossBar(text, 0, BossBar.Color.YELLOW, BossBar.Overlay.NOTCHED_10);
|
||||
// }
|
||||
//
|
||||
// public void deleteDisplayBar() {
|
||||
// if (activeBossBar != null) {
|
||||
// for (@NotNull Player p : Bukkit.getOnlinePlayers()) {
|
||||
// p.hideBossBar(activeBossBar);
|
||||
// }
|
||||
//
|
||||
// activeBossBar = null;
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// // SECTION UUID
|
||||
//
|
||||
// public @NotNull UUID getUUID() {
|
||||
// return uuid;
|
||||
// }
|
||||
//
|
||||
// /**
|
||||
// * Equals boolean.
|
||||
// *
|
||||
// * @param uuid the uuid
|
||||
// * @return the boolean
|
||||
// */
|
||||
// public boolean equals(UUID uuid) {
|
||||
// return getUUID().equals(uuid);
|
||||
// }
|
||||
//
|
||||
// /**
|
||||
// * Equals boolean.
|
||||
// *
|
||||
// * @param raid the raid
|
||||
// * @return the boolean
|
||||
// */
|
||||
// public boolean equals(@NotNull Raid raid) {
|
||||
// return getUUID().equals(raid.getUUID());
|
||||
// }
|
||||
//
|
||||
// // SECTION Accessors & Getters
|
||||
//
|
||||
// @Nullable
|
||||
// public TownBlock getHomeBlock() {
|
||||
// return homeBlock;
|
||||
// }
|
||||
//
|
||||
// public void setHomeBlock(TownBlock homeBlock) {
|
||||
// this.homeBlock = homeBlock;
|
||||
// }
|
||||
//
|
||||
// @Nullable
|
||||
// public Location getTownSpawn() {
|
||||
// return townSpawn;
|
||||
// }
|
||||
//
|
||||
// public void setTownSpawn(Location townSpawn) {
|
||||
// this.townSpawn = townSpawn;
|
||||
// }
|
||||
//
|
||||
// public boolean getSide1AreAttackers() {
|
||||
// return side1AreAttackers;
|
||||
// }
|
||||
//
|
||||
// public void setSide1AreAttackers(final boolean side1AreAttackers) {
|
||||
// this.side1AreAttackers = side1AreAttackers;
|
||||
// }
|
||||
//
|
||||
// @NotNull
|
||||
// public Set<Player> getPlayersOnBattlefield() {
|
||||
// return Stream.concat(attackers.stream(), defenders.stream()).collect(Collectors.toSet());
|
||||
// }
|
||||
//
|
||||
// @NotNull
|
||||
// public Set<Player> getAttackers() {
|
||||
// return attackers;
|
||||
// }
|
||||
//
|
||||
// @NotNull
|
||||
// public Set<Player> getDefenders() {
|
||||
// return defenders;
|
||||
// }
|
||||
//
|
||||
// @NotNull
|
||||
// public Set<Player> getAttackerPlayers() {
|
||||
// return attackerPlayers;
|
||||
// }
|
||||
//
|
||||
// @NotNull
|
||||
// public Set<Player> getDefenderPlayers() {
|
||||
// return defenderPlayers;
|
||||
// }
|
||||
//
|
||||
// @NotNull
|
||||
// public OfflinePlayer getRaidLeader() {
|
||||
// return raidLeader;
|
||||
// }
|
||||
//
|
||||
// public void setRaidLeader(OfflinePlayer raidLeader) {
|
||||
// this.raidLeader = raidLeader;
|
||||
// }
|
||||
//
|
||||
// @NotNull
|
||||
// public String getName() { // TODO Make better raidnames
|
||||
// return getTown().getName();
|
||||
// }
|
||||
//
|
||||
// // SECTION Time management
|
||||
//
|
||||
// @NotNull
|
||||
// public Instant getEndTime() {
|
||||
// return endTime;
|
||||
// }
|
||||
//
|
||||
// public void setEndTime(Instant time) {
|
||||
// endTime = time;
|
||||
// }
|
||||
//
|
||||
// // SECTION Player management
|
||||
//
|
||||
// public boolean isPlayerInRaid(UUID uuid) {
|
||||
// return attackerPlayersIncludingOffline.contains(uuid) || defenderPlayersIncludingOffline.contains(uuid);
|
||||
// }
|
||||
//
|
||||
// public boolean isPlayerInRaid(@NotNull Player p) {
|
||||
// return isPlayerInRaid(p.getUniqueId());
|
||||
// }
|
||||
//
|
||||
// public @NotNull BattleSide getPlayerSideInRaid(UUID uuid) {
|
||||
// if (attackerPlayersIncludingOffline.contains(uuid))
|
||||
// return BattleSide.ATTACKER;
|
||||
//
|
||||
// if (defenderPlayersIncludingOffline.contains(uuid))
|
||||
// return BattleSide.DEFENDER;
|
||||
//
|
||||
// return BattleSide.SPECTATOR;
|
||||
// }
|
||||
//
|
||||
// public @NotNull BattleSide getPlayerSideInRaid(@NotNull Player p) {
|
||||
// return getPlayerSideInRaid(p.getUniqueId());
|
||||
// }
|
||||
//
|
||||
// public void addPlayer(@NotNull Player p, @NotNull BattleSide side) {
|
||||
// addPlayer(p.getUniqueId(), side);
|
||||
// }
|
||||
//
|
||||
// public void addPlayer(@NotNull OfflinePlayer offlinePlayer, @NotNull BattleSide side) {
|
||||
// if (offlinePlayer.hasPlayedBefore())
|
||||
// addPlayer(offlinePlayer.getUniqueId(), side);
|
||||
// }
|
||||
//
|
||||
// public void addPlayer(@NotNull UUID uuid, @NotNull BattleSide side) {
|
||||
// if (isPlayerInRaid(uuid)) return;
|
||||
//
|
||||
// switch (side) {
|
||||
// case ATTACKER -> attackerPlayersIncludingOffline.add(uuid);
|
||||
// case DEFENDER -> defenderPlayersIncludingOffline.add(uuid);
|
||||
// }
|
||||
//
|
||||
// if (Bukkit.getOfflinePlayer(uuid).isOnline()) {
|
||||
// final @Nullable Player p = Bukkit.getPlayer(uuid);
|
||||
// addOnlinePlayer(p, side);
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// public void addOnlinePlayer(Player p, @NotNull BattleSide side) {
|
||||
// switch (side) {
|
||||
// case ATTACKER -> attackerPlayers.add(p);
|
||||
// case DEFENDER -> defenderPlayers.add(p);
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// public void removePlayer(@NotNull Player p) {
|
||||
// removePlayer(p.getUniqueId());
|
||||
// }
|
||||
//
|
||||
// public void removePlayer(@NotNull OfflinePlayer offlinePlayer) {
|
||||
// if (offlinePlayer.hasPlayedBefore())
|
||||
// removePlayer(offlinePlayer.getUniqueId());
|
||||
// }
|
||||
//
|
||||
// public void removePlayer(@NotNull UUID uuid) {
|
||||
// if (!isPlayerInRaid(uuid)) return;
|
||||
//
|
||||
// final @NotNull BattleSide side = getPlayerSideInRaid(uuid);
|
||||
//
|
||||
// switch (side) {
|
||||
// case ATTACKER -> attackerPlayersIncludingOffline.remove(uuid);
|
||||
// case DEFENDER -> defenderPlayersIncludingOffline.remove(uuid);
|
||||
// }
|
||||
//
|
||||
// if (Bukkit.getOfflinePlayer(uuid).isOnline()) {
|
||||
// final @Nullable Player p = Bukkit.getPlayer(uuid);
|
||||
// removeOnlinePlayer(p, side);
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// public void removeOnlinePlayer(Player p, @NotNull BattleSide side) {
|
||||
// switch (side) {
|
||||
// case ATTACKER -> attackerPlayers.remove(p);
|
||||
// case DEFENDER -> defenderPlayers.remove(p);
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// public Set<UUID> getAttackerPlayersIncludingOffline() {
|
||||
// return attackerPlayersIncludingOffline;
|
||||
// }
|
||||
//
|
||||
// public Set<UUID> getDefenderPlayersIncludingOffline() {
|
||||
// return defenderPlayersIncludingOffline;
|
||||
// }
|
||||
//
|
||||
// public void calculateOnlinePlayers() {
|
||||
// final @NotNull Set<Player> onlineAttackers = attackerPlayersIncludingOffline.stream()
|
||||
// .filter(uuid1 -> Bukkit.getOfflinePlayer(uuid1).isOnline())
|
||||
// .map(Bukkit::getPlayer)
|
||||
// .collect(Collectors.toSet());
|
||||
//
|
||||
// attackerPlayers.clear();
|
||||
// attackerPlayers.addAll(onlineAttackers);
|
||||
//
|
||||
// final @NotNull Set<Player> onlineDefenders = defenderPlayersIncludingOffline.stream()
|
||||
// .filter(uuid1 -> Bukkit.getOfflinePlayer(uuid1).isOnline())
|
||||
// .map(Bukkit::getPlayer)
|
||||
// .collect(Collectors.toSet());
|
||||
//
|
||||
// defenderPlayers.clear();
|
||||
// defenderPlayers.addAll(onlineDefenders);
|
||||
// }
|
||||
//
|
||||
// public void calculateBattlefieldPlayers(@NotNull Location location) {
|
||||
// final Set<Player> previousAttackersOnBattlefield = new HashSet<>(attackers);
|
||||
// final Set<Player> previousDefendersOnBattlefield = new HashSet<>(defenders);
|
||||
//
|
||||
// final @NotNull Set<Player> attackersOnBattlefield = attackerPlayers.stream()
|
||||
// .filter(OfflinePlayer::isOnline)
|
||||
// .filter(p -> location.getWorld().equals(p.getLocation().getWorld()))
|
||||
// .filter(p -> location.distance(p.getLocation()) < BATTLEFIELD_RANGE)
|
||||
// .collect(Collectors.toSet());
|
||||
//
|
||||
// attackers.clear();
|
||||
// attackers.addAll(attackersOnBattlefield);
|
||||
//
|
||||
// final @NotNull Set<Player> defendersOnBattlefield = defenderPlayers.stream()
|
||||
// .filter(OfflinePlayer::isOnline)
|
||||
// .filter(p -> location.getWorld().equals(p.getLocation().getWorld()))
|
||||
// .filter(p -> location.distance(p.getLocation()) < BATTLEFIELD_RANGE)
|
||||
// .collect(Collectors.toSet());
|
||||
//
|
||||
// defenders.clear();
|
||||
// defenders.addAll(defendersOnBattlefield);
|
||||
//
|
||||
// // Emit events for players leaving & entering the battlefield
|
||||
// for (Player p : previousAttackersOnBattlefield) {
|
||||
// if (p.isConnected() && !attackers.contains(p)) {
|
||||
// // TODO Player left battlefield
|
||||
// }
|
||||
// }
|
||||
// for (Player p : attackers) {
|
||||
// if (p.isConnected() && !previousAttackersOnBattlefield.contains(p)) {
|
||||
// // TODO Player entered battlefield
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// for (Player p : previousDefendersOnBattlefield) {
|
||||
// if (p.isConnected() && !defenders.contains(p)) {
|
||||
// // TODO Player left battlefield
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// for (Player p : defenders) {
|
||||
// if (p.isConnected() && !previousDefendersOnBattlefield.contains(p)) {
|
||||
// // TODO Player entered battlefield
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
}
|
||||
@@ -1,259 +0,0 @@
|
||||
package com.github.alathra.alathranwars.conflict.battle.raid;
|
||||
|
||||
import com.github.alathra.alathranwars.AlathranWars;
|
||||
import com.github.alathra.alathranwars.conflict.battle.beam.CrystalLaser;
|
||||
import com.github.alathra.alathranwars.conflict.battle.beam.Laser;
|
||||
import com.github.alathra.alathranwars.enums.CaptureProgressDirection;
|
||||
import com.github.alathra.alathranwars.enums.battle.BattleSide;
|
||||
import com.github.alathra.alathranwars.enums.battle.BattleVictoryReason;
|
||||
import com.github.alathra.alathranwars.utility.UtilsChat;
|
||||
import com.github.milkdrinkers.colorparser.ColorParser;
|
||||
import com.palmergames.bukkit.towny.object.Town;
|
||||
import com.palmergames.bukkit.towny.object.TownBlock;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import space.arim.morepaperlib.scheduling.ScheduledTask;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
|
||||
import static com.github.alathra.alathranwars.enums.CaptureProgressDirection.*;
|
||||
|
||||
/*public class RaidRunnable implements Runnable {
|
||||
// Settings
|
||||
private static final Duration ANNOUNCEMENT_COOLDOWN = Duration.ofMinutes(5);
|
||||
private final static int CAPTURE_RANGE = 10;
|
||||
private final @NotNull Raid raid;
|
||||
|
||||
// Variables
|
||||
private @NotNull CaptureProgressDirection oldProgressDirection = UNCONTESTED;
|
||||
private Instant nextAnnouncement;
|
||||
private final ScheduledTask task;
|
||||
private @Nullable Laser beam;
|
||||
|
||||
*//**
|
||||
* Start a raid
|
||||
*
|
||||
* @param raid the raid
|
||||
*//*
|
||||
public RaidRunnable(@NotNull Raid raid) {
|
||||
this.raid = raid;
|
||||
|
||||
raid.setRaidProgress(0);
|
||||
|
||||
raid.setHomeBlock(raid.getTown().getHomeBlockOrNull());
|
||||
raid.setTownSpawn(raid.getTown().getSpawnOrNull());
|
||||
|
||||
nextAnnouncement = Instant.now().plus(ANNOUNCEMENT_COOLDOWN);
|
||||
|
||||
task = AlathranWars.getPaperLib().scheduling().globalRegionalScheduler().runAtFixedRate(this, 0L, 20L);
|
||||
|
||||
raid.updateDisplayBar(CONTESTED);
|
||||
}
|
||||
|
||||
*//**
|
||||
* Resume a raid at tick
|
||||
*
|
||||
* @param raid the raid
|
||||
* @param raidProgress the raid ticks
|
||||
*//*
|
||||
public RaidRunnable(@NotNull Raid raid, int raidProgress) {
|
||||
this.raid = raid;
|
||||
|
||||
raid.setRaidProgress(raidProgress);
|
||||
|
||||
raid.setHomeBlock(raid.getTown().getHomeBlockOrNull());
|
||||
raid.setTownSpawn(raid.getTown().getSpawnOrNull());
|
||||
|
||||
nextAnnouncement = Instant.now().plus(ANNOUNCEMENT_COOLDOWN);
|
||||
|
||||
task = AlathranWars.getPaperLib().scheduling().globalRegionalScheduler().runAtFixedRate(this, 0L, 20L);
|
||||
|
||||
raid.updateDisplayBar(CONTESTED);
|
||||
}
|
||||
|
||||
public void cancel() {
|
||||
stopBeam();
|
||||
if (task.isCancelled()) return;
|
||||
|
||||
task.cancel();
|
||||
raid.deleteDisplayBar();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
final @NotNull Town town = raid.getTown();
|
||||
final @Nullable TownBlock homeBlock = raid.getHomeBlock();
|
||||
final @Nullable Location townSpawn = raid.getTownSpawn();
|
||||
|
||||
if (homeBlock != null && townSpawn != null) {
|
||||
town.setHomeBlock(homeBlock);
|
||||
town.setSpawn(townSpawn);
|
||||
}
|
||||
|
||||
// Render beam
|
||||
startBeam();
|
||||
|
||||
// Calculate battlefield players
|
||||
raid.calculateBattlefieldPlayers(townSpawn.toCenterLocation());
|
||||
|
||||
// Progress the raid
|
||||
final int attackersOnPoint = getPeopleOnPoint(townSpawn, BattleSide.ATTACKER);
|
||||
final int defendersOnPoint = getPeopleOnPoint(townSpawn, BattleSide.DEFENDER);
|
||||
final @NotNull CaptureProgressDirection progressDirection = getRaidProgressDirection(attackersOnPoint, defendersOnPoint);
|
||||
|
||||
// Raid is past max time or attackers haven't touched in time, defenders won
|
||||
if (
|
||||
(!progressDirection.equals(CONTESTED) && !progressDirection.equals(UP)) &&
|
||||
(Instant.now().isAfter(raid.getEndTime()) ||
|
||||
Instant.now().isAfter(raid.getLastTouched().plus(ATTACKERS_MUST_TOUCH_END)))
|
||||
) {
|
||||
cancel();
|
||||
raid.defendersWin(BattleVictoryReason.OPPONENT_LOST);
|
||||
return;
|
||||
}
|
||||
|
||||
// Attackers captured the town
|
||||
if (raid.getRaidProgress() >= MAX_RAID_PROGRESS) {
|
||||
cancel();
|
||||
raid.attackersWin(BattleVictoryReason.OPPONENT_LOST);
|
||||
return;
|
||||
}
|
||||
|
||||
switch (progressDirection) {
|
||||
case UP -> {
|
||||
final int playerOnPointDiff = attackersOnPoint - defendersOnPoint;
|
||||
|
||||
// If you have less than 5 people contesting you get (4 + excessPlayers) points per second
|
||||
if (playerOnPointDiff < 5) {
|
||||
raid.setRaidProgress(raid.getRaidProgress() + (4 + playerOnPointDiff));
|
||||
} else {
|
||||
raid.setRaidProgress(raid.getRaidProgress() + 10);
|
||||
}
|
||||
}
|
||||
case DOWN -> raid.setRaidProgress(raid.getRaidProgress() - 10);
|
||||
}
|
||||
|
||||
if (oldProgressDirection != progressDirection) {
|
||||
switch (progressDirection) {
|
||||
case UP -> {
|
||||
raid.getPlayersOnBattlefield().forEach(p -> p.sendMessage(
|
||||
ColorParser.of("<prefix>The Attackers are capturing the home block.")
|
||||
.parseMinimessagePlaceholder("prefix", UtilsChat.getPrefix())
|
||||
.build()
|
||||
));
|
||||
}
|
||||
case CONTESTED -> {
|
||||
if (oldProgressDirection.equals(UNCONTESTED))
|
||||
raid.getPlayersOnBattlefield().forEach(p -> p.sendMessage(
|
||||
ColorParser.of("<prefix>The home block is being contested.")
|
||||
.parseMinimessagePlaceholder("prefix", UtilsChat.getPrefix())
|
||||
.build()
|
||||
));
|
||||
}
|
||||
case UNCONTESTED -> {
|
||||
if (oldProgressDirection.equals(UP) || oldProgressDirection.equals(CONTESTED) || oldProgressDirection.equals(DOWN))
|
||||
raid.getPlayersOnBattlefield().forEach(p -> p.sendMessage(
|
||||
ColorParser.of("<prefix>The home block is no longer being contested.")
|
||||
.parseMinimessagePlaceholder("prefix", UtilsChat.getPrefix())
|
||||
.build()
|
||||
));
|
||||
}
|
||||
case DOWN -> {
|
||||
if (oldProgressDirection.equals(UP) || oldProgressDirection.equals(CONTESTED))
|
||||
raid.getPlayersOnBattlefield().forEach(p -> p.sendMessage(
|
||||
ColorParser.of("<prefix>The Defenders re-secured the home block.")
|
||||
.parseMinimessagePlaceholder("prefix", UtilsChat.getPrefix())
|
||||
.build()
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (Instant.now().isAfter(nextAnnouncement)) {
|
||||
nextAnnouncement = Instant.now().plus(ANNOUNCEMENT_COOLDOWN);
|
||||
|
||||
raid.getPlayersOnBattlefield().forEach(p -> p.sendMessage(
|
||||
ColorParser.of("<prefix>Raid time remaining: <time> minutes.")
|
||||
.parseMinimessagePlaceholder("prefix", UtilsChat.getPrefix())
|
||||
.parseMinimessagePlaceholder("time", String.valueOf(Duration.between(Instant.now(), raid.getEndTime()).toMinutesPart()))
|
||||
.build()
|
||||
));
|
||||
}
|
||||
|
||||
raid.updateDisplayBar(progressDirection);
|
||||
oldProgressDirection = progressDirection;
|
||||
}
|
||||
|
||||
public int getPeopleOnPoint(@NotNull Location townSpawn, @NotNull BattleSide battleSide) {
|
||||
int onPoint = 0;
|
||||
|
||||
for (final @NotNull Player p : (battleSide.equals(BattleSide.ATTACKER) ? raid.getAttackers() : raid.getDefenders())) {
|
||||
if (p.isDead())
|
||||
continue;
|
||||
|
||||
if (!townSpawn.getWorld().equals(p.getLocation().getWorld()))
|
||||
continue;
|
||||
|
||||
if (townSpawn.distance(p.getLocation()) <= CAPTURE_RANGE) {
|
||||
onPoint += 1;
|
||||
}
|
||||
}
|
||||
|
||||
return onPoint;
|
||||
}
|
||||
|
||||
public @NotNull CaptureProgressDirection getRaidProgressDirection(int attackersOnPoint, int defendersOnPoint) {
|
||||
final boolean attackersAreOnPoint = attackersOnPoint > 0;
|
||||
final boolean defendersAreOnPoint = defendersOnPoint > 0;
|
||||
|
||||
if (attackersAreOnPoint)
|
||||
raid.setLastTouched(Instant.now());
|
||||
|
||||
if (attackersAreOnPoint && defendersAreOnPoint) {
|
||||
|
||||
if (attackersOnPoint > defendersOnPoint)
|
||||
return UP;
|
||||
|
||||
return CONTESTED;
|
||||
} else if (attackersAreOnPoint && !defendersAreOnPoint) {
|
||||
if (raid.getRaidProgress() == MAX_RAID_PROGRESS)
|
||||
return CONTESTED;
|
||||
|
||||
return UP;
|
||||
} else {
|
||||
if (raid.getRaidProgress() == 0)
|
||||
return UNCONTESTED;
|
||||
|
||||
// If the attackers haven't touched in a while, begin reverting progress
|
||||
if (Instant.now().isAfter(raid.getLastTouched().plus(ATTACKERS_MUST_TOUCH_REVERT))) {
|
||||
return DOWN;
|
||||
} else {
|
||||
return UNCONTESTED;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void startBeam() {
|
||||
if (beam != null)
|
||||
return;
|
||||
|
||||
try {
|
||||
@Nullable Location loc1 = raid.getTownSpawn();
|
||||
@NotNull Location loc2 = new Location(loc1.getWorld(), loc1.getX(), loc1.getY() + 350D, loc1.getZ());
|
||||
|
||||
beam = new CrystalLaser(loc1, loc2, -1, 300);
|
||||
beam.start(AlathranWars.getInstance());
|
||||
} catch (ReflectiveOperationException ignored) {
|
||||
}
|
||||
}
|
||||
|
||||
private void stopBeam() {
|
||||
if (beam != null) {
|
||||
beam.stop();
|
||||
beam = null;
|
||||
}
|
||||
}
|
||||
}*/
|
||||
@@ -1,471 +0,0 @@
|
||||
package com.github.alathra.alathranwars.conflict.battle.siege;
|
||||
|
||||
import com.github.alathra.alathranwars.AlathranWars;
|
||||
import com.github.alathra.alathranwars.conflict.battle.AbstractBattleTeamManagement;
|
||||
import com.github.alathra.alathranwars.conflict.battle.Battle;
|
||||
import com.github.alathra.alathranwars.conflict.battle.phase.BattlePhaseManager;
|
||||
import com.github.alathra.alathranwars.conflict.battle.progress.BattleProgressManager;
|
||||
import com.github.alathra.alathranwars.conflict.war.War;
|
||||
import com.github.alathra.alathranwars.conflict.war.side.Side;
|
||||
import com.github.alathra.alathranwars.database.DatabaseQueries;
|
||||
import com.github.alathra.alathranwars.enums.CaptureProgressDirection;
|
||||
import com.github.alathra.alathranwars.enums.battle.*;
|
||||
import com.github.alathra.alathranwars.events.battle.BattleResultEvent;
|
||||
import com.github.alathra.alathranwars.events.battle.BattleStartEvent;
|
||||
import com.github.alathra.alathranwars.events.battle.PreBattleResultEvent;
|
||||
import com.github.alathra.alathranwars.events.battle.PreBattleStartEvent;
|
||||
import com.github.milkdrinkers.colorparser.ColorParser;
|
||||
import com.palmergames.bukkit.towny.object.Town;
|
||||
import com.palmergames.bukkit.towny.object.TownBlock;
|
||||
import net.kyori.adventure.bossbar.BossBar;
|
||||
import net.kyori.adventure.text.Component;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.OfflinePlayer;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.jetbrains.annotations.ApiStatus;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
/**
|
||||
* @author darksaid98
|
||||
*/
|
||||
public class Siege extends AbstractBattleTeamManagement implements Battle {
|
||||
public static final Duration SIEGE_DURATION = Duration.ofMinutes(60);
|
||||
public static final int MAX_SIEGE_PROGRESS_MINUTES = 8; // How many minutes attackers will need to be on point uncontested for to reach 100%
|
||||
public static final int MAX_SIEGE_PROGRESS = 60 * 10 * MAX_SIEGE_PROGRESS_MINUTES; // On reaching this, the attackers win. 10 points is added per second
|
||||
public static final Duration ATTACKERS_MUST_TOUCH_END = Duration.ofMinutes(40); // If point is not touched in this much time, defenders win
|
||||
public static final Duration ATTACKERS_MUST_TOUCH_REVERT = Duration.ofSeconds(60); // If point is not touched in this much time, siege progress begins reverting
|
||||
public static final int BATTLEFIELD_RANGE = 500;
|
||||
public static final int BATTLEFIELD_START_MAX_RANGE = BATTLEFIELD_RANGE * 2;
|
||||
public static final int BATTLEFIELD_START_MIN_RANGE = 75;
|
||||
public static final double SIEGE_VICTORY_MONEY = 2500.0;
|
||||
|
||||
// Battle fields
|
||||
private final UUID uuid;
|
||||
private final static BattleType battleType = BattleType.SIEGE;
|
||||
private final War war; // War which siege belongs to
|
||||
|
||||
// Misc fields
|
||||
private Instant endTime;
|
||||
private Instant lastTouched;
|
||||
private SiegeRunnable battleRunnable;
|
||||
private Town town; // Town of the siege
|
||||
private boolean side1AreAttackers; // bool of if side1 being attacker
|
||||
private OfflinePlayer siegeLeader;
|
||||
private @Nullable TownBlock homeBlock = null;
|
||||
private @Nullable Location townSpawn = null;
|
||||
private @Nullable BossBar activeBossBar = null;
|
||||
private boolean stopped = false; // Used to track if the siege has been already deleted
|
||||
|
||||
// Progress / Phases
|
||||
private final BattleProgressManager progressManager; // Represents the capture progress of the capture point in this case
|
||||
private final BattlePhaseManager<SiegePhase> phaseManager; // Controls the current stage of the siege
|
||||
|
||||
/**
|
||||
* Instantiates a new Siege. Used when creating a new siege.
|
||||
*
|
||||
* @param war the war
|
||||
* @param town the town
|
||||
* @param siegeLeader the siege leader
|
||||
*/
|
||||
public Siege(
|
||||
War war,
|
||||
Town town,
|
||||
Player siegeLeader
|
||||
) {
|
||||
super();
|
||||
uuid = UUID.randomUUID();
|
||||
|
||||
endTime = Instant.now().plus(SIEGE_DURATION);
|
||||
lastTouched = Instant.now();
|
||||
|
||||
this.war = war;
|
||||
this.town = town;
|
||||
this.siegeLeader = siegeLeader;
|
||||
this.progressManager = new BattleProgressManager(0, MAX_SIEGE_PROGRESS);
|
||||
this.phaseManager = new BattlePhaseManager<>(SiegePhase.SIEGE, 0, Instant.now());
|
||||
|
||||
side1AreAttackers = war.getSide(town).getTeam().equals(BattleTeam.SIDE_2);
|
||||
|
||||
if (getSide1AreAttackers()) {
|
||||
getWar().getSide1().getPlayers().forEach(p -> addPlayer(p, BattleSide.ATTACKER));
|
||||
getWar().getSide2().getPlayers().forEach(p -> addPlayer(p, BattleSide.DEFENDER));
|
||||
} else {
|
||||
getWar().getSide2().getPlayers().forEach(p -> addPlayer(p, BattleSide.ATTACKER));
|
||||
getWar().getSide1().getPlayers().forEach(p -> addPlayer(p, BattleSide.DEFENDER));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Instantiates a new Siege. Used when loading existing Siege from Database.
|
||||
*
|
||||
* @param war the war
|
||||
* @param uuid the uuid
|
||||
* @param town the town
|
||||
* @param siegeLeader the siege leader
|
||||
* @param endTime the end time
|
||||
* @param lastTouched the last touched
|
||||
* @param siegeProgress the siege progress
|
||||
* @param attackers the attacker players including offline
|
||||
* @param defenders the defender players including offline
|
||||
*/
|
||||
public Siege(
|
||||
War war,
|
||||
UUID uuid,
|
||||
Town town,
|
||||
OfflinePlayer siegeLeader,
|
||||
Instant endTime,
|
||||
Instant lastTouched,
|
||||
int siegeProgress,
|
||||
Set<UUID> attackers,
|
||||
Set<UUID> defenders,
|
||||
SiegePhase phase,
|
||||
int phaseProgress,
|
||||
Instant phaseStartTime
|
||||
) {
|
||||
super();
|
||||
this.war = war;
|
||||
this.uuid = uuid;
|
||||
this.town = town;
|
||||
this.siegeLeader = siegeLeader;
|
||||
this.endTime = endTime;
|
||||
this.lastTouched = lastTouched;
|
||||
this.progressManager = new BattleProgressManager(siegeProgress, MAX_SIEGE_PROGRESS);
|
||||
this.phaseManager = new BattlePhaseManager<>(phase, phaseProgress, phaseStartTime);
|
||||
attackers.stream()
|
||||
.map(Bukkit::getOfflinePlayer)
|
||||
.forEach(p -> addPlayer(p, BattleSide.ATTACKER));
|
||||
defenders.stream()
|
||||
.map(Bukkit::getOfflinePlayer)
|
||||
.forEach(p -> addPlayer(p, BattleSide.DEFENDER));
|
||||
|
||||
side1AreAttackers = war.getSide(town).getTeam().equals(BattleTeam.SIDE_2);
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts the battle
|
||||
*/
|
||||
@ApiStatus.Internal
|
||||
public void start() {
|
||||
if (!new PreBattleStartEvent(war, this, BattleType.SIEGE).callEvent()) return;
|
||||
|
||||
battleRunnable = new SiegeRunnable(this);
|
||||
stopped = false;
|
||||
|
||||
if (!war.isEventWar())
|
||||
if (AlathranWars.getVaultHook().isEconomyLoaded())
|
||||
AlathranWars.getVaultHook().getEconomy().withdrawPlayer(siegeLeader, SIEGE_VICTORY_MONEY);
|
||||
|
||||
new BattleStartEvent(war, this).callEvent();
|
||||
}
|
||||
|
||||
/**
|
||||
* Resumes the battle (after a server restart e.t.c.)
|
||||
*/
|
||||
@ApiStatus.Internal
|
||||
public void resume() {
|
||||
if (!new PreBattleStartEvent(war, this, BattleType.SIEGE).callEvent()) return;
|
||||
|
||||
battleRunnable = new SiegeRunnable(this, getProgressManager().get());
|
||||
stopped = false;
|
||||
|
||||
new BattleStartEvent(war, this).callEvent();
|
||||
}
|
||||
|
||||
/**
|
||||
* Stops the battle
|
||||
* </p>
|
||||
* Internal stop method for battles which triggers cleanup methods
|
||||
*/
|
||||
@ApiStatus.Internal
|
||||
public void stop() {
|
||||
if (stopped) return;
|
||||
stopped = true;
|
||||
battleRunnable.cancel();
|
||||
DatabaseQueries.deleteSiege(this); // TODO Run as latent event?
|
||||
war.removeSiege(this); // TODO Run as latent event?
|
||||
}
|
||||
|
||||
/**
|
||||
* Stop a battle in favor of the attackers
|
||||
*
|
||||
* @param reason what triggered the end
|
||||
*/
|
||||
public void attackersWin(BattleVictoryReason reason) {
|
||||
if (!new PreBattleResultEvent(war, this, BattleType.SIEGE, BattleVictor.ATTACKER, reason).callEvent()) return;
|
||||
|
||||
if (!war.isEventWar()) {
|
||||
if (AlathranWars.getVaultHook().isEconomyLoaded())
|
||||
AlathranWars.getVaultHook().getEconomy().depositPlayer(siegeLeader, SIEGE_VICTORY_MONEY);
|
||||
double amt;
|
||||
|
||||
if (town.getAccount().getHoldingBalance() > 10000.0) {
|
||||
amt = Math.floor(town.getAccount().getHoldingBalance()) / 4.0;
|
||||
town.getAccount().withdraw(amt, "Siege Defeat");
|
||||
} else {
|
||||
town.getAccount().withdraw(SIEGE_VICTORY_MONEY, "Siege Defeat");
|
||||
amt = SIEGE_VICTORY_MONEY;
|
||||
}
|
||||
|
||||
if (AlathranWars.getVaultHook().isEconomyLoaded())
|
||||
AlathranWars.getVaultHook().getEconomy().depositPlayer(siegeLeader, amt);
|
||||
}
|
||||
|
||||
new BattleResultEvent(war, this, BattleVictor.ATTACKER, reason).callEvent();
|
||||
|
||||
stop();
|
||||
}
|
||||
|
||||
/**
|
||||
* Stop a battle in favor of the defenders
|
||||
*
|
||||
* @param reason what triggered the end
|
||||
*/
|
||||
public void defendersWin(BattleVictoryReason reason) {
|
||||
if (!new PreBattleResultEvent(war, this, BattleType.SIEGE, BattleVictor.DEFENDER, reason).callEvent()) return;
|
||||
|
||||
if (!war.isEventWar())
|
||||
town.getAccount().deposit(SIEGE_VICTORY_MONEY, "Siege Victory");
|
||||
|
||||
new BattleResultEvent(war, this, BattleVictor.DEFENDER, reason).callEvent();
|
||||
|
||||
stop();
|
||||
}
|
||||
|
||||
/**
|
||||
* End a battle in favor of no one
|
||||
*
|
||||
* @param reason what triggered the end
|
||||
*/
|
||||
public void equalWin(BattleVictoryReason reason) {
|
||||
if (!new PreBattleResultEvent(war, this, BattleType.SIEGE, BattleVictor.DRAW, reason).callEvent()) return;
|
||||
|
||||
new BattleResultEvent(war, this, BattleVictor.DRAW, reason).callEvent();
|
||||
|
||||
stop();
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Instant getLastTouched() {
|
||||
return lastTouched;
|
||||
}
|
||||
|
||||
public void setLastTouched(Instant lastTouched) {
|
||||
this.lastTouched = lastTouched;
|
||||
}
|
||||
|
||||
public BattleProgressManager getProgressManager() {
|
||||
return progressManager;
|
||||
}
|
||||
|
||||
public float getSiegeProgressPercentage() {
|
||||
return (getProgressManager().get() * 1.0f) / MAX_SIEGE_PROGRESS;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Town getTown() {
|
||||
return town;
|
||||
}
|
||||
|
||||
public void setTown(final Town town) {
|
||||
this.town = town;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets attacker name string
|
||||
*/
|
||||
public Side getAttackerSide() {
|
||||
return getSide1AreAttackers() ? war.getSide1() : war.getSide2();
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets defender name string
|
||||
*/
|
||||
public Side getDefenderSide() {
|
||||
return getSide1AreAttackers() ? war.getSide2() : war.getSide1();
|
||||
}
|
||||
|
||||
// SECTION Display Bar
|
||||
|
||||
public void updateDisplayBar(@NotNull CaptureProgressDirection progressDirection) {
|
||||
if (activeBossBar == null)
|
||||
createNewDisplayBar();
|
||||
|
||||
for (Player p : Bukkit.getOnlinePlayers()) {
|
||||
p.hideBossBar(activeBossBar);
|
||||
}
|
||||
|
||||
for (Player p : this.getPlayersOnBattlefield()) {
|
||||
if (p != null)
|
||||
p.showBossBar(activeBossBar);
|
||||
}
|
||||
|
||||
final String color = switch (progressDirection) {
|
||||
case UP -> {
|
||||
if (getAttackerSide().getSide().equals(BattleSide.ATTACKER)) {
|
||||
activeBossBar.color(BossBar.Color.RED);
|
||||
yield "<red>";
|
||||
} else {
|
||||
activeBossBar.color(BossBar.Color.BLUE);
|
||||
yield "<blue>";
|
||||
}
|
||||
}
|
||||
case CONTESTED -> {
|
||||
activeBossBar.color(BossBar.Color.YELLOW);
|
||||
yield "<yellow>";
|
||||
}
|
||||
case UNCONTESTED -> {
|
||||
activeBossBar.color(BossBar.Color.WHITE);
|
||||
yield "<white>";
|
||||
}
|
||||
case DOWN -> {
|
||||
if (getAttackerSide().getSide().equals(BattleSide.ATTACKER)) {
|
||||
activeBossBar.color(BossBar.Color.BLUE);
|
||||
yield "<blue>";
|
||||
} else {
|
||||
activeBossBar.color(BossBar.Color.RED);
|
||||
yield "<red>";
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
if (Instant.now().isBefore(getEndTime())) {
|
||||
activeBossBar.name(
|
||||
ColorParser.of("<gray>Capture Progress: %s<progress> <gray>Time: %s<time>min".formatted(color, color))
|
||||
.parseMinimessagePlaceholder("progress", "%.0f%%".formatted(getSiegeProgressPercentage() * 100))
|
||||
.parseMinimessagePlaceholder("time", String.valueOf(Duration.between(Instant.now(), getEndTime()).toMinutes()))
|
||||
.build()
|
||||
);
|
||||
} else {
|
||||
activeBossBar.name(
|
||||
ColorParser.of("%sOVERTIME".formatted(color)).build()
|
||||
);
|
||||
}
|
||||
activeBossBar.progress(getSiegeProgressPercentage());
|
||||
}
|
||||
|
||||
public void createNewDisplayBar() {
|
||||
final Component text = ColorParser.of("<gray>Capture Progress: <yellow><progress> <gray>Time: <yellow><time>min")
|
||||
.parseMinimessagePlaceholder("progress", "%.0f%%".formatted(getSiegeProgressPercentage() * 100))
|
||||
.parseMinimessagePlaceholder("time", String.valueOf(Duration.between(Instant.now(), getEndTime()).toMinutesPart()))
|
||||
.build();
|
||||
|
||||
this.activeBossBar = BossBar.bossBar(text, 0, BossBar.Color.YELLOW, BossBar.Overlay.NOTCHED_10);
|
||||
}
|
||||
|
||||
public void deleteDisplayBar() {
|
||||
if (activeBossBar != null) {
|
||||
for (@NotNull Player p : Bukkit.getOnlinePlayers()) {
|
||||
p.hideBossBar(activeBossBar);
|
||||
}
|
||||
|
||||
activeBossBar = null;
|
||||
}
|
||||
}
|
||||
|
||||
// SECTION UUID
|
||||
|
||||
@Override
|
||||
public UUID getUUID() {
|
||||
return uuid;
|
||||
}
|
||||
|
||||
/**
|
||||
* Equals boolean.
|
||||
*
|
||||
* @param uuid the uuid
|
||||
* @return the boolean
|
||||
*/
|
||||
public boolean equals(UUID uuid) {
|
||||
return getUUID().equals(uuid);
|
||||
}
|
||||
|
||||
/**
|
||||
* Equals boolean.
|
||||
*
|
||||
* @param battle the battle
|
||||
* @return the boolean
|
||||
*/
|
||||
@Override
|
||||
public boolean equals(Battle battle) {
|
||||
return getUUID().equals(battle.getUUID());
|
||||
}
|
||||
|
||||
// SECTION BattleType
|
||||
|
||||
@Override
|
||||
public BattleType getBattleType() {
|
||||
return battleType;
|
||||
}
|
||||
|
||||
// SECTION Accessors & Getters
|
||||
|
||||
@Nullable
|
||||
public TownBlock getHomeBlock() {
|
||||
return homeBlock;
|
||||
}
|
||||
|
||||
public void setHomeBlock(@Nullable TownBlock homeBlock) {
|
||||
this.homeBlock = homeBlock;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public Location getTownSpawn() {
|
||||
return townSpawn;
|
||||
}
|
||||
|
||||
public void setTownSpawn(@Nullable Location townSpawn) {
|
||||
this.townSpawn = townSpawn;
|
||||
}
|
||||
|
||||
public boolean getSide1AreAttackers() {
|
||||
return side1AreAttackers;
|
||||
}
|
||||
|
||||
public void setSide1AreAttackers(final boolean side1AreAttackers) {
|
||||
this.side1AreAttackers = side1AreAttackers;
|
||||
}
|
||||
|
||||
public List<Player> getPlayersOnBattlefield() {
|
||||
return Stream.concat(getActivePlayers(BattleSide.ATTACKER).stream(), getActivePlayers(BattleSide.DEFENDER).stream()).toList();
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public OfflinePlayer getSiegeLeader() {
|
||||
return siegeLeader;
|
||||
}
|
||||
|
||||
public void setSiegeLeader(OfflinePlayer siegeLeader) {
|
||||
this.siegeLeader = siegeLeader;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String getName() { // TODO Make better siegenames
|
||||
return getTown().getName();
|
||||
}
|
||||
|
||||
// SECTION Time management
|
||||
|
||||
@NotNull
|
||||
public Instant getEndTime() {
|
||||
return endTime;
|
||||
}
|
||||
|
||||
public void setEndTime(Instant time) {
|
||||
endTime = time;
|
||||
}
|
||||
|
||||
// SECTION Phase Management
|
||||
|
||||
public BattlePhaseManager<SiegePhase> getPhaseManager() {
|
||||
return phaseManager;
|
||||
}
|
||||
}
|
||||
@@ -1,41 +0,0 @@
|
||||
package com.github.alathra.alathranwars.conflict.battle.siege;
|
||||
|
||||
import com.github.alathra.alathranwars.conflict.battle.phase.BattlePhaseSwitchException;
|
||||
import com.github.alathra.alathranwars.conflict.battle.phase.IBattlePhase;
|
||||
|
||||
public enum SiegePhase implements IBattlePhase<SiegePhase> {
|
||||
SIEGE(1),
|
||||
ENDING(2);
|
||||
|
||||
// Identifiers start at 1, used to traverse between stages
|
||||
private final int phaseIdentifier;
|
||||
|
||||
SiegePhase(int phaseIdentifier) {
|
||||
this.phaseIdentifier = phaseIdentifier;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getPhaseIdentifier() {
|
||||
return phaseIdentifier;
|
||||
}
|
||||
|
||||
@Override
|
||||
public SiegePhase next() throws BattlePhaseSwitchException {
|
||||
return next(fromIdentifier(getPhaseIdentifier()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public SiegePhase previous() throws BattlePhaseSwitchException {
|
||||
return previous(fromIdentifier(getPhaseIdentifier()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public SiegePhase next(SiegePhase phase) throws BattlePhaseSwitchException {
|
||||
return IBattlePhase.super.next(phase);
|
||||
}
|
||||
|
||||
@Override
|
||||
public SiegePhase previous(SiegePhase phase) throws BattlePhaseSwitchException {
|
||||
return IBattlePhase.super.previous(phase);
|
||||
}
|
||||
}
|
||||
-266
@@ -1,266 +0,0 @@
|
||||
package com.github.alathra.alathranwars.conflict.battle.siege;
|
||||
|
||||
import com.github.alathra.alathranwars.AlathranWars;
|
||||
import com.github.alathra.alathranwars.conflict.battle.beam.CrystalLaser;
|
||||
import com.github.alathra.alathranwars.conflict.battle.beam.Laser;
|
||||
import com.github.alathra.alathranwars.enums.CaptureProgressDirection;
|
||||
import com.github.alathra.alathranwars.enums.battle.BattleSide;
|
||||
import com.github.alathra.alathranwars.enums.battle.BattleVictoryReason;
|
||||
import com.github.alathra.alathranwars.utility.UtilsChat;
|
||||
import com.github.milkdrinkers.colorparser.ColorParser;
|
||||
import com.palmergames.bukkit.towny.object.Town;
|
||||
import com.palmergames.bukkit.towny.object.TownBlock;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import space.arim.morepaperlib.scheduling.ScheduledTask;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
|
||||
import static com.github.alathra.alathranwars.conflict.battle.siege.Siege.*;
|
||||
import static com.github.alathra.alathranwars.enums.CaptureProgressDirection.*;
|
||||
|
||||
public class SiegeRunnable implements Runnable {
|
||||
// Settings
|
||||
private static final Duration ANNOUNCEMENT_COOLDOWN = Duration.ofMinutes(5);
|
||||
private final static int CAPTURE_RANGE = 10;
|
||||
private final @NotNull Siege siege;
|
||||
|
||||
// Variables
|
||||
private @NotNull CaptureProgressDirection oldProgressDirection = UNCONTESTED;
|
||||
private Instant nextAnnouncement;
|
||||
private final ScheduledTask task;
|
||||
private @Nullable Laser beam;
|
||||
|
||||
/**
|
||||
* Start a siege
|
||||
*
|
||||
* @param siege the siege
|
||||
*/
|
||||
public SiegeRunnable(@NotNull Siege siege) {
|
||||
this.siege = siege;
|
||||
|
||||
siege.getProgressManager().set(0);
|
||||
|
||||
siege.setHomeBlock(siege.getTown().getHomeBlockOrNull());
|
||||
siege.setTownSpawn(siege.getTown().getSpawnOrNull());
|
||||
|
||||
nextAnnouncement = Instant.now().plus(ANNOUNCEMENT_COOLDOWN);
|
||||
|
||||
task = AlathranWars.getPaperLib().scheduling().globalRegionalScheduler().runAtFixedRate(this, 0L, 20L);
|
||||
|
||||
siege.updateDisplayBar(CONTESTED);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resume a siege at tick
|
||||
*
|
||||
* @param siege the siege
|
||||
* @param siegeProgress the siege ticks
|
||||
*/
|
||||
public SiegeRunnable(@NotNull Siege siege, int siegeProgress) {
|
||||
this.siege = siege;
|
||||
|
||||
siege.getProgressManager().set(siegeProgress);
|
||||
|
||||
siege.setHomeBlock(siege.getTown().getHomeBlockOrNull());
|
||||
siege.setTownSpawn(siege.getTown().getSpawnOrNull());
|
||||
|
||||
nextAnnouncement = Instant.now().plus(ANNOUNCEMENT_COOLDOWN);
|
||||
|
||||
task = AlathranWars.getPaperLib().scheduling().globalRegionalScheduler().runAtFixedRate(this, 0L, 20L);
|
||||
|
||||
siege.updateDisplayBar(CONTESTED);
|
||||
}
|
||||
|
||||
public void cancel() {
|
||||
stopBeam();
|
||||
if (task.isCancelled()) return;
|
||||
|
||||
task.cancel();
|
||||
siege.deleteDisplayBar();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
final @NotNull Town town = siege.getTown();
|
||||
final @Nullable TownBlock homeBlock = siege.getHomeBlock();
|
||||
final @Nullable Location townSpawn = siege.getTownSpawn();
|
||||
|
||||
if (homeBlock != null && townSpawn != null) {
|
||||
town.setHomeBlock(homeBlock);
|
||||
town.setSpawn(townSpawn);
|
||||
}
|
||||
|
||||
if (townSpawn == null)
|
||||
return;
|
||||
|
||||
// Render beam
|
||||
startBeam();
|
||||
|
||||
// Calculate battlefield players
|
||||
siege.calculateBattlefieldPlayers(townSpawn.toCenterLocation(), BATTLEFIELD_RANGE, this.siege.getWar(), siege);
|
||||
|
||||
// Progress the siege
|
||||
final int attackersOnPoint = getPeopleOnPoint(townSpawn, BattleSide.ATTACKER);
|
||||
final int defendersOnPoint = getPeopleOnPoint(townSpawn, BattleSide.DEFENDER);
|
||||
final @NotNull CaptureProgressDirection progressDirection = getSiegeProgressDirection(attackersOnPoint, defendersOnPoint);
|
||||
|
||||
// Siege is past max time or attackers haven't touched in time, defenders won
|
||||
if (
|
||||
(!progressDirection.equals(CONTESTED) && !progressDirection.equals(UP)) &&
|
||||
(Instant.now().isAfter(siege.getEndTime()) ||
|
||||
Instant.now().isAfter(siege.getLastTouched().plus(ATTACKERS_MUST_TOUCH_END)))
|
||||
) {
|
||||
cancel();
|
||||
siege.defendersWin(BattleVictoryReason.OPPONENT_LOST);
|
||||
return;
|
||||
}
|
||||
|
||||
// Attackers captured the town
|
||||
if (siege.getProgressManager().get() >= MAX_SIEGE_PROGRESS) {
|
||||
cancel();
|
||||
siege.attackersWin(BattleVictoryReason.OPPONENT_LOST);
|
||||
return;
|
||||
}
|
||||
|
||||
switch (progressDirection) {
|
||||
case UP -> {
|
||||
final int playerOnPointDiff = attackersOnPoint - defendersOnPoint;
|
||||
|
||||
// If you have less than 5 people contesting you get (4 + excessPlayers) points per second
|
||||
if (playerOnPointDiff < 5) {
|
||||
siege.getProgressManager().set(siege.getProgressManager().get() + (4 + playerOnPointDiff));
|
||||
} else {
|
||||
siege.getProgressManager().set(siege.getProgressManager().get() + 10);
|
||||
}
|
||||
}
|
||||
case DOWN -> siege.getProgressManager().set(siege.getProgressManager().get() - 10);
|
||||
}
|
||||
|
||||
if (oldProgressDirection != progressDirection) {
|
||||
switch (progressDirection) {
|
||||
case UP -> {
|
||||
siege.getPlayersOnBattlefield().forEach(p -> p.sendMessage(
|
||||
ColorParser.of("<prefix>The Attackers are capturing the home block.")
|
||||
.parseMinimessagePlaceholder("prefix", UtilsChat.getPrefix())
|
||||
.build()
|
||||
));
|
||||
}
|
||||
case CONTESTED -> {
|
||||
if (oldProgressDirection.equals(UNCONTESTED))
|
||||
siege.getPlayersOnBattlefield().forEach(p -> p.sendMessage(
|
||||
ColorParser.of("<prefix>The home block is being contested.")
|
||||
.parseMinimessagePlaceholder("prefix", UtilsChat.getPrefix())
|
||||
.build()
|
||||
));
|
||||
}
|
||||
case UNCONTESTED -> {
|
||||
if (oldProgressDirection.equals(UP) || oldProgressDirection.equals(CONTESTED) || oldProgressDirection.equals(DOWN))
|
||||
siege.getPlayersOnBattlefield().forEach(p -> p.sendMessage(
|
||||
ColorParser.of("<prefix>The home block is no longer being contested.")
|
||||
.parseMinimessagePlaceholder("prefix", UtilsChat.getPrefix())
|
||||
.build()
|
||||
));
|
||||
}
|
||||
case DOWN -> {
|
||||
if (oldProgressDirection.equals(UP) || oldProgressDirection.equals(CONTESTED))
|
||||
siege.getPlayersOnBattlefield().forEach(p -> p.sendMessage(
|
||||
ColorParser.of("<prefix>The Defenders re-secured the home block.")
|
||||
.parseMinimessagePlaceholder("prefix", UtilsChat.getPrefix())
|
||||
.build()
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (Instant.now().isAfter(nextAnnouncement)) {
|
||||
nextAnnouncement = Instant.now().plus(ANNOUNCEMENT_COOLDOWN);
|
||||
|
||||
siege.getPlayersOnBattlefield().forEach(p -> p.sendMessage(
|
||||
ColorParser.of("<prefix>Siege time remaining: <time> minutes.")
|
||||
.parseMinimessagePlaceholder("prefix", UtilsChat.getPrefix())
|
||||
.parseMinimessagePlaceholder("time", String.valueOf(Duration.between(Instant.now(), siege.getEndTime()).toMinutesPart()))
|
||||
.build()
|
||||
));
|
||||
}
|
||||
|
||||
siege.updateDisplayBar(progressDirection);
|
||||
oldProgressDirection = progressDirection;
|
||||
}
|
||||
|
||||
private int getPeopleOnPoint(Location townSpawn, BattleSide battleSide) {
|
||||
int onPoint = 0;
|
||||
|
||||
for (final Player p : (battleSide.equals(BattleSide.ATTACKER) ? siege.getActivePlayers(BattleSide.ATTACKER) : siege.getActivePlayers(BattleSide.DEFENDER))) {
|
||||
if (p.isDead())
|
||||
continue;
|
||||
|
||||
if (!townSpawn.getWorld().equals(p.getLocation().getWorld()))
|
||||
continue;
|
||||
|
||||
if (townSpawn.distance(p.getLocation()) <= CAPTURE_RANGE) {
|
||||
onPoint += 1;
|
||||
}
|
||||
}
|
||||
|
||||
return onPoint;
|
||||
}
|
||||
|
||||
private CaptureProgressDirection getSiegeProgressDirection(int attackersOnPoint, int defendersOnPoint) {
|
||||
final boolean attackersAreOnPoint = attackersOnPoint > 0;
|
||||
final boolean defendersAreOnPoint = defendersOnPoint > 0;
|
||||
|
||||
if (attackersAreOnPoint)
|
||||
siege.setLastTouched(Instant.now());
|
||||
|
||||
if (attackersAreOnPoint && defendersAreOnPoint) {
|
||||
|
||||
if (attackersOnPoint > defendersOnPoint)
|
||||
return UP;
|
||||
|
||||
return CONTESTED;
|
||||
} else if (attackersAreOnPoint && !defendersAreOnPoint) {
|
||||
if (siege.getProgressManager().get() == MAX_SIEGE_PROGRESS)
|
||||
return CONTESTED;
|
||||
|
||||
return UP;
|
||||
} else {
|
||||
if (siege.getProgressManager().get() == 0)
|
||||
return UNCONTESTED;
|
||||
|
||||
// If the attackers haven't touched in a while, begin reverting progress
|
||||
if (Instant.now().isAfter(siege.getLastTouched().plus(ATTACKERS_MUST_TOUCH_REVERT))) {
|
||||
return DOWN;
|
||||
} else {
|
||||
return UNCONTESTED;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void startBeam() {
|
||||
if (beam != null)
|
||||
return;
|
||||
|
||||
try {
|
||||
try {
|
||||
@Nullable Location loc1 = siege.getTownSpawn();
|
||||
@NotNull Location loc2 = new Location(loc1.getWorld(), loc1.getX(), loc1.getY() + 350D, loc1.getZ());
|
||||
|
||||
beam = new CrystalLaser(loc1, loc2, -1, 300);
|
||||
beam.start(AlathranWars.getInstance());
|
||||
} catch (ReflectiveOperationException ignored) {
|
||||
}
|
||||
} catch (NoClassDefFoundError ignored1) {
|
||||
}
|
||||
}
|
||||
|
||||
private void stopBeam() {
|
||||
if (beam != null) {
|
||||
beam.stop();
|
||||
beam = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,853 +0,0 @@
|
||||
package com.github.alathra.alathranwars.conflict.war;
|
||||
|
||||
import com.github.alathra.alathranwars.conflict.Conflict;
|
||||
import com.github.alathra.alathranwars.conflict.Occupation;
|
||||
import com.github.alathra.alathranwars.conflict.battle.raid.Raid;
|
||||
import com.github.alathra.alathranwars.conflict.battle.siege.Siege;
|
||||
import com.github.alathra.alathranwars.conflict.war.side.Side;
|
||||
import com.github.alathra.alathranwars.conflict.war.side.SideBuilder;
|
||||
import com.github.alathra.alathranwars.conflict.war.side.SideCreationException;
|
||||
import com.github.alathra.alathranwars.database.DatabaseQueries;
|
||||
import com.github.alathra.alathranwars.enums.ConflictType;
|
||||
import com.github.alathra.alathranwars.enums.WarDeleteReason;
|
||||
import com.github.alathra.alathranwars.enums.battle.BattleSide;
|
||||
import com.github.alathra.alathranwars.enums.battle.BattleTeam;
|
||||
import com.github.alathra.alathranwars.enums.battle.BattleVictoryReason;
|
||||
import com.github.alathra.alathranwars.events.PreWarCreateEvent;
|
||||
import com.github.alathra.alathranwars.events.PreWarDeleteEvent;
|
||||
import com.github.alathra.alathranwars.events.WarCreateEvent;
|
||||
import com.github.alathra.alathranwars.events.WarDeleteEvent;
|
||||
import com.github.alathra.alathranwars.hook.NameColorHandler;
|
||||
import com.github.alathra.alathranwars.utility.UtilsChat;
|
||||
import com.github.milkdrinkers.colorparser.ColorParser;
|
||||
import com.palmergames.bukkit.towny.object.Government;
|
||||
import com.palmergames.bukkit.towny.object.Nation;
|
||||
import com.palmergames.bukkit.towny.object.Town;
|
||||
import dev.jorel.commandapi.CommandAPIBukkit;
|
||||
import dev.jorel.commandapi.exceptions.WrapperCommandSyntaxException;
|
||||
import net.kyori.adventure.key.Key;
|
||||
import net.kyori.adventure.sound.Sound;
|
||||
import net.kyori.adventure.title.Title;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.OfflinePlayer;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.jetbrains.annotations.ApiStatus;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
/**
|
||||
* The type New war.
|
||||
*/
|
||||
public class War extends Conflict {
|
||||
private final String name; // Used in commands and such, like "TidalHaven.vs.Meme"
|
||||
private final String label;
|
||||
private final ConflictType conflictType = ConflictType.WAR;
|
||||
private boolean event;
|
||||
|
||||
private Side side1;
|
||||
private Side side2;
|
||||
private final Side attacker; // Reference variable to side1 or side2
|
||||
private final Side defender; // Reference variable to side1 or side2
|
||||
|
||||
private Set<Siege> sieges = new HashSet<>();
|
||||
private Set<Raid> raids = new HashSet<>();
|
||||
|
||||
/**
|
||||
* Instantiates a existing War.
|
||||
*
|
||||
* @param uuid the uuid
|
||||
* @param name the name
|
||||
* @param label the label
|
||||
* @param side1 the side 1
|
||||
* @param side2 the side 2
|
||||
* @param sieges the sieges
|
||||
* @param raids the raids
|
||||
* @param event the event
|
||||
*/
|
||||
@ApiStatus.Internal
|
||||
War(
|
||||
UUID uuid,
|
||||
String name,
|
||||
String label,
|
||||
Side side1,
|
||||
Side side2,
|
||||
Set<Siege> sieges,
|
||||
Set<Raid> raids,
|
||||
boolean event
|
||||
) {
|
||||
super(uuid);
|
||||
this.name = name;
|
||||
this.label = label;
|
||||
|
||||
this.side1 = side1;
|
||||
this.side2 = side2;
|
||||
|
||||
this.attacker = side1.getSide().equals(BattleSide.ATTACKER) ? this.side1 : this.side2;
|
||||
this.defender = side1.getSide().equals(BattleSide.DEFENDER) ? this.side1 : this.side2;
|
||||
|
||||
this.sieges = sieges;
|
||||
this.raids = raids;
|
||||
this.event = event;
|
||||
|
||||
resume();
|
||||
}
|
||||
|
||||
/**
|
||||
* Instantiates a new War.
|
||||
*
|
||||
* @param uuid the uuid
|
||||
* @param label the label
|
||||
* @param aggressor the aggressor
|
||||
* @param victim the victim
|
||||
* @param event the event
|
||||
* @throws SideCreationException the side creation exception
|
||||
* @throws WrapperCommandSyntaxException the wrapper command syntax exception
|
||||
*/
|
||||
@ApiStatus.Internal
|
||||
War(
|
||||
UUID uuid,
|
||||
String label,
|
||||
Government aggressor,
|
||||
Government victim,
|
||||
boolean event
|
||||
) throws SideCreationException, WrapperCommandSyntaxException {
|
||||
super(uuid);
|
||||
this.label = label;
|
||||
|
||||
this.name = "%s.vs.%s".formatted(aggressor.getName(), victim.getName());
|
||||
if (WarController.getInstance().getWar(this.name) != null)
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>A war already exists with that name!").build());
|
||||
|
||||
this.side1 = new SideBuilder()
|
||||
.setWarUUID(getUUID())
|
||||
.setUuid(UUID.randomUUID())
|
||||
.setLeader(aggressor)
|
||||
.setSide(BattleSide.ATTACKER)
|
||||
.setTeam(BattleTeam.SIDE_1)
|
||||
.build();
|
||||
this.side2 = new SideBuilder()
|
||||
.setWarUUID(getUUID())
|
||||
.setUuid(UUID.randomUUID())
|
||||
.setLeader(victim)
|
||||
.setSide(BattleSide.DEFENDER)
|
||||
.setTeam(BattleTeam.SIDE_2)
|
||||
.build();
|
||||
|
||||
this.attacker = side1.getSide().equals(BattleSide.ATTACKER) ? this.side1 : this.side2;
|
||||
this.defender = side1.getSide().equals(BattleSide.DEFENDER) ? this.side1 : this.side2;
|
||||
this.event = event;
|
||||
|
||||
if (!new PreWarCreateEvent(this).callEvent())
|
||||
return;
|
||||
|
||||
// TODO All logic below this point should be separated out
|
||||
WarController.getInstance().addWar(this);
|
||||
|
||||
start();
|
||||
|
||||
new WarCreateEvent(this).callEvent();
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets name of the war.
|
||||
*
|
||||
* @return the name
|
||||
*/
|
||||
@NotNull
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets label of the war.
|
||||
*
|
||||
* @return the label
|
||||
*/
|
||||
@NotNull
|
||||
public String getLabel() {
|
||||
return label;
|
||||
}
|
||||
|
||||
/**
|
||||
* Compare war by names.
|
||||
*
|
||||
* @param warName the war name
|
||||
* @return the boolean
|
||||
*/
|
||||
public boolean equals(String warName) {
|
||||
return this.name.equals(warName);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets side 1.
|
||||
*
|
||||
* @return the side 1
|
||||
*/
|
||||
@NotNull
|
||||
public Side getSide1() {
|
||||
return side1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets side 2.
|
||||
*
|
||||
* @return the side 2
|
||||
*/
|
||||
@NotNull
|
||||
public Side getSide2() {
|
||||
return side2;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets sides in a list.
|
||||
*
|
||||
* @return the sides
|
||||
*/
|
||||
@NotNull
|
||||
public Set<Side> getSides() {
|
||||
return Set.of(
|
||||
getSide1(),
|
||||
getSide2()
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets attacker side.
|
||||
*
|
||||
* @return the attacker
|
||||
*/
|
||||
@NotNull
|
||||
public Side getAttacker() {
|
||||
return attacker;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets defender side.
|
||||
*
|
||||
* @return the defender
|
||||
*/
|
||||
@NotNull
|
||||
public Side getDefender() {
|
||||
return defender;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets side by name.
|
||||
*
|
||||
* @param name the name
|
||||
* @return the side
|
||||
*/
|
||||
@Nullable
|
||||
public Side getSide(String name) {
|
||||
if (getSide1().equals(name))
|
||||
return getSide1();
|
||||
|
||||
if (getSide2().equals(name))
|
||||
return getSide2();
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets side by the side UUID.
|
||||
*
|
||||
* @param uuid the uuid
|
||||
* @return the side
|
||||
*/
|
||||
@Nullable
|
||||
public Side getSide(UUID uuid) {
|
||||
if (getSide1().equals(uuid))
|
||||
return getSide1();
|
||||
|
||||
if (getSide2().equals(uuid))
|
||||
return getSide2();
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
// SECTION Battles
|
||||
|
||||
/**
|
||||
* Gets sieges in a list.
|
||||
*
|
||||
* @return the sieges
|
||||
*/
|
||||
@NotNull
|
||||
public Set<Siege> getSieges() {
|
||||
return sieges;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets sieges for the war.
|
||||
*
|
||||
* @param sieges the sieges
|
||||
*/
|
||||
@ApiStatus.Internal
|
||||
public void setSieges(Set<Siege> sieges) {
|
||||
this.sieges = sieges;
|
||||
this.sieges.forEach(Siege::resume);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets siege by the siege UUID.
|
||||
*
|
||||
* @param uuid the uuid
|
||||
* @return the siege
|
||||
*/
|
||||
@Nullable
|
||||
public Siege getSiege(UUID uuid) {
|
||||
return sieges.stream()
|
||||
.filter(s -> s.equals(uuid))
|
||||
.findAny()
|
||||
.orElse(null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add siege to war.
|
||||
*
|
||||
* @param siege the siege
|
||||
*/
|
||||
@ApiStatus.Internal
|
||||
public void addSiege(Siege siege) {
|
||||
sieges.add(siege);
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove siege from war.
|
||||
*
|
||||
* @param siege the siege
|
||||
*/
|
||||
@ApiStatus.Internal
|
||||
public void removeSiege(Siege siege) {
|
||||
sieges.remove(siege);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets raids.
|
||||
*
|
||||
* @return the raids
|
||||
*/
|
||||
@NotNull
|
||||
public Set<Raid> getRaids() {
|
||||
return raids;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets raids for the war.
|
||||
*
|
||||
* @param raids the raids
|
||||
*/
|
||||
@ApiStatus.Internal
|
||||
public void setRaids(Set<Raid> raids) {
|
||||
this.raids = raids;
|
||||
// TODO Raids
|
||||
// this.raids.forEach(Raid::resume);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets raid by the raid UUID.
|
||||
*
|
||||
* @param uuid the uuid
|
||||
* @return the raid
|
||||
*/
|
||||
@Nullable
|
||||
public Raid getRaid(UUID uuid) {
|
||||
return raids.stream()
|
||||
.filter(s -> s.equals(uuid))
|
||||
.findAny()
|
||||
.orElse(null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add raid to war.
|
||||
*
|
||||
* @param raid the raid
|
||||
*/
|
||||
@ApiStatus.Internal
|
||||
public void addRaid(Raid raid) {
|
||||
raids.add(raid);
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove raid from war.
|
||||
*
|
||||
* @param raid the raid
|
||||
*/
|
||||
@ApiStatus.Internal
|
||||
public void removeRaid(Raid raid) {
|
||||
raids.remove(raid);
|
||||
}
|
||||
|
||||
/**
|
||||
* Is town under siege in this war.
|
||||
*
|
||||
* @param town the town
|
||||
* @return the boolean
|
||||
*/
|
||||
public boolean isTownUnderSiege(Town town) {
|
||||
return sieges.stream().anyMatch(siege -> siege.getTown().equals(town));
|
||||
}
|
||||
|
||||
/**
|
||||
* Is town under raid in this war.
|
||||
*
|
||||
* @param town the town
|
||||
* @return the boolean
|
||||
*/
|
||||
public boolean isTownUnderRaid(Town town) {
|
||||
// TODO Raids
|
||||
return false;
|
||||
// return raids.stream().anyMatch(raid -> raid.getTown().equals(town));
|
||||
}
|
||||
|
||||
// SECITON Nation & Town Getters
|
||||
|
||||
/**
|
||||
* Gets nations in the war excluding surrendered ones.
|
||||
*
|
||||
* @return the nations
|
||||
*/
|
||||
public Set<Nation> getNations() {
|
||||
return Stream.concat(
|
||||
getSide1().getNations().stream(),
|
||||
getSide2().getNations().stream()
|
||||
)
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets all surrendered nations in the war.
|
||||
*
|
||||
* @return the surrendered nations
|
||||
*/
|
||||
public Set<Nation> getNationsSurrendered() {
|
||||
return Stream.concat(
|
||||
getSide1().getNationsSurrendered().stream(),
|
||||
getSide2().getNationsSurrendered().stream()
|
||||
)
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets all nations in the war including surrendered.
|
||||
*
|
||||
* @return the all nations
|
||||
*/
|
||||
public Set<Nation> getNationsAll() {
|
||||
return Stream.concat(
|
||||
getSide1().getNations().stream(),
|
||||
Stream.concat(
|
||||
getSide2().getNations().stream(),
|
||||
getNationsSurrendered().stream()
|
||||
)
|
||||
)
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets towns in the war excluding surrendered ones.
|
||||
*
|
||||
* @return the towns
|
||||
*/
|
||||
public Set<Town> getTowns() {
|
||||
return Stream.concat(
|
||||
getSide1().getTowns().stream(),
|
||||
getSide2().getTowns().stream()
|
||||
)
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets all surrendered towns in the war.
|
||||
*
|
||||
* @return the surrendered towns
|
||||
*/
|
||||
public Set<Town> getTownsSurrendered() {
|
||||
return Stream.concat(
|
||||
getSide1().getTownsSurrendered().stream(),
|
||||
getSide2().getTownsSurrendered().stream()
|
||||
)
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets all towns in the war including surrendered towns.
|
||||
*
|
||||
* @return the all towns
|
||||
*/
|
||||
public Set<Town> getTownsAll() {
|
||||
return Stream.concat(
|
||||
getSide1().getTowns().stream(),
|
||||
Stream.concat(
|
||||
getSide2().getTowns().stream(),
|
||||
getTownsSurrendered().stream()
|
||||
)
|
||||
)
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
// SECTION Players Getters
|
||||
|
||||
/**
|
||||
* Get all players in the war (excluding surrendered)
|
||||
* @return player list
|
||||
*/
|
||||
public List<OfflinePlayer> getPlayers() {
|
||||
return Stream.concat(
|
||||
getSide1().getPlayers().stream(),
|
||||
getSide2().getPlayers().stream()
|
||||
).toList();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all players in the war (excludes non-surrendered players)
|
||||
* @return player list
|
||||
*/
|
||||
public List<OfflinePlayer> getPlayersSurrendered() {
|
||||
return Stream.concat(
|
||||
getSide1().getPlayersSurrendered().stream(),
|
||||
getSide2().getPlayersSurrendered().stream()
|
||||
).toList();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all players in the war (includes surrendered players)
|
||||
* @return player list
|
||||
*/
|
||||
public List<OfflinePlayer> getPlayersAll() {
|
||||
return Stream.concat(getSide1().getPlayersAll().stream(), getSide2().getPlayersAll().stream()).toList();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all online players in the war (excluding surrendered)
|
||||
* @return player list
|
||||
*/
|
||||
public List<Player> getPlayersOnline() {
|
||||
return Stream.concat(
|
||||
getSide1().getPlayersOnline().stream(),
|
||||
getSide2().getPlayersOnline().stream()
|
||||
).toList();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all online players in the war (excludes non-surrendered players)
|
||||
* @return player list
|
||||
*/
|
||||
public List<Player> getPlayersSurrenderedOnline() {
|
||||
return Stream.concat(
|
||||
getSide1().getPlayersSurrenderedOnline().stream(),
|
||||
getSide2().getPlayersSurrenderedOnline().stream()
|
||||
).toList();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all online players in the war (includes surrendered players)
|
||||
* @return player list
|
||||
*/
|
||||
public List<Player> getPlayersOnlineAll() {
|
||||
return Stream.concat(
|
||||
getSide1().getPlayersOnlineAll().stream(),
|
||||
getSide2().getPlayersOnlineAll().stream()
|
||||
).toList();
|
||||
}
|
||||
|
||||
// SECTION Misc
|
||||
|
||||
/**
|
||||
* Check if player is in war.
|
||||
*
|
||||
* @param p the p
|
||||
* @return the boolean
|
||||
*/
|
||||
public boolean isInWar(Player p) {
|
||||
return side1.isOnSide(p) || side2.isOnSide(p);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if player is in war.
|
||||
*
|
||||
* @param uuid the uuid
|
||||
* @return the boolean
|
||||
*/
|
||||
public boolean isInWar(UUID uuid) {
|
||||
return side1.isOnSide(uuid) || side2.isOnSide(uuid);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the side of the player or null if they are not in the war.
|
||||
*
|
||||
* @param p the p
|
||||
* @return the player side
|
||||
*/
|
||||
@Nullable
|
||||
public Side getPlayerSide(Player p) {
|
||||
return getPlayerSide(p.getUniqueId());
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets player side by player UUID or null if they are not in the war.
|
||||
*
|
||||
* @param uuid the uuid
|
||||
* @return the player side
|
||||
*/
|
||||
@Nullable
|
||||
public Side getPlayerSide(UUID uuid) {
|
||||
if (side1.isOnSide(uuid))
|
||||
return getSide1();
|
||||
|
||||
if (side2.isOnSide(uuid))
|
||||
return getSide2();
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Is nation or town in war.
|
||||
*
|
||||
* @param government the nation or town
|
||||
* @return the boolean
|
||||
*/
|
||||
public boolean isInWar(Government government) {
|
||||
return side1.isOnSide(government) || side2.isOnSide(government);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets nation or town side, or null if not in war.
|
||||
*
|
||||
* @param government the nation or town
|
||||
* @return the town side
|
||||
*/
|
||||
@Nullable
|
||||
public Side getSide(Government government) {
|
||||
if (side1.isOnSide(government))
|
||||
return getSide1();
|
||||
|
||||
if (side2.isOnSide(government))
|
||||
return getSide2();
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a side exists with the specified name.
|
||||
*
|
||||
* @param sideName the side name
|
||||
* @return the boolean
|
||||
*/
|
||||
public boolean isSideValid(String sideName) {
|
||||
return getSide1().equals(sideName) || getSide2().equals(sideName);
|
||||
}
|
||||
|
||||
/**
|
||||
* Cancel all active sieges in the war.
|
||||
*/
|
||||
@ApiStatus.Internal
|
||||
public void cancelSieges() {
|
||||
getTowns().forEach(this::cancelSieges);
|
||||
}
|
||||
|
||||
/**
|
||||
* Cancel all active sieges in the war. Ends the sieges in a draw.
|
||||
*
|
||||
* @param town the town
|
||||
*/
|
||||
@ApiStatus.Internal
|
||||
public void cancelSieges(Town town) {
|
||||
if (this != null) {
|
||||
Side townSide = getSide(town);
|
||||
|
||||
if (townSide == null) return;
|
||||
|
||||
getSieges().forEach(siege -> { // TODO INFINITE LOOP, runs surrenderTown
|
||||
if (siege.getTown().equals(town)) {
|
||||
if (siege.getAttackerSide().equals(townSide)) {
|
||||
siege.defendersWin(BattleVictoryReason.ADMIN_CANCEL);
|
||||
} else {
|
||||
siege.attackersWin(BattleVictoryReason.ADMIN_CANCEL);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Makes a government surrender (Recursively surrenders subjects AKA nations, towns, players)
|
||||
*
|
||||
* @param government the government
|
||||
*/
|
||||
public void surrender(Government government) {
|
||||
if (government instanceof Nation nation) {
|
||||
Side nationSide = getSide(nation);
|
||||
if (nationSide == null) return;
|
||||
|
||||
final @Nullable Nation occupier = nationSide.equals(getSide1()) ? getSide2().getTown().getNationOrNull() : getSide1().getTown().getNationOrNull();
|
||||
Occupation.setOccupied(nation, occupier);
|
||||
|
||||
nationSide.surrender(nation);
|
||||
// TODO Cancel in progress sieges for towns?
|
||||
nationSide.processSurrenders();
|
||||
} else if (government instanceof Town town) {
|
||||
Side townSide = getSide(town);
|
||||
if (townSide == null) return;
|
||||
|
||||
final @Nullable Nation townNation = town.getNationOrNull();
|
||||
final @Nullable Nation occupier = townSide.equals(getSide1()) ? getSide2().getTown().getNationOrNull() : getSide1().getTown().getNationOrNull();
|
||||
Occupation.setOccupied(town, occupier);
|
||||
townSide.surrender(town);
|
||||
|
||||
if (townNation != null) {
|
||||
if (townSide.shouldSurrender(townNation)) {
|
||||
surrender(townNation);
|
||||
}
|
||||
}
|
||||
|
||||
// TODO Cancel in progress sieges for towns?
|
||||
townSide.processSurrenders();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Makes a government un-surrender (Recursively un-surrenders subjects AKA nations, towns, players)
|
||||
*
|
||||
* @param government the government
|
||||
*/
|
||||
public void unsurrender(Government government) {
|
||||
if (government instanceof Nation nation) {
|
||||
Side nationSide = getSide(nation);
|
||||
if (nationSide == null) return;
|
||||
|
||||
nationSide.unsurrender(nation);
|
||||
nation.getTowns().forEach(this::unsurrender);
|
||||
} else if (government instanceof Town town) {
|
||||
Side townSide = getSide(town);
|
||||
if (townSide == null) return;
|
||||
|
||||
Occupation.removeOccupied(town);
|
||||
|
||||
townSide.unsurrender(town);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Start a new war after creation.
|
||||
*/
|
||||
@ApiStatus.Internal
|
||||
public void start() {
|
||||
Bukkit.broadcast(ColorParser.of(UtilsChat.getPrefix() + "The war of <war> has started between <attacker> and <defender>.")
|
||||
.parseMinimessagePlaceholder("war", getLabel())
|
||||
.parseMinimessagePlaceholder("attacker", getAttacker().getName())
|
||||
.parseMinimessagePlaceholder("defender", getDefender().getName())
|
||||
.build()
|
||||
);
|
||||
|
||||
final Title warTitle = Title.title(
|
||||
ColorParser.of("<gradient:#D72A09:#B01F03><u><b>War")
|
||||
.build(),
|
||||
ColorParser.of("<gray><i>The war of <war> has begun!")
|
||||
.parseMinimessagePlaceholder("war", getLabel())
|
||||
.build(),
|
||||
Title.Times.times(Duration.ofMillis(500), Duration.ofMillis(3500), Duration.ofMillis(500))
|
||||
);
|
||||
final Sound warSound = Sound.sound(Key.key("entity.wither.spawn"), Sound.Source.VOICE, 0.5f, 1.0F);
|
||||
|
||||
side1.getPlayersOnline().forEach(player -> {
|
||||
player.showTitle(warTitle);
|
||||
player.playSound(warSound);
|
||||
});
|
||||
side2.getPlayersOnline().forEach(player -> {
|
||||
player.showTitle(warTitle);
|
||||
player.playSound(warSound);
|
||||
});
|
||||
|
||||
side1.applyNameTags();
|
||||
side2.applyNameTags();
|
||||
}
|
||||
|
||||
/**
|
||||
* Resume a pre-existing war after loading it from db.
|
||||
*/
|
||||
@ApiStatus.Internal
|
||||
public void resume() {
|
||||
side1.applyNameTags();
|
||||
side2.applyNameTags();
|
||||
}
|
||||
|
||||
/**
|
||||
* End a war for the specified reason. Triggered internally by {@link War#defeat(Side)} & {@link War#draw()}.
|
||||
*
|
||||
* @param reason the reason
|
||||
*/
|
||||
@ApiStatus.Internal
|
||||
public void end(WarDeleteReason reason) {
|
||||
if (!new PreWarDeleteEvent(this, reason).callEvent())
|
||||
return;
|
||||
|
||||
getSieges().forEach(Siege::stop);
|
||||
getTownsAll().forEach(Occupation::removeOccupied);
|
||||
|
||||
DatabaseQueries.deleteWar(this);
|
||||
WarController.getInstance().removeWar(this);
|
||||
|
||||
// Run check after war is removed to cleanup player tags
|
||||
getPlayersOnline().forEach(p -> NameColorHandler.getInstance().calculatePlayerColors(p));
|
||||
|
||||
new WarDeleteEvent(this, reason).callEvent();
|
||||
}
|
||||
|
||||
/**
|
||||
* End the war in defeat for the specified side. Internally runs {@link War#end(WarDeleteReason)}.
|
||||
*
|
||||
* @param loserSide the loser side
|
||||
*/
|
||||
public void defeat(Side loserSide) {
|
||||
Side loser = loserSide.equals(getSide1()) ? getSide1() : getSide2();
|
||||
Side winner = loserSide.equals(getSide1()) ? getSide2() : getSide1();
|
||||
|
||||
Bukkit.broadcast(ColorParser.of(UtilsChat.getPrefix() + "The war of <war> has ended. <red><winner> <reset>has triumphed against <red><loser><reset>.")
|
||||
.parseMinimessagePlaceholder("war", getLabel())
|
||||
.parseMinimessagePlaceholder("winner", winner.getName())
|
||||
.parseMinimessagePlaceholder("loser", loser.getName())
|
||||
.build()
|
||||
);
|
||||
|
||||
end(WarDeleteReason.DEFEAT);
|
||||
}
|
||||
|
||||
/**
|
||||
* End the war in a white peace/draw. Internally runs {@link War#end(WarDeleteReason)}.
|
||||
*/
|
||||
public void draw() {
|
||||
Bukkit.broadcast(ColorParser.of(UtilsChat.getPrefix() + "The war of <war> has ended with a white peace.")
|
||||
.parseMinimessagePlaceholder("war", getLabel())
|
||||
.build()
|
||||
);
|
||||
|
||||
end(WarDeleteReason.DRAW);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets if this is an event war.
|
||||
*
|
||||
* @param event the event
|
||||
*/
|
||||
public void setEventWar(boolean event) {
|
||||
this.event = event;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets if this is an event war. Event wars skip or execute certain logic as they are for player events.
|
||||
*
|
||||
* @return the boolean
|
||||
*/
|
||||
public boolean isEventWar() {
|
||||
return event;
|
||||
}
|
||||
}
|
||||
@@ -1,156 +0,0 @@
|
||||
package com.github.alathra.alathranwars.conflict.war;
|
||||
|
||||
import com.github.alathra.alathranwars.conflict.battle.raid.Raid;
|
||||
import com.github.alathra.alathranwars.conflict.battle.siege.Siege;
|
||||
import com.github.alathra.alathranwars.conflict.war.side.Side;
|
||||
import com.github.alathra.alathranwars.conflict.war.side.SideCreationException;
|
||||
import com.github.alathra.alathranwars.enums.ConflictType;
|
||||
import com.palmergames.bukkit.towny.object.Government;
|
||||
import dev.jorel.commandapi.exceptions.WrapperCommandSyntaxException;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
|
||||
public class WarBuilder {
|
||||
private @Nullable UUID uuid;
|
||||
private @Nullable String name;
|
||||
private @Nullable String label;
|
||||
private ConflictType conflictType = ConflictType.WAR;
|
||||
private boolean event = false;
|
||||
private @Nullable Side side1;
|
||||
private @Nullable Side side2;
|
||||
private @Nullable Set<Siege> sieges = new HashSet<>();
|
||||
private @Nullable Set<Raid> raids = new HashSet<>();
|
||||
|
||||
private @Nullable Government aggressor;
|
||||
private @Nullable Government victim;
|
||||
|
||||
public WarBuilder() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a new war from save data
|
||||
* @return a new war
|
||||
* @throws WarCreationException exception
|
||||
*/
|
||||
public War resume() throws WarCreationException {
|
||||
if (uuid == null)
|
||||
throw new WarCreationException("Missing state uuid required to create War!");
|
||||
|
||||
if (name == null)
|
||||
throw new WarCreationException("Missing state name required to create War!");
|
||||
|
||||
if (label == null)
|
||||
throw new WarCreationException("Missing state label required to create War!");
|
||||
|
||||
if (side1 == null)
|
||||
throw new WarCreationException("Missing state side1 required to create War!");
|
||||
|
||||
if (side2 == null)
|
||||
throw new WarCreationException("Missing state side2 required to create War!");
|
||||
|
||||
if (sieges == null)
|
||||
throw new WarCreationException("Missing state sieges required to create War!");
|
||||
|
||||
if (raids == null)
|
||||
throw new WarCreationException("Missing state raids required to create War!");
|
||||
|
||||
return new War(
|
||||
uuid,
|
||||
name,
|
||||
label,
|
||||
side1,
|
||||
side2,
|
||||
sieges,
|
||||
raids,
|
||||
event
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a new War
|
||||
* @return a new war
|
||||
* @throws WrapperCommandSyntaxException exception
|
||||
* @throws SideCreationException exception
|
||||
*/
|
||||
public War create() throws WrapperCommandSyntaxException, SideCreationException {
|
||||
this.setUuid(UUID.randomUUID());
|
||||
|
||||
if (uuid == null)
|
||||
throw new WarCreationException("Missing state uuid required to create War!");
|
||||
|
||||
if (label == null)
|
||||
throw new WarCreationException("Missing state label required to create War!");
|
||||
|
||||
if (aggressor == null)
|
||||
throw new WarCreationException("Missing state aggressor required to create War!");
|
||||
|
||||
if (victim == null)
|
||||
throw new WarCreationException("Missing state victim required to create War!");
|
||||
|
||||
return new War(
|
||||
uuid,
|
||||
label,
|
||||
aggressor,
|
||||
victim,
|
||||
event
|
||||
);
|
||||
}
|
||||
|
||||
public WarBuilder setUuid(UUID uuid) {
|
||||
this.uuid = uuid;
|
||||
return this;
|
||||
}
|
||||
|
||||
public WarBuilder setName(String name) {
|
||||
this.name = name;
|
||||
return this;
|
||||
}
|
||||
|
||||
public WarBuilder setLabel(String label) {
|
||||
this.label = label;
|
||||
return this;
|
||||
}
|
||||
|
||||
public WarBuilder setConflictType(ConflictType conflictType) {
|
||||
this.conflictType = conflictType;
|
||||
return this;
|
||||
}
|
||||
|
||||
public WarBuilder setSide1(Side side1) {
|
||||
this.side1 = side1;
|
||||
return this;
|
||||
}
|
||||
|
||||
public WarBuilder setSide2(Side side2) {
|
||||
this.side2 = side2;
|
||||
return this;
|
||||
}
|
||||
|
||||
public WarBuilder setEvent(boolean event) {
|
||||
this.event = event;
|
||||
return this;
|
||||
}
|
||||
|
||||
public WarBuilder setSieges(Set<Siege> sieges) {
|
||||
this.sieges = sieges;
|
||||
return this;
|
||||
}
|
||||
|
||||
public WarBuilder setRaids(Set<Raid> raids) {
|
||||
this.raids = raids;
|
||||
return this;
|
||||
}
|
||||
|
||||
public WarBuilder setAggressor(Government aggressor) {
|
||||
this.aggressor = aggressor;
|
||||
return this;
|
||||
}
|
||||
|
||||
public WarBuilder setVictim(Government victim) {
|
||||
this.victim = victim;
|
||||
return this;
|
||||
}
|
||||
}
|
||||
@@ -1,465 +0,0 @@
|
||||
package com.github.alathra.alathranwars.conflict.war;
|
||||
|
||||
import com.github.alathra.alathranwars.conflict.battle.raid.Raid;
|
||||
import com.github.alathra.alathranwars.conflict.battle.siege.Siege;
|
||||
import com.github.alathra.alathranwars.conflict.war.side.Side;
|
||||
import com.github.alathra.alathranwars.database.DatabaseQueries;
|
||||
import com.palmergames.bukkit.towny.object.Government;
|
||||
import com.palmergames.bukkit.towny.object.Nation;
|
||||
import com.palmergames.bukkit.towny.object.Town;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.jetbrains.annotations.ApiStatus;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import javax.inject.Singleton;
|
||||
import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* The singleton War controller.
|
||||
*/
|
||||
@Singleton
|
||||
public class WarController {
|
||||
private static WarController instance;
|
||||
private Set<War> wars = new HashSet<>();
|
||||
|
||||
private WarController() {
|
||||
if (instance != null)
|
||||
Bukkit.getServer().getLogger().warning("Tried to re-initialize singleton");
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets or creates an instance of the war controller.
|
||||
*
|
||||
* @return the instance
|
||||
*/
|
||||
public static WarController getInstance() {
|
||||
if (instance == null)
|
||||
instance = new WarController();
|
||||
|
||||
return instance;
|
||||
}
|
||||
|
||||
/**
|
||||
* Load all wars into memory from database.
|
||||
*/
|
||||
@ApiStatus.Internal
|
||||
public void loadAll() {
|
||||
wars = DatabaseQueries.loadAll();
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a war to the war controller.
|
||||
*
|
||||
* @param war the war
|
||||
*/
|
||||
@ApiStatus.Internal
|
||||
public void addWar(War war) {
|
||||
getWars().add(war);
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove a war from the war controller.
|
||||
*
|
||||
* @param war the war
|
||||
*/
|
||||
@ApiStatus.Internal
|
||||
public void removeWar(War war) {
|
||||
getWars().remove(war);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets all wars.
|
||||
*
|
||||
* @return the wars
|
||||
*/
|
||||
public Set<War> getWars() {
|
||||
return wars;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets war by its name or returns null.
|
||||
*
|
||||
* @param warName the war name
|
||||
* @return the war
|
||||
*/
|
||||
@Nullable
|
||||
public War getWar(String warName) {
|
||||
return getWars().stream()
|
||||
.filter(war -> war.equals(warName))
|
||||
.findAny()
|
||||
.orElse(null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets war by its UUID or returns null.
|
||||
*
|
||||
* @param uuid the uuid
|
||||
* @return the war
|
||||
*/
|
||||
@Nullable
|
||||
public War getWar(UUID uuid) {
|
||||
return getWars().stream()
|
||||
.filter(war -> war.equals(uuid))
|
||||
.findAny()
|
||||
.orElse(null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Is nation or town in any wars. (Includes surrendered nations & towns)
|
||||
*
|
||||
* @param government the government
|
||||
* @return the boolean
|
||||
*/
|
||||
public boolean isInAnyWars(Government government) {
|
||||
return getWars().stream()
|
||||
.anyMatch(war -> war.isInWar(government));
|
||||
}
|
||||
|
||||
/**
|
||||
* Is player in any wars. Includes if surrendered.
|
||||
*
|
||||
* @param p the p
|
||||
* @return the boolean
|
||||
*/
|
||||
public boolean isInAnyWars(Player p) {
|
||||
return isInAnyWars(p.getUniqueId());
|
||||
}
|
||||
|
||||
/**
|
||||
* Is player in any wars. Includes if surrendered.
|
||||
*
|
||||
* @param uuid the uuid
|
||||
* @return the boolean
|
||||
*/
|
||||
public boolean isInAnyWars(UUID uuid) {
|
||||
return getWars().stream()
|
||||
.anyMatch(war -> war.isInWar(uuid));
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets nation or town wars. (Includes surrendered nations & towns)
|
||||
*
|
||||
* @param government the government
|
||||
* @return the nation wars
|
||||
*/
|
||||
public Set<War> getWars(Government government) {
|
||||
return getWars().stream()
|
||||
.filter(war -> war.isInWar(government))
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets list of player wars. Includes if surrendered.
|
||||
*
|
||||
* @param p the p
|
||||
* @return the player wars
|
||||
*/
|
||||
public Set<War> getWars(Player p) {
|
||||
return getWars(p.getUniqueId());
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets list of player wars. Includes if surrendered.
|
||||
*
|
||||
* @param uuid the uuid
|
||||
* @return the player wars
|
||||
*/
|
||||
public Set<War> getWars(UUID uuid) {
|
||||
return getWars().stream()
|
||||
.filter(war -> war.isInWar(uuid))
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
// SECTION Battles
|
||||
|
||||
/**
|
||||
* Gets siege by the siege UUID.
|
||||
*
|
||||
* @param uuid the uuid
|
||||
* @return the siege
|
||||
*/
|
||||
@Nullable
|
||||
public Siege getSiege(UUID uuid) {
|
||||
return getWars().stream()
|
||||
.map(war -> war.getSiege(uuid))
|
||||
.filter(Objects::nonNull)
|
||||
.findAny()
|
||||
.orElse(null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets raid by the raid UUID.
|
||||
*
|
||||
* @param uuid the uuid
|
||||
* @return the raid
|
||||
*/
|
||||
@Nullable
|
||||
public Raid getRaid(UUID uuid) {
|
||||
return getWars().stream()
|
||||
.map(war -> war.getRaid(uuid))
|
||||
.filter(Objects::nonNull)
|
||||
.findAny()
|
||||
.orElse(null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Is nation or town in any sieges. Includes surrendered nations/towns.
|
||||
*
|
||||
* @param government the government
|
||||
* @return the boolean
|
||||
*/
|
||||
public boolean isInAnySieges(Government government) {
|
||||
if (government instanceof Nation nation) {
|
||||
return nation.getTowns().stream()
|
||||
.anyMatch(this::isInAnySieges);
|
||||
} else if (government instanceof Town town) {
|
||||
return getWars().stream()
|
||||
.anyMatch(war -> war.isInWar(town) && war.isTownUnderSiege(town));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Is nation or town in any raids. Includes surrendered nations/towns.
|
||||
*
|
||||
* @param government the government
|
||||
* @return the boolean
|
||||
*/
|
||||
public boolean isInAnyRaids(Government government) {
|
||||
if (government instanceof Nation nation) {
|
||||
return nation.getTowns().stream()
|
||||
.anyMatch(this::isInAnyRaids);
|
||||
} else if (government instanceof Town town) {
|
||||
return getWars().stream()
|
||||
.anyMatch(war -> war.isInWar(town) && war.isTownUnderRaid(town));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a list of all active sieges.
|
||||
*
|
||||
* @return the sieges
|
||||
*/
|
||||
public Set<Siege> getSieges() {
|
||||
return getWars().stream()
|
||||
.map(War::getSieges)
|
||||
.flatMap(Set::stream)
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets nation or town sieges. Includes surrendered nation/town.
|
||||
*
|
||||
* @param government the government
|
||||
* @return the town sieges
|
||||
*/
|
||||
public Set<Siege> getSieges(Government government) {
|
||||
if (government instanceof Nation nation) {
|
||||
return nation.getTowns().stream()
|
||||
.flatMap(town -> getSieges(town).stream())
|
||||
.collect(Collectors.toSet());
|
||||
} else if (government instanceof Town town) {
|
||||
return getSieges().stream()
|
||||
.filter(siege -> siege.getAttackerSide().isOnSide(town) || siege.getDefenderSide().isOnSide(town))
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
return Set.of();
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets player sieges.
|
||||
*
|
||||
* @param p the p
|
||||
* @return the player sieges
|
||||
*/
|
||||
public Set<Siege> getSieges(Player p) {
|
||||
return getSieges(p.getUniqueId());
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets player sieges. Returns true for offline players.
|
||||
*
|
||||
* @param uuid the uuid
|
||||
* @return the player sieges
|
||||
*/
|
||||
public Set<Siege> getSieges(UUID uuid) {
|
||||
return getSieges().stream()
|
||||
.filter(siege -> siege.isPlayerParticipating(uuid))
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a list of all active raids.
|
||||
*
|
||||
* @return the raids
|
||||
*/
|
||||
public Set<Raid> getRaids() {
|
||||
return getWars().stream()
|
||||
.map(War::getRaids)
|
||||
.flatMap(Set::stream)
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets nation or town raids. Includes surrendered nation/town.
|
||||
*
|
||||
* @param government the government
|
||||
* @return the town raids
|
||||
*/
|
||||
public Set<Raid> getRaids(Government government) {
|
||||
// TODO Raids
|
||||
/*if (government instanceof Nation nation) {
|
||||
return nation.getTowns().stream()
|
||||
.flatMap(town -> getRaids(town).stream())
|
||||
.collect(Collectors.toSet());
|
||||
} else if (government instanceof Town town) {
|
||||
return getRaids().stream()
|
||||
.filter(raid -> raid.getAttackerSide().isOnSide(town) || raid.getDefenderSide().isOnSide(town))
|
||||
.collect(Collectors.toSet());
|
||||
}*/
|
||||
return Set.of();
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets player raids.
|
||||
*
|
||||
* @param p the p
|
||||
* @return the player raids
|
||||
*/
|
||||
public Set<Raid> getRaids(Player p) {
|
||||
return getRaids(p.getUniqueId());
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets player raids. Returns true for offline players.
|
||||
*
|
||||
* @param uuid the uuid
|
||||
* @return the player raids
|
||||
*/
|
||||
public Set<Raid> getRaids(UUID uuid) {
|
||||
// TODO Raids
|
||||
/*return getRaids().stream()
|
||||
.filter(raid -> raid.isPlayerInRaid(uuid))
|
||||
.collect(Collectors.toSet());*/
|
||||
return Collections.emptySet();
|
||||
}
|
||||
|
||||
// SECTION Misc
|
||||
|
||||
/**
|
||||
* Gets side by the side UUID.
|
||||
*
|
||||
* @param uuid the uuid
|
||||
* @return the side
|
||||
*/
|
||||
@Nullable
|
||||
public Side getSide(UUID uuid) {
|
||||
return getWars().stream()
|
||||
.map(war -> war.getSide(uuid))
|
||||
.filter(Objects::nonNull)
|
||||
.findAny()
|
||||
.orElse(null);
|
||||
}
|
||||
|
||||
// SECTION API
|
||||
|
||||
/**
|
||||
* Gets a list of war names.
|
||||
*
|
||||
* @return the war names
|
||||
*/
|
||||
public List<String> getWarNames() {
|
||||
return getWars().stream()
|
||||
.map(War::getName)
|
||||
.sorted(String::compareToIgnoreCase)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a list of war labels.
|
||||
*
|
||||
* @return the war labels
|
||||
*/
|
||||
public List<String> getWarLabels() {
|
||||
return getWars().stream()
|
||||
.map(War::getLabel)
|
||||
.sorted(String::compareToIgnoreCase)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets nations at war. Does not include surrendered nations.
|
||||
*
|
||||
* @return the nations at war
|
||||
*/
|
||||
public Set<Nation> getNationsAtWar() {
|
||||
return getWars().stream()
|
||||
.map(War::getNations)
|
||||
.flatMap(Set::stream)
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets towns at war. Does not include surrendered towns.
|
||||
*
|
||||
* @return the towns at war
|
||||
*/
|
||||
public Set<Town> getTownsAtWar() {
|
||||
return getWars().stream()
|
||||
.map(War::getTowns)
|
||||
.flatMap(Set::stream)
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if two sides are opposing each-other in a war
|
||||
* @param side1 a side
|
||||
* @param side2 a side
|
||||
* @return true if opposing each-other in a war
|
||||
*/
|
||||
public boolean isAtWar(Side side1, Side side2) {
|
||||
// Return early if comparing same side to prevent false positive
|
||||
if (side1.equals(side2))
|
||||
return false;
|
||||
|
||||
return side1.getWar().equals(side2.getWar());
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if two governments are at war with each-other
|
||||
* @param government1 nation or town
|
||||
* @param government2 nation or town
|
||||
* @return true if governments are on opposing sides in any war
|
||||
*/
|
||||
public boolean isAtWar(Government government1, Government government2) {
|
||||
Set<War> wars1 = getWars(government1);
|
||||
Set<War> wars2 = getWars(government2);
|
||||
|
||||
/*final boolean isInSameWar = wars1.stream().anyMatch(wars2::contains);
|
||||
if (!isInSameWar)
|
||||
return false;*/
|
||||
|
||||
// Get list of common wars
|
||||
Set<War> sharedWars = wars1.stream()
|
||||
.filter(wars2::contains)
|
||||
.collect(Collectors.toSet());
|
||||
|
||||
// Iterate shared wars and check if on opposite sides
|
||||
for (War war : sharedWars) {
|
||||
Side side1 = war.getSide(government1);
|
||||
Side side2 = war.getSide(government2);
|
||||
|
||||
if (side1 == null || side2 == null)
|
||||
continue;
|
||||
|
||||
if (!isAtWar(side1, side2)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
package com.github.alathra.alathranwars.conflict.war;
|
||||
|
||||
import com.github.alathra.alathranwars.conflict.war.side.SideCreationException;
|
||||
|
||||
public class WarCreationException extends SideCreationException {
|
||||
public WarCreationException(String errorMessage) {
|
||||
super(errorMessage);
|
||||
}
|
||||
}
|
||||
-546
@@ -1,546 +0,0 @@
|
||||
package com.github.alathra.alathranwars.conflict.war.side;
|
||||
|
||||
import com.palmergames.bukkit.towny.object.Government;
|
||||
import com.palmergames.bukkit.towny.object.Nation;
|
||||
import com.palmergames.bukkit.towny.object.Resident;
|
||||
import com.palmergames.bukkit.towny.object.Town;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.OfflinePlayer;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
/**
|
||||
* Provides methods for handling all members of a side
|
||||
*/
|
||||
public abstract class AbstractSideTeamManager {
|
||||
private final Set<Nation> nations = new HashSet<>(); // Collection of nations in the war (excludes surrendered)
|
||||
private final Set<Town> towns = new HashSet<>(); // Collection of towns in the war (excludes surrendered)
|
||||
private final Set<OfflinePlayer> players = new HashSet<>(); // Collection of players in the war (excludes surrendered)
|
||||
|
||||
private final Set<Nation> nationsSurrendered = new HashSet<>(); // Collection surrendered of nations in the war (excludes non-surrendered)
|
||||
private final Set<Town> townsSurrendered = new HashSet<>(); // Collection of surrendered towns in the war (excludes non-surrendered)
|
||||
private final Set<OfflinePlayer> playersSurrendered = new HashSet<>(); // Collection of surrendered players in the war (excludes non-surrendered)
|
||||
|
||||
public AbstractSideTeamManager() {}
|
||||
|
||||
public AbstractSideTeamManager(
|
||||
Set<Nation> nations,
|
||||
Set<Town> towns,
|
||||
Set<OfflinePlayer> players,
|
||||
Set<Nation> nationsSurrendered,
|
||||
Set<Town> townsSurrendered,
|
||||
Set<OfflinePlayer> playersSurrendered
|
||||
) {
|
||||
this.nations.addAll(nations);
|
||||
this.towns.addAll(towns);
|
||||
this.players.addAll(players);
|
||||
this.nationsSurrendered.addAll(nationsSurrendered);
|
||||
this.townsSurrendered.addAll(townsSurrendered);
|
||||
this.playersSurrendered.addAll(playersSurrendered);
|
||||
}
|
||||
|
||||
// SECTION Governments management
|
||||
|
||||
/**
|
||||
* Add a government to the side (Recursively adds subjects AKA towns, players)
|
||||
* @param government a government
|
||||
*/
|
||||
public void add(Government government) {
|
||||
if (government instanceof Nation nation) {
|
||||
nations.add(nation);
|
||||
nation.getTowns().forEach(this::add);
|
||||
} else if (government instanceof Town town) {
|
||||
towns.add(town);
|
||||
town.getResidents().stream()
|
||||
.map(Resident::getUUID)
|
||||
.map(Bukkit::getOfflinePlayer)
|
||||
.forEach(this::add);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove a government from the side (Recursively removes subjects AKA towns, players)
|
||||
* @param government a government
|
||||
*/
|
||||
public void remove(Government government) {
|
||||
if (government instanceof Nation nation) {
|
||||
nations.remove(nation);
|
||||
nation.getTowns().forEach(this::remove);
|
||||
} else if (government instanceof Town town) {
|
||||
towns.remove(town);
|
||||
town.getResidents().stream()
|
||||
.map(Resident::getUUID)
|
||||
.map(Bukkit::getOfflinePlayer)
|
||||
.forEach(this::remove);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a surrendered government to the side (Recursively adds subjects AKA towns, players)
|
||||
* @param government a government
|
||||
*/
|
||||
public void addSurrendered(Government government) {
|
||||
if (government instanceof Nation nation) {
|
||||
nationsSurrendered.add(nation);
|
||||
nation.getTowns().forEach(this::addSurrendered);
|
||||
} else if (government instanceof Town town) {
|
||||
townsSurrendered.add(town);
|
||||
town.getResidents().stream()
|
||||
.map(Resident::getUUID)
|
||||
.map(Bukkit::getOfflinePlayer)
|
||||
.forEach(this::addSurrendered);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove a surrendered government from the side (Recursively removes subjects AKA towns, players)
|
||||
* @param government a government
|
||||
*/
|
||||
public void removeSurrendered(Government government) {
|
||||
if (government instanceof Nation nation) {
|
||||
nationsSurrendered.remove(nation);
|
||||
nation.getTowns().forEach(this::removeSurrendered);
|
||||
} else if (government instanceof Town town) {
|
||||
townsSurrendered.remove(town);
|
||||
town.getResidents().stream()
|
||||
.map(Resident::getUUID)
|
||||
.map(Bukkit::getOfflinePlayer)
|
||||
.forEach(this::removeSurrendered);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Kick a government from the side (Recursively kicks subjects AKA towns, players)
|
||||
* @param government a government
|
||||
*/
|
||||
public void kick(Government government) {
|
||||
remove(government);
|
||||
removeSurrendered(government);
|
||||
}
|
||||
|
||||
// SECTION Players management
|
||||
|
||||
/**
|
||||
* Add a player to the side
|
||||
* @param p a player
|
||||
*/
|
||||
public void add(Player p) {
|
||||
add(p.getUniqueId());
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a player to the side
|
||||
* @param uuid a player uuid
|
||||
*/
|
||||
public void add(UUID uuid) {
|
||||
add(Bukkit.getOfflinePlayer(uuid));
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a player to the side
|
||||
* @param p a player
|
||||
*/
|
||||
public void add(OfflinePlayer p) {
|
||||
players.add(p);
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove a player from the side
|
||||
* @param p a player
|
||||
*/
|
||||
public void remove(Player p) {
|
||||
remove(p.getUniqueId());
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove a player from the side
|
||||
* @param uuid a player uuid
|
||||
*/
|
||||
public void remove(UUID uuid) {
|
||||
remove(Bukkit.getOfflinePlayer(uuid));
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove a player from the side
|
||||
* @param p a player
|
||||
*/
|
||||
public void remove(OfflinePlayer p) {
|
||||
players.remove(p);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a surrendered player to the side
|
||||
* @param p a player
|
||||
*/
|
||||
public void addSurrendered(Player p) {
|
||||
add(p.getUniqueId());
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a surrendered player to the side
|
||||
* @param uuid a player uuid
|
||||
*/
|
||||
public void addSurrendered(UUID uuid) {
|
||||
add(Bukkit.getOfflinePlayer(uuid));
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a surrendered player to the side
|
||||
* @param p a player
|
||||
*/
|
||||
public void addSurrendered(OfflinePlayer p) {
|
||||
playersSurrendered.add(p);
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove a surrendered player from the side
|
||||
* @param p a player
|
||||
*/
|
||||
public void removeSurrendered(Player p) {
|
||||
remove(p.getUniqueId());
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove a surrendered player from the side
|
||||
* @param uuid a player uuid
|
||||
*/
|
||||
public void removeSurrendered(UUID uuid) {
|
||||
remove(Bukkit.getOfflinePlayer(uuid));
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove a surrendered player from the side
|
||||
* @param p a player
|
||||
*/
|
||||
public void removeSurrendered(OfflinePlayer p) {
|
||||
playersSurrendered.remove(p);
|
||||
}
|
||||
|
||||
/**
|
||||
* Kick a player from the side
|
||||
* @param p a player
|
||||
*/
|
||||
public void kick(Player p) {
|
||||
remove(p);
|
||||
removeSurrendered(p);
|
||||
}
|
||||
|
||||
/**
|
||||
* Kick a player from the side
|
||||
* @param uuid a player uuid
|
||||
*/
|
||||
public void kick(UUID uuid) {
|
||||
remove(uuid);
|
||||
removeSurrendered(uuid);
|
||||
}
|
||||
|
||||
/**
|
||||
* Kick a player from the side
|
||||
* @param p a player
|
||||
*/
|
||||
public void kick(OfflinePlayer p) {
|
||||
remove(p);
|
||||
removeSurrendered(p);
|
||||
}
|
||||
|
||||
// SECTION Governments Getters
|
||||
|
||||
/**
|
||||
* Get nations on this side (excludes surrendered nations)
|
||||
* @return the nations
|
||||
*/
|
||||
public Set<Nation> getNations() {
|
||||
return nations;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get nations on this side (excludes non-surrendered nations)
|
||||
* @return the nations
|
||||
*/
|
||||
public Set<Nation> getNationsSurrendered() {
|
||||
return nationsSurrendered;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all nations on this side (includes surrendered nations)
|
||||
* @return the nations
|
||||
*/
|
||||
public List<Nation> getNationsAll() {
|
||||
return Stream.concat(getNations().stream(), getNationsSurrendered().stream()).toList();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get towns on this side (excludes surrendered towns)
|
||||
* @return the towns
|
||||
*/
|
||||
public Set<Town> getTowns() {
|
||||
return towns;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get towns on this side (excludes non-surrendered towns)
|
||||
* @return the towns
|
||||
*/
|
||||
public Set<Town> getTownsSurrendered() {
|
||||
return townsSurrendered;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all towns on this side (includes surrendered towns)
|
||||
* @return the towns
|
||||
*/
|
||||
public List<Town> getTownsAll() {
|
||||
return Stream.concat(getTowns().stream(), getTownsSurrendered().stream()).toList();
|
||||
}
|
||||
|
||||
// SECTION Players Getters
|
||||
|
||||
/**
|
||||
* Get all players on this side (excluding surrendered)
|
||||
* @return player list
|
||||
*/
|
||||
public List<OfflinePlayer> getPlayers() {
|
||||
return players.stream().toList();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all players on this side (excludes non-surrendered players)
|
||||
* @return player list
|
||||
*/
|
||||
public List<OfflinePlayer> getPlayersSurrendered() {
|
||||
return playersSurrendered.stream().toList();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all players on this side (includes surrendered players)
|
||||
* @return player list
|
||||
*/
|
||||
public List<OfflinePlayer> getPlayersAll() {
|
||||
return Stream.concat(getPlayers().stream(), getPlayersSurrendered().stream()).toList();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all online players on this side (excluding surrendered)
|
||||
* @return player list
|
||||
*/
|
||||
public List<Player> getPlayersOnline() {
|
||||
return players.stream()
|
||||
.filter(OfflinePlayer::isOnline)
|
||||
.map(OfflinePlayer::getPlayer)
|
||||
.toList();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all online players on this side (excludes non-surrendered players)
|
||||
* @return player list
|
||||
*/
|
||||
public List<Player> getPlayersSurrenderedOnline() {
|
||||
return playersSurrendered.stream()
|
||||
.filter(OfflinePlayer::isOnline)
|
||||
.map(OfflinePlayer::getPlayer)
|
||||
.toList();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all online players on this side (includes surrendered players)
|
||||
* @return player list
|
||||
*/
|
||||
public List<Player> getPlayersOnlineAll() {
|
||||
return Stream.concat(getPlayersOnline().stream(), getPlayersSurrenderedOnline().stream()).toList();
|
||||
}
|
||||
|
||||
// Checks
|
||||
|
||||
/**
|
||||
* Check if a government is on this side (includes surrendered governments)
|
||||
* @param government the government
|
||||
* @return true if on side
|
||||
*/
|
||||
public boolean isOnSide(Government government) {
|
||||
if (government instanceof Nation nation) {
|
||||
return nations.contains(nation) || nationsSurrendered.contains(nation);
|
||||
} else if (government instanceof Town town) {
|
||||
return towns.contains(town) || townsSurrendered.contains(town);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a player is on this side (includes surrendered players)
|
||||
* @param p the player
|
||||
* @return true if on side
|
||||
*/
|
||||
public boolean isOnSide(Player p) {
|
||||
return isOnSide(p.getUniqueId());
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a player is on this side (includes surrendered players)
|
||||
* @param uuid the player uuid
|
||||
* @return true if on side
|
||||
*/
|
||||
public boolean isOnSide(UUID uuid) {
|
||||
return isOnSide(Bukkit.getOfflinePlayer(uuid));
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a player is on this side (includes surrendered players)
|
||||
* @param p the player
|
||||
* @return true if on side
|
||||
*/
|
||||
public boolean isOnSide(OfflinePlayer p) {
|
||||
return players.contains(p) || playersSurrendered.contains(p);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a government is surrendered on this side
|
||||
* @param government the government
|
||||
* @return true if on side and surrendered
|
||||
*/
|
||||
public boolean isSurrendered(Government government) {
|
||||
if (government instanceof Nation nation) {
|
||||
return nationsSurrendered.contains(nation);
|
||||
} else if (government instanceof Town town) {
|
||||
return townsSurrendered.contains(town);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a player is surrendered on this side
|
||||
* @param p the player
|
||||
* @return true if on side and surrendered
|
||||
*/
|
||||
public boolean isSurrendered(Player p) {
|
||||
return isSurrendered(p.getUniqueId());
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a player is surrendered on this side
|
||||
* @param uuid the player uuid
|
||||
* @return true if on side and surrendered
|
||||
*/
|
||||
public boolean isSurrendered(UUID uuid) {
|
||||
return isSurrendered(Bukkit.getOfflinePlayer(uuid));
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a player is surrendered on this side
|
||||
* @param p the player
|
||||
* @return true if on side and surrendered
|
||||
*/
|
||||
public boolean isSurrendered(OfflinePlayer p) {
|
||||
return playersSurrendered.contains(p);
|
||||
}
|
||||
|
||||
// SECTION Surrendering
|
||||
|
||||
/**
|
||||
* Makes a government surrender (Recursively surrenders subjects AKA nations, towns, players)
|
||||
* @param government the government
|
||||
*/
|
||||
public void surrender(Government government) {
|
||||
if (isSurrendered(government))
|
||||
return;
|
||||
|
||||
if (government instanceof Nation nation) {
|
||||
remove(nation);
|
||||
addSurrendered(nation);
|
||||
} else if (government instanceof Town town) {
|
||||
remove(town);
|
||||
addSurrendered(town);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Makes a player surrender
|
||||
* @param p the player
|
||||
*/
|
||||
public void surrender(Player p) { surrender(p.getUniqueId()); }
|
||||
|
||||
/**
|
||||
* Makes a player surrender
|
||||
* @param uuid the player uuid
|
||||
*/
|
||||
public void surrender(UUID uuid) { surrender(Bukkit.getOfflinePlayer(uuid)); }
|
||||
|
||||
/**
|
||||
* Makes a player surrender
|
||||
* @param p the player
|
||||
*/
|
||||
public void surrender(OfflinePlayer p) {
|
||||
if (!isSurrendered(p))
|
||||
return;
|
||||
|
||||
remove(p);
|
||||
addSurrendered(p);
|
||||
}
|
||||
|
||||
/**
|
||||
* Makes a government un-surrender (Recursively un-surrenders subjects AKA nations, towns, players)
|
||||
* @param government the government
|
||||
*/
|
||||
public void unsurrender(Government government) {
|
||||
if (!isSurrendered(government))
|
||||
return;
|
||||
|
||||
if (government instanceof Nation nation) {
|
||||
removeSurrendered(nation);
|
||||
add(nation);
|
||||
} else if (government instanceof Town town) {
|
||||
removeSurrendered(town);
|
||||
add(town);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Makes a player un-surrender
|
||||
* @param p the player
|
||||
*/
|
||||
public void unsurrender(Player p) { unsurrender(p.getUniqueId()); }
|
||||
|
||||
/**
|
||||
* Makes a player un-surrender
|
||||
* @param uuid the player uuid
|
||||
*/
|
||||
public void unsurrender(UUID uuid) { unsurrender(Bukkit.getOfflinePlayer(uuid)); }
|
||||
|
||||
/**
|
||||
* Makes a player un-surrender
|
||||
* @param p the player
|
||||
*/
|
||||
public void unsurrender(OfflinePlayer p) {
|
||||
if (isSurrendered(p))
|
||||
return;
|
||||
|
||||
removeSurrendered(p);
|
||||
add(p);
|
||||
}
|
||||
|
||||
// SECTION Misc methods
|
||||
|
||||
/**
|
||||
* Check if this side is no longer able to continue fighting a war
|
||||
* @return true if there are no more nations or towns to participate in the war
|
||||
*/
|
||||
public boolean shouldSurrender() {
|
||||
return getNations().isEmpty() && getTowns().isEmpty();
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if this nation is no longer able to continue fighting a war
|
||||
* @param nation the nation
|
||||
* @return true if there are no more un-surrendered towns from the nation to participate in the war
|
||||
*/
|
||||
public boolean shouldSurrender(Nation nation) {
|
||||
final int townsQty = nation.getNumTowns();
|
||||
final int surrenderedTownsQty = nation.getTowns().stream().filter(this::isSurrendered).mapToInt(value -> 1).sum();
|
||||
return surrenderedTownsQty == townsQty;
|
||||
|
||||
}
|
||||
}
|
||||
@@ -1,266 +0,0 @@
|
||||
package com.github.alathra.alathranwars.conflict.war.side;
|
||||
|
||||
import com.github.alathra.alathranwars.conflict.IAssociatedWar;
|
||||
import com.github.alathra.alathranwars.conflict.IUnique;
|
||||
import com.github.alathra.alathranwars.conflict.war.War;
|
||||
import com.github.alathra.alathranwars.conflict.war.WarController;
|
||||
import com.github.alathra.alathranwars.enums.battle.BattleSide;
|
||||
import com.github.alathra.alathranwars.enums.battle.BattleTeam;
|
||||
import com.github.alathra.alathranwars.hook.NameColorHandler;
|
||||
import com.palmergames.bukkit.towny.object.Government;
|
||||
import com.palmergames.bukkit.towny.object.Nation;
|
||||
import com.palmergames.bukkit.towny.object.Town;
|
||||
import org.bukkit.OfflinePlayer;
|
||||
import org.jetbrains.annotations.ApiStatus;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
|
||||
public class Side extends AbstractSideTeamManager implements IUnique<Side>, IAssociatedWar {
|
||||
private static final Duration SIEGE_COOLDOWN = Duration.ofMinutes(30);
|
||||
private static final Duration RAID_COOLDOWN = Duration.ofMinutes(30);
|
||||
private final UUID warUUID;
|
||||
private final UUID uuid;
|
||||
private final BattleSide side;
|
||||
private final BattleTeam team;
|
||||
private final String name; // A town name
|
||||
|
||||
private final Town town; // The initiating town or capital of the nation
|
||||
private Instant siegeGrace = Instant.now().minus(SIEGE_COOLDOWN); // The time after which this side can be besieged
|
||||
private Instant raidGrace = Instant.now().minus(RAID_COOLDOWN); // The time after which this side can be raided
|
||||
|
||||
private int score = 0;
|
||||
|
||||
/**
|
||||
* Instantiates a existing Side.
|
||||
* @throws SideCreationException exception
|
||||
*/
|
||||
@ApiStatus.Internal
|
||||
Side(
|
||||
UUID warUUID,
|
||||
UUID uuid,
|
||||
Government government,
|
||||
BattleSide side,
|
||||
BattleTeam team,
|
||||
String name,
|
||||
Set<Nation> nations,
|
||||
Set<Town> towns,
|
||||
Set<OfflinePlayer> players,
|
||||
Set<Nation> nationsSurrendered,
|
||||
Set<Town> townsSurrendered,
|
||||
Set<OfflinePlayer> playersSurrendered,
|
||||
Instant siegeGrace,
|
||||
Instant raidGrace
|
||||
) throws SideCreationException {
|
||||
super(nations, towns, players, nationsSurrendered, townsSurrendered, playersSurrendered);
|
||||
this.warUUID = warUUID;
|
||||
this.uuid = uuid;
|
||||
this.side = side;
|
||||
this.team = team;
|
||||
this.name = name;
|
||||
this.siegeGrace = siegeGrace;
|
||||
this.raidGrace = raidGrace;
|
||||
|
||||
if (government instanceof Nation nation) {
|
||||
this.town = nation.getCapital();
|
||||
} else if (government instanceof Town town2) {
|
||||
this.town = town2;
|
||||
} else {
|
||||
throw new SideCreationException("No town or nation specified!");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Instantiates a new Side.
|
||||
* @throws SideCreationException exception
|
||||
*/
|
||||
@ApiStatus.Internal
|
||||
Side(
|
||||
UUID warUUID,
|
||||
UUID uuid,
|
||||
Government government,
|
||||
BattleSide side,
|
||||
BattleTeam team
|
||||
) throws SideCreationException {
|
||||
super();
|
||||
this.warUUID = warUUID;
|
||||
this.uuid = uuid;
|
||||
this.side = side;
|
||||
this.team = team;
|
||||
|
||||
if (government instanceof Nation nation) {
|
||||
this.town = nation.getCapital();
|
||||
add(nation);
|
||||
} else if (government instanceof Town town2) {
|
||||
this.town = town2;
|
||||
add(town2);
|
||||
} else {
|
||||
throw new SideCreationException("No town or nation specified!");
|
||||
}
|
||||
|
||||
this.name = this.town.getName();
|
||||
}
|
||||
|
||||
public BattleSide getSide() {
|
||||
return side;
|
||||
}
|
||||
|
||||
public BattleTeam getTeam() {
|
||||
return team;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
// Participant management
|
||||
|
||||
public void applyNameTags() {
|
||||
getPlayersOnlineAll().forEach(
|
||||
player -> NameColorHandler.getInstance().calculatePlayerColors(player)
|
||||
);
|
||||
}
|
||||
|
||||
// Graces
|
||||
|
||||
public Instant getSiegeGrace() {
|
||||
return siegeGrace;
|
||||
}
|
||||
|
||||
public void setSiegeGrace() {
|
||||
siegeGrace = Instant.now().plus(SIEGE_COOLDOWN);
|
||||
}
|
||||
|
||||
public boolean isSiegeGraceActive() {
|
||||
return siegeGrace.isAfter(Instant.now());
|
||||
}
|
||||
|
||||
public Duration getSiegeGraceCooldown() {
|
||||
return Duration.between(Instant.now(), siegeGrace);
|
||||
}
|
||||
|
||||
public Instant getRaidGrace() {
|
||||
return raidGrace;
|
||||
}
|
||||
|
||||
public void setRaidGrace() {
|
||||
raidGrace = Instant.now().plus(RAID_COOLDOWN);
|
||||
}
|
||||
|
||||
public boolean isRaidGraceActive() {
|
||||
return raidGrace.isAfter(Instant.now());
|
||||
}
|
||||
|
||||
public Duration getRaidGraceCooldown() {
|
||||
return Duration.between(Instant.now(), this.raidGrace);
|
||||
}
|
||||
|
||||
// Score
|
||||
|
||||
public int getScore() {
|
||||
return score;
|
||||
}
|
||||
|
||||
public void setScore(int score) {
|
||||
this.score = score;
|
||||
}
|
||||
|
||||
public void addScore(int add) {
|
||||
this.score += add;
|
||||
}
|
||||
|
||||
// Comparators & UUID
|
||||
|
||||
@Override
|
||||
public UUID getUUID() {
|
||||
return uuid;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(UUID uuid) {
|
||||
return getUUID().equals(uuid);
|
||||
}
|
||||
|
||||
public boolean equals(Side side) {
|
||||
return getUUID().equals(side.getUUID());
|
||||
}
|
||||
|
||||
public boolean equals(String sideName) {
|
||||
return this.name.equals(sideName);
|
||||
}
|
||||
|
||||
// Associated war
|
||||
|
||||
@Override
|
||||
public boolean equals(War war) {
|
||||
return this.warUUID.equals(war.getUUID());
|
||||
}
|
||||
|
||||
@Override
|
||||
public War getWar() {
|
||||
return WarController.getInstance().getWar(warUUID);
|
||||
}
|
||||
|
||||
public void processSurrenders() {
|
||||
if (shouldSurrender())
|
||||
surrenderWar();
|
||||
}
|
||||
|
||||
private void surrenderWar() {
|
||||
War war = getWar();
|
||||
if (war != null)
|
||||
getWar().defeat(this);
|
||||
}
|
||||
|
||||
public Town getTown() {
|
||||
return town;
|
||||
}
|
||||
|
||||
// Player management
|
||||
|
||||
@Override
|
||||
public void add(OfflinePlayer p) {
|
||||
super.add(p);
|
||||
|
||||
// Add player to battles
|
||||
getWar().getSieges().forEach(siege -> {
|
||||
if (siege.getAttackerSide().equals(this)) {
|
||||
siege.addPlayer(p, BattleSide.ATTACKER);
|
||||
} else if (siege.getDefenderSide().equals(this)) {
|
||||
siege.addPlayer(p, BattleSide.DEFENDER);
|
||||
}
|
||||
});
|
||||
// TODO Raids
|
||||
/*getWar().getRaids().forEach(raid -> {
|
||||
if (raid.getAttackerSide().equals(this)) {
|
||||
raid.addPlayer(p, BattleSide.ATTACKER);
|
||||
} else if (raid.getDefenderSide().equals(this)) {
|
||||
raid.addPlayer(p, BattleSide.DEFENDER);
|
||||
}
|
||||
});*/
|
||||
}
|
||||
|
||||
@Override
|
||||
public void remove(OfflinePlayer p) {
|
||||
super.remove(p);
|
||||
|
||||
// Remove player from battles
|
||||
getWar().getSieges().forEach(siege -> {
|
||||
if (siege.getAttackerSide().equals(this)) {
|
||||
siege.removePlayer(p, BattleSide.ATTACKER);
|
||||
} else if (siege.getDefenderSide().equals(this)) {
|
||||
siege.removePlayer(p, BattleSide.DEFENDER);
|
||||
}
|
||||
});
|
||||
// TODO Raids
|
||||
/*getWar().getRaids().forEach(raid -> {
|
||||
if (raid.getAttackerSide().equals(this)) {
|
||||
raid.removePlayer(p, BattleSide.ATTACKER);
|
||||
} else if (raid.getDefenderSide().equals(this)) {
|
||||
raid.removePlayer(p, BattleSide.DEFENDER);
|
||||
}
|
||||
});*/
|
||||
}
|
||||
}
|
||||
@@ -1,206 +0,0 @@
|
||||
package com.github.alathra.alathranwars.conflict.war.side;
|
||||
|
||||
import com.github.alathra.alathranwars.enums.battle.BattleSide;
|
||||
import com.github.alathra.alathranwars.enums.battle.BattleTeam;
|
||||
import com.palmergames.bukkit.towny.object.Government;
|
||||
import com.palmergames.bukkit.towny.object.Nation;
|
||||
import com.palmergames.bukkit.towny.object.Town;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.OfflinePlayer;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class SideBuilder {
|
||||
private @Nullable UUID warUUID;
|
||||
private @Nullable UUID uuid;
|
||||
private @Nullable BattleSide side;
|
||||
private @Nullable BattleTeam team;
|
||||
private @Nullable String name;
|
||||
|
||||
private @Nullable Government government;
|
||||
|
||||
private @Nullable Set<Nation> nations;
|
||||
private @Nullable Set<Town> towns;
|
||||
private @Nullable Set<OfflinePlayer> players;
|
||||
|
||||
private @Nullable Set<Nation> nationsSurrendered;
|
||||
private @Nullable Set<Town> townsSurrendered;
|
||||
private @Nullable Set<OfflinePlayer> playersSurrendered;
|
||||
|
||||
private @Nullable Instant siegeGrace;
|
||||
private @Nullable Instant raidGrace;
|
||||
|
||||
public SideBuilder() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a new side from save data
|
||||
* @return a new side
|
||||
* @throws SideCreationException exception
|
||||
*/
|
||||
public Side rebuild() throws SideCreationException {
|
||||
if (warUUID == null)
|
||||
throw new SideCreationException("Missing state warUUID required to create Side!");
|
||||
|
||||
if (uuid == null)
|
||||
throw new SideCreationException("Missing state uuid required to create Side!");
|
||||
|
||||
if (government == null)
|
||||
throw new SideCreationException("Missing state government required to create Side!");
|
||||
|
||||
if (side == null)
|
||||
throw new SideCreationException("Missing state side required to create Side!");
|
||||
|
||||
if (team == null)
|
||||
throw new SideCreationException("Missing state team required to create Side!");
|
||||
|
||||
if (name == null)
|
||||
throw new SideCreationException("Missing state name required to create Side!");
|
||||
|
||||
if (towns == null)
|
||||
throw new SideCreationException("Missing state towns required to create Side!");
|
||||
|
||||
if (nations == null)
|
||||
throw new SideCreationException("Missing state nations required to create Side!");
|
||||
|
||||
if (players == null)
|
||||
throw new SideCreationException("Missing state players required to create Side!");
|
||||
|
||||
if (townsSurrendered == null)
|
||||
throw new SideCreationException("Missing state townsSurrendered required to create Side!");
|
||||
|
||||
if (nationsSurrendered == null)
|
||||
throw new SideCreationException("Missing state nationsSurrendered required to create Side!");
|
||||
|
||||
if (playersSurrendered == null)
|
||||
throw new SideCreationException("Missing state playersSurrendered required to create Side!");
|
||||
|
||||
if (siegeGrace == null)
|
||||
throw new SideCreationException("Missing state siegeGrace required to create Side!");
|
||||
|
||||
if (raidGrace == null)
|
||||
throw new SideCreationException("Missing state raidGrace required to create Side!");
|
||||
|
||||
return new Side(
|
||||
warUUID,
|
||||
uuid,
|
||||
government,
|
||||
side,
|
||||
team,
|
||||
name,
|
||||
nations,
|
||||
towns,
|
||||
players,
|
||||
nationsSurrendered,
|
||||
townsSurrendered,
|
||||
playersSurrendered,
|
||||
siegeGrace,
|
||||
raidGrace
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a new Side
|
||||
* @return a new side
|
||||
* @throws SideCreationException exception
|
||||
*/
|
||||
public Side build() throws SideCreationException {
|
||||
if (warUUID == null)
|
||||
throw new SideCreationException("Missing state warUUID required to create Side!");
|
||||
|
||||
if (uuid == null)
|
||||
throw new SideCreationException("Missing state uuid required to create Side!");
|
||||
|
||||
if (government == null)
|
||||
throw new SideCreationException("Missing state government required to create Side!");
|
||||
|
||||
if (side == null)
|
||||
throw new SideCreationException("Missing state side required to create Side!");
|
||||
|
||||
if (team == null)
|
||||
throw new SideCreationException("Missing state team required to create Side!");
|
||||
|
||||
return new Side(
|
||||
warUUID,
|
||||
uuid,
|
||||
government,
|
||||
side,
|
||||
team
|
||||
);
|
||||
}
|
||||
|
||||
public SideBuilder setWarUUID(UUID warUUID) {
|
||||
this.warUUID = warUUID;
|
||||
return this;
|
||||
}
|
||||
|
||||
public SideBuilder setUuid(UUID uuid) {
|
||||
this.uuid = uuid;
|
||||
return this;
|
||||
}
|
||||
|
||||
public SideBuilder setSide(BattleSide side) {
|
||||
this.side = side;
|
||||
return this;
|
||||
}
|
||||
|
||||
public SideBuilder setTeam(BattleTeam team) {
|
||||
this.team = team;
|
||||
return this;
|
||||
}
|
||||
|
||||
public SideBuilder setName(String name) {
|
||||
this.name = name;
|
||||
return this;
|
||||
}
|
||||
|
||||
public SideBuilder setLeader(Government target) {
|
||||
this.government = target;
|
||||
return this;
|
||||
}
|
||||
|
||||
public SideBuilder setNations(Set<Nation> nations) {
|
||||
this.nations = nations;
|
||||
return this;
|
||||
}
|
||||
|
||||
public SideBuilder setTowns(Set<Town> towns) {
|
||||
this.towns = towns;
|
||||
return this;
|
||||
}
|
||||
|
||||
public SideBuilder setPlayers(@NotNull Set<UUID> players) {
|
||||
this.players = players.stream().map(Bukkit::getOfflinePlayer).collect(Collectors.toSet());
|
||||
return this;
|
||||
}
|
||||
|
||||
public SideBuilder setNationsSurrendered(Set<Nation> nationsSurrendered) {
|
||||
this.nationsSurrendered = nationsSurrendered;
|
||||
return this;
|
||||
}
|
||||
|
||||
public SideBuilder setTownsSurrendered(Set<Town> townsSurrendered) {
|
||||
this.townsSurrendered = townsSurrendered;
|
||||
return this;
|
||||
}
|
||||
|
||||
public SideBuilder setPlayersSurrendered(@NotNull Set<UUID> playersSurrendered) {
|
||||
this.playersSurrendered = playersSurrendered.stream().map(Bukkit::getOfflinePlayer).collect(Collectors.toSet());
|
||||
return this;
|
||||
}
|
||||
|
||||
public SideBuilder setSiegeGrace(Instant siegeGrace) {
|
||||
this.siegeGrace = siegeGrace;
|
||||
return this;
|
||||
}
|
||||
|
||||
public SideBuilder setRaidGrace(Instant raidGrace) {
|
||||
this.raidGrace = raidGrace;
|
||||
return this;
|
||||
}
|
||||
}
|
||||
-7
@@ -1,7 +0,0 @@
|
||||
package com.github.alathra.alathranwars.conflict.war.side;
|
||||
|
||||
public class SideCreationException extends Exception {
|
||||
public SideCreationException(String errorMessage) {
|
||||
super(errorMessage);
|
||||
}
|
||||
}
|
||||
@@ -1,40 +0,0 @@
|
||||
package com.github.alathra.alathranwars.data;
|
||||
|
||||
import com.github.alathra.alathranwars.AlathranWars;
|
||||
import com.palmergames.bukkit.towny.object.Town;
|
||||
import com.palmergames.bukkit.towny.object.metadata.LocationDataField;
|
||||
import com.palmergames.bukkit.towny.utils.MetaDataUtil;
|
||||
import org.bukkit.Location;
|
||||
|
||||
public class TownMetaController {
|
||||
private AlathranWars plugin;
|
||||
private static LocationDataField defendersSpawn = new LocationDataField("alathranwars_defendersSpawn");
|
||||
|
||||
TownMetaController(AlathranWars plugin) {
|
||||
this.plugin = plugin;
|
||||
}
|
||||
|
||||
public static boolean hasDefendersSpawn(Town town) {
|
||||
return town.hasMeta(defendersSpawn.getKey());
|
||||
}
|
||||
|
||||
public static Location getDefendersSpawn(Town town) {
|
||||
if (hasDefendersSpawn(town)) {
|
||||
return MetaDataUtil.getLocation(town, defendersSpawn);
|
||||
} else {
|
||||
Location location = town.getSpawnOrNull();
|
||||
|
||||
setDefendersSpawn(town, location);
|
||||
|
||||
return location;
|
||||
}
|
||||
}
|
||||
|
||||
public static void setDefendersSpawn(Town town, Location location) {
|
||||
if (hasDefendersSpawn(town)) {
|
||||
MetaDataUtil.setLocation(town, defendersSpawn, location, true);
|
||||
} else {
|
||||
town.addMetaData(new LocationDataField(defendersSpawn.getKey(), location));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,537 +0,0 @@
|
||||
package com.github.alathra.alathranwars.database;
|
||||
|
||||
import com.github.alathra.alathranwars.conflict.battle.siege.Siege;
|
||||
import com.github.alathra.alathranwars.conflict.battle.siege.SiegePhase;
|
||||
import com.github.alathra.alathranwars.conflict.war.War;
|
||||
import com.github.alathra.alathranwars.conflict.war.WarBuilder;
|
||||
import com.github.alathra.alathranwars.conflict.war.WarController;
|
||||
import com.github.alathra.alathranwars.conflict.war.WarCreationException;
|
||||
import com.github.alathra.alathranwars.conflict.war.side.Side;
|
||||
import com.github.alathra.alathranwars.conflict.war.side.SideBuilder;
|
||||
import com.github.alathra.alathranwars.conflict.war.side.SideCreationException;
|
||||
import com.github.alathra.alathranwars.enums.battle.BattleSide;
|
||||
import com.github.alathra.alathranwars.enums.battle.BattleTeam;
|
||||
import com.github.alathra.alathranwars.utility.DB;
|
||||
import com.github.alathra.alathranwars.utility.Logger;
|
||||
import com.palmergames.bukkit.towny.TownyAPI;
|
||||
import com.palmergames.bukkit.towny.object.Nation;
|
||||
import com.palmergames.bukkit.towny.object.Town;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.OfflinePlayer;
|
||||
import org.jetbrains.annotations.Contract;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import org.jooq.DSLContext;
|
||||
import org.jooq.Record;
|
||||
import org.jooq.Result;
|
||||
import org.jooq.exception.DataAccessException;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.SQLException;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneOffset;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
|
||||
import static com.github.alathra.alathranwars.database.schema.Tables.*;
|
||||
import static com.github.alathra.alathranwars.database.QueryUtil.*;
|
||||
|
||||
/**
|
||||
* A holder class for all SQL queries
|
||||
*/
|
||||
public abstract class DatabaseQueries {
|
||||
// Setters
|
||||
|
||||
public static void saveAll() {
|
||||
try (
|
||||
Connection con = DB.getConnection();
|
||||
) {
|
||||
DSLContext context = DB.getContext(con);
|
||||
|
||||
for (War war : WarController.getInstance().getWars()) {
|
||||
context
|
||||
.insertInto(LIST, LIST.UUID, LIST.NAME, LIST.LABEL, LIST.SIDE1, LIST.SIDE2, LIST.EVENT)
|
||||
.values(
|
||||
fromUUIDToBytes(war.getUUID()),
|
||||
war.getName(),
|
||||
war.getLabel(),
|
||||
fromUUIDToBytes(war.getSide1().getUUID()),
|
||||
fromUUIDToBytes(war.getSide2().getUUID()),
|
||||
war.isEventWar() ? (byte) 1 : (byte) 0
|
||||
)
|
||||
.onDuplicateKeyUpdate()
|
||||
.set(LIST.NAME, war.getName())
|
||||
.set(LIST.LABEL, war.getLabel())
|
||||
.set(LIST.SIDE1, fromUUIDToBytes(war.getSide1().getUUID()))
|
||||
.set(LIST.SIDE2, fromUUIDToBytes(war.getSide2().getUUID()))
|
||||
.execute();
|
||||
|
||||
// Save sides
|
||||
for (Side side : war.getSides()) {
|
||||
saveSide(con, side);
|
||||
}
|
||||
|
||||
// Save sieges
|
||||
for (Siege siege : war.getSieges()) {
|
||||
saveSiege(con, siege);
|
||||
}
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
Logger.get().error("SQL Query failed to save data!", e);
|
||||
}
|
||||
}
|
||||
|
||||
public static void saveSide(Connection con, Side side) {
|
||||
try {
|
||||
DSLContext context = DB.getContext(con);
|
||||
|
||||
context
|
||||
.insertInto(SIDES, SIDES.WAR, SIDES.UUID, SIDES.SIDE, SIDES.TEAM, SIDES.NAME, SIDES.TOWN, SIDES.SIEGE_GRACE, SIDES.RAID_GRACE)
|
||||
.values(
|
||||
fromUUIDToBytes(side.getWar().getUUID()),
|
||||
fromUUIDToBytes(side.getUUID()),
|
||||
side.getSide().toString(),
|
||||
side.getTeam().toString(),
|
||||
side.getName(),
|
||||
fromUUIDToBytes(side.getTown().getUUID()),
|
||||
LocalDateTime.ofInstant(side.getSiegeGrace(), ZoneOffset.UTC),
|
||||
LocalDateTime.ofInstant(side.getRaidGrace(), ZoneOffset.UTC)
|
||||
)
|
||||
.onDuplicateKeyUpdate()
|
||||
.set(SIDES.SIDE, side.getSide().toString())
|
||||
.set(SIDES.TEAM, side.getTeam().toString())
|
||||
.set(SIDES.NAME, side.getName())
|
||||
.set(SIDES.TOWN, fromUUIDToBytes(side.getTown().getUUID()))
|
||||
.set(SIDES.SIEGE_GRACE, LocalDateTime.ofInstant(side.getSiegeGrace(), ZoneOffset.UTC))
|
||||
.set(SIDES.RAID_GRACE, LocalDateTime.ofInstant(side.getRaidGrace(), ZoneOffset.UTC))
|
||||
.execute();
|
||||
|
||||
saveSideNations(con, side);
|
||||
saveSideTowns(con, side);
|
||||
saveSidePlayers(con, side);
|
||||
} catch (DataAccessException e) {
|
||||
Logger.get().error("SQL Query failed to save side!", e);
|
||||
}
|
||||
}
|
||||
|
||||
public static void saveSideNations(Connection con, Side side) {
|
||||
try {
|
||||
transaction(con, (connection, context) -> {
|
||||
context
|
||||
.deleteFrom(SIDES_NATIONS)
|
||||
.where(SIDES_NATIONS.SIDE.equal(fromUUIDToBytes(side.getUUID())))
|
||||
.execute();
|
||||
|
||||
for (Nation nation : side.getNations()) {
|
||||
context.insertInto(SIDES_NATIONS, SIDES_NATIONS.SIDE, SIDES_NATIONS.NATION, SIDES_NATIONS.SURRENDERED)
|
||||
.values(
|
||||
fromUUIDToBytes(side.getUUID()),
|
||||
fromUUIDToBytes(nation.getUUID()),
|
||||
(byte) 0
|
||||
)
|
||||
.execute();
|
||||
}
|
||||
|
||||
for (Nation nation : side.getNationsSurrendered()) {
|
||||
context.insertInto(SIDES_NATIONS, SIDES_NATIONS.SIDE, SIDES_NATIONS.NATION, SIDES_NATIONS.SURRENDERED)
|
||||
.values(
|
||||
fromUUIDToBytes(side.getUUID()),
|
||||
fromUUIDToBytes(nation.getUUID()),
|
||||
(byte) 1
|
||||
)
|
||||
.execute();
|
||||
}
|
||||
});
|
||||
} catch (SQLException | DataAccessException e) {
|
||||
Logger.get().error("SQL Query failed to save side nations!", e);
|
||||
}
|
||||
}
|
||||
|
||||
public static void saveSideTowns(Connection con, Side side) {
|
||||
try {
|
||||
transaction(con, (connection, context) -> {
|
||||
context
|
||||
.deleteFrom(SIDES_TOWNS)
|
||||
.where(SIDES_TOWNS.SIDE.equal(fromUUIDToBytes(side.getUUID())))
|
||||
.execute();
|
||||
|
||||
for (Town town : side.getTowns()) {
|
||||
context.insertInto(SIDES_TOWNS, SIDES_TOWNS.SIDE, SIDES_TOWNS.TOWN, SIDES_TOWNS.SURRENDERED)
|
||||
.values(
|
||||
fromUUIDToBytes(side.getUUID()),
|
||||
fromUUIDToBytes(town.getUUID()),
|
||||
(byte) 0
|
||||
)
|
||||
.execute();
|
||||
}
|
||||
|
||||
for (Town town : side.getTownsSurrendered()) {
|
||||
context.insertInto(SIDES_TOWNS, SIDES_TOWNS.SIDE, SIDES_TOWNS.TOWN, SIDES_TOWNS.SURRENDERED)
|
||||
.values(
|
||||
fromUUIDToBytes(side.getUUID()),
|
||||
fromUUIDToBytes(town.getUUID()),
|
||||
(byte) 1
|
||||
)
|
||||
.execute();
|
||||
}
|
||||
});
|
||||
} catch (SQLException | DataAccessException e) {
|
||||
Logger.get().error("SQL Query failed to save side towns!", e);
|
||||
}
|
||||
}
|
||||
|
||||
public static void saveSidePlayers(Connection con, Side side) {
|
||||
try {
|
||||
transaction(con, (connection, context) -> {
|
||||
context
|
||||
.deleteFrom(SIDES_PLAYERS)
|
||||
.where(SIDES_PLAYERS.SIDE.equal(fromUUIDToBytes(side.getUUID())))
|
||||
.execute();
|
||||
|
||||
for (OfflinePlayer p : side.getPlayersAll()) {
|
||||
context.insertInto(SIDES_PLAYERS, SIDES_PLAYERS.SIDE, SIDES_PLAYERS.PLAYER, SIDES_PLAYERS.SURRENDERED)
|
||||
.values(
|
||||
fromUUIDToBytes(side.getUUID()),
|
||||
fromUUIDToBytes(p.getUniqueId()),
|
||||
(byte) 0
|
||||
)
|
||||
.execute();
|
||||
}
|
||||
|
||||
for (OfflinePlayer p : side.getPlayersSurrendered()) {
|
||||
context.insertInto(SIDES_PLAYERS, SIDES_PLAYERS.SIDE, SIDES_PLAYERS.PLAYER, SIDES_PLAYERS.SURRENDERED)
|
||||
.values(
|
||||
fromUUIDToBytes(side.getUUID()),
|
||||
fromUUIDToBytes(p.getUniqueId()),
|
||||
(byte) 1
|
||||
)
|
||||
.execute();
|
||||
}
|
||||
});
|
||||
} catch (SQLException | DataAccessException e) {
|
||||
Logger.get().error("SQL Query failed to save side players!", e);
|
||||
}
|
||||
}
|
||||
|
||||
private static void saveSiege(Connection con, Siege siege) {
|
||||
try {
|
||||
DSLContext context = DB.getContext(con);
|
||||
|
||||
context.insertInto(SIEGES, SIEGES.WAR, SIEGES.UUID, SIEGES.TOWN, SIEGES.SIEGE_LEADER, SIEGES.END_TIME, SIEGES.LAST_TOUCHED, SIEGES.SIEGE_PROGRESS, SIEGES.PHASE_CURRENT, SIEGES.PHASE_PROGRESS, SIEGES.PHASE_START_TIME)
|
||||
.values(
|
||||
fromUUIDToBytes(siege.getWar().getUUID()),
|
||||
fromUUIDToBytes(siege.getUUID()),
|
||||
fromUUIDToBytes(siege.getTown().getUUID()),
|
||||
fromUUIDToBytes(siege.getSiegeLeader().getUniqueId()),
|
||||
LocalDateTime.ofInstant(siege.getEndTime(), ZoneOffset.UTC),
|
||||
LocalDateTime.ofInstant(siege.getLastTouched(), ZoneOffset.UTC),
|
||||
siege.getProgressManager().get(),
|
||||
siege.getPhaseManager().get().name(),
|
||||
siege.getPhaseManager().getProgress(),
|
||||
LocalDateTime.ofInstant(siege.getPhaseManager().getStartTime(), ZoneOffset.UTC)
|
||||
)
|
||||
.onDuplicateKeyUpdate()
|
||||
.set(SIEGES.WAR, fromUUIDToBytes(siege.getWar().getUUID()))
|
||||
.set(SIEGES.TOWN, fromUUIDToBytes(siege.getTown().getUUID()))
|
||||
.set(SIEGES.SIEGE_LEADER, fromUUIDToBytes(siege.getSiegeLeader().getUniqueId()))
|
||||
.set(SIEGES.END_TIME, LocalDateTime.ofInstant(siege.getEndTime(), ZoneOffset.UTC))
|
||||
.set(SIEGES.LAST_TOUCHED, LocalDateTime.ofInstant(siege.getLastTouched(), ZoneOffset.UTC))
|
||||
.set(SIEGES.SIEGE_PROGRESS, siege.getProgressManager().get())
|
||||
.set(SIEGES.PHASE_CURRENT, siege.getPhaseManager().get().name())
|
||||
.set(SIEGES.PHASE_PROGRESS, siege.getPhaseManager().getProgress())
|
||||
.set(SIEGES.PHASE_START_TIME, LocalDateTime.ofInstant(siege.getPhaseManager().getStartTime(), ZoneOffset.UTC))
|
||||
.execute();
|
||||
|
||||
saveSiegePlayers(con, siege);
|
||||
} catch (DataAccessException e) {
|
||||
Logger.get().error("SQL Query threw an error!", e);
|
||||
}
|
||||
}
|
||||
|
||||
public static void saveSiegePlayers(Connection con, Siege siege) {
|
||||
try {
|
||||
transaction(con, (connection, context) -> {
|
||||
context
|
||||
.deleteFrom(SIEGE_PLAYERS)
|
||||
.where(SIEGE_PLAYERS.SIEGE.equal(fromUUIDToBytes(siege.getUUID())))
|
||||
.execute();
|
||||
|
||||
for (UUID uuid : siege.getPlayers(BattleSide.ATTACKER).stream().map(OfflinePlayer::getUniqueId).toList()) {
|
||||
context.insertInto(SIEGE_PLAYERS, SIEGE_PLAYERS.SIEGE, SIEGE_PLAYERS.PLAYER, SIEGE_PLAYERS.TEAM)
|
||||
.values(
|
||||
fromUUIDToBytes(siege.getUUID()),
|
||||
fromUUIDToBytes(uuid),
|
||||
(byte) 0
|
||||
)
|
||||
.execute();
|
||||
}
|
||||
|
||||
for (UUID uuid : siege.getPlayers(BattleSide.DEFENDER).stream().map(OfflinePlayer::getUniqueId).toList()) {
|
||||
context.insertInto(SIEGE_PLAYERS, SIEGE_PLAYERS.SIEGE, SIEGE_PLAYERS.PLAYER, SIEGE_PLAYERS.TEAM)
|
||||
.values(
|
||||
fromUUIDToBytes(siege.getUUID()),
|
||||
fromUUIDToBytes(uuid),
|
||||
(byte) 1
|
||||
)
|
||||
.execute();
|
||||
}
|
||||
});
|
||||
} catch (SQLException | DataAccessException e) {
|
||||
Logger.get().error("SQL Query threw an error!", e);
|
||||
}
|
||||
}
|
||||
|
||||
// Getters
|
||||
public static @NotNull Set<War> loadAll() {
|
||||
Set<War> wars = new HashSet<>();
|
||||
|
||||
try (
|
||||
Connection con = DB.getConnection();
|
||||
) {
|
||||
DSLContext context = DB.getContext(con);
|
||||
|
||||
Result<Record> result = context.select()
|
||||
.from(LIST)
|
||||
.fetch();
|
||||
|
||||
for (Record r : result) {
|
||||
UUID uuid = fromBytesToUUID(r.get(LIST.UUID));
|
||||
String name = r.get(LIST.NAME);
|
||||
String label = r.get(LIST.LABEL);
|
||||
@Nullable Side side1 = loadSide(con, uuid, fromBytesToUUID(r.get(LIST.SIDE1)));
|
||||
@Nullable Side side2 = loadSide(con, uuid, fromBytesToUUID(r.get(LIST.SIDE2)));
|
||||
boolean event = r.get(LIST.EVENT, Boolean.class);
|
||||
|
||||
wars.add(
|
||||
new WarBuilder()
|
||||
.setUuid(uuid)
|
||||
.setName(name)
|
||||
.setLabel(label)
|
||||
.setSide1(side1)
|
||||
.setSide2(side2)
|
||||
.setSieges(new HashSet<>())
|
||||
.setRaids(new HashSet<>())
|
||||
.setEvent(event)
|
||||
.resume()
|
||||
);
|
||||
}
|
||||
|
||||
for (War war : wars) {
|
||||
@NotNull Set<Siege> sieges = loadSieges(con, war);
|
||||
war.setSieges(sieges);
|
||||
}
|
||||
} catch (SQLException | DataAccessException e) {
|
||||
Logger.get().error("SQL Query threw an error!", e);
|
||||
} catch (WarCreationException e) {
|
||||
Logger.get().error("Failed to re-create war from database!", e);
|
||||
}
|
||||
|
||||
return wars;
|
||||
}
|
||||
|
||||
@Contract("_, _, _ -> new")
|
||||
public static @Nullable Side loadSide(Connection con, UUID warUUID, UUID uuid) {
|
||||
try {
|
||||
DSLContext context = DB.getContext(con);
|
||||
|
||||
Record r = context.select()
|
||||
.from(SIDES)
|
||||
.where(SIDES.WAR.equal(fromUUIDToBytes(warUUID)))
|
||||
.and(SIDES.UUID.equal(fromUUIDToBytes(uuid)))
|
||||
.fetchOne();
|
||||
|
||||
if (r == null) return null;
|
||||
|
||||
// Side data
|
||||
BattleSide side = BattleSide.valueOf(r.get(SIDES.SIDE));
|
||||
BattleTeam team = BattleTeam.valueOf(r.get(SIDES.TEAM));
|
||||
String name = r.get(SIDES.NAME);
|
||||
@Nullable Town town = TownyAPI.getInstance().getTown(fromBytesToUUID(r.get(SIDES.TOWN)));
|
||||
Instant siegeGrace = r.get(SIDES.SIEGE_GRACE).toInstant(ZoneOffset.UTC);
|
||||
Instant raidGrace = r.get(SIDES.RAID_GRACE).toInstant(ZoneOffset.UTC);
|
||||
|
||||
// Load players
|
||||
Set<UUID> players = new HashSet<>();
|
||||
Set<UUID> playersSurrendered = new HashSet<>();
|
||||
Result<Record> resultPlayers = context.select()
|
||||
.from(SIDES_PLAYERS)
|
||||
.where(SIDES_PLAYERS.SIDE.equal(fromUUIDToBytes(uuid)))
|
||||
.fetch();
|
||||
resultPlayers.forEach(
|
||||
record -> {
|
||||
if (record.get(SIDES_PLAYERS.SURRENDERED).equals((byte) 0)) {
|
||||
players.add(fromBytesToUUID(record.get(SIDES_PLAYERS.PLAYER)));
|
||||
} else {
|
||||
playersSurrendered.add(fromBytesToUUID(record.get(SIDES_PLAYERS.PLAYER)));
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
// Load nations
|
||||
Set<Nation> nations = new HashSet<>();
|
||||
Set<Nation> nationsSurrendered = new HashSet<>();
|
||||
Result<Record> resultNations = context.select()
|
||||
.from(SIDES_NATIONS)
|
||||
.where(SIDES_NATIONS.SIDE.equal(fromUUIDToBytes(uuid)))
|
||||
.fetch();
|
||||
resultNations.forEach(
|
||||
record -> {
|
||||
final UUID identifier = fromBytesToUUID(record.get(SIDES_NATIONS.NATION));
|
||||
if (record.get(SIDES_NATIONS.SURRENDERED).equals((byte) 0)) {
|
||||
@Nullable Nation nation = TownyAPI.getInstance().getNation(identifier);
|
||||
if (nation != null)
|
||||
nations.add(nation);
|
||||
} else {
|
||||
@Nullable Nation nation = TownyAPI.getInstance().getNation(identifier);
|
||||
if (nation != null)
|
||||
nationsSurrendered.add(nation);
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
// Load towns
|
||||
Set<Town> towns = new HashSet<>();
|
||||
Set<Town> townsSurrendered = new HashSet<>();
|
||||
Result<Record> resultTowns = context.select()
|
||||
.from(SIDES_TOWNS)
|
||||
.where(SIDES_TOWNS.SIDE.equal(fromUUIDToBytes(uuid)))
|
||||
.fetch();
|
||||
resultTowns.forEach(
|
||||
record -> {
|
||||
final UUID identifier = fromBytesToUUID(record.get(SIDES_TOWNS.TOWN));
|
||||
if (record.get(SIDES_TOWNS.SURRENDERED).equals((byte) 0)) {
|
||||
@Nullable Town town2 = TownyAPI.getInstance().getTown(identifier);
|
||||
if (town2 != null)
|
||||
towns.add(town2);
|
||||
} else {
|
||||
@Nullable Town town2 = TownyAPI.getInstance().getTown(identifier);
|
||||
if (town2 != null)
|
||||
townsSurrendered.add(town2);
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
return new SideBuilder() // TODO IllegalStateException
|
||||
.setWarUUID(warUUID)
|
||||
.setUuid(uuid)
|
||||
.setLeader(town)
|
||||
.setSide(side)
|
||||
.setTeam(team)
|
||||
.setName(name)
|
||||
.setTowns(towns)
|
||||
.setNations(nations)
|
||||
.setPlayers(players)
|
||||
.setTownsSurrendered(townsSurrendered)
|
||||
.setNationsSurrendered(nationsSurrendered)
|
||||
.setPlayersSurrendered(playersSurrendered)
|
||||
.setSiegeGrace(siegeGrace)
|
||||
.setRaidGrace(raidGrace)
|
||||
.rebuild();
|
||||
} catch (SideCreationException e) {
|
||||
Logger.get().error("SQL Query threw an error!", e);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static @NotNull Set<Siege> loadSieges(Connection con, War war) {
|
||||
Set<Siege> sieges = new HashSet<>();
|
||||
|
||||
try {
|
||||
DSLContext context = DB.getContext(con);
|
||||
|
||||
Result<Record> result = context.select()
|
||||
.from(SIEGES)
|
||||
.where(SIEGES.WAR.equal(fromUUIDToBytes(war.getUUID())))
|
||||
.fetch();
|
||||
|
||||
for (Record r : result) {
|
||||
UUID uuid = fromBytesToUUID(r.get(SIEGES.UUID));
|
||||
@Nullable Town town = TownyAPI.getInstance().getTown(fromBytesToUUID(r.get(SIEGES.TOWN)));
|
||||
OfflinePlayer siegeLeader = Bukkit.getOfflinePlayer(fromBytesToUUID(r.get(SIEGES.SIEGE_LEADER)));
|
||||
Instant endTime = r.get(SIEGES.END_TIME).toInstant(ZoneOffset.UTC);
|
||||
Instant lastTouched = r.get(SIEGES.LAST_TOUCHED).toInstant(ZoneOffset.UTC);
|
||||
int siegeProgress = r.get(SIEGES.SIEGE_PROGRESS);
|
||||
Set<UUID> attackersIncludingOffline = new HashSet<>();
|
||||
Set<UUID> defendersIncludingOffline = new HashSet<>();
|
||||
|
||||
Result<Record> resultPlayers = context.select()
|
||||
.from(SIEGE_PLAYERS)
|
||||
.where(SIEGE_PLAYERS.SIEGE.equal(fromUUIDToBytes(uuid)))
|
||||
.fetch();
|
||||
resultPlayers.forEach(
|
||||
record -> {
|
||||
if (record.get(SIEGE_PLAYERS.TEAM).equals((byte) 0)) {
|
||||
attackersIncludingOffline.add(fromBytesToUUID(record.get(SIEGE_PLAYERS.PLAYER)));
|
||||
} else {
|
||||
defendersIncludingOffline.add(fromBytesToUUID(record.get(SIEGE_PLAYERS.PLAYER)));
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
SiegePhase phase;
|
||||
try {
|
||||
phase = SiegePhase.valueOf(r.get(SIEGES.PHASE_CURRENT));
|
||||
} catch (IllegalArgumentException e) {
|
||||
phase = SiegePhase.SIEGE;
|
||||
}
|
||||
int phaseProgress = r.get(SIEGES.PHASE_PROGRESS);
|
||||
Instant phaseStartTime = r.get(SIEGES.PHASE_START_TIME).toInstant(ZoneOffset.UTC);
|
||||
|
||||
|
||||
|
||||
sieges.add(new Siege(
|
||||
war,
|
||||
uuid,
|
||||
town,
|
||||
siegeLeader,
|
||||
endTime,
|
||||
lastTouched,
|
||||
siegeProgress,
|
||||
attackersIncludingOffline,
|
||||
defendersIncludingOffline,
|
||||
phase,
|
||||
phaseProgress,
|
||||
phaseStartTime
|
||||
));
|
||||
}
|
||||
} catch (DataAccessException e) {
|
||||
Logger.get().error("SQL Query threw an error!", e);
|
||||
}
|
||||
|
||||
return sieges;
|
||||
}
|
||||
|
||||
// Deleters
|
||||
|
||||
public static void deleteWar(War war) {
|
||||
try (
|
||||
Connection con = DB.getConnection();
|
||||
) {
|
||||
DSLContext context = DB.getContext(con);
|
||||
|
||||
context
|
||||
.deleteFrom(LIST)
|
||||
.where(LIST.UUID.equal(fromUUIDToBytes(war.getUUID())))
|
||||
.execute();
|
||||
} catch (SQLException | DataAccessException e) {
|
||||
Logger.get().error("SQL Query threw an error!", e);
|
||||
}
|
||||
}
|
||||
|
||||
public static void deleteSiege(Siege siege) {
|
||||
try (
|
||||
Connection con = DB.getConnection();
|
||||
) {
|
||||
DSLContext context = DB.getContext(con);
|
||||
|
||||
context
|
||||
.deleteFrom(SIEGES)
|
||||
.where(SIEGES.UUID.equal(fromUUIDToBytes(siege.getUUID())))
|
||||
.execute();
|
||||
} catch (SQLException | DataAccessException e) {
|
||||
Logger.get().error("SQL Query threw an error!", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,293 +0,0 @@
|
||||
package com.github.alathra.alathranwars.database;
|
||||
|
||||
import com.mysql.cj.jdbc.MysqlDataSource;
|
||||
import com.mysql.jdbc.Driver;
|
||||
import org.h2.jdbcx.JdbcDataSource;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import org.jooq.SQLDialect;
|
||||
import org.mariadb.jdbc.MariaDbDataSource;
|
||||
import org.sqlite.JDBC;
|
||||
import org.sqlite.SQLiteDataSource;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Enum containing information for handling different Database types.
|
||||
*/
|
||||
public enum DatabaseType {
|
||||
/**
|
||||
* SQLite database type.
|
||||
*/
|
||||
H2("H2", org.h2.Driver.class.getName(), JdbcDataSource.class.getName(), "h2", ';', ';'),
|
||||
SQLITE("SQLite", JDBC.class.getName(), SQLiteDataSource.class.getName(), "sqlite", '?', '&'),
|
||||
/**
|
||||
* MySQL database type.
|
||||
*/
|
||||
MYSQL("MySQL", Driver.class.getName(), MysqlDataSource.class.getName(), "mysql", '?', '&'),
|
||||
/**
|
||||
* MariaDB database type.
|
||||
*/
|
||||
MARIADB("MariaDB", org.mariadb.jdbc.Driver.class.getName(), MariaDbDataSource.class.getName(), "mariadb", '?', '&'),
|
||||
;
|
||||
|
||||
private final String driverName;
|
||||
private final String driverClassName;
|
||||
private final String dataSourceClassName;
|
||||
private final String jdbcPrefix;
|
||||
private final char jdbcPropertyPrefix;
|
||||
private final char jdbcPropertySeparator;
|
||||
|
||||
DatabaseType(String driverName, String driverClassName, String dataSourceClassName, String jdbcPrefix, char jdbcPropertyPrefix, char jdbcPropertySeparator) {
|
||||
this.driverName = driverName;
|
||||
this.driverClassName = driverClassName;
|
||||
this.dataSourceClassName = dataSourceClassName;
|
||||
this.jdbcPrefix = jdbcPrefix;
|
||||
this.jdbcPropertyPrefix = jdbcPropertyPrefix;
|
||||
this.jdbcPropertySeparator = jdbcPropertySeparator;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets driver name.
|
||||
*
|
||||
* @return the driver name
|
||||
*/
|
||||
public String getDriverName() {
|
||||
return driverName;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets driver class name.
|
||||
*
|
||||
* @return the driver class name
|
||||
*/
|
||||
public String getDriverClassName() {
|
||||
return driverClassName;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets data source class name.
|
||||
*
|
||||
* @return the data source class name
|
||||
*/
|
||||
public String getDataSourceClassName() {
|
||||
return dataSourceClassName;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the jdbc prefix.
|
||||
*
|
||||
* @return the jdbc prefix like <code>mysql</code> or <code>mariadb</code>
|
||||
*/
|
||||
public String getJdbcPrefix() {
|
||||
return jdbcPrefix;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the jdbc property prefix.
|
||||
*
|
||||
* @return the jdbc property prefix like <code>{@literal ;}</code> or <code>{@literal ?}</code>
|
||||
*/
|
||||
public char getJdbcPropertyPrefix() {
|
||||
return jdbcPropertyPrefix;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the jdbc property separator.
|
||||
*
|
||||
* @return the jdbc property separator like <code>{@literal ;}</code> or <code>{@literal &}</code>
|
||||
*/
|
||||
public char getJdbcPropertySeparator() {
|
||||
return jdbcPropertySeparator;
|
||||
}
|
||||
|
||||
/**
|
||||
* Format a map of connection properties into a valid jdbc connection properties string.
|
||||
*
|
||||
* @param properties the properties
|
||||
* @return the string
|
||||
*/
|
||||
public String formatJdbcConnectionProperties(Map<String, Object> properties) {
|
||||
if (properties.isEmpty()) return "";
|
||||
|
||||
List<String> connectionProperties = properties.entrySet().stream()
|
||||
.map(map -> "%s=%s".formatted(map.getKey(), map.getValue()))
|
||||
.toList();
|
||||
|
||||
return String.join(Character.toString(getJdbcPropertySeparator()), connectionProperties);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Gets database type from jdbc prefix.
|
||||
*
|
||||
* @param prefix the prefix
|
||||
* @return the database type or null
|
||||
*/
|
||||
@Nullable
|
||||
public static DatabaseType getDatabaseTypeFromJdbcPrefix(String prefix) {
|
||||
for (DatabaseType type : DatabaseType.values()) {
|
||||
if (type.equals(prefix.toLowerCase())) {
|
||||
return type;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return getDriverName();
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if this DatabaseType is equal to another.
|
||||
*
|
||||
* @param DatabaseType the database type
|
||||
* @return boolean
|
||||
*/
|
||||
public boolean equals(DatabaseType DatabaseType) {
|
||||
return this.equals(DatabaseType.getDriverName());
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if this DatabaseType is equal to another.
|
||||
*
|
||||
* @param databaseTypeName the database type name
|
||||
* @return boolean
|
||||
*/
|
||||
public boolean equals(String databaseTypeName) {
|
||||
return this.getDriverName().equalsIgnoreCase(databaseTypeName);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets sql dialect for this DatabaseType.
|
||||
*
|
||||
* @return the sql dialect
|
||||
*/
|
||||
public SQLDialect getSQLDialect() {
|
||||
return switch (this) {
|
||||
case H2 -> SQLDialect.H2;
|
||||
case SQLITE -> SQLDialect.SQLITE;
|
||||
case MYSQL -> SQLDialect.MYSQL;
|
||||
case MARIADB -> SQLDialect.MARIADB;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets table defaults for this DatabaseType.
|
||||
*
|
||||
* @return the table defaults
|
||||
*/
|
||||
public String getTableDefaults() {
|
||||
return switch (this) {
|
||||
case H2, SQLITE -> "";
|
||||
case MARIADB, MYSQL -> " CHARACTER SET utf8mb4 COLLATE utf8mb4_bin";
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets connection properties for this DatabaseType.
|
||||
*
|
||||
* @return the connection properties
|
||||
*/
|
||||
public String getDefaultConnectionProperties() {
|
||||
return getJdbcPropertyPrefix() + switch (this) {
|
||||
case H2 -> DatabaseType.H2.formatJdbcConnectionProperties(
|
||||
Map.of(
|
||||
"AUTO_SERVER", "TRUE",
|
||||
"MODE", "MYSQL", // MySQL support mode
|
||||
"CASE_INSENSITIVE_IDENTIFIERS", "TRUE",
|
||||
"IGNORECASE", "TRUE"
|
||||
)
|
||||
);
|
||||
case SQLITE -> "";
|
||||
case MYSQL -> DatabaseType.MYSQL.formatJdbcConnectionProperties(
|
||||
Map.of(
|
||||
// Base settings
|
||||
"useUnicode", true,
|
||||
"characterEncoding", "UTF-8",
|
||||
|
||||
// Performance improvements
|
||||
"defaultFetchSize", 1000,
|
||||
|
||||
// Help debug in case of deadlock
|
||||
"includeInnodbStatusInDeadlockExceptions", true,
|
||||
"includeThreadDumpInDeadlockExceptions", true,
|
||||
|
||||
// https://github.com/brettwooldridge/HikariCP/wiki/Rapid-Recovery#mysql
|
||||
"socketTimeout", 14000L,
|
||||
// Needed for use with connection init-SQL (hikariConf.setConnectionInitSql)
|
||||
"allowMultiQueries", true,
|
||||
// Help debug in case of exceptions
|
||||
"dumpQueriesOnException", true
|
||||
)
|
||||
);
|
||||
case MARIADB -> DatabaseType.MARIADB.formatJdbcConnectionProperties(
|
||||
Map.of(
|
||||
// Base settings
|
||||
"useUnicode", true,
|
||||
"characterEncoding", "UTF-8",
|
||||
|
||||
// Performance improvements
|
||||
"defaultFetchSize", 1000,
|
||||
|
||||
// Help debug in case of deadlock
|
||||
"includeInnodbStatusInDeadlockExceptions", true,
|
||||
"includeThreadDumpInDeadlockExceptions", true,
|
||||
|
||||
// https://github.com/brettwooldridge/HikariCP/wiki/Rapid-Recovery#mysql
|
||||
"socketTimeout", 14000L,
|
||||
// Needed for use with connection init-SQL (hikariConf.setConnectionInitSql)
|
||||
"allowMultiQueries", true,
|
||||
// Help debug in case of exceptions
|
||||
"dumpQueriesOnException", true
|
||||
)
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets connection init sql for this DatabaseType.
|
||||
*
|
||||
* @return the connection init sql
|
||||
*/
|
||||
public String getConnectionInitSql() {
|
||||
return switch (this) {
|
||||
case SQLITE, H2 -> "";
|
||||
case MYSQL -> "SET NAMES utf8mb4 COLLATE utf8mb4_bin; " + setSqlModes(
|
||||
// MySQL defaults
|
||||
"STRICT_TRANS_TABLES",
|
||||
"ERROR_FOR_DIVISION_BY_ZERO",
|
||||
"NO_ENGINE_SUBSTITUTION",
|
||||
// ANSI SQL Compliance
|
||||
"ANSI",
|
||||
"NO_BACKSLASH_ESCAPES",
|
||||
"NO_ZERO_IN_DATE",
|
||||
"NO_ZERO_DATE");
|
||||
case MARIADB -> "SET NAMES utf8mb4 COLLATE utf8mb4_bin; " + setSqlModes(
|
||||
// MariaDB defaults
|
||||
"STRICT_TRANS_TABLES",
|
||||
"ERROR_FOR_DIVISION_BY_ZERO",
|
||||
"NO_AUTO_CREATE_USER",
|
||||
"NO_ENGINE_SUBSTITUTION",
|
||||
// ANSI SQL Compliance
|
||||
"ANSI",
|
||||
"NO_BACKSLASH_ESCAPES",
|
||||
"SIMULTANEOUS_ASSIGNMENT", // MDEV-13417
|
||||
"NO_ZERO_IN_DATE",
|
||||
"NO_ZERO_DATE");
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates a concatenated SQL query from the specified parameters.
|
||||
*
|
||||
* @param sqlModes database parameters
|
||||
* @return string
|
||||
*/
|
||||
private static String setSqlModes(String... sqlModes) {
|
||||
final String modes = String.join(",", sqlModes);
|
||||
return "SET @@SQL_MODE = CONCAT(@@SQL_MODE, '," + modes + "')";
|
||||
}
|
||||
}
|
||||
@@ -1,75 +0,0 @@
|
||||
package com.github.alathra.alathranwars.database;
|
||||
|
||||
import com.github.alathra.alathranwars.utility.DB;
|
||||
import org.jooq.DSLContext;
|
||||
import org.jooq.exception.DataAccessException;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
import java.sql.Connection;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Savepoint;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* Convenience class containing utility methods for querying databases.
|
||||
*/
|
||||
public abstract class QueryUtil {
|
||||
/**
|
||||
* Used in {@link #transaction(Connection, LambdaInterface)}.
|
||||
*/
|
||||
public interface LambdaInterface {
|
||||
void execute(Connection connection, DSLContext dslContext) throws SQLException, DataAccessException;
|
||||
}
|
||||
|
||||
/**
|
||||
* A quick wrapper for creating a transaction. The changes executed in the lambda context ar rolled back if any error occurs.
|
||||
* @param con A SQL connection
|
||||
* @param lambda A lambda method which defines what code to execute
|
||||
* @throws SQLException Exception
|
||||
* @throws DataAccessException Exception
|
||||
*/
|
||||
public static void transaction(Connection con, LambdaInterface lambda) throws SQLException, DataAccessException {
|
||||
DSLContext context = DB.getContext(con);
|
||||
|
||||
final Savepoint savePoint = con.setSavepoint();
|
||||
final boolean autoCommit = con.getAutoCommit();
|
||||
|
||||
try {
|
||||
con.setAutoCommit(false);
|
||||
|
||||
lambda.execute(con, context);
|
||||
|
||||
con.commit();
|
||||
} catch (SQLException | DataAccessException e) {
|
||||
con.rollback(savePoint);
|
||||
} finally {
|
||||
con.setAutoCommit(autoCommit);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert uuid to an array of bytes.
|
||||
*
|
||||
* @param uuid the uuid
|
||||
* @return the byte array
|
||||
*/
|
||||
public static byte[] fromUUIDToBytes(UUID uuid) {
|
||||
ByteBuffer bb = ByteBuffer.wrap(new byte[16]);
|
||||
bb.putLong(uuid.getMostSignificantBits());
|
||||
bb.putLong(uuid.getLeastSignificantBits());
|
||||
return bb.array();
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert byte array to uuid.
|
||||
*
|
||||
* @param bytes the byte array
|
||||
* @return the uuid
|
||||
*/
|
||||
public static UUID fromBytesToUUID(byte[] bytes) {
|
||||
ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
|
||||
long high = byteBuffer.getLong();
|
||||
long low = byteBuffer.getLong();
|
||||
return new UUID(high, low);
|
||||
}
|
||||
}
|
||||
@@ -1,282 +0,0 @@
|
||||
package com.github.alathra.alathranwars.database.config;
|
||||
|
||||
import com.github.alathra.alathranwars.database.DatabaseType;
|
||||
import com.github.milkdrinkers.crate.Config;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import org.jetbrains.annotations.TestOnly;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* The type Database config.
|
||||
*/
|
||||
public class DatabaseConfig {
|
||||
// Essential details
|
||||
private final DatabaseType databaseType;
|
||||
private String tablePrefix;
|
||||
|
||||
// Connection details
|
||||
private final @Nullable Path path;
|
||||
private final String host;
|
||||
private final int port;
|
||||
private final String database;
|
||||
private final String username;
|
||||
private final String password;
|
||||
|
||||
private final boolean repair;
|
||||
|
||||
// Pool options
|
||||
private final int maxPoolSize;
|
||||
private final int minIdle;
|
||||
private final long maxLifeTime;
|
||||
private final long keepAliveTime;
|
||||
private final long connectionTimeout;
|
||||
|
||||
// JDBC properties
|
||||
private final Map<String, Object> connectionProperties;
|
||||
|
||||
/**
|
||||
* Instantiates a new Database config.
|
||||
*
|
||||
* @param databaseType the database type
|
||||
* @param tablePrefix the table prefix
|
||||
* @param path the path
|
||||
* @param host the host
|
||||
* @param port the port
|
||||
* @param database the database
|
||||
* @param username the username
|
||||
* @param password the password
|
||||
* @param repair the repair
|
||||
* @param maxPoolSize the max pool size
|
||||
* @param minIdle the min idle
|
||||
* @param maxLifeTime the max life time
|
||||
* @param keepAliveTime the keep alive time
|
||||
* @param connectionTimeout the connection timeout
|
||||
* @param connectionProperties the connection properties
|
||||
*/
|
||||
DatabaseConfig(
|
||||
DatabaseType databaseType,
|
||||
String tablePrefix,
|
||||
@Nullable Path path,
|
||||
String host,
|
||||
int port,
|
||||
String database,
|
||||
String username,
|
||||
String password,
|
||||
boolean repair,
|
||||
int maxPoolSize,
|
||||
int minIdle,
|
||||
long maxLifeTime,
|
||||
long keepAliveTime,
|
||||
long connectionTimeout,
|
||||
Map<String, Object> connectionProperties
|
||||
) {
|
||||
this.databaseType = databaseType;
|
||||
this.tablePrefix = tablePrefix;
|
||||
this.path = path;
|
||||
this.host = host;
|
||||
this.port = port;
|
||||
this.database = database;
|
||||
this.username = username;
|
||||
this.password = password;
|
||||
this.repair = repair;
|
||||
this.maxPoolSize = maxPoolSize;
|
||||
this.minIdle = minIdle;
|
||||
this.maxLifeTime = maxLifeTime;
|
||||
this.keepAliveTime = keepAliveTime;
|
||||
this.connectionTimeout = connectionTimeout;
|
||||
this.connectionProperties = connectionProperties;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets database type.
|
||||
*
|
||||
* @return the database type
|
||||
*/
|
||||
public DatabaseType getDatabaseType() {
|
||||
return databaseType;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets path.
|
||||
*
|
||||
* @return the path
|
||||
*/
|
||||
public Optional<Path> getPath() {
|
||||
return Optional.ofNullable(path);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets table prefix.
|
||||
*
|
||||
* @param tablePrefix the table prefix
|
||||
*/
|
||||
@TestOnly
|
||||
public void setTablePrefix(String tablePrefix) {
|
||||
this.tablePrefix = tablePrefix;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets table prefix.
|
||||
*
|
||||
* @return the table prefix
|
||||
*/
|
||||
public String getTablePrefix() {
|
||||
return tablePrefix;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets host.
|
||||
*
|
||||
* @return the host
|
||||
*/
|
||||
public String getHost() {
|
||||
return host;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets port.
|
||||
*
|
||||
* @return the port
|
||||
*/
|
||||
public int getPort() {
|
||||
return port;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets database.
|
||||
*
|
||||
* @return the database
|
||||
*/
|
||||
public String getDatabase() {
|
||||
return database;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets username.
|
||||
*
|
||||
* @return the username
|
||||
*/
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets password.
|
||||
*
|
||||
* @return the password
|
||||
*/
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
/**
|
||||
* Is repair boolean.
|
||||
*
|
||||
* @return the boolean
|
||||
*/
|
||||
public boolean isRepair() {
|
||||
return repair;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets max pool size.
|
||||
*
|
||||
* @return the max pool size
|
||||
*/
|
||||
public int getMaxPoolSize() {
|
||||
return maxPoolSize;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets min idle.
|
||||
*
|
||||
* @return the min idle
|
||||
*/
|
||||
public int getMinIdle() {
|
||||
return minIdle;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets max life time.
|
||||
*
|
||||
* @return the max life time
|
||||
*/
|
||||
public long getMaxLifeTime() {
|
||||
return maxLifeTime;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets keep alive time.
|
||||
*
|
||||
* @return the keep alive time
|
||||
*/
|
||||
public long getKeepAliveTime() {
|
||||
return keepAliveTime;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets connection timeout.
|
||||
*
|
||||
* @return the connection timeout
|
||||
*/
|
||||
public long getConnectionTimeout() {
|
||||
return connectionTimeout;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets connection properties.
|
||||
*
|
||||
* @return the connection properties
|
||||
*/
|
||||
public String getConnectionProperties() {
|
||||
return getDatabaseType().formatJdbcConnectionProperties(connectionProperties).isEmpty() ? "" : getDatabaseType().getJdbcPropertySeparator() + getDatabaseType().formatJdbcConnectionProperties(connectionProperties);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets database config from file.
|
||||
*
|
||||
* @param cfg the cfg
|
||||
* @return the database config from file
|
||||
*/
|
||||
public static DatabaseConfig getDatabaseConfigFromFile(Config cfg) {
|
||||
String databaseType = cfg.getString("database.type");
|
||||
String tablePrefix = cfg.getString("database.table-prefix");
|
||||
|
||||
String host = cfg.getString("database.host");
|
||||
Integer port = cfg.getInt("database.port");
|
||||
String database = cfg.getString("database.database");
|
||||
String username = cfg.getString("database.username");
|
||||
String password = cfg.getString("database.password");
|
||||
|
||||
boolean repair = cfg.getBoolean("database.advanced.repair");
|
||||
|
||||
Integer maxPoolSize = cfg.getInt("database.advanced.connection-pool.max-pool-size");
|
||||
Integer minIdle = cfg.getInt("database.advanced.connection-pool.min-idle");
|
||||
Long maxLifeTime = cfg.getLong("database.advanced.connection-pool.max-lifetime");
|
||||
Long keepAliveTime = cfg.getLong("database.advanced.connection-pool.keepalive-time");
|
||||
Long connectionTimeout = cfg.getLong("database.advanced.connection-pool.connection-timeout");
|
||||
|
||||
Map<String, Object> connectionProperties = cfg.getMapParameterized("database.advanced.connection-properties");
|
||||
|
||||
return new DatabaseConfigBuilder()
|
||||
.withDatabaseType(databaseType)
|
||||
.withTablePrefix(tablePrefix)
|
||||
.withPath(Path.of(cfg.getFilePath()).getParent())
|
||||
.withHost(host)
|
||||
.withPort(port)
|
||||
.withDatabase(database)
|
||||
.withUsername(username)
|
||||
.withPassword(password)
|
||||
.withRepair(repair)
|
||||
.withMaxPoolSize(maxPoolSize)
|
||||
.withMinIdle(minIdle)
|
||||
.withMaxLifeTime(maxLifeTime)
|
||||
.withKeepAliveTime(keepAliveTime)
|
||||
.withConnectionTimeout(connectionTimeout)
|
||||
.withConnectionProperties(connectionProperties)
|
||||
.build();
|
||||
}
|
||||
}
|
||||
-264
@@ -1,264 +0,0 @@
|
||||
package com.github.alathra.alathranwars.database.config;
|
||||
|
||||
import com.github.alathra.alathranwars.database.DatabaseType;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* The type Database config builder.
|
||||
*/
|
||||
public class DatabaseConfigBuilder {
|
||||
private @Nullable DatabaseType databaseType;
|
||||
private @Nullable String tablePrefix;
|
||||
|
||||
private @Nullable Path path;
|
||||
private @Nullable String host;
|
||||
private @Nullable Integer port;
|
||||
private @Nullable String database;
|
||||
private @Nullable String username;
|
||||
private @Nullable String password;
|
||||
|
||||
private @Nullable Boolean repair;
|
||||
|
||||
private @Nullable Integer maxPoolSize;
|
||||
private @Nullable Integer minIdle;
|
||||
private @Nullable Long maxLifeTime;
|
||||
private @Nullable Long keepAliveTime;
|
||||
private @Nullable Long connectionTimeout;
|
||||
|
||||
private @Nullable Map<String, Object> connectionProperties;
|
||||
|
||||
/**
|
||||
* With database type database config builder.
|
||||
*
|
||||
* @param vendorPrefix the vendor prefix
|
||||
* @return the database config builder
|
||||
*/
|
||||
public DatabaseConfigBuilder withDatabaseType(String vendorPrefix) {
|
||||
this.databaseType = DatabaseType.getDatabaseTypeFromJdbcPrefix(vendorPrefix.toLowerCase());
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* With table prefix database config builder.
|
||||
*
|
||||
* @param tablePrefix the table prefix
|
||||
* @return the database config builder
|
||||
*/
|
||||
public DatabaseConfigBuilder withTablePrefix(String tablePrefix) {
|
||||
this.tablePrefix = tablePrefix;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* With path database config builder.
|
||||
*
|
||||
* @param path the path
|
||||
* @return the database config builder
|
||||
*/
|
||||
public DatabaseConfigBuilder withPath(Path path) {
|
||||
this.path = path;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* With host database config builder.
|
||||
*
|
||||
* @param host the host
|
||||
* @return the database config builder
|
||||
*/
|
||||
public DatabaseConfigBuilder withHost(String host) {
|
||||
this.host = host;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* With port database config builder.
|
||||
*
|
||||
* @param port the port
|
||||
* @return the database config builder
|
||||
*/
|
||||
public DatabaseConfigBuilder withPort(Integer port) {
|
||||
this.port = port;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* With database database config builder.
|
||||
*
|
||||
* @param database the database
|
||||
* @return the database config builder
|
||||
*/
|
||||
public DatabaseConfigBuilder withDatabase(String database) {
|
||||
this.database = database;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* With username database config builder.
|
||||
*
|
||||
* @param username the username
|
||||
* @return the database config builder
|
||||
*/
|
||||
public DatabaseConfigBuilder withUsername(String username) {
|
||||
this.username = username;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* With password database config builder.
|
||||
*
|
||||
* @param password the password
|
||||
* @return the database config builder
|
||||
*/
|
||||
public DatabaseConfigBuilder withPassword(String password) {
|
||||
this.password = password;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* With repair database config builder.
|
||||
*
|
||||
* @param repair the repair
|
||||
* @return the database config builder
|
||||
*/
|
||||
public DatabaseConfigBuilder withRepair(boolean repair) {
|
||||
this.repair = repair;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* With max pool size database config builder.
|
||||
*
|
||||
* @param maxPoolSize the max pool size
|
||||
* @return the database config builder
|
||||
*/
|
||||
public DatabaseConfigBuilder withMaxPoolSize(Integer maxPoolSize) {
|
||||
this.maxPoolSize = maxPoolSize;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* With min idle database config builder.
|
||||
*
|
||||
* @param minIdle the min idle
|
||||
* @return the database config builder
|
||||
*/
|
||||
public DatabaseConfigBuilder withMinIdle(Integer minIdle) {
|
||||
this.minIdle = minIdle;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* With max life time database config builder.
|
||||
*
|
||||
* @param maxLifeTime the max life time
|
||||
* @return the database config builder
|
||||
*/
|
||||
public DatabaseConfigBuilder withMaxLifeTime(Long maxLifeTime) {
|
||||
this.maxLifeTime = maxLifeTime;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* With keep alive time database config builder.
|
||||
*
|
||||
* @param keepAliveTime the keep alive time
|
||||
* @return the database config builder
|
||||
*/
|
||||
public DatabaseConfigBuilder withKeepAliveTime(Long keepAliveTime) {
|
||||
this.keepAliveTime = keepAliveTime;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* With connection timeout database config builder.
|
||||
*
|
||||
* @param connectionTimeout the connection timeout
|
||||
* @return the database config builder
|
||||
*/
|
||||
public DatabaseConfigBuilder withConnectionTimeout(Long connectionTimeout) {
|
||||
this.connectionTimeout = connectionTimeout;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* With connection properties database config builder.
|
||||
*
|
||||
* @param connectionProperties the connection properties
|
||||
* @return the database config builder
|
||||
*/
|
||||
public DatabaseConfigBuilder withConnectionProperties(Map<String, Object> connectionProperties) {
|
||||
this.connectionProperties = connectionProperties;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build database config.
|
||||
*
|
||||
* @return the database config
|
||||
*/
|
||||
public DatabaseConfig build() {
|
||||
if (databaseType == null)
|
||||
databaseType = DatabaseType.SQLITE;
|
||||
|
||||
if (tablePrefix == null)
|
||||
tablePrefix = "";
|
||||
|
||||
if (host == null)
|
||||
host = "localhost";
|
||||
|
||||
if (port == null)
|
||||
port = 3306;
|
||||
|
||||
if (database == null)
|
||||
database = "database_name";
|
||||
|
||||
if (username == null)
|
||||
username = "root";
|
||||
|
||||
if (password == null)
|
||||
password = "";
|
||||
|
||||
if (repair == null)
|
||||
repair = false;
|
||||
|
||||
if (maxPoolSize == null)
|
||||
maxPoolSize = 10;
|
||||
|
||||
if (minIdle == null)
|
||||
minIdle = 10;
|
||||
|
||||
if (maxLifeTime == null)
|
||||
maxLifeTime = 180_000L;
|
||||
|
||||
if (keepAliveTime == null)
|
||||
keepAliveTime = 60_000L;
|
||||
|
||||
if (connectionTimeout == null)
|
||||
connectionTimeout = 20_000L;
|
||||
|
||||
if (connectionProperties == null) {
|
||||
connectionProperties = new HashMap<>();
|
||||
|
||||
if (databaseType.equals(DatabaseType.MYSQL) || databaseType.equals(DatabaseType.MARIADB)) {
|
||||
connectionProperties.putIfAbsent("useSSL", "false");
|
||||
connectionProperties.putIfAbsent("cachePrepStmts", true);
|
||||
connectionProperties.putIfAbsent("prepStmtCacheSize", 250);
|
||||
connectionProperties.putIfAbsent("prepStmtCacheSqlLimit", 2048L);
|
||||
connectionProperties.putIfAbsent("useServerPrepStmts", true);
|
||||
connectionProperties.putIfAbsent("useLocalSessionState", true);
|
||||
connectionProperties.putIfAbsent("rewriteBatchedStatements", true);
|
||||
connectionProperties.putIfAbsent("cacheResultSetMetadata", true);
|
||||
connectionProperties.putIfAbsent("cacheServerConfiguration", true);
|
||||
connectionProperties.putIfAbsent("elideSetAutoCommits", true);
|
||||
connectionProperties.putIfAbsent("maintainTimeStats", false);
|
||||
}
|
||||
}
|
||||
|
||||
return new DatabaseConfig(databaseType, tablePrefix, path, host, port, database, username, password, repair, maxPoolSize, minIdle, maxLifeTime, keepAliveTime, connectionTimeout, connectionProperties);
|
||||
}
|
||||
}
|
||||
-34
@@ -1,34 +0,0 @@
|
||||
package com.github.alathra.alathranwars.database.exception;
|
||||
|
||||
/**
|
||||
* Database initialization exception is thrown during database initialization.
|
||||
*/
|
||||
public class DatabaseInitializationException extends RuntimeException {
|
||||
/**
|
||||
* Instantiates a new Database initialization exception.
|
||||
*
|
||||
* @param t the throwable
|
||||
*/
|
||||
public DatabaseInitializationException(Throwable t) {
|
||||
super(t);
|
||||
}
|
||||
|
||||
/**
|
||||
* Instantiates a new Database initialization exception.
|
||||
*
|
||||
* @param s the message
|
||||
* @param t the throwable
|
||||
*/
|
||||
public DatabaseInitializationException(String s, Throwable t) {
|
||||
super(s, t);
|
||||
}
|
||||
|
||||
/**
|
||||
* Instantiates a new Database initialization exception.
|
||||
*
|
||||
* @param s the message
|
||||
*/
|
||||
public DatabaseInitializationException(String s) {
|
||||
super(s);
|
||||
}
|
||||
}
|
||||
-15
@@ -1,15 +0,0 @@
|
||||
package com.github.alathra.alathranwars.database.exception;
|
||||
|
||||
/**
|
||||
* Database migration exception is thrown whenever a Flyway migration fails.
|
||||
*/
|
||||
public class DatabaseMigrationException extends Exception {
|
||||
/**
|
||||
* Instantiates a new Database migration exception.
|
||||
*
|
||||
* @param t the throwable
|
||||
*/
|
||||
public DatabaseMigrationException(Throwable t) {
|
||||
super(t);
|
||||
}
|
||||
}
|
||||
@@ -1,249 +0,0 @@
|
||||
package com.github.alathra.alathranwars.database.handler;
|
||||
|
||||
import com.zaxxer.hikari.HikariDataSource;
|
||||
import com.github.alathra.alathranwars.Reloadable;
|
||||
import com.github.alathra.alathranwars.config.ConfigHandler;
|
||||
import com.github.alathra.alathranwars.database.DatabaseType;
|
||||
import com.github.alathra.alathranwars.database.config.DatabaseConfig;
|
||||
import com.github.alathra.alathranwars.database.exception.DatabaseInitializationException;
|
||||
import com.github.alathra.alathranwars.database.exception.DatabaseMigrationException;
|
||||
import com.github.alathra.alathranwars.database.jooq.JooqContext;
|
||||
import com.github.alathra.alathranwars.database.migration.MigrationHandler;
|
||||
import com.github.alathra.alathranwars.database.pool.ConnectionPoolFactory;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import org.slf4j.Logger;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.DatabaseMetaData;
|
||||
import java.sql.SQLException;
|
||||
|
||||
/**
|
||||
* Class that handles HikariCP connection pool, jOOQ and Flyway migrations.
|
||||
*/
|
||||
public class DatabaseHandler implements Reloadable {
|
||||
private JooqContext jooqContext;
|
||||
private HikariDataSource connectionPool;
|
||||
private @Nullable DatabaseConfig databaseConfig = null;
|
||||
private @Nullable ConfigHandler configHandler = null;
|
||||
private final Logger logger;
|
||||
private boolean isRunning = false;
|
||||
|
||||
/**
|
||||
* Instantiates a new Database handler.
|
||||
*
|
||||
* @param configHandler the config handler
|
||||
* @param logger the logger
|
||||
*/
|
||||
public DatabaseHandler(@NotNull ConfigHandler configHandler, Logger logger) {
|
||||
this.configHandler = configHandler;
|
||||
this.logger = logger;
|
||||
}
|
||||
|
||||
/**
|
||||
* Instantiates a new Database handler.
|
||||
*
|
||||
* @param databaseConfig the database config
|
||||
* @param logger the logger
|
||||
*/
|
||||
public DatabaseHandler(@NotNull DatabaseConfig databaseConfig, Logger logger) {
|
||||
this.databaseConfig = databaseConfig;
|
||||
this.logger = logger;
|
||||
}
|
||||
|
||||
/**
|
||||
* On plugin load.
|
||||
*/
|
||||
@Override
|
||||
public void onLoad() {
|
||||
try {
|
||||
// Load database config from file, or use provided databaseConfig from constructor
|
||||
if (configHandler != null)
|
||||
this.databaseConfig = DatabaseConfig.getDatabaseConfigFromFile(configHandler.getDatabaseConfig());
|
||||
|
||||
// Start connection pool
|
||||
startup();
|
||||
} catch (DatabaseInitializationException e) {
|
||||
logger.error("[DB] Database initialization error: {}", e.getMessage());
|
||||
} finally {
|
||||
if (!isRunning()) {
|
||||
logger.warn("[DB] Error while initializing database. Functionality will be limited.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* On plugin enable.
|
||||
*/
|
||||
@Override
|
||||
public void onEnable() {
|
||||
}
|
||||
|
||||
/**
|
||||
* On plugin disable.
|
||||
*/
|
||||
@Override
|
||||
public void onDisable() {
|
||||
if (!isRunning())
|
||||
return;
|
||||
|
||||
try {
|
||||
shutdown();
|
||||
} catch (Exception e) {
|
||||
logger.error("[DB] Error while shutting down database:", e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns if the database is setup and functioning properly.
|
||||
*
|
||||
* @return the boolean
|
||||
*/
|
||||
public boolean isRunning() {
|
||||
return isRunning;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets database.
|
||||
*
|
||||
* @return the database
|
||||
*/
|
||||
public DatabaseType getDB() {
|
||||
return getDatabaseConfig().getDatabaseType();
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets jooq context.
|
||||
*
|
||||
* @return the jooq context
|
||||
*/
|
||||
public JooqContext getJooqContext() {
|
||||
return jooqContext;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets connection pool.
|
||||
*
|
||||
* @return the connection pool
|
||||
*/
|
||||
public HikariDataSource getConnectionPool() {
|
||||
return connectionPool;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets database config.
|
||||
*
|
||||
* @return the database config
|
||||
*/
|
||||
public DatabaseConfig getDatabaseConfig() {
|
||||
if (databaseConfig == null)
|
||||
throw new IllegalStateException("Database config is still null but was accessed in getDB!");
|
||||
|
||||
return databaseConfig;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a connection from the connection pool.
|
||||
*
|
||||
* @return the connection
|
||||
* @throws SQLException the sql exception
|
||||
*/
|
||||
@NotNull
|
||||
public Connection getConnection() throws SQLException {
|
||||
if (connectionPool == null)
|
||||
throw new SQLException("[DB] Unable to getConnection a connection from the pool. (connectionPool is null)");
|
||||
|
||||
final Connection connection = connectionPool.getConnection();
|
||||
if (connection == null)
|
||||
throw new SQLException("[DB] Unable to getConnection a connection from the pool. (connectionPool#getConnection returned null)");
|
||||
|
||||
return connection;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a connection pool using HikariCP and executes Flyway migrations using jOOQ.
|
||||
*/
|
||||
public void startup() throws DatabaseInitializationException {
|
||||
if (databaseConfig == null)
|
||||
throw new DatabaseInitializationException("Attempted to start a database connection pool but database config is null!");
|
||||
|
||||
if (connectionPool != null)
|
||||
throw new DatabaseInitializationException("Attempted to create a new database connection pool while running! (connectionPool is not null)");
|
||||
|
||||
// Initialize connection pool
|
||||
connectionPool = ConnectionPoolFactory.create(
|
||||
databaseConfig,
|
||||
logger
|
||||
);
|
||||
|
||||
// Check if using invalid database type (Note, these cases throw in the previous method)
|
||||
try (Connection connection = connectionPool.getConnection()) {
|
||||
DatabaseMetaData databaseMetaData = connection.getMetaData();
|
||||
String vendorVersionName = databaseMetaData.getDatabaseProductVersion().toLowerCase();
|
||||
|
||||
if (vendorVersionName.contains("mariadb") && getDB().equals(DatabaseType.MYSQL)) {
|
||||
throw new RuntimeException("Attempted to connect to a mariadb database using mysql as database type! (Please change the type to mariadb in database.yml)");
|
||||
} else if (vendorVersionName.contains("mysql") && getDB().equals(DatabaseType.MARIADB)) {
|
||||
throw new RuntimeException("Attempted to connect to a mysql database using mariadb as database type! (Please change the type to mysql in database.yml)");
|
||||
}
|
||||
} catch (Throwable t) {
|
||||
throw new DatabaseInitializationException(t.getMessage());
|
||||
}
|
||||
|
||||
// Disable JOOQ nonsense
|
||||
System.setProperty("org.jooq.no-logo", "true");
|
||||
System.setProperty("org.jooq.no-tips", "true");
|
||||
|
||||
// Setup JOOQ
|
||||
jooqContext = new JooqContext(
|
||||
databaseConfig.getDatabaseType().getSQLDialect(),
|
||||
databaseConfig.getTablePrefix()
|
||||
);
|
||||
|
||||
// Migrate with Flyway
|
||||
migrate();
|
||||
|
||||
isRunning = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Closes the connection pool.
|
||||
*/
|
||||
public void shutdown() {
|
||||
if (!isRunning())
|
||||
return;
|
||||
|
||||
logger.info("[DB] Shutting down database pool...");
|
||||
|
||||
if (connectionPool == null) {
|
||||
logger.error("[DB] Skipped closing database pool because the connection pool is null. Was there a previous error which needs to be fixed? Check your logs!");
|
||||
return;
|
||||
}
|
||||
|
||||
if (connectionPool.isClosed()) {
|
||||
logger.error("[DB] Skipped closing database pool: connection is already closed.");
|
||||
return;
|
||||
}
|
||||
|
||||
connectionPool.close();
|
||||
connectionPool = null;
|
||||
isRunning = false;
|
||||
|
||||
logger.info("[DB] Closed database pool.");
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute database migrations with Flyway.
|
||||
*/
|
||||
private void migrate() throws DatabaseInitializationException {
|
||||
try {
|
||||
new MigrationHandler(
|
||||
connectionPool,
|
||||
databaseConfig
|
||||
)
|
||||
.migrate();
|
||||
} catch (DatabaseMigrationException e) {
|
||||
throw new DatabaseInitializationException("Failed to migrate database schemas to new version! Please backup your database and report the issue.", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,103 +0,0 @@
|
||||
package com.github.alathra.alathranwars.database.jooq;
|
||||
|
||||
import com.github.alathra.alathranwars.database.config.DatabaseConfig;
|
||||
import org.jetbrains.annotations.TestOnly;
|
||||
import org.jooq.*;
|
||||
import org.jooq.conf.*;
|
||||
import org.jooq.exception.DataAccessException;
|
||||
import org.jooq.impl.DefaultConfiguration;
|
||||
import org.jooq.tools.JooqLogger;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* Utility class for getting jOOQ Context to use with HikariCP.
|
||||
*/
|
||||
public final class JooqContext {
|
||||
static {
|
||||
JooqLogger.globalThreshold(Log.Level.ERROR); // Silence JOOQ warnings
|
||||
}
|
||||
|
||||
private static final Pattern MATCH_ALL_EXCEPT_INFORMATION_SCHEMA = Pattern.compile("^(?!INFORMATION_SCHEMA)(.*?)$");
|
||||
private static final Pattern MATCH_ALL = Pattern.compile("^(.*?)$");
|
||||
private final SQLDialect dialect;
|
||||
private final String replacement; //
|
||||
|
||||
/**
|
||||
* Instantiates a new Jooq context.
|
||||
*
|
||||
* @param databaseConfig the database config
|
||||
*/
|
||||
@TestOnly
|
||||
public JooqContext(DatabaseConfig databaseConfig) {
|
||||
this.dialect = databaseConfig.getDatabaseType().getSQLDialect();
|
||||
this.replacement = "%s$0".formatted(databaseConfig.getTablePrefix());
|
||||
}
|
||||
|
||||
/**
|
||||
* Instantiates a new Jooq context.
|
||||
*
|
||||
* @param dialect the getSQLDialect
|
||||
* @param tablePrefix the prefix to add in front of tables
|
||||
*/
|
||||
public JooqContext(SQLDialect dialect, String tablePrefix) {
|
||||
this.dialect = dialect;
|
||||
this.replacement = "%s$0".formatted(tablePrefix);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create DSL Context.
|
||||
*
|
||||
* @param connection the connection
|
||||
* @return the dsl context
|
||||
*/
|
||||
public DSLContext createContext(Connection connection) {
|
||||
record SimpleConnectionProvider(Connection connection) implements ConnectionProvider {
|
||||
|
||||
@Override
|
||||
public Connection acquire() throws DataAccessException {
|
||||
return connection;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void release(Connection connection) throws DataAccessException {}
|
||||
}
|
||||
return createWith(new SimpleConnectionProvider(connection));
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies default configuration
|
||||
*
|
||||
* @param connectionProvider A connection lifecycle handler API.
|
||||
* @return DSLContext
|
||||
*/
|
||||
private DSLContext createWith(ConnectionProvider connectionProvider) {
|
||||
return new DefaultConfiguration()
|
||||
.set(connectionProvider)
|
||||
.set(dialect)
|
||||
.set(createSettings())
|
||||
.set(new ExecuteListenerProvider[0])
|
||||
.dsl();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns base settings for DSL Contexts.
|
||||
*
|
||||
* @return Settings
|
||||
*/
|
||||
private Settings createSettings() {
|
||||
return new Settings()
|
||||
.withBackslashEscaping(BackslashEscaping.OFF)
|
||||
.withRenderSchema(false)
|
||||
.withRenderMapping(new RenderMapping() // Support the tables having custom prefix
|
||||
.withSchemata(new MappedSchema()
|
||||
.withInputExpression(MATCH_ALL_EXCEPT_INFORMATION_SCHEMA)
|
||||
.withTables(new MappedTable()
|
||||
.withInputExpression(MATCH_ALL)
|
||||
.withOutput(replacement)
|
||||
)
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
-93
@@ -1,93 +0,0 @@
|
||||
package com.github.alathra.alathranwars.database.migration;
|
||||
|
||||
import com.github.alathra.alathranwars.database.config.DatabaseConfig;
|
||||
import com.github.alathra.alathranwars.database.exception.DatabaseMigrationException;
|
||||
import org.flywaydb.core.Flyway;
|
||||
import org.flywaydb.core.api.ClassProvider;
|
||||
import org.flywaydb.core.api.FlywayException;
|
||||
import org.flywaydb.core.api.migration.JavaMigration;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Handles Flyway migrations.
|
||||
*/
|
||||
public class MigrationHandler {
|
||||
// List of Java migrations
|
||||
private final List<Class<? extends JavaMigration>> migrations = List.of(
|
||||
// V3__Example.class
|
||||
);
|
||||
|
||||
private final DataSource dataSource;
|
||||
private final DatabaseConfig databaseConfig;
|
||||
private Flyway flyway;
|
||||
|
||||
/**
|
||||
* Instantiates a new Database migration handler.
|
||||
*
|
||||
* @param dataSource the data source
|
||||
* @param databaseConfig the database config
|
||||
*/
|
||||
public MigrationHandler(DataSource dataSource, DatabaseConfig databaseConfig) {
|
||||
this.dataSource = dataSource;
|
||||
this.databaseConfig = databaseConfig;
|
||||
initializeFlywayInstance();
|
||||
}
|
||||
|
||||
private void initializeFlywayInstance() {
|
||||
final ClassProvider<JavaMigration> javaMigrationClassProvider = new MigrationProvider(migrations);
|
||||
final Map<String, String> SQL_PLACEHOLDERS = Map.of(
|
||||
"tablePrefix", databaseConfig.getTablePrefix()
|
||||
);
|
||||
|
||||
this.flyway = Flyway
|
||||
.configure(getClass().getClassLoader())
|
||||
.loggers("slf4j")
|
||||
.baselineOnMigrate(true)
|
||||
.baselineVersion("0.0")
|
||||
.validateMigrationNaming(true)
|
||||
.javaMigrationClassProvider(javaMigrationClassProvider)
|
||||
.dataSource(dataSource)
|
||||
.locations(
|
||||
"classpath:database-migrations",
|
||||
"db/migration"
|
||||
)
|
||||
.table(databaseConfig.getTablePrefix() + "schema_history") // Configure tables and migrations
|
||||
.placeholders(SQL_PLACEHOLDERS)
|
||||
.load();
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute Flyway migration. All pending migrations will be applied in order.
|
||||
*
|
||||
* @throws DatabaseMigrationException database migration exception
|
||||
*/
|
||||
public void migrate() throws DatabaseMigrationException {
|
||||
try {
|
||||
this.flyway.migrate();
|
||||
} catch (FlywayException e) {
|
||||
throw new DatabaseMigrationException(e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Executes Flyway repair. Repairs the Flyway schema history table. This will perform the following actions:
|
||||
*
|
||||
* <ul>
|
||||
* <li>Remove any failed migrations on databases without DDL transactions (User objects left behind must still be cleaned up manually)</li>
|
||||
* <li>Realign the checksums, descriptions and types of the applied migration</li>
|
||||
* </ul>
|
||||
*
|
||||
* @throws DatabaseMigrationException database migration exception
|
||||
*/
|
||||
public void repair() throws DatabaseMigrationException {
|
||||
try {
|
||||
if (databaseConfig.isRepair())
|
||||
this.flyway.repair();
|
||||
} catch (FlywayException e) {
|
||||
throw new DatabaseMigrationException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
-28
@@ -1,28 +0,0 @@
|
||||
package com.github.alathra.alathranwars.database.migration;
|
||||
|
||||
import org.flywaydb.core.api.ClassProvider;
|
||||
import org.flywaydb.core.api.migration.JavaMigration;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Flyway migrations provider. Convenience/utility record for using Java migrations with Flyway.
|
||||
*/
|
||||
public record MigrationProvider(
|
||||
List<Class<? extends JavaMigration>> migrations
|
||||
) implements ClassProvider<JavaMigration> {
|
||||
/**
|
||||
* Instantiates a new Flyway migrations provider.
|
||||
*
|
||||
* @param migrations the migrations
|
||||
*/
|
||||
public MigrationProvider(List<Class<? extends JavaMigration>> migrations) {
|
||||
this.migrations = List.copyOf(migrations);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collection<Class<? extends JavaMigration>> getClasses() {
|
||||
return migrations;
|
||||
}
|
||||
}
|
||||
-34
@@ -1,34 +0,0 @@
|
||||
package com.github.alathra.alathranwars.database.migration.migrations;
|
||||
|
||||
import com.github.alathra.alathranwars.utility.DB;
|
||||
import org.flywaydb.core.api.migration.BaseJavaMigration;
|
||||
import org.flywaydb.core.api.migration.Context;
|
||||
import org.jooq.DSLContext;
|
||||
|
||||
import static org.jooq.impl.DSL.field;
|
||||
import static org.jooq.impl.DSL.table;
|
||||
import static org.jooq.impl.SQLDataType.VARCHAR;
|
||||
|
||||
/**
|
||||
* Example Java Flyway migration using jOOQ.
|
||||
*/
|
||||
public class V3__Example extends BaseJavaMigration {
|
||||
@Override
|
||||
public void migrate(final Context flywayContext) throws Exception {
|
||||
try {
|
||||
final DSLContext context = DB.getContext(flywayContext.getConnection());
|
||||
|
||||
context
|
||||
.alterTable(table("test"))
|
||||
.addColumn(field("memes", VARCHAR((32))))
|
||||
.execute();
|
||||
|
||||
context
|
||||
.alterTableIfExists(table("test"))
|
||||
.addColumnIfNotExists(field("column_name", VARCHAR(32).notNull()/*.defaultValue("default")*/))
|
||||
.execute();
|
||||
} catch (Exception e) {
|
||||
// Logger.pool().error(e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
-88
@@ -1,88 +0,0 @@
|
||||
package com.github.alathra.alathranwars.database.pool;
|
||||
|
||||
import com.zaxxer.hikari.HikariConfig;
|
||||
import com.github.alathra.alathranwars.database.DatabaseType;
|
||||
import com.github.alathra.alathranwars.database.config.DatabaseConfig;
|
||||
import com.github.alathra.alathranwars.database.config.DatabaseConfigBuilder;
|
||||
import com.github.alathra.alathranwars.database.exception.DatabaseInitializationException;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.util.Optional;
|
||||
|
||||
import static com.github.alathra.alathranwars.database.DatabaseType.*;
|
||||
|
||||
public abstract class ConnectionPoolConfigFactory {
|
||||
public static HikariConfig get() throws DatabaseInitializationException {
|
||||
return get(new DatabaseConfigBuilder().build());
|
||||
}
|
||||
|
||||
public static HikariConfig get(DatabaseConfig config) throws DatabaseInitializationException {
|
||||
HikariConfig hikariConfig = new HikariConfig();
|
||||
|
||||
final DatabaseType databaseType = config.getDatabaseType();
|
||||
|
||||
// Create RDBMS specific jdbc url
|
||||
final String jdbcUrl = switch (databaseType) {
|
||||
case SQLITE, H2 -> {
|
||||
final Optional<Path> path = config.getPath();
|
||||
if (path.isEmpty())
|
||||
throw new DatabaseInitializationException("Path was null when setting up database!");
|
||||
|
||||
final String fileName = databaseType.equals(SQLITE) ? "database.sqlite" : "database";
|
||||
|
||||
yield "jdbc:%s:file:%s%s".formatted(
|
||||
databaseType.getJdbcPrefix(),
|
||||
path.get().resolve(fileName).toAbsolutePath(),
|
||||
databaseType.getDefaultConnectionProperties()
|
||||
);
|
||||
}
|
||||
case MYSQL, MARIADB -> {
|
||||
yield "jdbc:%s://%s:%s/%s%s%s".formatted(
|
||||
databaseType.getJdbcPrefix(),
|
||||
config.getHost(),
|
||||
config.getPort(),
|
||||
config.getDatabase(),
|
||||
databaseType.getDefaultConnectionProperties(),
|
||||
config.getConnectionProperties()
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
// Set username & password
|
||||
switch (databaseType) {
|
||||
case SQLITE, H2 -> {
|
||||
hikariConfig.setUsername("sa");
|
||||
hikariConfig.setPassword("");
|
||||
}
|
||||
case MYSQL, MARIADB -> {
|
||||
hikariConfig.setUsername(config.getUsername());
|
||||
hikariConfig.setPassword(config.getPassword());
|
||||
}
|
||||
}
|
||||
|
||||
// Set pool configuration
|
||||
hikariConfig.setMaximumPoolSize(config.getMaxPoolSize());
|
||||
hikariConfig.setMinimumIdle(config.getMinIdle());
|
||||
hikariConfig.setMaxLifetime(config.getMaxLifeTime());
|
||||
hikariConfig.setKeepaliveTime(config.getKeepAliveTime());
|
||||
hikariConfig.setConnectionTimeout(config.getConnectionTimeout());
|
||||
|
||||
// Set database driver class and jdbc url
|
||||
try {
|
||||
Class.forName(databaseType.getDataSourceClassName());
|
||||
} catch (ClassNotFoundException e) {
|
||||
throw new DatabaseInitializationException("Failed to initialise jdbc driver!", e);
|
||||
}
|
||||
hikariConfig.setDataSourceClassName(databaseType.getDataSourceClassName());
|
||||
hikariConfig.addDataSourceProperty("url", jdbcUrl);
|
||||
|
||||
// Misc pool configuration
|
||||
hikariConfig.setPoolName("%s-hikari".formatted(databaseType.getJdbcPrefix()));
|
||||
hikariConfig.setAutoCommit(true);
|
||||
hikariConfig.setTransactionIsolation("TRANSACTION_REPEATABLE_READ");
|
||||
hikariConfig.setIsolateInternalQueries(true);
|
||||
hikariConfig.setConnectionInitSql(databaseType.getConnectionInitSql());
|
||||
|
||||
return hikariConfig;
|
||||
}
|
||||
}
|
||||
-19
@@ -1,19 +0,0 @@
|
||||
package com.github.alathra.alathranwars.database.pool;
|
||||
|
||||
import com.zaxxer.hikari.HikariConfig;
|
||||
import com.zaxxer.hikari.HikariDataSource;
|
||||
import com.github.alathra.alathranwars.database.config.DatabaseConfig;
|
||||
import com.github.alathra.alathranwars.database.exception.DatabaseInitializationException;
|
||||
import org.slf4j.Logger;
|
||||
|
||||
public abstract class ConnectionPoolFactory {
|
||||
public static HikariDataSource create(DatabaseConfig databaseConfig, Logger logger) throws DatabaseInitializationException {
|
||||
try {
|
||||
HikariConfig hikariConfig = ConnectionPoolConfigFactory.get(databaseConfig);
|
||||
|
||||
return new HikariDataSource(hikariConfig);
|
||||
} catch (Throwable t) {
|
||||
throw new DatabaseInitializationException("Failed to initialize database pool during startup. Are you using the correct database type?");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
package com.github.alathra.alathranwars.enums;
|
||||
|
||||
public enum CaptureProgressDirection {
|
||||
UP,
|
||||
CONTESTED,
|
||||
UNCONTESTED,
|
||||
DOWN
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
package com.github.alathra.alathranwars.enums;
|
||||
|
||||
public enum CommandArgsSiege {
|
||||
IN_SIEGE,
|
||||
OUT_SIEGE,
|
||||
ALL_SIEGES,
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
package com.github.alathra.alathranwars.enums;
|
||||
|
||||
public enum CommandArgsWar {
|
||||
IN_WAR,
|
||||
OUT_WAR,
|
||||
ALL_WARS,
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
package com.github.alathra.alathranwars.enums;
|
||||
|
||||
public enum ConflictType {
|
||||
WAR
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
package com.github.alathra.alathranwars.enums;
|
||||
|
||||
public enum WarDeleteReason {
|
||||
DRAW,
|
||||
DEFEAT,
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
package com.github.alathra.alathranwars.enums.battle;
|
||||
|
||||
public enum BattleSide {
|
||||
ATTACKER,
|
||||
DEFENDER,
|
||||
SPECTATOR,
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
package com.github.alathra.alathranwars.enums.battle;
|
||||
|
||||
public enum BattleTeam {
|
||||
SIDE_1,
|
||||
SIDE_2,
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
package com.github.alathra.alathranwars.enums.battle;
|
||||
|
||||
public enum BattleType {
|
||||
SIEGE,
|
||||
RAID,
|
||||
}
|
||||
Loaded 100 of 187 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user