mastermind_generator 0.0.1.pre.pre.alpha

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 0b37d479689687d682817b6be649134828be6f5c06c8924c31e04808cbd39593
4
+ data.tar.gz: b4877a03cf8323951a705643f8a7c1b5dcaf4198028e69ad38ad0fa716992bba
5
+ SHA512:
6
+ metadata.gz: 55c912aaf50dd9c4cfa42b9e3782c5d1c9d1263cfab49957c13a43e3692783eeb12ac9799581e0050d6f879bca0fced7dee6cffa4a790a8d258e717c27a6fae2
7
+ data.tar.gz: 319c2edd011d3cf3e1659d061d215b40fe2e28326f0eb301459ae32151df339ac0a04332d89956a6dd4d1ecb253f36aa7b3d8d5ac06f61ddb7b6307d89735b96
data/.gitignore ADDED
@@ -0,0 +1,10 @@
1
+ *.gem
2
+ /.bundle/
3
+ /.yardoc
4
+ /_yardoc/
5
+ /coverage/
6
+ /doc/
7
+ /pkg/
8
+ /spec/reports/
9
+ /tmp/
10
+ /.idea/
data/.rubocop.yml ADDED
@@ -0,0 +1,15 @@
1
+ AllCops:
2
+ TargetRubyVersion: 3.0
3
+ NewCops: enable
4
+ SuggestExtensions: false
5
+
6
+ Style/StringLiterals:
7
+ Enabled: true
8
+ EnforcedStyle: double_quotes
9
+
10
+ Style/StringLiteralsInInterpolation:
11
+ Enabled: true
12
+ EnforcedStyle: double_quotes
13
+
14
+ Layout/LineLength:
15
+ Max: 120
data/.travis.yml ADDED
@@ -0,0 +1,6 @@
1
+ ---
2
+ language: ruby
3
+ cache: bundler
4
+ rvm:
5
+ - 3.0.0
6
+ before_install: gem install bundler -v 2.2.8
@@ -0,0 +1,84 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ 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, religion, or sexual identity and orientation.
6
+
7
+ We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
8
+
9
+ ## Our Standards
10
+
11
+ Examples of behavior that contributes to a positive environment for our community include:
12
+
13
+ * Demonstrating empathy and kindness toward other people
14
+ * Being respectful of differing opinions, viewpoints, and experiences
15
+ * Giving and gracefully accepting constructive feedback
16
+ * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
17
+ * Focusing on what is best not just for us as individuals, but for the overall community
18
+
19
+ Examples of unacceptable behavior include:
20
+
21
+ * The use of sexualized language or imagery, and sexual attention or
22
+ advances of any kind
23
+ * Trolling, insulting or derogatory comments, and personal or political attacks
24
+ * Public or private harassment
25
+ * Publishing others' private information, such as a physical or email
26
+ address, without their explicit permission
27
+ * Other conduct which could reasonably be considered inappropriate in a
28
+ professional setting
29
+
30
+ ## Enforcement Responsibilities
31
+
32
+ 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.
33
+
34
+ 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.
35
+
36
+ ## Scope
37
+
38
+ 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.
39
+
40
+ ## Enforcement
41
+
42
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at sbagdat@gmail.com. All complaints will be reviewed and investigated promptly and fairly.
43
+
44
+ All community leaders are obligated to respect the privacy and security of the reporter of any incident.
45
+
46
+ ## Enforcement Guidelines
47
+
48
+ Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
49
+
50
+ ### 1. Correction
51
+
52
+ **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
53
+
54
+ **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.
55
+
56
+ ### 2. Warning
57
+
58
+ **Community Impact**: A violation through a single incident or series of actions.
59
+
60
+ **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.
61
+
62
+ ### 3. Temporary Ban
63
+
64
+ **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
65
+
66
+ **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.
67
+
68
+ ### 4. Permanent Ban
69
+
70
+ **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.
71
+
72
+ **Consequence**: A permanent ban from any sort of public interaction within the community.
73
+
74
+ ## Attribution
75
+
76
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
77
+ available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
78
+
79
+ Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
80
+
81
+ [homepage]: https://www.contributor-covenant.org
82
+
83
+ For answers to common questions about this code of conduct, see the FAQ at
84
+ https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
data/Gemfile ADDED
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ source "https://rubygems.org"
4
+
5
+ gemspec
6
+
7
+ gem "minitest", "~> 5.14.3"
8
+ gem "minitest-reporters", ">= 0.5.0"
9
+ gem "rake", "~> 13.0"
10
+ gem "rubocop", "~> 1.8.1"
11
+ gem "rubocop-minitest", "~> 0.10.3"
12
+ gem "simplecov", "~> 0.21.2"
data/Gemfile.lock ADDED
@@ -0,0 +1,62 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ mastermind_generator (0.0.1.pre.pre.alpha)
5
+
6
+ GEM
7
+ remote: https://rubygems.org/
8
+ specs:
9
+ ansi (1.5.0)
10
+ ast (2.4.2)
11
+ builder (3.2.4)
12
+ docile (1.3.5)
13
+ minitest (5.14.4)
14
+ minitest-reporters (1.4.3)
15
+ ansi
16
+ builder
17
+ minitest (>= 5.0)
18
+ ruby-progressbar
19
+ parallel (1.20.1)
20
+ parser (3.0.0.0)
21
+ ast (~> 2.4.1)
22
+ rainbow (3.0.0)
23
+ rake (13.0.3)
24
+ regexp_parser (2.1.1)
25
+ rexml (3.2.4)
26
+ rubocop (1.8.1)
27
+ parallel (~> 1.10)
28
+ parser (>= 3.0.0.0)
29
+ rainbow (>= 2.2.2, < 4.0)
30
+ regexp_parser (>= 1.8, < 3.0)
31
+ rexml
32
+ rubocop-ast (>= 1.2.0, < 2.0)
33
+ ruby-progressbar (~> 1.7)
34
+ unicode-display_width (>= 1.4.0, < 3.0)
35
+ rubocop-ast (1.4.1)
36
+ parser (>= 2.7.1.5)
37
+ rubocop-minitest (0.10.3)
38
+ rubocop (>= 0.87, < 2.0)
39
+ ruby-progressbar (1.11.0)
40
+ simplecov (0.21.2)
41
+ docile (~> 1.1)
42
+ simplecov-html (~> 0.11)
43
+ simplecov_json_formatter (~> 0.1)
44
+ simplecov-html (0.12.3)
45
+ simplecov_json_formatter (0.1.2)
46
+ unicode-display_width (2.0.0)
47
+
48
+ PLATFORMS
49
+ x86_64-darwin-20
50
+ x86_64-linux
51
+
52
+ DEPENDENCIES
53
+ mastermind_generator!
54
+ minitest (~> 5.14.3)
55
+ minitest-reporters (>= 0.5.0)
56
+ rake (~> 13.0)
57
+ rubocop (~> 1.8.1)
58
+ rubocop-minitest (~> 0.10.3)
59
+ simplecov (~> 0.21.2)
60
+
61
+ BUNDLED WITH
62
+ 2.2.5
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2021 Sıtkı Bağdat
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,43 @@
1
+ # MastermindGenerator
2
+
3
+ Welcome to your new gem! In this directory, you'll find the files you need to be able to package up your Ruby library into a gem. Put your Ruby code in the file `lib/mastermind_generator`. To experiment with that code, run `bin/console` for an interactive prompt.
4
+
5
+ TODO: Delete this and the text above, and describe your gem
6
+
7
+ ## Installation
8
+
9
+ Add this line to your application's Gemfile:
10
+
11
+ ```ruby
12
+ gem 'mastermind_generator'
13
+ ```
14
+
15
+ And then execute:
16
+
17
+ $ bundle install
18
+
19
+ Or install it yourself as:
20
+
21
+ $ gem install mastermind_generator
22
+
23
+ ## Usage
24
+
25
+ TODO: Write usage instructions here
26
+
27
+ ## Development
28
+
29
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake test` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
30
+
31
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org).
32
+
33
+ ## Contributing
34
+
35
+ Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/mastermind_generator. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/[USERNAME]/mastermind_generator/blob/master/CODE_OF_CONDUCT.md).
36
+
37
+ ## License
38
+
39
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
40
+
41
+ ## Code of Conduct
42
+
43
+ Everyone interacting in the MastermindGenerator project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/[USERNAME]/mastermind_generator/blob/master/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,16 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rake/testtask"
5
+
6
+ Rake::TestTask.new(:test) do |t|
7
+ t.libs << "test"
8
+ t.libs << "lib"
9
+ t.test_files = FileList["test/**/*_test.rb"]
10
+ end
11
+
12
+ require "rubocop/rake_task"
13
+
14
+ RuboCop::RakeTask.new
15
+
16
+ task default: %i[test rubocop]
data/bin/console ADDED
@@ -0,0 +1,15 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require "bundler/setup"
5
+ require "mastermind_generator"
6
+
7
+ # You can add fixtures and/or initialization code here to make experimenting
8
+ # with your gem easier. You can also use a different console, if you like.
9
+
10
+ # (If you use this, don't forget to add pry to your Gemfile!)
11
+ # require "pry"
12
+ # Pry.start
13
+
14
+ require "irb"
15
+ IRB.start(__FILE__)
data/bin/setup ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
data/demo/.rubocop.yml ADDED
@@ -0,0 +1,18 @@
1
+ AllCops:
2
+ TargetRubyVersion: 3.0
3
+ NewCops: enable
4
+ SuggestExtensions: false
5
+ Exclude:
6
+ - '**/*_test.rb'
7
+ - '**/factories/*s.rb'
8
+
9
+ Style/StringLiterals:
10
+ Enabled: true
11
+ EnforcedStyle: double_quotes
12
+
13
+ Style/StringLiteralsInInterpolation:
14
+ Enabled: true
15
+ EnforcedStyle: double_quotes
16
+
17
+ Layout/LineLength:
18
+ Max: 120
data/demo/Gemfile ADDED
@@ -0,0 +1,11 @@
1
+ # frozen_string_literal: true
2
+
3
+ source "https://rubygems.org"
4
+
5
+ gem "mastermind_generator"
6
+ gem "minitest", ">=5.14.3"
7
+ gem "minitest-reporters", ">= 0.5.0"
8
+ gem "rake", ">=13.0.3"
9
+ gem "rubocop", ">=1.8.1"
10
+ gem "rubocop-minitest", ">=0.10.3"
11
+ gem "simplecov", ">=0.21.2"
data/demo/Gemfile.lock ADDED
@@ -0,0 +1,57 @@
1
+ GEM
2
+ remote: https://rubygems.org/
3
+ specs:
4
+ ansi (1.5.0)
5
+ ast (2.4.2)
6
+ builder (3.2.4)
7
+ docile (1.3.5)
8
+ mastermind_generator (0.0.1.pre.pre.alpha)
9
+ minitest (5.14.4)
10
+ minitest-reporters (1.4.3)
11
+ ansi
12
+ builder
13
+ minitest (>= 5.0)
14
+ ruby-progressbar
15
+ parallel (1.20.1)
16
+ parser (3.0.0.0)
17
+ ast (~> 2.4.1)
18
+ rainbow (3.0.0)
19
+ rake (13.0.3)
20
+ regexp_parser (2.1.1)
21
+ rexml (3.2.4)
22
+ rubocop (1.11.0)
23
+ parallel (~> 1.10)
24
+ parser (>= 3.0.0.0)
25
+ rainbow (>= 2.2.2, < 4.0)
26
+ regexp_parser (>= 1.8, < 3.0)
27
+ rexml
28
+ rubocop-ast (>= 1.2.0, < 2.0)
29
+ ruby-progressbar (~> 1.7)
30
+ unicode-display_width (>= 1.4.0, < 3.0)
31
+ rubocop-ast (1.4.1)
32
+ parser (>= 2.7.1.5)
33
+ rubocop-minitest (0.10.3)
34
+ rubocop (>= 0.87, < 2.0)
35
+ ruby-progressbar (1.11.0)
36
+ simplecov (0.21.2)
37
+ docile (~> 1.1)
38
+ simplecov-html (~> 0.11)
39
+ simplecov_json_formatter (~> 0.1)
40
+ simplecov-html (0.12.3)
41
+ simplecov_json_formatter (0.1.2)
42
+ unicode-display_width (2.0.0)
43
+
44
+ PLATFORMS
45
+ x86_64-darwin-20
46
+
47
+ DEPENDENCIES
48
+ mastermind_generator
49
+ minitest (>= 5.14.3)
50
+ minitest-reporters (>= 0.5.0)
51
+ rake (>= 13.0.3)
52
+ rubocop (>= 1.8.1)
53
+ rubocop-minitest (>= 0.10.3)
54
+ simplecov (>= 0.21.2)
55
+
56
+ BUNDLED WITH
57
+ 2.2.5
data/demo/README.md ADDED
@@ -0,0 +1 @@
1
+ # Demo
data/demo/Rakefile ADDED
@@ -0,0 +1,14 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "rake/testtask"
4
+ require "rubocop/rake_task"
5
+
6
+ Rake::TestTask.new do |t|
7
+ t.libs << "test"
8
+ t.libs << "lib"
9
+ t.test_files = FileList["test/**/*_test.rb"]
10
+ end
11
+
12
+ RuboCop::RakeTask.new
13
+
14
+ task default: %i[test rubocop]
@@ -0,0 +1,141 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "mastermind_generator"
4
+ require_relative "mastermind/mg_configuration"
5
+ require_relative "mastermind/console_interface"
6
+
7
+ # Mastermind game
8
+ class Mastermind
9
+ include MastermindGenerator
10
+
11
+ def initialize
12
+ @cli = ConsoleInterface.new
13
+ @game = nil
14
+ end
15
+
16
+ def play
17
+ welcome
18
+ action = ask_what_you_want
19
+ perform(action)
20
+ end
21
+
22
+ private
23
+
24
+ attr_reader :cli, :difficulty, :game
25
+
26
+ def perform(action)
27
+ exit if %w[q quit].include?(action)
28
+
29
+ if %w[i instructions].include?(action)
30
+ instructions
31
+ elsif %w[p play].include?(action)
32
+ start_the_game
33
+ else
34
+ raise ArgumentError, "Wrong option selected: #{action}"
35
+ end
36
+ end
37
+
38
+ def ask_for_play_again
39
+ cli.ask_question("Do you want to (p)lay again or (q)uit?")
40
+ cli.answer
41
+ end
42
+
43
+ def start_the_game
44
+ loop do
45
+ @game = Game.new(ask_for_difficulty)
46
+ how_to_play
47
+ add_players
48
+ game_loop
49
+ break if %w[q quit].include?(ask_for_play_again)
50
+ end
51
+ end
52
+
53
+ def game_loop
54
+ loop do
55
+ take_a_guess
56
+ if game.finished?
57
+ congrats
58
+ break
59
+ else
60
+ feedback
61
+ end
62
+ game.next_turn if game.players.length > 1
63
+ end
64
+ end
65
+
66
+ def feedback
67
+ stats = player.guess.statistics
68
+ cli.print_message("'#{stats[:value].upcase}' has #{stats[:element_count]} of the correct elements with "\
69
+ " #{stats[:position_count]} in the correct positions.\nYou've taken #{stats[:count]} guess.")
70
+ end
71
+
72
+ def congrats
73
+ player = game.player
74
+ cli.print_message("Congratulations #{player.name}! You guessed the sequence '#{game.sequence.value.upcase}' in "\
75
+ "#{player.guesses.length} guesses over #{player.timer.duration_as_text}.")
76
+ end
77
+
78
+ def take_a_guess
79
+ cli.ask_question("Hey #{game.player.name}! What's your guess?")
80
+ begin
81
+ game.take_a_guess(cli.answer)
82
+ rescue SequenceTooLongError, SequenceTooShortError, SequenceHasInvalidCharsError => e
83
+ cli.print_message("#{e.message}. Try again!")
84
+ retry
85
+ end
86
+ end
87
+
88
+ def welcome
89
+ cli.print_message("Welcome to MASTERMIND\n")
90
+ end
91
+
92
+ def ask_what_you_want
93
+ cli.ask_question("Would you like to (p)lay, read the (i)nstructions, or (q)uit?")
94
+ cli.answer
95
+ end
96
+
97
+ def ask_for_difficulty
98
+ cli.ask_question("Choose difficulty level: (b)eginner, (i)ntermediate, (a)dvanced.")
99
+ answer = cli.answer
100
+ { "b" => :beginner, "i" => :intermediate, "a" => :advanced }[answer[0]]
101
+ end
102
+
103
+ def how_to_play
104
+ dif = game.difficulty
105
+ cli.print_message(
106
+ "I have generated #{sequence_type(dif.level)} with #{dif.sequence_length} elements made up "\
107
+ "of: #{printable_item_list}. Use (q)uit at any time to end the game."
108
+ )
109
+ end
110
+
111
+ def add_players
112
+ players_count = 0
113
+ loop do
114
+ cli.ask_question("How many players will play [1 or 2].")
115
+ players_count = cli.answer.to_i
116
+ break if players_count.between?(1, 2)
117
+ end
118
+ players_count.times do
119
+ cli.ask_question("Enter player name.")
120
+ game.add_player(cli.answer)
121
+ end
122
+ end
123
+
124
+ def instructions
125
+ cli.print_message("Instructions will be here!")
126
+ end
127
+
128
+ def sequence_type(difficulty_level)
129
+ "a#{"n" if difficulty_level != :beginner} #{difficulty_level} sequence"
130
+ end
131
+
132
+ def printable_item_list
133
+ item_list = game.sequence.items.map { printable_item_name(_1) }
134
+ "#{item_list[..-2].join(", ")}, and #{item_list.last}"
135
+ end
136
+
137
+ def printable_item_name(item)
138
+ value = item.value
139
+ "(#{value[0]})#{value[1..]}"
140
+ end
141
+ end
@@ -0,0 +1,23 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Console interface for input/output to ask questions and get answers
4
+ class ConsoleInterface
5
+ attr_reader :input, :output
6
+
7
+ def initialize(input: $stdin, output: $stdout)
8
+ @input = input
9
+ @output = output
10
+ end
11
+
12
+ def print_message(message)
13
+ output.puts message
14
+ end
15
+
16
+ def ask_question(question)
17
+ output.print "#{question}\n> "
18
+ end
19
+
20
+ def answer
21
+ input.gets.strip.downcase
22
+ end
23
+ end
@@ -0,0 +1,10 @@
1
+ # frozen_string_literal: true
2
+
3
+ MastermindGenerator.configure do |config|
4
+ config.items = %w[red green blue yellow purple orange]
5
+ config.difficulties = {
6
+ beginner: { item_count: 4, sequence_length: 4 },
7
+ intermediate: { item_count: 5, sequence_length: 6 },
8
+ advanced: { item_count: 6, sequence_length: 8 }
9
+ }
10
+ end
@@ -0,0 +1,39 @@
1
+ require 'stringio'
2
+ require './test/test_helper'
3
+ require 'mastermind/console_interface'
4
+
5
+ class ConsoleInterfaceTest < MiniTest::Test
6
+
7
+ def test_it_exists
8
+ console_interface = ConsoleInterface.new
9
+
10
+ assert_instance_of ConsoleInterface, console_interface
11
+ end
12
+
13
+ def test_it_can_print_a_message
14
+ output = StringIO.new
15
+ console_interface = ConsoleInterface.new(output: output)
16
+ message = 'Hello'
17
+
18
+ console_interface.print_message(message)
19
+
20
+ assert_match(/#{message}/, output.string)
21
+ end
22
+
23
+ def test_it_can_ask_a_question
24
+ output = StringIO.new
25
+ console_interface = ConsoleInterface.new(output: output)
26
+ question = 'Would you like to continue'
27
+
28
+ console_interface.ask_question(question)
29
+
30
+ assert_match(/Would you like to continue/, output.string)
31
+ end
32
+
33
+ def test_it_can_get_answer
34
+ input = StringIO.new('input')
35
+ console_interface = ConsoleInterface.new(input: input)
36
+
37
+ assert_equal 'input', console_interface.answer
38
+ end
39
+ end
@@ -0,0 +1,11 @@
1
+ # frozen_string_literal: true
2
+
3
+ $LOAD_PATH.unshift File.expand_path("../lib", __dir__)
4
+
5
+ require "simplecov"
6
+ SimpleCov.start
7
+
8
+ require "minitest/autorun"
9
+ require "minitest/unit"
10
+ require "mocha/minitest"
11
+ require "minitest/pride"
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require "mastermind_generator"
@@ -0,0 +1,17 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "mastermind_generator/version"
4
+ require_relative "mastermind_generator/configuration"
5
+ require_relative "mastermind_generator/item"
6
+ require_relative "mastermind_generator/difficulty"
7
+ require_relative "mastermind_generator/sequence"
8
+ require_relative "mastermind_generator/guess"
9
+ require_relative "mastermind_generator/player"
10
+ require_relative "mastermind_generator/sequence_generator"
11
+ require_relative "mastermind_generator/helpers/time_helpers"
12
+ require_relative "mastermind_generator/timer"
13
+ require_relative "mastermind_generator/game"
14
+
15
+ # Mastermind generator module
16
+ module MastermindGenerator
17
+ end
@@ -0,0 +1,28 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Mastermind generator module
4
+ module MastermindGenerator
5
+ # Configuration for the gem
6
+ class Configuration
7
+ attr_accessor :items, :difficulties
8
+
9
+ def initialize
10
+ @items = nil
11
+ @difficulties = nil
12
+ end
13
+ end
14
+
15
+ class << self
16
+ def configuration
17
+ @configuration ||= Configuration.new
18
+ end
19
+
20
+ def reset
21
+ @configuration = Configuration.new
22
+ end
23
+
24
+ def configure
25
+ yield configuration
26
+ end
27
+ end
28
+ end
@@ -0,0 +1,21 @@
1
+ # frozen_string_literal: true
2
+
3
+ module MastermindGenerator
4
+ # Exception for passing invalid difficulty value as an argument to `Difficulty.new`
5
+ class InvalidDifficultyError < StandardError; end
6
+
7
+ # Reprsents difficulty of the game
8
+ # It affects of how many items will be used for secret sequences
9
+ class Difficulty
10
+ attr_reader :level, :item_count, :sequence_length
11
+
12
+ def initialize(level)
13
+ valid_difficulties = MastermindGenerator.configuration.difficulties
14
+ raise InvalidDifficultyError unless valid_difficulties.key?(level)
15
+
16
+ @level = level
17
+ @item_count = valid_difficulties.dig(level, :item_count)
18
+ @sequence_length = valid_difficulties.dig(level, :sequence_length)
19
+ end
20
+ end
21
+ end
@@ -0,0 +1,51 @@
1
+ # frozen_string_literal: true
2
+
3
+ module MastermindGenerator
4
+ # Mastermind game class
5
+ class Game
6
+ attr_reader :difficulty, :sequence, :players
7
+
8
+ def initialize(difficulty)
9
+ @difficulty = Difficulty.new(difficulty)
10
+ @sequence = SequenceGenerator.new(@difficulty).generate
11
+ @players = []
12
+ @turn_counter = 1
13
+ end
14
+
15
+ def take_a_guess(value)
16
+ seq = Sequence.new(difficulty, value)
17
+ guess = Guess.new(seq)
18
+ player.timer.start
19
+ player.take_a_guess(guess)
20
+ player.guess.assign_target(sequence)
21
+ end
22
+
23
+ def player
24
+ return players.first if players.length == 1
25
+
26
+ @turn_counter.odd? ? players.first : players.last
27
+ end
28
+
29
+ def add_player(player_name)
30
+ return if players.length > 1
31
+
32
+ players << Player.new(player_name)
33
+ end
34
+
35
+ def finished?
36
+ return false unless player.guess.succeed?
37
+
38
+ player.timer.stop
39
+ true
40
+ end
41
+
42
+ def winner
43
+ player if finished?
44
+ end
45
+
46
+ def next_turn
47
+ player.timer.pause
48
+ @turn_counter += 1
49
+ end
50
+ end
51
+ end
@@ -0,0 +1,51 @@
1
+ # frozen_string_literal: true
2
+
3
+ module MastermindGenerator
4
+ # Responsible for guessing
5
+ class Guess
6
+ attr_reader :sequence, :target
7
+
8
+ def initialize(sequence)
9
+ @sequence = sequence
10
+ @target = nil
11
+ end
12
+
13
+ def assign_target(target)
14
+ @target = target
15
+ end
16
+
17
+ def succeed?
18
+ target == sequence
19
+ end
20
+
21
+ def correct_element_count
22
+ sequence.codes.reduce(0) { |sum, code| sum + [target.value.count(code), sequence.value.count(code)].min }
23
+ end
24
+
25
+ def correct_position_count
26
+ seuence_target_packs.count { _1 == _2 }
27
+ end
28
+
29
+ def correct_position_hints
30
+ seuence_target_packs.map { _1 == _2 ? _1 : "_" }.join
31
+ end
32
+
33
+ def statistics
34
+ {
35
+ value: sequence.value,
36
+ target: target&.value.to_s,
37
+ status: succeed? ? "success" : "fail",
38
+ count: guesses.length,
39
+ element_count: correct_element_count,
40
+ position_count: correct_position_count,
41
+ position_hints: correct_position_hints
42
+ }
43
+ end
44
+
45
+ private
46
+
47
+ def seuence_target_packs
48
+ sequence.value.chars.zip(target.value.chars)
49
+ end
50
+ end
51
+ end
@@ -0,0 +1,35 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Contains helper method related to written time
4
+ module TimeHelpers
5
+ private
6
+
7
+ def time_in_writing(seconds)
8
+ seconds = seconds.to_i
9
+ [hours_in_writting(seconds), minutes_in_writting(seconds), seconds_in_writting(seconds)].compact.join(", ")
10
+ end
11
+
12
+ def hours_in_writting(seconds)
13
+ hours = seconds / 3600
14
+ return nil if hours.zero?
15
+ return "an hour" if hours == 1
16
+
17
+ "#{hours} hours"
18
+ end
19
+
20
+ def minutes_in_writting(seconds)
21
+ minutes = (seconds % 3600) / 60
22
+ return nil if minutes.zero?
23
+ return "a minute" if minutes == 1
24
+
25
+ "#{minutes} minutes"
26
+ end
27
+
28
+ def seconds_in_writting(seconds)
29
+ seconds = seconds % 60
30
+ return nil if seconds.zero?
31
+ return "a second" if seconds == 1
32
+
33
+ "#{seconds} seconds"
34
+ end
35
+ end
@@ -0,0 +1,29 @@
1
+ # frozen_string_literal: true
2
+
3
+ module MastermindGenerator
4
+ # Respresents single Item object
5
+ # - item name
6
+ # - code(first char of item name)
7
+ # - input_code (using for asking guess)
8
+ class Item
9
+ attr_reader :value
10
+
11
+ # Item.new('blue') # => <#... @value='blue'>
12
+ # Item.new('green') # => <#... @value='green'>
13
+ #
14
+ # Creates a new +Item+ object and return it.
15
+ #
16
+ # @param [String] value
17
+ def initialize(value)
18
+ @value = value
19
+ end
20
+
21
+ # item = Item.new('red')
22
+ # item.code # => 'r'
23
+ #
24
+ # Returns first character of +item.value+
25
+ def code
26
+ value[0]
27
+ end
28
+ end
29
+ end
@@ -0,0 +1,26 @@
1
+ # frozen_string_literal: true
2
+
3
+ module MastermindGenerator
4
+ # Player
5
+ class Player
6
+ attr_reader :name, :guesses, :timer
7
+
8
+ def initialize(name)
9
+ @name = name
10
+ @guesses = []
11
+ @timer = Timer.new
12
+ end
13
+
14
+ def take_a_guess(guess)
15
+ guesses.prepend(guess)
16
+ end
17
+
18
+ def guess
19
+ guesses.first
20
+ end
21
+
22
+ def winner?
23
+ guess.succeed?
24
+ end
25
+ end
26
+ end
@@ -0,0 +1,68 @@
1
+ # frozen_string_literal: true
2
+
3
+ module MastermindGenerator
4
+ # Raises if sequence lentgh is too short
5
+ class SequenceTooShortError < StandardError
6
+ def message
7
+ "Sequence is too short"
8
+ end
9
+ end
10
+
11
+ # Raises if sequence lentgh is too long
12
+ class SequenceTooLongError < StandardError
13
+ def message
14
+ "Sequence is too long"
15
+ end
16
+ end
17
+
18
+ # Raises if sequence has invalid characters in it
19
+ class SequenceHasInvalidCharsError < StandardError
20
+ def message
21
+ "Sequence has invalid characters in it"
22
+ end
23
+ end
24
+
25
+ # Respresents valid sequence that created according to difficulty level
26
+ class Sequence
27
+ attr_reader :items, :value, :difficulty
28
+
29
+ def initialize(difficulty, value)
30
+ @difficulty = difficulty
31
+ @items = MastermindGenerator
32
+ .configuration
33
+ .items[..difficulty.item_count - 1]
34
+ .map { Item.new(_1) }
35
+ @value = validate(value)
36
+ end
37
+
38
+ def codes
39
+ items.map(&:code)
40
+ end
41
+
42
+ def ==(other)
43
+ value == other.value
44
+ end
45
+
46
+ private
47
+
48
+ def validate(value)
49
+ raise(SequenceTooLongError) if long?(value)
50
+ raise(SequenceTooShortError) if short?(value)
51
+ raise(SequenceHasInvalidCharsError) if contains_invalid_chars?(value)
52
+
53
+ value
54
+ end
55
+
56
+ def contains_invalid_chars?(value)
57
+ value.chars.any? { !codes.include?(_1) }
58
+ end
59
+
60
+ def short?(value)
61
+ value.length < difficulty.sequence_length
62
+ end
63
+
64
+ def long?(value)
65
+ value.length > difficulty.sequence_length
66
+ end
67
+ end
68
+ end
@@ -0,0 +1,17 @@
1
+ # frozen_string_literal: true
2
+
3
+ module MastermindGenerator
4
+ # Responsible for creating random sequences
5
+ class SequenceGenerator
6
+ def initialize(difficulty)
7
+ @difficulty = difficulty
8
+ end
9
+
10
+ def generate
11
+ value = Array.new(@difficulty.sequence_length).map do
12
+ MastermindGenerator.configuration.items[..@difficulty.item_count - 1].sample[0]
13
+ end.join
14
+ Sequence.new(@difficulty, value)
15
+ end
16
+ end
17
+ end
@@ -0,0 +1,37 @@
1
+ # frozen_string_literal: true
2
+
3
+ module MastermindGenerator
4
+ # Exception for ending timer without starting it before
5
+ class TimerNotStartedError < StandardError; end
6
+
7
+ # A simple timer
8
+ # Calculates the time between start and end times
9
+ class Timer
10
+ include TimeHelpers
11
+
12
+ def start
13
+ @stop_time = nil
14
+ @start_time ||= Time.new # rubocop:disable Naming/MemoizedInstanceVariableName
15
+ end
16
+
17
+ def stop
18
+ raise TimerNotStartedError unless start_time
19
+
20
+ self.stop_time = Time.new
21
+ end
22
+
23
+ alias pause stop
24
+
25
+ def duration
26
+ stop_time - start_time
27
+ end
28
+
29
+ def duration_as_text
30
+ time_in_writing(stop_time - start_time)
31
+ end
32
+
33
+ private
34
+
35
+ attr_accessor :start_time, :stop_time
36
+ end
37
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module MastermindGenerator
4
+ VERSION = "0.0.1.pre-alpha"
5
+ end
@@ -0,0 +1,27 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "./lib/mastermind_generator/version"
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = "mastermind_generator"
7
+ spec.version = MastermindGenerator::VERSION
8
+ spec.authors = ["Sıtkı Bağdat"]
9
+ spec.email = ["sbagdat@gmail.com"]
10
+
11
+ spec.summary = "Mastermind game generator API"
12
+ spec.description = "Mastermind game generator API"
13
+ spec.homepage = "https://github.com/sbagdat/mastermind_generator"
14
+ spec.license = "MIT"
15
+ spec.required_ruby_version = Gem::Requirement.new(">= 3.0.0")
16
+
17
+ spec.metadata["homepage_uri"] = spec.homepage
18
+ spec.metadata["source_code_uri"] = spec.homepage
19
+ spec.metadata["changelog_uri"] = "https://github.com/sbagdat/mastermind_generator/blob/main/CHANGELOG.md"
20
+
21
+ spec.files = Dir.chdir(File.expand_path(__dir__)) do
22
+ `git ls-files -z`.split("\x0").reject { |f| f.match(%r{\A(?:test|spec|features)/}) }
23
+ end
24
+ spec.bindir = "exe"
25
+ spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) }
26
+ spec.require_paths = ["lib"]
27
+ end
metadata ADDED
@@ -0,0 +1,82 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: mastermind_generator
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.0.1.pre.pre.alpha
5
+ platform: ruby
6
+ authors:
7
+ - Sıtkı Bağdat
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2021-03-12 00:00:00.000000000 Z
12
+ dependencies: []
13
+ description: Mastermind game generator API
14
+ email:
15
+ - sbagdat@gmail.com
16
+ executables:
17
+ - mastermind_generator
18
+ extensions: []
19
+ extra_rdoc_files: []
20
+ files:
21
+ - ".gitignore"
22
+ - ".rubocop.yml"
23
+ - ".travis.yml"
24
+ - CODE_OF_CONDUCT.md
25
+ - Gemfile
26
+ - Gemfile.lock
27
+ - LICENSE.txt
28
+ - README.md
29
+ - Rakefile
30
+ - bin/console
31
+ - bin/setup
32
+ - demo/.rubocop.yml
33
+ - demo/Gemfile
34
+ - demo/Gemfile.lock
35
+ - demo/README.md
36
+ - demo/Rakefile
37
+ - demo/lib/mastermind.rb
38
+ - demo/lib/mastermind/console_interface.rb
39
+ - demo/lib/mastermind/mg_configuration.rb
40
+ - demo/test/console_interface_test.rb
41
+ - demo/test/test_helper.rb
42
+ - exe/mastermind_generator
43
+ - lib/mastermind_generator.rb
44
+ - lib/mastermind_generator/configuration.rb
45
+ - lib/mastermind_generator/difficulty.rb
46
+ - lib/mastermind_generator/game.rb
47
+ - lib/mastermind_generator/guess.rb
48
+ - lib/mastermind_generator/helpers/time_helpers.rb
49
+ - lib/mastermind_generator/item.rb
50
+ - lib/mastermind_generator/player.rb
51
+ - lib/mastermind_generator/sequence.rb
52
+ - lib/mastermind_generator/sequence_generator.rb
53
+ - lib/mastermind_generator/timer.rb
54
+ - lib/mastermind_generator/version.rb
55
+ - mastermind_generator.gemspec
56
+ homepage: https://github.com/sbagdat/mastermind_generator
57
+ licenses:
58
+ - MIT
59
+ metadata:
60
+ homepage_uri: https://github.com/sbagdat/mastermind_generator
61
+ source_code_uri: https://github.com/sbagdat/mastermind_generator
62
+ changelog_uri: https://github.com/sbagdat/mastermind_generator/blob/main/CHANGELOG.md
63
+ post_install_message:
64
+ rdoc_options: []
65
+ require_paths:
66
+ - lib
67
+ required_ruby_version: !ruby/object:Gem::Requirement
68
+ requirements:
69
+ - - ">="
70
+ - !ruby/object:Gem::Version
71
+ version: 3.0.0
72
+ required_rubygems_version: !ruby/object:Gem::Requirement
73
+ requirements:
74
+ - - ">"
75
+ - !ruby/object:Gem::Version
76
+ version: 1.3.1
77
+ requirements: []
78
+ rubygems_version: 3.2.5
79
+ signing_key:
80
+ specification_version: 4
81
+ summary: Mastermind game generator API
82
+ test_files: []