just_go 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: 0a20c00410fd18fbc14bb5eb25da67f17868e47c
4
+ data.tar.gz: 6ed1b0d8a6b57cef3128cf22f41c59905da2262f
5
+ SHA512:
6
+ metadata.gz: bc25de5574dfe3faaba8f20b516b82b6b640751692a289479daf4c55a5521d75a3272de80487355f3a34e68e3b49fb2f0bda85cd948431a8f684e917d075de27
7
+ data.tar.gz: a240185c13acb7b34bee290a762555cd039e9e16e9390c848c3896d865fa88da4d7f269802c078eba0f247b58f54b85fac9712fc58b987f3f51a918f9be52b3e
data/.gitignore ADDED
@@ -0,0 +1,11 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /Gemfile.lock
4
+ /_yardoc/
5
+ /coverage/
6
+ /doc/
7
+ /pkg/
8
+ /spec/reports/
9
+ /tmp/
10
+ *.DS_Store
11
+ *.swp
@@ -0,0 +1,74 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ In the interest of fostering an open and welcoming environment, we as
6
+ contributors and maintainers pledge to making participation in our project and
7
+ our community a harassment-free experience for everyone, regardless of age, body
8
+ size, disability, ethnicity, gender identity and expression, level of experience,
9
+ nationality, personal appearance, race, religion, or sexual identity and
10
+ orientation.
11
+
12
+ ## Our Standards
13
+
14
+ Examples of behavior that contributes to creating a positive environment
15
+ include:
16
+
17
+ * Using welcoming and inclusive language
18
+ * Being respectful of differing viewpoints and experiences
19
+ * Gracefully accepting constructive criticism
20
+ * Focusing on what is best for the community
21
+ * Showing empathy towards other community members
22
+
23
+ Examples of unacceptable behavior by participants include:
24
+
25
+ * The use of sexualized language or imagery and unwelcome sexual attention or
26
+ advances
27
+ * Trolling, insulting/derogatory comments, and personal or political attacks
28
+ * Public or private harassment
29
+ * Publishing others' private information, such as a physical or electronic
30
+ address, without explicit permission
31
+ * Other conduct which could reasonably be considered inappropriate in a
32
+ professional setting
33
+
34
+ ## Our Responsibilities
35
+
36
+ Project maintainers are responsible for clarifying the standards of acceptable
37
+ behavior and are expected to take appropriate and fair corrective action in
38
+ response to any instances of unacceptable behavior.
39
+
40
+ Project maintainers have the right and responsibility to remove, edit, or
41
+ reject comments, commits, code, wiki edits, issues, and other contributions
42
+ that are not aligned to this Code of Conduct, or to ban temporarily or
43
+ permanently any contributor for other behaviors that they deem inappropriate,
44
+ threatening, offensive, or harmful.
45
+
46
+ ## Scope
47
+
48
+ This Code of Conduct applies both within project spaces and in public spaces
49
+ when an individual is representing the project or its community. Examples of
50
+ representing a project or community include using an official project e-mail
51
+ address, posting via an official social media account, or acting as an appointed
52
+ representative at an online or offline event. Representation of a project may be
53
+ further defined and clarified by project maintainers.
54
+
55
+ ## Enforcement
56
+
57
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
58
+ reported by contacting the project team at mark@mrlhumphreys.com. All
59
+ complaints will be reviewed and investigated and will result in a response that
60
+ is deemed necessary and appropriate to the circumstances. The project team is
61
+ obligated to maintain confidentiality with regard to the reporter of an incident.
62
+ Further details of specific enforcement policies may be posted separately.
63
+
64
+ Project maintainers who do not follow or enforce the Code of Conduct in good
65
+ faith may face temporary or permanent repercussions as determined by other
66
+ members of the project's leadership.
67
+
68
+ ## Attribution
69
+
70
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
71
+ available at [http://contributor-covenant.org/version/1/4][version]
72
+
73
+ [homepage]: http://contributor-covenant.org
74
+ [version]: http://contributor-covenant.org/version/1/4/
data/Gemfile ADDED
@@ -0,0 +1,6 @@
1
+ source "https://rubygems.org"
2
+
3
+ git_source(:github) {|repo_name| "https://github.com/#{repo_name}" }
4
+
5
+ # Specify your gem's dependencies in just_go.gemspec
6
+ gemspec
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2019 Mark Humphreys
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,85 @@
1
+ # JustGo
2
+
3
+ A go egnine written in ruby. It provides a representation of go game complete with rules enforcement and serialisation.
4
+
5
+ ## Installation
6
+
7
+ Add this line to your application's Gemfile:
8
+
9
+ ```ruby
10
+ gem 'just_go'
11
+ ```
12
+
13
+ And then execute:
14
+
15
+ $ bundle
16
+
17
+ Or install it yourself as:
18
+
19
+ $ gem install just_go
20
+
21
+ ## Usage
22
+
23
+ To start, a new game can be instantiated with the default state:
24
+
25
+ ```ruby
26
+ game_state = JustCheckers::GameState.default
27
+ ```
28
+
29
+ Moves can be made by passing in the player number and the id of the point. It will return true if the move is valid, otherwise it will return false.
30
+
31
+ ```ruby
32
+ game_state.move(1, 63)
33
+ ```
34
+
35
+ Players can pass turn with the pass method, passing in the player number.
36
+
37
+ ```ruby
38
+ game_state.pass(1)
39
+ ```
40
+
41
+ The last change with all its details are found in the `last_change` attribute.
42
+
43
+ ```ruby
44
+ game_state.last_change
45
+ ```
46
+
47
+ If something happens, errors may be found in the errors attribute
48
+
49
+ ```ruby
50
+ game_state.errors
51
+ ```
52
+
53
+ The winner can be found by calling winner on the object
54
+
55
+ ```ruby
56
+ game_state.winner
57
+ ```
58
+
59
+ The score can be obtained through the score method
60
+
61
+ ```ruby
62
+ game_state.score
63
+ ```
64
+
65
+ Also, the game can be serialized into a hash.
66
+
67
+ ```ruby
68
+ game_state.as_json
69
+ ```
70
+
71
+ ## Development
72
+
73
+ After checking out the repo, run `bin/setup` to install dependencies. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
74
+
75
+ ## Contributing
76
+
77
+ Bug reports and pull requests are welcome on GitHub at https://github.com/mrlhumphreys/just_go. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](http://contributor-covenant.org) code of conduct.
78
+
79
+ ## License
80
+
81
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
82
+
83
+ ## Code of Conduct
84
+
85
+ Everyone interacting in the JustGo project’s codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/mrlhumphreys/just_go/blob/master/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,10 @@
1
+ require 'rake/testtask'
2
+ require 'bundler/gem_tasks'
3
+
4
+ Rake::TestTask.new do |t|
5
+ t.libs << 'test'
6
+ t.test_files = FileList['test/just_go/*_test.rb']
7
+ end
8
+
9
+ desc 'run tests'
10
+ task :default => :test
data/bin/console ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "just_go"
5
+
6
+ # You can add fixtures and/or initialization code here to make experimenting
7
+ # with your gem easier. You can also use a different console, if you like.
8
+
9
+ # (If you use this, don't forget to add pry to your Gemfile!)
10
+ # require "pry"
11
+ # Pry.start
12
+
13
+ require "irb"
14
+ 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/just_go.gemspec ADDED
@@ -0,0 +1,31 @@
1
+
2
+ lib = File.expand_path("../lib", __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require "just_go/version"
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "just_go"
8
+ spec.version = JustGo::VERSION
9
+ spec.authors = ["Mark Humphreys"]
10
+ spec.email = ["mark@mrlhumphreys.com"]
11
+
12
+ spec.summary = %q{A go engine written in ruby}
13
+ spec.description = %q{Provides a representation of a go game complete with rules enforcement and serialisation.}
14
+ spec.homepage = "https://github.com/mrlhumphreys/just_go"
15
+ spec.license = "MIT"
16
+
17
+ # Specify which files should be added to the gem when it is released.
18
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
19
+ spec.files = Dir.chdir(File.expand_path('..', __FILE__)) do
20
+ `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
21
+ end
22
+ spec.bindir = "exe"
23
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
24
+ spec.require_paths = ["lib"]
25
+
26
+ spec.required_ruby_version = '>= 2.2'
27
+
28
+ spec.add_development_dependency "bundler", "~> 1.17"
29
+ spec.add_development_dependency "rake", "~> 10.0"
30
+ spec.add_development_dependency 'minitest', '~> 5.8'
31
+ end
@@ -0,0 +1,24 @@
1
+ require 'forwardable'
2
+
3
+ module JustGo
4
+
5
+ # = Chain
6
+ #
7
+ # A collection of Points with stones of the same chain id
8
+ class Chain
9
+ extend Forwardable
10
+
11
+ def initialize(points: [])
12
+ @points = points
13
+ end
14
+
15
+ attr_reader :points
16
+
17
+ def_delegator :points, :include?
18
+
19
+ def player_number
20
+ points.first.stone.player_number
21
+ end
22
+ end
23
+ end
24
+
@@ -0,0 +1,20 @@
1
+ module JustGo
2
+
3
+ # = Error
4
+ #
5
+ # An error with a message
6
+ class Error
7
+
8
+ # New errors can be instantiated with
9
+ #
10
+ # @option [String] message
11
+ # the message to display.
12
+ #
13
+ # ==== Example:
14
+ # # Instantiates a new Error
15
+ # JustGo::Error.new("Custom Message")
16
+ def initialize(message="Generic Error")
17
+ @message = message
18
+ end
19
+ end
20
+ end
@@ -0,0 +1,22 @@
1
+ require 'just_go/errors/error'
2
+
3
+ module JustGo
4
+
5
+ # = KoRuleViolationError
6
+ #
7
+ # A not players turn error with a message
8
+ class KoRuleViolationError < Error
9
+
10
+ # New not players turn errors can be instantiated with
11
+ #
12
+ # @option [String] message
13
+ # the message to display.
14
+ #
15
+ # ==== Example:
16
+ # # Instantiates a new KoRuleViolationError
17
+ # JustGo::KoRuleViolationError.new("Custom Message")
18
+ def initialize(message="Move puts board in previous state")
19
+ super
20
+ end
21
+ end
22
+ end
@@ -0,0 +1,22 @@
1
+ require 'just_go/errors/error'
2
+
3
+ module JustGo
4
+
5
+ # = NoLibertiesError
6
+ #
7
+ # A not players turn error with a message
8
+ class NoLibertiesError < Error
9
+
10
+ # New not players turn errors can be instantiated with
11
+ #
12
+ # @option [String] message
13
+ # the message to display.
14
+ #
15
+ # ==== Example:
16
+ # # Instantiates a new NoLibertiesError
17
+ # JustGo::NoLibertiesError.new("Custom Message")
18
+ def initialize(message="Point has no liberties")
19
+ super
20
+ end
21
+ end
22
+ end
@@ -0,0 +1,22 @@
1
+ require 'just_go/errors/error'
2
+
3
+ module JustGo
4
+
5
+ # = NotPlayersTurnError
6
+ #
7
+ # A not players turn error with a message
8
+ class NotPlayersTurnError < Error
9
+
10
+ # New not players turn errors can be instantiated with
11
+ #
12
+ # @option [String] message
13
+ # the message to display.
14
+ #
15
+ # ==== Example:
16
+ # # Instantiates a new NotPlayersTurnError
17
+ # JustGo::NotPlayersTurnError.new("Custom Message")
18
+ def initialize(message="It is not the player's turn yet.")
19
+ super
20
+ end
21
+ end
22
+ end
@@ -0,0 +1,22 @@
1
+ require 'just_go/errors/error'
2
+
3
+ module JustGo
4
+
5
+ # = PointNotEmptyError
6
+ #
7
+ # A point not empty error with a message
8
+ class PointNotEmptyError < Error
9
+
10
+ # New not players turn errors can be instantiated with
11
+ #
12
+ # @option [String] message
13
+ # the message to display.
14
+ #
15
+ # ==== Example:
16
+ # # Instantiates a new PointNotEmptyError
17
+ # JustGo::PointNotEmptyError.new("Custom Message")
18
+ def initialize(message="Point is not empty")
19
+ super
20
+ end
21
+ end
22
+ end
@@ -0,0 +1,22 @@
1
+ require 'just_go/errors/error'
2
+
3
+ module JustGo
4
+
5
+ # = PointNotFoundError
6
+ #
7
+ # A point not found error with a message
8
+ class PointNotFoundError < Error
9
+
10
+ # New not players turn errors can be instantiated with
11
+ #
12
+ # @option [String] message
13
+ # the message to display.
14
+ #
15
+ # ==== Example:
16
+ # # Instantiates a new PointNotFoundError
17
+ # JustGo::PointNotFoundError.new("Custom Message")
18
+ def initialize(message="Can't find point with that id")
19
+ super
20
+ end
21
+ end
22
+ end
@@ -0,0 +1,147 @@
1
+ require 'just_go/point_set'
2
+ require 'just_go/errors/not_players_turn_error'
3
+ require 'just_go/errors/point_not_empty_error'
4
+ require 'just_go/errors/point_not_found_error'
5
+ require 'just_go/errors/no_liberties_error'
6
+ require 'just_go/errors/ko_rule_violation_error'
7
+
8
+ module JustGo
9
+
10
+ # = Game State
11
+ #
12
+ # Represents a game of Go in progress.
13
+ class GameState
14
+ BOARD_SIZE = 19
15
+
16
+ def initialize(current_player_number: , points: , prisoner_counts: , previous_state: nil, passed: { 0 => false, 1 => false })
17
+ @current_player_number = current_player_number
18
+ @points = JustGo::PointSet.new(points: points)
19
+ @prisoner_counts = prisoner_counts
20
+ @previous_state = previous_state
21
+ @passed = passed
22
+ @errors = []
23
+ @last_change = {}
24
+ end
25
+
26
+ attr_reader :current_player_number
27
+ attr_reader :points
28
+ attr_reader :prisoner_counts
29
+ attr_reader :previous_state
30
+ attr_reader :passed
31
+ attr_reader :errors
32
+ attr_reader :last_change
33
+
34
+ def self.default
35
+ self.new(
36
+ current_player_number: 1,
37
+ points: BOARD_SIZE.times.map do |row|
38
+ BOARD_SIZE.times.map do |col|
39
+ {
40
+ id: row*BOARD_SIZE + col,
41
+ x: col,
42
+ y: row,
43
+ stone: nil
44
+ }
45
+ end
46
+ end.flatten,
47
+ prisoner_counts: {
48
+ 1 => 0,
49
+ 2 => 0,
50
+ },
51
+ previous_state: nil
52
+ )
53
+ end
54
+
55
+ def as_json
56
+ {
57
+ current_player_number: current_player_number,
58
+ points: points.as_json,
59
+ prisoner_counts: prisoner_counts,
60
+ previous_state: previous_state
61
+ }
62
+ end
63
+
64
+ def move(player_number, point_id)
65
+ @errors = []
66
+
67
+ point = points.find_by_id(point_id)
68
+
69
+ if current_player_number != player_number
70
+ @errors.push JustGo::NotPlayersTurnError.new
71
+ elsif point.nil?
72
+ @errors.push JustGo::PointNotFoundError.new
73
+ elsif point.occupied?
74
+ @errors.push JustGo::PointNotEmptyError.new
75
+ elsif points.liberties_for(point).zero? && points.deprives_liberties?(point, player_number) && !points.deprives_opponents_liberties?(point, player_number)
76
+ @errors.push JustGo::NoLibertiesError.new
77
+ else
78
+ dupped = points.dup
79
+ dupped.perform_move(point, player_number)
80
+
81
+ if dupped.minify == @previous_state
82
+ @errors.push JustGo::KoRuleViolationError.new
83
+ else
84
+ @passed[next_player_number] = false
85
+
86
+ @previous_state = points.minify
87
+
88
+ stone_count = points.perform_move(point, player_number)
89
+
90
+ @prisoner_counts[player_number] += stone_count
91
+
92
+ pass_turn
93
+ end
94
+ end
95
+
96
+ errors.empty?
97
+ end
98
+
99
+ def pass(player_number)
100
+ if current_player_number != player_number
101
+ @errors.push JustGo::NotPlayersTurnError.new
102
+ else
103
+ @passed[player_number] = true
104
+ if @passed[next_player_number]
105
+ points.mark_territories
106
+ else
107
+ pass_turn
108
+ end
109
+ end
110
+
111
+ errors.empty?
112
+ end
113
+
114
+ def score
115
+ {
116
+ 1 => player_score(1),
117
+ 2 => player_score(2)
118
+ }
119
+ end
120
+
121
+ def winner
122
+ if @passed.values.all?
123
+ score.max_by { |_player, score| score }.first
124
+ else
125
+ nil
126
+ end
127
+ end
128
+
129
+ private
130
+
131
+ def player_score(player_number)
132
+ @prisoner_counts[player_number] + territory_count(player_number)
133
+ end
134
+
135
+ def territory_count(player_number)
136
+ points.territories_for(player_number).sum(&:size)
137
+ end
138
+
139
+ def pass_turn
140
+ @current_player_number = next_player_number
141
+ end
142
+
143
+ def next_player_number
144
+ current_player_number == 1 ? 2 : 1
145
+ end
146
+ end
147
+ end
@@ -0,0 +1,83 @@
1
+ require 'just_go/stone'
2
+
3
+ module JustGo
4
+
5
+ # = Point
6
+ #
7
+ # A Point on a go board
8
+ class Point
9
+ def initialize(id: , x: , y: , stone: , territory_id: nil)
10
+ @id = id
11
+ @x = x
12
+ @y = y
13
+ @stone = case stone
14
+ when JustGo::Stone
15
+ stone
16
+ when Hash
17
+ JustGo::Stone.new(stone)
18
+ when nil
19
+ stone
20
+ else
21
+ raise ArgumentError, "stone must be Stone, Hash or nil"
22
+ end
23
+ @territory_id = territory_id
24
+ end
25
+
26
+ attr_reader :id
27
+ attr_reader :x
28
+ attr_reader :y
29
+ attr_reader :stone
30
+ attr_reader :territory_id
31
+
32
+ def as_json
33
+ _stone = stone ? stone.as_json : nil
34
+ {
35
+ id: id,
36
+ x: x,
37
+ y: y,
38
+ stone: _stone,
39
+ territory_id: territory_id
40
+ }
41
+ end
42
+
43
+ def ==(other)
44
+ self.id == other.id
45
+ end
46
+
47
+ def occupied?
48
+ !stone.nil?
49
+ end
50
+
51
+ def unoccupied?
52
+ stone.nil?
53
+ end
54
+
55
+ def occupied_by?(player_number)
56
+ !stone.nil? && stone.player_number == player_number
57
+ end
58
+
59
+ def occupied_by_opponent?(player_number)
60
+ !stone.nil? && stone.player_number != player_number
61
+ end
62
+
63
+ def unmarked?
64
+ territory_id.nil?
65
+ end
66
+
67
+ def place(s)
68
+ @stone = s
69
+ end
70
+
71
+ def capture_stone
72
+ @stone = nil
73
+ end
74
+
75
+ def add_to_territory(t_id)
76
+ @territory_id = t_id
77
+ end
78
+
79
+ def clear_territory
80
+ @territory_id = nil
81
+ end
82
+ end
83
+ end
@@ -0,0 +1,248 @@
1
+ require 'forwardable'
2
+ require 'just_go/point'
3
+ require 'just_go/chain'
4
+ require 'just_go/territory'
5
+
6
+ module JustGo
7
+
8
+ # = PointSet
9
+ #
10
+ # A collection of Points with useful filtering functions
11
+ class PointSet
12
+ extend Forwardable
13
+
14
+ def initialize(points: [])
15
+ @points = case
16
+ when !points.is_a?(Array)
17
+ raise ArgumentError, 'points must be an array of Hash or Point'
18
+ when points.all? { |p| p.is_a?(Hash) }
19
+ points.map { |p| JustGo::Point.new(p) }
20
+ when points.all? { |p| p.is_a?(JustGo::Point) }
21
+ points
22
+ else
23
+ raise ArgumentError, 'points must be an array of Hash or Point'
24
+ end
25
+ end
26
+
27
+ attr_reader :points
28
+
29
+ def_delegator :points, :find
30
+ def_delegator :points, :map
31
+ def_delegator :points, :each
32
+ def_delegator :points, :size
33
+ def_delegator :points, :all?
34
+
35
+ def as_json
36
+ points.map(&:as_json)
37
+ end
38
+
39
+ def select(&block)
40
+ _points = points.select(&block)
41
+ self.class.new(points: _points)
42
+ end
43
+
44
+ def find_by_id(point_id)
45
+ find { |p| p.id == point_id }
46
+ end
47
+
48
+ def occupied
49
+ select(&:occupied?)
50
+ end
51
+
52
+ def unoccupied
53
+ select(&:unoccupied?)
54
+ end
55
+
56
+ def occupied_by(player_number)
57
+ select { |p| p.occupied_by?(player_number) }
58
+ end
59
+
60
+ def occupied_by_opponent(player_number)
61
+ select { |p| p.occupied_by_opponent?(player_number) }
62
+ end
63
+
64
+ def adjacent(point_or_group)
65
+ case point_or_group
66
+ when JustGo::Point
67
+ select do |p|
68
+ vector = Vector.new(point_or_group, p)
69
+ vector.orthogonal? && vector.magnitude == 1
70
+ end
71
+ when JustGo::Chain
72
+ _points = point_or_group.points.map do |p|
73
+ adjacent(p).points
74
+ end.flatten.reject do |p|
75
+ point_or_group.include?(p)
76
+ end.uniq do |p|
77
+ p.id
78
+ end
79
+
80
+ self.class.new(points: _points)
81
+ when JustGo::Territory
82
+ _points = point_or_group.points.map do |p|
83
+ adjacent(p).points
84
+ end.flatten.reject do |p|
85
+ point_or_group.include?(p)
86
+ end.uniq do |p|
87
+ p.id
88
+ end
89
+
90
+ self.class.new(points: _points)
91
+ else
92
+ raise ArgumentError, 'Must be Point or Chain or Territory'
93
+ end
94
+ end
95
+
96
+ def where(args)
97
+ scope = self
98
+ args.each do |field, value|
99
+ scope = scope.select do |p|
100
+ case value
101
+ when Array
102
+ value.include?(p.send(field))
103
+ else
104
+ p.send(field) == value
105
+ end
106
+ end
107
+ end
108
+ scope
109
+ end
110
+
111
+ def chains(chain_ids=nil)
112
+ if chain_ids
113
+ chain_ids.map do |c_id|
114
+ _points = select { |p| p.stone && p.stone.chain_id == c_id }.points
115
+ JustGo::Chain.new(points: _points)
116
+ end
117
+ else
118
+ all_chain_ids = select { |p| p.stone }.map { |p| p.stone.chain_id }.uniq
119
+ chains(all_chain_ids)
120
+ end
121
+ end
122
+
123
+ def territories(territory_ids=nil)
124
+ if territory_ids
125
+ territory_ids.map do |t_id|
126
+ _points = select { |p| p.territory_id == t_id }.points
127
+ JustGo::Territory.new(points: _points)
128
+ end
129
+ else
130
+ all_territory_ids = select(&:territory_id).map(&:territory_id).uniq
131
+ territories(all_territory_ids)
132
+ end
133
+ end
134
+
135
+ def territories_for(player_number)
136
+ territories.select { |t| adjacent(t).all? { |p| p.occupied_by?(player_number) } }
137
+ end
138
+
139
+ def liberties_for(point_or_chain)
140
+ adjacent(point_or_chain).unoccupied.size
141
+ end
142
+
143
+ def deprives_liberties?(point, player_number)
144
+ chain_ids = adjacent(point).occupied_by(player_number).map { |p| p.stone.chain_id }.uniq
145
+ _chains = chains(chain_ids)
146
+ _chains.all? { |c| liberties_for(c) == 1 }
147
+ end
148
+
149
+ def deprives_opponents_liberties?(point, player_number)
150
+ chain_ids = adjacent(point).occupied_by_opponent(player_number).map { |p| p.stone.chain_id }.uniq
151
+ _chains = chains(chain_ids)
152
+ _chains.any? { |c| liberties_for(c) == 1 }
153
+ end
154
+
155
+ def update_joined_chains(point_id, player_number)
156
+ point = find_by_id(point_id)
157
+ existing_chain_ids = adjacent(point).occupied_by(player_number).map { |p| p.stone.chain_id }.uniq
158
+ existing_chains = chains(existing_chain_ids)
159
+
160
+ existing_chains.each do |c|
161
+ c.points.each do |p|
162
+ p.stone.join_chain(point.stone)
163
+ end
164
+ end
165
+ end
166
+
167
+ def capture_stones(player_number)
168
+ stone_count = 0
169
+
170
+ chains.select do |c|
171
+ c.player_number != player_number && liberties_for(c) == 0
172
+ end.each do |c|
173
+ c.points.each do |p|
174
+ p.capture_stone
175
+ stone_count += 1
176
+ end
177
+ end
178
+
179
+ stone_count
180
+ end
181
+
182
+ def minify
183
+ points.map do |p|
184
+ player_number = p.stone && p.stone.player_number
185
+ player_number ? player_number.to_s : '-'
186
+ end.join
187
+ end
188
+
189
+ def place(point_id, stone)
190
+ point = find_by_id(point_id)
191
+ point.place(stone)
192
+ end
193
+
194
+ def next_stone_id
195
+ (occupied.map { |p| p.stone.id }.max || 0) + 1
196
+ end
197
+
198
+ def adjacent_chain_id(point, player_number)
199
+ adjacent(point).occupied_by(player_number).map { |p| p.stone.chain_id }.first
200
+ end
201
+
202
+ def next_chain_id
203
+ (occupied.map { |p| p.stone.chain_id }.max || 0) + 1
204
+ end
205
+
206
+ def build_stone(point, player_number)
207
+ JustGo::Stone.new(
208
+ id: next_stone_id,
209
+ player_number: player_number,
210
+ chain_id: adjacent_chain_id(point, player_number) || next_chain_id
211
+ )
212
+ end
213
+
214
+ def perform_move(point, player_number)
215
+ stone = build_stone(point, player_number)
216
+ place(point.id, stone)
217
+ update_joined_chains(point.id, player_number)
218
+ capture_stones(player_number)
219
+ end
220
+
221
+ def dup
222
+ self.class.new(points: as_json)
223
+ end
224
+
225
+ def mark_territories
226
+ points.each(&:clear_territory)
227
+ points.each do |point|
228
+ if point.unoccupied? && point.unmarked?
229
+ territory_ids = adjacent(point).unoccupied.map(&:territory_id).compact
230
+ add_territory_id = case territory_ids.size
231
+ when 0
232
+ (points.map(&:territory_id).compact.max || 0) + 1
233
+ when 1
234
+ territory_ids.first
235
+ else
236
+ min_id, *other_ids = territory_ids.sort
237
+ where(territory_id: other_ids).each do |other_point|
238
+ other_point.add_to_territory(min_id)
239
+ end
240
+ min_id
241
+ end
242
+
243
+ point.add_to_territory(add_territory_id)
244
+ end
245
+ end
246
+ end
247
+ end
248
+ end
@@ -0,0 +1,29 @@
1
+ module JustGo
2
+
3
+ # = Stone
4
+ #
5
+ # A stone that is placed on the board.
6
+ class Stone
7
+ def initialize(id: , player_number: , chain_id: nil)
8
+ @id = id
9
+ @player_number = player_number
10
+ @chain_id = chain_id
11
+ end
12
+
13
+ attr_reader :id
14
+ attr_reader :player_number
15
+ attr_reader :chain_id
16
+
17
+ def as_json
18
+ {
19
+ id: id,
20
+ player_number: player_number,
21
+ chain_id: chain_id
22
+ }
23
+ end
24
+
25
+ def join_chain(stone)
26
+ @chain_id = stone.chain_id
27
+ end
28
+ end
29
+ end
@@ -0,0 +1,23 @@
1
+ require 'forwardable'
2
+
3
+ module JustGo
4
+
5
+ # = Territory
6
+ #
7
+ # A collection of Points with the same territory id
8
+ class Territory
9
+ extend Forwardable
10
+
11
+ def initialize(points: [])
12
+ @points = points
13
+ end
14
+
15
+ attr_reader :points
16
+
17
+ def_delegator :points, :include?
18
+ def_delegator :points, :size
19
+
20
+ end
21
+ end
22
+
23
+
@@ -0,0 +1,25 @@
1
+ module JustGo
2
+ Vector = Struct.new(:origin, :destination) do
3
+ def magnitude
4
+ if dx.abs == 0
5
+ dy.abs
6
+ elsif dy.abs == 0
7
+ dx.abs
8
+ else
9
+ nil
10
+ end
11
+ end
12
+
13
+ def orthogonal?
14
+ dx == 0 || dy == 0
15
+ end
16
+
17
+ def dx
18
+ destination.x - origin.x
19
+ end
20
+
21
+ def dy
22
+ destination.y - origin.y
23
+ end
24
+ end
25
+ end
@@ -0,0 +1,4 @@
1
+ module JustGo
2
+ # :nodoc:
3
+ VERSION = "0.1.0"
4
+ end
data/lib/just_go.rb ADDED
@@ -0,0 +1,6 @@
1
+ require "just_go/version"
2
+
3
+ # :nodoc:
4
+ module JustGo
5
+
6
+ end
metadata ADDED
@@ -0,0 +1,111 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: just_go
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Mark Humphreys
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2019-07-08 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: bundler
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '1.17'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '1.17'
27
+ - !ruby/object:Gem::Dependency
28
+ name: rake
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '10.0'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '10.0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: minitest
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '5.8'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '5.8'
55
+ description: Provides a representation of a go game complete with rules enforcement
56
+ and serialisation.
57
+ email:
58
+ - mark@mrlhumphreys.com
59
+ executables: []
60
+ extensions: []
61
+ extra_rdoc_files: []
62
+ files:
63
+ - ".gitignore"
64
+ - CODE_OF_CONDUCT.md
65
+ - Gemfile
66
+ - LICENSE.txt
67
+ - README.md
68
+ - Rakefile
69
+ - bin/console
70
+ - bin/setup
71
+ - just_go.gemspec
72
+ - lib/just_go.rb
73
+ - lib/just_go/chain.rb
74
+ - lib/just_go/errors/error.rb
75
+ - lib/just_go/errors/ko_rule_violation_error.rb
76
+ - lib/just_go/errors/no_liberties_error.rb
77
+ - lib/just_go/errors/not_players_turn_error.rb
78
+ - lib/just_go/errors/point_not_empty_error.rb
79
+ - lib/just_go/errors/point_not_found_error.rb
80
+ - lib/just_go/game_state.rb
81
+ - lib/just_go/point.rb
82
+ - lib/just_go/point_set.rb
83
+ - lib/just_go/stone.rb
84
+ - lib/just_go/territory.rb
85
+ - lib/just_go/vector.rb
86
+ - lib/just_go/version.rb
87
+ homepage: https://github.com/mrlhumphreys/just_go
88
+ licenses:
89
+ - MIT
90
+ metadata: {}
91
+ post_install_message:
92
+ rdoc_options: []
93
+ require_paths:
94
+ - lib
95
+ required_ruby_version: !ruby/object:Gem::Requirement
96
+ requirements:
97
+ - - ">="
98
+ - !ruby/object:Gem::Version
99
+ version: '2.2'
100
+ required_rubygems_version: !ruby/object:Gem::Requirement
101
+ requirements:
102
+ - - ">="
103
+ - !ruby/object:Gem::Version
104
+ version: '0'
105
+ requirements: []
106
+ rubyforge_project:
107
+ rubygems_version: 2.6.11
108
+ signing_key:
109
+ specification_version: 4
110
+ summary: A go engine written in ruby
111
+ test_files: []