diff --git a/config.json b/config.json index 28e3914..5937ecd 100644 --- a/config.json +++ b/config.json @@ -607,6 +607,14 @@ "prerequisites": [], "difficulty": 7 }, + { + "slug": "yacht", + "name": "Yacht", + "uuid": "e1ee7633-1f85-4f87-8f06-20b9d1818c88", + "practices": [], + "prerequisites": [], + "difficulty": 7 + }, { "slug": "alphametics", "name": "Alphametics", diff --git a/exercises/practice/yacht/.docs/instructions.md b/exercises/practice/yacht/.docs/instructions.md new file mode 100644 index 0000000..519b7a6 --- /dev/null +++ b/exercises/practice/yacht/.docs/instructions.md @@ -0,0 +1,30 @@ +# Instructions + +Given five dice and a category, calculate the score of the dice for that category. + +~~~~exercism/note +You'll always be presented with five dice. +Each dice's value will be between one and six inclusively. +The dice may be unordered. +~~~~ + +## Scores in Yacht + +| Category | Score | Description | Example | +| --------------- | ---------------------- | ---------------------------------------- | ------------------- | +| Ones | 1 × number of ones | Any combination | 1 1 1 4 5 scores 3 | +| Twos | 2 × number of twos | Any combination | 2 2 3 4 5 scores 4 | +| Threes | 3 × number of threes | Any combination | 3 3 3 3 3 scores 15 | +| Fours | 4 × number of fours | Any combination | 1 2 3 3 5 scores 0 | +| Fives | 5 × number of fives | Any combination | 5 1 5 2 5 scores 15 | +| Sixes | 6 × number of sixes | Any combination | 2 3 4 5 6 scores 6 | +| Full House | Total of the dice | Three of one number and two of another | 3 3 3 5 5 scores 19 | +| Four of a Kind | Total of the four dice | At least four dice showing the same face | 4 4 4 4 6 scores 16 | +| Little Straight | 30 points | 1-2-3-4-5 | 1 2 3 4 5 scores 30 | +| Big Straight | 30 points | 2-3-4-5-6 | 2 3 4 5 6 scores 30 | +| Choice | Sum of the dice | Any combination | 2 3 3 4 6 scores 18 | +| Yacht | 50 points | All five dice showing the same face | 4 4 4 4 4 scores 50 | + +If the dice do **not** satisfy the requirements of a category, the score is zero. +If, for example, _Four Of A Kind_ is entered in the _Yacht_ category, zero points are scored. +A _Yacht_ scores zero if entered in the _Full House_ category. diff --git a/exercises/practice/yacht/.docs/introduction.md b/exercises/practice/yacht/.docs/introduction.md new file mode 100644 index 0000000..5b541f5 --- /dev/null +++ b/exercises/practice/yacht/.docs/introduction.md @@ -0,0 +1,11 @@ +# Introduction + +Each year, something new is "all the rage" in your high school. +This year it is a dice game: [Yacht][yacht]. + +The game of Yacht is from the same family as Poker Dice, Generala and particularly Yahtzee, of which it is a precursor. +The game consists of twelve rounds. +In each, five dice are rolled and the player chooses one of twelve categories. +The chosen category is then used to score the throw of the dice. + +[yacht]: https://en.wikipedia.org/wiki/Yacht_(dice_game) diff --git a/exercises/practice/yacht/.meta/config.json b/exercises/practice/yacht/.meta/config.json new file mode 100644 index 0000000..3cff426 --- /dev/null +++ b/exercises/practice/yacht/.meta/config.json @@ -0,0 +1,22 @@ +{ + "authors": [ + "IsaacG" + ], + "files": { + "solution": [ + "yacht.gd" + ], + "test": [ + "yacht_test.gd", + "run_tests", + "lib/test_runner.gd", + "project.godot" + ], + "example": [ + ".meta/example.gd" + ] + }, + "blurb": "Score a single throw of dice in the game Yacht.", + "source": "James Kilfiger, using Wikipedia", + "source_url": "https://en.wikipedia.org/wiki/Yacht_(dice_game)" +} diff --git a/exercises/practice/yacht/.meta/example.gd b/exercises/practice/yacht/.meta/example.gd new file mode 100644 index 0000000..a52a2d7 --- /dev/null +++ b/exercises/practice/yacht/.meta/example.gd @@ -0,0 +1,54 @@ +enum { + YACHT, + ONES, + TWOS, + THREES, + FOURS, + FIVES, + SIXES, + FULL_HOUSE, + FOUR_OF_A_KIND, + LITTLE_STRAIGHT, + BIG_STRAIGHT, + CHOICE +} + + +func sum(numbers): + var out = 0 + for i in numbers: + out += i + return out + + +func score(dice, category): + var count = {} + for die in dice: + if die not in count: + count[die] = 0 + count[die] += 1 + + var values = [] + for die in count: + values.append(count[die]) + + match category: + CHOICE: + return sum(dice) + YACHT when len(count) == 1: + return 50 + LITTLE_STRAIGHT when len(count) == 5 and 6 not in count: + return 30 + BIG_STRAIGHT when len(count) == 5 and 1 not in count: + return 30 + FULL_HOUSE when len(count) == 2 and 2 in values: + return sum(dice) + FOUR_OF_A_KIND when len(count) <= 2 and (4 in values or 5 in values): + for die in count: + if count[die] >= 4: + return die * 4 + _: + if category in count: + return category * count[category] + + return 0 diff --git a/exercises/practice/yacht/.meta/template.j2 b/exercises/practice/yacht/.meta/template.j2 new file mode 100644 index 0000000..d87bdc5 --- /dev/null +++ b/exercises/practice/yacht/.meta/template.j2 @@ -0,0 +1,8 @@ +{% for case in cases %} +func test_{{ case.func_name }}(solution_script): + var got = solution_script.{{ case.property }}({{ case.input.dice | quote }}, solution_script.{{ case.input.category | upper | replace(" ", "_") }}) + var want = {{ case.expected | quote }} + return [got, want] + +{% endfor %} + diff --git a/exercises/practice/yacht/.meta/tests.toml b/exercises/practice/yacht/.meta/tests.toml new file mode 100644 index 0000000..b9d9203 --- /dev/null +++ b/exercises/practice/yacht/.meta/tests.toml @@ -0,0 +1,97 @@ +# This is an auto-generated file. +# +# Regenerating this file via `configlet sync` will: +# - Recreate every `description` key/value pair +# - Recreate every `reimplements` key/value pair, where they exist in problem-specifications +# - Remove any `include = true` key/value pair (an omitted `include` key implies inclusion) +# - Preserve any other key/value pair +# +# As user-added comments (using the # character) will be removed when this file +# is regenerated, comments can be added via a `comment` key. + +[3060e4a5-4063-4deb-a380-a630b43a84b6] +description = "Yacht" + +[15026df2-f567-482f-b4d5-5297d57769d9] +description = "Not Yacht" + +[36b6af0c-ca06-4666-97de-5d31213957a4] +description = "Ones" + +[023a07c8-6c6e-44d0-bc17-efc5e1b8205a] +description = "Ones, out of order" + +[7189afac-cccd-4a74-8182-1cb1f374e496] +description = "No ones" + +[793c4292-dd14-49c4-9707-6d9c56cee725] +description = "Twos" + +[dc41bceb-d0c5-4634-a734-c01b4233a0c6] +description = "Fours" + +[f6125417-5c8a-4bca-bc5b-b4b76d0d28c8] +description = "Yacht counted as threes" + +[464fc809-96ed-46e4-acb8-d44e302e9726] +description = "Yacht of 3s counted as fives" + +[d054227f-3a71-4565-a684-5c7e621ec1e9] +description = "Fives" + +[e8a036e0-9d21-443a-8b5f-e15a9e19a761] +description = "Sixes" + +[51cb26db-6b24-49af-a9ff-12f53b252eea] +description = "Full house two small, three big" + +[1822ca9d-f235-4447-b430-2e8cfc448f0c] +description = "Full house three small, two big" + +[b208a3fc-db2e-4363-a936-9e9a71e69c07] +description = "Two pair is not a full house" + +[b90209c3-5956-445b-8a0b-0ac8b906b1c2] +description = "Four of a kind is not a full house" + +[32a3f4ee-9142-4edf-ba70-6c0f96eb4b0c] +description = "Yacht is not a full house" + +[b286084d-0568-4460-844a-ba79d71d79c6] +description = "Four of a Kind" + +[f25c0c90-5397-4732-9779-b1e9b5f612ca] +description = "Yacht can be scored as Four of a Kind" + +[9f8ef4f0-72bb-401a-a871-cbad39c9cb08] +description = "Full house is not Four of a Kind" + +[b4743c82-1eb8-4a65-98f7-33ad126905cd] +description = "Little Straight" + +[7ac08422-41bf-459c-8187-a38a12d080bc] +description = "Little Straight as Big Straight" + +[97bde8f7-9058-43ea-9de7-0bc3ed6d3002] +description = "Four in order but not a little straight" + +[cef35ff9-9c5e-4fd2-ae95-6e4af5e95a99] +description = "No pairs but not a little straight" + +[fd785ad2-c060-4e45-81c6-ea2bbb781b9d] +description = "Minimum is 1, maximum is 5, but not a little straight" + +[35bd74a6-5cf6-431a-97a3-4f713663f467] +description = "Big Straight" + +[87c67e1e-3e87-4f3a-a9b1-62927822b250] +description = "Big Straight as little straight" + +[c1fa0a3a-40ba-4153-a42d-32bc34d2521e] +description = "No pairs but not a big straight" + +[207e7300-5d10-43e5-afdd-213e3ac8827d] +description = "Choice" + +[b524c0cf-32d2-4b40-8fb3-be3500f3f135] +description = "Yacht as choice" diff --git a/exercises/practice/yacht/lib/test_runner.gd b/exercises/practice/yacht/lib/test_runner.gd new file mode 100644 index 0000000..be91311 --- /dev/null +++ b/exercises/practice/yacht/lib/test_runner.gd @@ -0,0 +1,541 @@ +class_name TestRunner +extends SceneTree + + +class ErrorReader: + """ErrorReader reads from a STDERR file (cmd 2>/file). + + It filters out the less useful Godot output and handles retrieving lines iteratively. + """ + + const EXPECTED_GODOT_ERRORS = [ + ( + "ERROR: Could not create directory: /root/.local\n" + + " at: make_dir_recursive (core/io/dir_access.cpp:180)\n" + ), + ( + "ERROR: Error attempting to create data dir: " + + "/root/.local/share/godot/app_userdata/[unnamed project].\n" + + " at: ensure_user_data_dir (core/os/os.cpp:344)\n" + ), + ( + "ERROR: Could not create editor data directory: /root/.local/share/godot\n" + + " at: EditorPaths (editor/editor_paths.cpp:183)\n" + ), + ( + "ERROR: Could not create directory: /root/.config\n" + + " at: make_dir_recursive (core/io/dir_access.cpp:180)\n" + ), + ( + "ERROR: Could not create editor config directory: /root/.config/godot\n" + + " at: EditorPaths (editor/editor_paths.cpp:198)\n" + ), + ( + "ERROR: Could not create directory: /root/.cache\n" + + " at: make_dir_recursive (core/io/dir_access.cpp:180)\n" + ), + ( + "ERROR: Could not create editor cache directory: /root/.cache/godot\n" + + " at: EditorPaths (editor/editor_paths.cpp:219)\n" + ), + ( + "ERROR: Can't save resource to empty path. " + + "Provide non-empty path or a Resource with non-empty resource_path.\n" + + " at: save (core/io/resource_saver.cpp:105)\n" + ), + ( + "ERROR: Error saving editor settings to \n" + + " at: save (editor/editor_settings.cpp:1013)\n" + ), + ] + var already_processed_bytes: int = 0 + var filename: String = "" + var color_sequence = RegEx.create_from_string("\\e\\[\\d[\\d;]*m") + + func _init(filename: String) -> void: + self.already_processed_bytes = 0 + self.filename = filename + if not self.filename.is_empty() and ResourceLoader.exists(self.filename): + self.get_error_message() + + func check() -> Error: + if not FileAccess.file_exists(self.filename): + push_error("STDERR must be redirected to '%s' when using '--json'" % self.filename) + return ERR_FILE_NOT_FOUND + if OS.get_stderr_type() != OS.STD_HANDLE_FILE: + push_error("STDERR must be redirected to '%s' when using '--json'" % self.filename) + return ERR_FILE_NOT_FOUND + return OK + + func get_error_message() -> String: + """ + Checks the contents of the STDERR file, where error output from the + currently running test suite should be stored. If there is any relevant output + there, this method will return it. If the file is empty, an empty string is returned. + + This method will remove previously read output from the returned message. It should + be called after executing every test, to ensure that the message contains only output + relevant for the given test. + + NOTE: running a Godot instance without full access to certain folders in the + home directory (`~/.config`, `~/.local`, `~/.cache`) will result in additional + errors. This happens when GDScript test runner is executed in Docker. However, + these errors do not stop the execution of the program, so they can be ignored. + This method filters them out, leaving only the errors caused by the actual tests. + """ + if self.filename.is_empty(): + return "" + + var error_output = FileAccess.get_file_as_string(self.filename) + error_output = error_output.erase(0, self.already_processed_bytes) + self.already_processed_bytes += len(error_output) + + # By default, Godot's error messages are printed with colors. To include the output in the + # `results.json` file, color markers need to be removed first. + error_output = self.color_sequence.sub(error_output, "", true) + + # Filter out the expected error messages + for expected_error in EXPECTED_GODOT_ERRORS: + error_output = error_output.replace(expected_error, "") + + return error_output + + +class ResultWriter: + var json_file: String = "" + var stderr: ErrorReader = null + + func _init(json_file: String, stderr: ErrorReader) -> void: + self.json_file = json_file + self.stderr = stderr + + func delete_existing() -> Error: + """ + Removes the previous `results.json` file, to ensure that the current test suite will not use it. + """ + if self.json_file.is_empty(): + return OK + if FileAccess.file_exists(self.json_file): + DirAccess.remove_absolute(self.json_file) + var error_message: String = self.stderr.get_error_message() + if not error_message.is_empty(): + push_error(error_message) + return FAILED + return OK + + func write(results: Dictionary) -> Error: + """ + If output_dir_path is empty, outputs friendly-formatted test results to + stdout. + + Otherwise, writes JSON results to results.json in the given path. + """ + if self.json_file.is_empty(): + return print_friendly_results(results) + return write_results_file(results) + + func print_friendly_results(results: Dictionary) -> Error: + """ + Prints rich results to stdout. + """ + var rich_results = [""] + if results.status == "pass": + rich_results.push_back("[color=yellow]Exercise passed! Nicely done![/color]") + else: + rich_results.push_back("Exercise has at least one failed test:") + for test in results.tests: + if test.status == "pass": + rich_results.push_back(" %s [color=yellow]passed ✔[/color]" % test.name) + else: + rich_results.push_back( + " %s [color=pink]failed: %s[/color]" % [test.name, test.message] + ) + print_rich("\n".join(rich_results)) + return OK + + func write_results_file(results: Dictionary) -> Error: + """ + Saves a dictionary as a `results.json` file in the output directory. The file + is indented with 4 spaces, keys are not sorted. + + The `results` dictionary represents the full output of a single exercise's + test suite, according to the Test Runner Interface documentation: + + https://exercism.org/docs/building/tooling/test-runners/interface + + This method automatically adds `'version' = 2` to the results. + """ + # Due to keys not being sorted, `version` should be inserted first + var full_results = {"version": 2} + full_results.merge(results) + + var pretty_results = JSON.stringify(full_results, " ", false) + + var results_json = FileAccess.open(self.json_file, FileAccess.WRITE) + if results_json == null: + var err = FileAccess.get_open_error() + push_error("Failed to write the file: %s (%s)" % [self.json_file, error_string(err)]) + return err + + results_json.store_string(pretty_results + "\n") + return OK + + +class ArgParser: + """ArgParser reads the cmdline and parses inputs and options.""" + + var solution_script_path: String = "" + var test_suite_script_path: String = "" + var run_all: bool = false + var json: bool = false + var json_file: String = "" + + func usage(message: String) -> void: + print("Usage:") + print("test_runner [--all] [--json filename.json] ") + if not message.is_empty(): + print() + print(message) + + func parse_args() -> Error: + """ + Validates the number of args passed to the script and sets values of the following + global variables, based on the given args: + * `solution_script_path` + * `test_suite_script_path` + """ + var args = OS.get_cmdline_user_args() + var positional: Array = [] + + var idx := 0 + while idx < len(args): + var arg = args[idx] + if arg == "--all": + run_all = true + elif arg.begins_with("--json"): + if arg.contains("="): + var parts = arg.split("=", true, 1) + if parts[0] == "--json": + self.json = true + self.json_file = parts[1] + else: + usage("Invalid flag %s" % arg) + return ERR_INVALID_PARAMETER + elif idx + 1 < len(args): + self.json = true + self.json_file = args[idx + 1] + idx += 1 + else: + usage("Flag %s is missing a filename" % arg) + return ERR_INVALID_PARAMETER + elif arg.begins_with("--"): + usage("Invalid flag %s" % arg) + return ERR_INVALID_PARAMETER + else: + positional.append(arg) + idx += 1 + + if len(positional) != 2: + usage("Expecting 2 positional args but got %d" % len(positional)) + return ERR_INVALID_PARAMETER + + var slug = positional[0] + var solution_dir_path = positional[1] + + # Test folders use dashes, but test files use underscores + var gdscript_path = solution_dir_path.path_join(slug.replace("-", "_")) + + self.solution_script_path = gdscript_path + ".gd" + self.test_suite_script_path = gdscript_path + "_test.gd" + + return OK + + func files() -> Array: + return [self.solution_script_path, self.test_suite_script_path] + + +class Runner: + var test_suite: Object = null + var solution: Object = null + var stderr: ErrorReader = null + var result_writer: ResultWriter = null + + func _init( + test_suite: Object, solution: Object, stderr: ErrorReader, result_writer: ResultWriter + ) -> void: + self.test_suite = test_suite + self.solution = solution + self.stderr = stderr + self.result_writer = result_writer + + func extract_methods() -> Dictionary: + """Extract the source code of a method from a script.""" + var in_func: bool = false + var parts = [] + var methods: Dictionary = {} + var name: String = "" + var func_re: RegEx = RegEx.create_from_string("^func ([^(]+)\\(") + for line in self.test_suite.get_script().source_code.split("\n"): + if not in_func: + var matched = func_re.search(line) + if matched: + in_func = true + name = matched.get_strings()[1] + parts = [] + elif not line.begins_with("\t") and not line.begins_with(" "): + if in_func: + in_func = false + methods[name] = "\n".join(parts) + else: + parts.append(line) + + return methods + + func get_failed_test_message(actual, expected) -> String: + """ + Generates a message for a failed test. If given values are strings, + this method will wrap them in single quotes, to distinguish from + other types, like integers (e.g. '3' vs 3). + + This method should be used if the actual and expected values for a + given test are different, or if they have different types. + """ + var values = [] + + for value in [actual, expected]: + var formatted_value = str(value) + if typeof(value) == TYPE_STRING: + formatted_value = "'{0}'".format([formatted_value]) + values.append(formatted_value) + + return "Expected output was {1}, actual output was {0}.".format(values) + + func run_tests() -> Array: + """ + Runs the given test suite agains the given solution script. Returns an Array + representing the results of each test case, in the same order that they are defined + in the test suite. Each test result is a Dictionary containing 3 values: + + * `name`: the name of the test case + * `status`: 'pass', 'fail', or 'error' + * `message`: null if the test passed, otherwise it contains the details of the failure/error + + This method will look for methods starting with `test_` in the test script, and + then call them with the solution script as the only argument. The `test_` method's + name will be used as the `name` value for each test result. + + If any stderr output was generated during the execution of the `test_` method, + `status` will be set to 'error'. The test will also receive an 'error' status + if calling the `test_` method returned null (which indicates execution issues). + + Otherwise, the `test_` method should return an Array of 2 elements: the actual value, + and the expected value. The values will be compared and if they are the same, the test will + pass. Otherwise, it will fail, with a relevant message being set by this method. + """ + var test_results = [] + var test_codes = self.extract_methods() + + for method in self.test_suite.get_method_list(): + if not method["name"].begins_with("test_"): + continue + var test_method_name = method["name"] + print("-> " + test_method_name) + var test_method = self.test_suite.get(test_method_name) + + var output = test_method.call(self.solution) + var error_message = self.stderr.get_error_message() + + if output == null: + ( + test_results + . append( + { + "name": test_method_name, + "status": "error", + "message": error_message, + } + ) + ) + else: + var actual = output[0] + var expected = output[1] + + var passed = ( + typeof(actual) == typeof(expected) + and actual == expected + and error_message.is_empty() + ) + + var status = "error" + if error_message.is_empty(): + status = "pass" if passed else "fail" + error_message = ( + null if passed else self.get_failed_test_message(actual, expected) + ) + + var test_code = test_codes[method["name"]] + # The code would be cleaner if the test suite actually checked the values. + # Instead, the test suite returns an array with two values which are compared (above). + # This `replace()` hides some of that implementation detail by communicating that the + # array elements are being compared for equality. + test_code = test_code.replace("return [", "assert_equal [") + test_code = test_code.replace("\t", " ") + test_code = test_code.dedent().strip_edges() + + ( + test_results + . append( + { + "name": test_method_name, + "status": status, + "message": error_message, + "test_code": test_code, + } + ) + ) + + return test_results + + func run(run_all: bool) -> void: + """ + Executes the current suite against the current solution. Stores the results in the + `results.json` file in the output dir. + """ + var test_results = run_tests() + var results = {} + + # Check if any tests were executed + if len(test_results) == 0: + results = {"status": "error", "message": "No tests were executed.", "tests": []} + else: + results = {"status": "pass", "tests": test_results} + + # If any of the tests failed, change the global status to `fail` + for test_result in test_results: + if test_result["status"] != "pass": + results["status"] = "fail" + break + + if not run_all and results["status"] != "pass": + var success_count: int = 0 + for test_result in test_results: + if test_result["status"] == "pass": + success_count += 1 + + var has_failure = false + var filtered_results = [] + for test_result in test_results: + if test_result["status"] == "pass": + filtered_results.append(test_result) + elif not has_failure: + has_failure = true + test_result["message"] = ( + "Passes %d/%d tests. First failure: %s" + % [ + success_count, + len(test_results), + test_result["message"], + ] + ) + filtered_results.append(test_result) + results["tests"] = filtered_results + + self.result_writer.write(results) + + +func load_solution(path: String) -> Object: + """Load a script. This helper is needed to catch failures without aborting the error handling.""" + if not FileAccess.file_exists(path): + return null + var re = RegEx.create_from_string("^( )+") + var replace = RegEx.create_from_string("( )+") + var changed = false + var lines = [] + for line in FileAccess.open(path, FileAccess.READ).get_as_text().split("\n"): + var m = re.search(line) + if m == null: + lines.append(line) + else: + changed = true + var new = [] + for i in range(m.get_end() / 4): + new.append("\t") + new.append(line.substr(m.get_end())) + lines.append("".join(new)) + if not changed: + return load(path).new() + + path = OS.get_temp_dir() + "/solution.gd" + FileAccess.open(path, FileAccess.WRITE).store_string("\n".join(lines)) + var solution = load(path).new() + DirAccess.remove_absolute(path) + return solution + + +func load_solution_script( + solution_script_path: String, result_writer: ResultWriter, stderr: ErrorReader +) -> Array: + """ + Loads the solution script and saves it in a global variable. In case of any + issues, this method will save the `results.json` file with `error` status. + """ + # Make sure the STDERR file is empty. + stderr.get_error_message() + var solution_script = load_solution(solution_script_path) + + if solution_script == null: + var message: String = "The solution file could not be parsed." + # Extract the error message, up until the "Failed to load" line + # which is specific to the test runner, not the user's solution. + var error_message: String = stderr.get_error_message() + if not error_message.is_empty(): + var msg = [] + var stop = ( + 'ERROR: Failed to load script "%s" with error "Parse error".' % solution_script_path + ) + for line in error_message.split("\n"): + if line == stop: + break + msg.append(line) + message += "\n" + "\n".join(msg) + var results = {"status": "error", "message": message, "tests": []} + result_writer.write(results) + return [null, ERR_PARSE_ERROR] + + return [solution_script, OK] + + +func _init(): + # Calling `quit(1)` doesn't stop the program immediately, so a `return` is necessary. + # That's why errors are checked directly in `_init()`, instead of calling `quit(1)` + # in each method. + var args = ArgParser.new() + if args.parse_args() != OK: + quit(1) + return + for file in args.files(): + if not ResourceLoader.exists(file): + push_error("File %s not found." % file) + quit(1) + return + + var stderr = ErrorReader.new("/tmp/stderr") + if args.json and stderr.check() != OK: + quit(1) + return + + var result_writer = ResultWriter.new(args.json_file, stderr) + if result_writer.delete_existing() != OK: + quit(1) + return + + var r = load_solution_script(args.solution_script_path, result_writer, stderr) + if r[1] != OK: + quit(1) + return + var solution = r[0] + + var test_suite = load(args.test_suite_script_path).new() + + Runner.new(test_suite, solution, stderr, result_writer).run(args.run_all) + quit() diff --git a/exercises/practice/yacht/project.godot b/exercises/practice/yacht/project.godot new file mode 100644 index 0000000..08680b1 --- /dev/null +++ b/exercises/practice/yacht/project.godot @@ -0,0 +1,5 @@ +config_version=5 + +[application] +config/name="Exercism - Yacht" +config/features=PackedStringArray("4.7") diff --git a/exercises/practice/yacht/run_tests b/exercises/practice/yacht/run_tests new file mode 100755 index 0000000..ed18a90 --- /dev/null +++ b/exercises/practice/yacht/run_tests @@ -0,0 +1,6 @@ +#!/usr/bin/env bash + +slug=${PWD##*/} +[[ -f "${slug//-/_}.gd" ]] || die "Error! solution file is missing" +[[ -f "${slug//-/_}_test.gd" ]] || die "Error! test file is missing" +exec godot --headless --script ./lib/test_runner.gd -- "${slug}" "${PWD}" diff --git a/exercises/practice/yacht/yacht.gd b/exercises/practice/yacht/yacht.gd new file mode 100644 index 0000000..a52a2d7 --- /dev/null +++ b/exercises/practice/yacht/yacht.gd @@ -0,0 +1,54 @@ +enum { + YACHT, + ONES, + TWOS, + THREES, + FOURS, + FIVES, + SIXES, + FULL_HOUSE, + FOUR_OF_A_KIND, + LITTLE_STRAIGHT, + BIG_STRAIGHT, + CHOICE +} + + +func sum(numbers): + var out = 0 + for i in numbers: + out += i + return out + + +func score(dice, category): + var count = {} + for die in dice: + if die not in count: + count[die] = 0 + count[die] += 1 + + var values = [] + for die in count: + values.append(count[die]) + + match category: + CHOICE: + return sum(dice) + YACHT when len(count) == 1: + return 50 + LITTLE_STRAIGHT when len(count) == 5 and 6 not in count: + return 30 + BIG_STRAIGHT when len(count) == 5 and 1 not in count: + return 30 + FULL_HOUSE when len(count) == 2 and 2 in values: + return sum(dice) + FOUR_OF_A_KIND when len(count) <= 2 and (4 in values or 5 in values): + for die in count: + if count[die] >= 4: + return die * 4 + _: + if category in count: + return category * count[category] + + return 0 diff --git a/exercises/practice/yacht/yacht_test.gd b/exercises/practice/yacht/yacht_test.gd new file mode 100644 index 0000000..ddc09ac --- /dev/null +++ b/exercises/practice/yacht/yacht_test.gd @@ -0,0 +1,172 @@ +func test_yacht(solution_script): + var got = solution_script.score([5, 5, 5, 5, 5], solution_script.YACHT) + var want = 50 + return [got, want] + + +func test_not_yacht(solution_script): + var got = solution_script.score([1, 3, 3, 2, 5], solution_script.YACHT) + var want = 0 + return [got, want] + + +func test_ones(solution_script): + var got = solution_script.score([1, 1, 1, 3, 5], solution_script.ONES) + var want = 3 + return [got, want] + + +func test_ones_out_of_order(solution_script): + var got = solution_script.score([3, 1, 1, 5, 1], solution_script.ONES) + var want = 3 + return [got, want] + + +func test_no_ones(solution_script): + var got = solution_script.score([4, 3, 6, 5, 5], solution_script.ONES) + var want = 0 + return [got, want] + + +func test_twos(solution_script): + var got = solution_script.score([2, 3, 4, 5, 6], solution_script.TWOS) + var want = 2 + return [got, want] + + +func test_fours(solution_script): + var got = solution_script.score([1, 4, 1, 4, 1], solution_script.FOURS) + var want = 8 + return [got, want] + + +func test_yacht_counted_as_threes(solution_script): + var got = solution_script.score([3, 3, 3, 3, 3], solution_script.THREES) + var want = 15 + return [got, want] + + +func test_yacht_of_3s_counted_as_fives(solution_script): + var got = solution_script.score([3, 3, 3, 3, 3], solution_script.FIVES) + var want = 0 + return [got, want] + + +func test_fives(solution_script): + var got = solution_script.score([1, 5, 3, 5, 3], solution_script.FIVES) + var want = 10 + return [got, want] + + +func test_sixes(solution_script): + var got = solution_script.score([2, 3, 4, 5, 6], solution_script.SIXES) + var want = 6 + return [got, want] + + +func test_full_house_two_small_three_big(solution_script): + var got = solution_script.score([2, 2, 4, 4, 4], solution_script.FULL_HOUSE) + var want = 16 + return [got, want] + + +func test_full_house_three_small_two_big(solution_script): + var got = solution_script.score([5, 3, 3, 5, 3], solution_script.FULL_HOUSE) + var want = 19 + return [got, want] + + +func test_two_pair_is_not_a_full_house(solution_script): + var got = solution_script.score([2, 2, 4, 4, 5], solution_script.FULL_HOUSE) + var want = 0 + return [got, want] + + +func test_four_of_a_kind_is_not_a_full_house(solution_script): + var got = solution_script.score([1, 4, 4, 4, 4], solution_script.FULL_HOUSE) + var want = 0 + return [got, want] + + +func test_yacht_is_not_a_full_house(solution_script): + var got = solution_script.score([2, 2, 2, 2, 2], solution_script.FULL_HOUSE) + var want = 0 + return [got, want] + + +func test_four_of_a_kind(solution_script): + var got = solution_script.score([6, 6, 4, 6, 6], solution_script.FOUR_OF_A_KIND) + var want = 24 + return [got, want] + + +func test_yacht_can_be_scored_as_four_of_a_kind(solution_script): + var got = solution_script.score([3, 3, 3, 3, 3], solution_script.FOUR_OF_A_KIND) + var want = 12 + return [got, want] + + +func test_full_house_is_not_four_of_a_kind(solution_script): + var got = solution_script.score([3, 3, 3, 5, 5], solution_script.FOUR_OF_A_KIND) + var want = 0 + return [got, want] + + +func test_little_straight(solution_script): + var got = solution_script.score([3, 5, 4, 1, 2], solution_script.LITTLE_STRAIGHT) + var want = 30 + return [got, want] + + +func test_little_straight_as_big_straight(solution_script): + var got = solution_script.score([1, 2, 3, 4, 5], solution_script.BIG_STRAIGHT) + var want = 0 + return [got, want] + + +func test_four_in_order_but_not_a_little_straight(solution_script): + var got = solution_script.score([1, 1, 2, 3, 4], solution_script.LITTLE_STRAIGHT) + var want = 0 + return [got, want] + + +func test_no_pairs_but_not_a_little_straight(solution_script): + var got = solution_script.score([1, 2, 3, 4, 6], solution_script.LITTLE_STRAIGHT) + var want = 0 + return [got, want] + + +func test_minimum_is_1_maximum_is_5_but_not_a_little_straight(solution_script): + var got = solution_script.score([1, 1, 3, 4, 5], solution_script.LITTLE_STRAIGHT) + var want = 0 + return [got, want] + + +func test_big_straight(solution_script): + var got = solution_script.score([4, 6, 2, 5, 3], solution_script.BIG_STRAIGHT) + var want = 30 + return [got, want] + + +func test_big_straight_as_little_straight(solution_script): + var got = solution_script.score([6, 5, 4, 3, 2], solution_script.LITTLE_STRAIGHT) + var want = 0 + return [got, want] + + +func test_no_pairs_but_not_a_big_straight(solution_script): + var got = solution_script.score([6, 5, 4, 3, 1], solution_script.BIG_STRAIGHT) + var want = 0 + return [got, want] + + +func test_choice(solution_script): + var got = solution_script.score([3, 3, 5, 6, 6], solution_script.CHOICE) + var want = 23 + return [got, want] + + +func test_yacht_as_choice(solution_script): + var got = solution_script.score([2, 2, 2, 2, 2], solution_script.CHOICE) + var want = 10 + return [got, want]