From 6db0a1da7d7fef5d5beab223976afecc9c19c851 Mon Sep 17 00:00:00 2001 From: KimMead Date: Sun, 6 Jun 2021 18:03:30 -0500 Subject: [PATCH] Done. --- .gitignore | 90 ++-- .learn | 32 +- .rspec | 4 +- Gemfile | 12 +- Gemfile.lock | 68 ++-- README.md | 290 ++++++------- RUBRIC.md | 12 +- bin/tictactoe | 6 +- config/environment.rb | 8 +- lib/board.rb | 53 +++ lib/game.rb | 77 ++++ lib/player.rb | 7 + lib/players/computer.rb | 27 ++ lib/players/human.rb | 9 + spec/01_board_spec.rb | 256 ++++++------ spec/02_player_spec.rb | 42 +- spec/03_human_player_spec.rb | 36 +- spec/04_game_spec.rb | 702 ++++++++++++++++---------------- spec/05_computer_player_spec.rb | 40 +- spec/spec_helper.rb | 74 ++-- 20 files changed, 1009 insertions(+), 836 deletions(-) diff --git a/.gitignore b/.gitignore index 377a2ed208a..db38eeb577d 100644 --- a/.gitignore +++ b/.gitignore @@ -1,45 +1,45 @@ -# Created by https://www.gitignore.io/api/node - -.DS_Store - -### Node ### -# Logs -logs -*.log -npm-debug.log* - -# Runtime data -pids -*.pid -*.seed - -# Directory for instrumented libs generated by jscoverage/JSCover -lib-cov - -# Compiled binary addons (http://nodejs.org/api/addons.html) -build/Release - -# Dependency directories -node_modules -jspm_packages - -# Optional npm cache directory -.npm - -# Optional REPL history -.node_repl_history - -# Learn-specific .results.json -.results.json - -# Ignore bundler config. -/.bundle - -# Ignore the default SQLite database. -/db/*.sqlite3 -/db/*.sqlite3-journal - -# Ignore all logfiles and tempfiles. -/log/* -!/log/.keep -/tmp +# Created by https://www.gitignore.io/api/node + +.DS_Store + +### Node ### +# Logs +logs +*.log +npm-debug.log* + +# Runtime data +pids +*.pid +*.seed + +# Directory for instrumented libs generated by jscoverage/JSCover +lib-cov + +# Compiled binary addons (http://nodejs.org/api/addons.html) +build/Release + +# Dependency directories +node_modules +jspm_packages + +# Optional npm cache directory +.npm + +# Optional REPL history +.node_repl_history + +# Learn-specific .results.json +.results.json + +# Ignore bundler config. +/.bundle + +# Ignore the default SQLite database. +/db/*.sqlite3 +/db/*.sqlite3-journal + +# Ignore all logfiles and tempfiles. +/log/* +!/log/.keep +/tmp diff --git a/.learn b/.learn index a3d56843d9c..9bb8d4b9834 100644 --- a/.learn +++ b/.learn @@ -1,16 +1,16 @@ -tags: - - project - - OO - - AI - - TTT -languages: - - ruby -resources: -project: - review_criteria: - - All tests pass - - 0 player mode works - - 1 player mode works - - 2 player mode works - - Game is playable via CLI - - AI is able to play with some strategy +tags: + - project + - OO + - AI + - TTT +languages: + - ruby +resources: +project: + review_criteria: + - All tests pass + - 0 player mode works + - 1 player mode works + - 2 player mode works + - Game is playable via CLI + - AI is able to play with some strategy diff --git a/.rspec b/.rspec index 83e16f80447..2d868da82fb 100644 --- a/.rspec +++ b/.rspec @@ -1,2 +1,2 @@ ---color ---require spec_helper +--color +--require spec_helper diff --git a/Gemfile b/Gemfile index 6834358a53d..74e4acaf002 100644 --- a/Gemfile +++ b/Gemfile @@ -1,6 +1,6 @@ -# A sample Gemfile -source "https://rubygems.org" - -gem 'rspec' -gem 'pry' -gem 'require_all' +# A sample Gemfile +source "https://rubygems.org" + +gem 'rspec' +gem 'pry' +gem 'require_all' diff --git a/Gemfile.lock b/Gemfile.lock index c66f69eb343..1f0bb3b839a 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -1,34 +1,34 @@ -GEM - remote: https://rubygems.org/ - specs: - coderay (1.1.2) - diff-lcs (1.3) - method_source (0.9.2) - pry (0.12.2) - coderay (~> 1.1.0) - method_source (~> 0.9.0) - require_all (2.0.0) - rspec (3.8.0) - rspec-core (~> 3.8.0) - rspec-expectations (~> 3.8.0) - rspec-mocks (~> 3.8.0) - rspec-core (3.8.0) - rspec-support (~> 3.8.0) - rspec-expectations (3.8.2) - diff-lcs (>= 1.2.0, < 2.0) - rspec-support (~> 3.8.0) - rspec-mocks (3.8.0) - diff-lcs (>= 1.2.0, < 2.0) - rspec-support (~> 3.8.0) - rspec-support (3.8.0) - -PLATFORMS - ruby - -DEPENDENCIES - pry - require_all - rspec - -BUNDLED WITH - 2.0.1 +GEM + remote: https://rubygems.org/ + specs: + coderay (1.1.2) + diff-lcs (1.3) + method_source (0.9.2) + pry (0.12.2) + coderay (~> 1.1.0) + method_source (~> 0.9.0) + require_all (2.0.0) + rspec (3.8.0) + rspec-core (~> 3.8.0) + rspec-expectations (~> 3.8.0) + rspec-mocks (~> 3.8.0) + rspec-core (3.8.0) + rspec-support (~> 3.8.0) + rspec-expectations (3.8.2) + diff-lcs (>= 1.2.0, < 2.0) + rspec-support (~> 3.8.0) + rspec-mocks (3.8.0) + diff-lcs (>= 1.2.0, < 2.0) + rspec-support (~> 3.8.0) + rspec-support (3.8.0) + +PLATFORMS + ruby + +DEPENDENCIES + pry + require_all + rspec + +BUNDLED WITH + 2.1.4 diff --git a/README.md b/README.md index f554cb60b17..1a963e89cac 100644 --- a/README.md +++ b/README.md @@ -1,145 +1,145 @@ -# Tic-tac-toe with AI - -## Objectives -1. Build a command-line interface (CLI). -2. Create a domain model with multiple relating and collaborating objects. - -## Overview -The goal of this project is to build a version of Tic-tac-toe with 0-, 1-, and 2-player modes: - - A 0-player game has two computer players playing against each other with no interaction from the user. - - A 1-player game has a human playing against a computer. - - A 2-player game has two human players. - -You'll be implementing Tic-tac-toe using multiple objects that relate and collaborate, including separate classes for human players and computer players. The computer player class will have some sort of artificial intelligence or logic to make move decisions. Finally, you'll wrap all of this up in a CLI. - -> **BE CAREFUL** While you _might_ be able to re-use some of your code that worked in previous labs, the expectations in _this_ lab are higher! This is true to real-life development as well: as our programs get more sophisticated, the code we used to rely on is no longer appropriate. - -## Working together -Working on a software project with another person is not something to be taken lightly. While you are a fantastic solo coder, software development is often a collaborative activity. Just like anything else, there is skill in collaborating on code. In the end, collaborating with another person boils down to three different styles: - - - Pair - Pair the entire time working linearly together - - Pass - Each person completes 1 requirement and then passes the project to the other person - - Parallel - work on different parts at the same time by agreeing on interfaces and stubs and meeting in the middle - - Person A codes the board and the human player class - - Person B creates the game engine, expecting a working board and player with stubs - - Person A creates the computer player - - Work together on the AI (It's hard) - -Remember! The goal at The Flatiron School is not to do, it is to *learn*. Make sure you have worked in all three styles of collaboration. We want you to learn how the different styles work. The most important part is that together you and your partner understand every piece of the code. - -## Requirements -- Passing Unit Tests -- 0, 1, or 2 player Tic-tac-toe. -- Command Line Interface -- Computer AI - -## Project Structure -``` -├── Gemfile -├── Gemfile.lock -├── README.md -├── Rakefile -├── bin -│   └── tictactoe -├── config -│   └── environment.rb -├── lib - ├── players -    ├── computer.rb -    └── human.rb - ├── board.rb - ├── game.rb -    └── player.rb -└── spec - ├── 01_board_spec.rb - ├── 02_player_spec.rb - ├── 03_human_player_spec.rb - ├── 04_game_spec.rb - ├── 05_computer_player_spec.rb - └── spec_helper.rb -``` - -#### `Gemfile` and `config/environment.rb` -This project is supported by Bundler and includes a `Gemfile`. - -Run `bundle install` before getting started on the project. - -As this project has quite a few files, an `environment.rb` is included that loads all the code in your project along with Bundler. You do not ever need to edit this file. When you see `require_relative '../config/environment'`, as in `bin/tictactoe`, that is how your environment and code are loaded. - -#### `lib` - Tic-tac-toe models -You will be implementing Tic-tac-toe through a domain model that uses multiple classes to encapsulate the different logical components and units in Tic-tac-toe. - -##### `board.rb` - `Board` -The `Board` class represents the data and logic of a Tic-tac-toe game board. It has a property, `cells`, that stores the data of the state of the board in an array. The `#reset!` method can reset the state of the cells to what a board should look like at the start of a game, an array with 9 `" "` elements. - -When a board is initialized, it should start with cells for a new game of Tic-tac-toe. You can and should use `#reset!`. - -A board can print its current state with the `#display` method. - -You'll also build a `#position` method that takes in the user's input in the form of 1-9 strings like "2" or "9" and looks up the value of the cells at the correct index from the array's perspective. All other methods will take input in the user's perspective of 1-9 strings and use `#position` to look up the value according to the cells' array index. - -Similarly, you're going to build an `#update` method that represents updating the board when a player makes a move. This method will take two arguments, the first will be the position the user wants to occupy in the form of 1-9 strings that you will need to convert to the board cells' array index, along with the player object making the move. When you update the appropriate index in the cells, you will set it equal to the token of the player object by calling the `#token` method on the player. - -Finally, a board can return values based on its state such as `#full?` when entirely occupied with "X" and "O"s and a `#turn_count` based on how many positions in the cells array are filled. `#taken?` will return true or false for an individual position. `#valid_move?` will ensure that moves are between 1-9 and not taken. - -##### `player.rb` - `Player` -The `Player` class is not actually a valid player of Tic-tac-toe but rather a root class that will act as an inheritance point for actual player classes such as `Human < Player` and `Computer < Player`. The `Player` root class will define only the most basic properties of a player, that they have a `token` property that can be set upon initialization. - -Every player subclass will implement a `#move` method that represents how that type of player makes a move in Tic-tac-toe. - -##### 'players/human.rb' - `Players::Human` -Define a class `Human` that inherits from `Player`. This class should be namespaced inside the module `Players` because the `human.rb` file is inside the `players/` directory. This keeps our code nice and tidy. - -The human player must implement a `#move` method that takes in a `board` argument and allows a human player to enter a move via the CLI. The method should return the value the user enters. Even though the method accepts a `board` argument, it does not need to use it. - ->Note on namespacing: You'll notice here that if we do `Players::Human < Player` our inheritance won't function properly. This is because the `Players` module is not yet defined. So to do this, we'll need to do: -```ruby -module Players - class Human < Player - # your code here - end -end -``` -Now when you call your Human class, you'll have to call it inside its name space with `Players::Human`. - -##### `game.rb` - `Game` -The `Game` class is the main model of the application and represents a singular instance of a Tic-tac-toe session. - - * A game has one `Board` through its `board` property. - * A game has two `Player`s stored in a `player_1` and `player_2` property. - -`Board` and `Player` do not directly relate to the `Game` but do collaborate with each other through arguments. - -Beyond providing relationships with players and a board, the `Game` instance must also provide the basic game runtime and logic. These methods relate to the state of the game such as `#current_player`, `#won?`, and `#winner`. The other methods relate to managing a game, like `#start`, `#play`, and `#turn`. The test suite describes the method requirements. - -##### 'players/computer.rb' - `Players::Computer` -Define a class `Players::Computer` that represents a computer player of Tic-tac-toe. Implement a `#move` method that accepts a board and returns the move the computer wants to make in the form of a 1-9 string. How the computer decides to make that move is up to you but it must be capable of returning a valid move at some point. - -```ruby -def move(board) - "1" -end -``` - -Returns a valid move for the first move but after that your program will go into an infinite loop because the computer will constantly try to occupy the `"1"` position in the board even though it is already occupied. So don't do that. - -Think about the levels of intelligence you can build into this method. Start with the simplest level of intelligence, and get more and more complicated. Each step of the way you should have a working computer player though. - -Remember, Tic-tac-toe when played perfectly is unwinnable. You should strive to build computer logic that when the computer plays, the game is unwinnable. You can hardcode your logic, things like "On turn 1 always try to go in the middle if you can" and if not "try to go in a corner" or any logic tree you can think of - there is an algorithm called Min/Max, but it's going to be hard to implement given our current implementation of a Game, so we recommend building something that's a more colloquial or condition-based algorithm. - -#### `bin/tictactoe` -The requirements of your CLI are as follows, free for you to implement however you see fit as we provide no tests against the CLI. - - * Greet the user with a message. - * Prompt the user for what kind of game they want to play, 0,1, or 2 player. - * Ask the user for who should go first and be "X". - * Use the input to correctly initialize a `Game` with the appropriate player types and token values. - * When the game is over, the CLI should prompt the user if they would like to play again and allow them to choose a new configuration for the game as described above. If the user doesn't want to play again, exit the program. - -You can implement this logic within the `bin/tictactoe` directly or encapsulate it within `Game` via a method like `#start` and simply evoke that method in the CLI. There is no wrong way to implement code that works. - -If you'd like, implement a "wargames" game type. When asked what kind of game they want to play or for the number of players, if the user types in "wargames", have the computer play itself 100 times and report how many times the game was won. This is not a requirement, it would just be fun. A perfect computer AI should never be able to win, like in the case of thermonuclear war. - -The rest is up to you and your team. Have fun, implement the spirit of the project, meet the requirements as you interpret them, be creative, and don't worry, there are no wrong answers with code. - -

View Tic-tac-toe with AI on Learn.co and start learning to code for free.

+# Tic-tac-toe with AI + +## Objectives +1. Build a command-line interface (CLI). +2. Create a domain model with multiple relating and collaborating objects. + +## Overview +The goal of this project is to build a version of Tic-tac-toe with 0-, 1-, and 2-player modes: + - A 0-player game has two computer players playing against each other with no interaction from the user. + - A 1-player game has a human playing against a computer. + - A 2-player game has two human players. + +You'll be implementing Tic-tac-toe using multiple objects that relate and collaborate, including separate classes for human players and computer players. The computer player class will have some sort of artificial intelligence or logic to make move decisions. Finally, you'll wrap all of this up in a CLI. + +> **BE CAREFUL** While you _might_ be able to re-use some of your code that worked in previous labs, the expectations in _this_ lab are higher! This is true to real-life development as well: as our programs get more sophisticated, the code we used to rely on is no longer appropriate. + +## Working together +Working on a software project with another person is not something to be taken lightly. While you are a fantastic solo coder, software development is often a collaborative activity. Just like anything else, there is skill in collaborating on code. In the end, collaborating with another person boils down to three different styles: + + - Pair - Pair the entire time working linearly together + - Pass - Each person completes 1 requirement and then passes the project to the other person + - Parallel - work on different parts at the same time by agreeing on interfaces and stubs and meeting in the middle + - Person A codes the board and the human player class + - Person B creates the game engine, expecting a working board and player with stubs + - Person A creates the computer player + - Work together on the AI (It's hard) + +Remember! The goal at The Flatiron School is not to do, it is to *learn*. Make sure you have worked in all three styles of collaboration. We want you to learn how the different styles work. The most important part is that together you and your partner understand every piece of the code. + +## Requirements +- Passing Unit Tests +- 0, 1, or 2 player Tic-tac-toe. +- Command Line Interface +- Computer AI + +## Project Structure +``` +├── Gemfile +├── Gemfile.lock +├── README.md +├── Rakefile +├── bin +│   └── tictactoe +├── config +│   └── environment.rb +├── lib + ├── players +    ├── computer.rb +    └── human.rb + ├── board.rb + ├── game.rb +    └── player.rb +└── spec + ├── 01_board_spec.rb + ├── 02_player_spec.rb + ├── 03_human_player_spec.rb + ├── 04_game_spec.rb + ├── 05_computer_player_spec.rb + └── spec_helper.rb +``` + +#### `Gemfile` and `config/environment.rb` +This project is supported by Bundler and includes a `Gemfile`. + +Run `bundle install` before getting started on the project. + +As this project has quite a few files, an `environment.rb` is included that loads all the code in your project along with Bundler. You do not ever need to edit this file. When you see `require_relative '../config/environment'`, as in `bin/tictactoe`, that is how your environment and code are loaded. + +#### `lib` - Tic-tac-toe models +You will be implementing Tic-tac-toe through a domain model that uses multiple classes to encapsulate the different logical components and units in Tic-tac-toe. + +##### `board.rb` - `Board` +The `Board` class represents the data and logic of a Tic-tac-toe game board. It has a property, `cells`, that stores the data of the state of the board in an array. The `#reset!` method can reset the state of the cells to what a board should look like at the start of a game, an array with 9 `" "` elements. + +When a board is initialized, it should start with cells for a new game of Tic-tac-toe. You can and should use `#reset!`. + +A board can print its current state with the `#display` method. + +You'll also build a `#position` method that takes in the user's input in the form of 1-9 strings like "2" or "9" and looks up the value of the cells at the correct index from the array's perspective. All other methods will take input in the user's perspective of 1-9 strings and use `#position` to look up the value according to the cells' array index. + +Similarly, you're going to build an `#update` method that represents updating the board when a player makes a move. This method will take two arguments, the first will be the position the user wants to occupy in the form of 1-9 strings that you will need to convert to the board cells' array index, along with the player object making the move. When you update the appropriate index in the cells, you will set it equal to the token of the player object by calling the `#token` method on the player. + +Finally, a board can return values based on its state such as `#full?` when entirely occupied with "X" and "O"s and a `#turn_count` based on how many positions in the cells array are filled. `#taken?` will return true or false for an individual position. `#valid_move?` will ensure that moves are between 1-9 and not taken. + +##### `player.rb` - `Player` +The `Player` class is not actually a valid player of Tic-tac-toe but rather a root class that will act as an inheritance point for actual player classes such as `Human < Player` and `Computer < Player`. The `Player` root class will define only the most basic properties of a player, that they have a `token` property that can be set upon initialization. + +Every player subclass will implement a `#move` method that represents how that type of player makes a move in Tic-tac-toe. + +##### 'players/human.rb' - `Players::Human` +Define a class `Human` that inherits from `Player`. This class should be namespaced inside the module `Players` because the `human.rb` file is inside the `players/` directory. This keeps our code nice and tidy. + +The human player must implement a `#move` method that takes in a `board` argument and allows a human player to enter a move via the CLI. The method should return the value the user enters. Even though the method accepts a `board` argument, it does not need to use it. + +>Note on namespacing: You'll notice here that if we do `Players::Human < Player` our inheritance won't function properly. This is because the `Players` module is not yet defined. So to do this, we'll need to do: +```ruby +module Players + class Human < Player + # your code here + end +end +``` +Now when you call your Human class, you'll have to call it inside its name space with `Players::Human`. + +##### `game.rb` - `Game` +The `Game` class is the main model of the application and represents a singular instance of a Tic-tac-toe session. + + * A game has one `Board` through its `board` property. + * A game has two `Player`s stored in a `player_1` and `player_2` property. + +`Board` and `Player` do not directly relate to the `Game` but do collaborate with each other through arguments. + +Beyond providing relationships with players and a board, the `Game` instance must also provide the basic game runtime and logic. These methods relate to the state of the game such as `#current_player`, `#won?`, and `#winner`. The other methods relate to managing a game, like `#start`, `#play`, and `#turn`. The test suite describes the method requirements. + +##### 'players/computer.rb' - `Players::Computer` +Define a class `Players::Computer` that represents a computer player of Tic-tac-toe. Implement a `#move` method that accepts a board and returns the move the computer wants to make in the form of a 1-9 string. How the computer decides to make that move is up to you but it must be capable of returning a valid move at some point. + +```ruby +def move(board) + "1" +end +``` + +Returns a valid move for the first move but after that your program will go into an infinite loop because the computer will constantly try to occupy the `"1"` position in the board even though it is already occupied. So don't do that. + +Think about the levels of intelligence you can build into this method. Start with the simplest level of intelligence, and get more and more complicated. Each step of the way you should have a working computer player though. + +Remember, Tic-tac-toe when played perfectly is unwinnable. You should strive to build computer logic that when the computer plays, the game is unwinnable. You can hardcode your logic, things like "On turn 1 always try to go in the middle if you can" and if not "try to go in a corner" or any logic tree you can think of - there is an algorithm called Min/Max, but it's going to be hard to implement given our current implementation of a Game, so we recommend building something that's a more colloquial or condition-based algorithm. + +#### `bin/tictactoe` +The requirements of your CLI are as follows, free for you to implement however you see fit as we provide no tests against the CLI. + + * Greet the user with a message. + * Prompt the user for what kind of game they want to play, 0,1, or 2 player. + * Ask the user for who should go first and be "X". + * Use the input to correctly initialize a `Game` with the appropriate player types and token values. + * When the game is over, the CLI should prompt the user if they would like to play again and allow them to choose a new configuration for the game as described above. If the user doesn't want to play again, exit the program. + +You can implement this logic within the `bin/tictactoe` directly or encapsulate it within `Game` via a method like `#start` and simply evoke that method in the CLI. There is no wrong way to implement code that works. + +If you'd like, implement a "wargames" game type. When asked what kind of game they want to play or for the number of players, if the user types in "wargames", have the computer play itself 100 times and report how many times the game was won. This is not a requirement, it would just be fun. A perfect computer AI should never be able to win, like in the case of thermonuclear war. + +The rest is up to you and your team. Have fun, implement the spirit of the project, meet the requirements as you interpret them, be creative, and don't worry, there are no wrong answers with code. + +

View Tic-tac-toe with AI on Learn.co and start learning to code for free.

diff --git a/RUBRIC.md b/RUBRIC.md index e2f5b0089e3..7754806df8a 100644 --- a/RUBRIC.md +++ b/RUBRIC.md @@ -1,6 +1,6 @@ - - [ ] All tests pass - - [ ] 0 player mode works - - [ ] 1 player mode works - - [ ] 2 player mode works - - [ ] Game is playable via CLI - - [ ] AI is able to play with some strategy + - [ ] All tests pass + - [ ] 0 player mode works + - [ ] 1 player mode works + - [ ] 2 player mode works + - [ ] Game is playable via CLI + - [ ] AI is able to play with some strategy diff --git a/bin/tictactoe b/bin/tictactoe index 7ddd394b19b..f709e043944 100755 --- a/bin/tictactoe +++ b/bin/tictactoe @@ -1,3 +1,3 @@ -#!/usr/bin/env ruby - -require_relative '../config/environment' +#!/usr/bin/env ruby + +require_relative '../config/environment' diff --git a/config/environment.rb b/config/environment.rb index bc76990da02..706d1f8459f 100644 --- a/config/environment.rb +++ b/config/environment.rb @@ -1,4 +1,4 @@ -require 'bundler' -Bundler.require - -require_all 'lib' +require 'bundler' +Bundler.require + +require_all 'lib' diff --git a/lib/board.rb b/lib/board.rb index e69de29bb2d..31ed877b9aa 100644 --- a/lib/board.rb +++ b/lib/board.rb @@ -0,0 +1,53 @@ +class Board + attr_accessor :cells + +def initialize + reset! +end + +def reset! + @cells = Array.new(9," ") +end + + +def display + puts " #{cells[0]} | #{cells[1]} | #{cells[2]} " + puts "-----------" + puts " #{cells[3]} | #{cells[4]} | #{cells[5]} " + puts "-----------" + puts " #{cells[6]} | #{cells[7]} | #{cells[8]} " + +end + +def position(input) + cells[input.to_i-1] +end + +def full? + cells.all? do |character| + if character == "X" || character == "O" + true + else + false + end + end +end + +def turn_count + cells.count{|char| char=="X" || char==="O"} +end + +def taken?(position) + self.cells[position.to_i-1] == "X" || + self.cells[position.to_i-1] == "O" +end + +def valid_move?(position) + !taken?(position) && position.to_i >0 && position.to_i <=9 +end + +def update(position, player) + self.cells[position.to_i-1] = player.token +end + +end \ No newline at end of file diff --git a/lib/game.rb b/lib/game.rb index e69de29bb2d..15a7ed18326 100644 --- a/lib/game.rb +++ b/lib/game.rb @@ -0,0 +1,77 @@ +class Game + attr_accessor :board, :player_1, :player_2 + +WIN_COMBINATIONS = [ +[0, 1, 2], +[3, 4, 5], +[6, 7, 8], +[0, 3, 6], +[1, 4, 7], +[2, 5, 8], +[0, 4, 8], +[2, 4, 6] +] + +def initialize(player_1 = Players::Human.new("X"), player_2 = Players::Human.new("O"), board = Board.new) + @player_1 = player_1 + @player_2 = player_2 + @board = board + @board.display +end + + +def current_player + board.turn_count.even? ? player_1 : player_2 +end + +def won? + WIN_COMBINATIONS.find do |combo| + if @board.cells[combo[0]] == @board.cells[combo[1]] && + @board.cells[combo[1]] == @board.cells[combo[2]] && + @board.taken?(combo[0]+1) + return combo + end + end + return false +end + +def draw? + @board.full? && !won? ? true : false +end + +def over? + (won? || draw?) ? true : false +end + +def winner + if won? + combo = won? + @board.cells[combo[0]] + end +end + +def turn + puts "Please enter a number 1-9:" + @user_input = current_player.move(@board) + if @board.valid_move?(@user_input) + @board.update(@user_input, current_player) + else puts "Please enter a number 1-9:" + @board.display + turn + end + @board.display + +end + +def play + turn until over? + if won? + puts "Congratulations #{winner}!" + elsif draw? + puts "Cat's Game!" + end +end + + +end + diff --git a/lib/player.rb b/lib/player.rb index e69de29bb2d..43c5ed0ba3e 100644 --- a/lib/player.rb +++ b/lib/player.rb @@ -0,0 +1,7 @@ +class Player + attr_reader :token + +def initialize(token) + @token = token +end +end \ No newline at end of file diff --git a/lib/players/computer.rb b/lib/players/computer.rb index e69de29bb2d..be4a3165171 100644 --- a/lib/players/computer.rb +++ b/lib/players/computer.rb @@ -0,0 +1,27 @@ +module Players + class Computer < Player + + def move(board) + if board.cells[4] == " " + "5" + elsif board.cells[0] == " " + "1" + elsif board.cells[2] == " " + "3" + elsif board.cells[6] == " " + "7" + elsif board.cells[8] == " " + "9" + elsif board.cells[1] == " " + "2" + elsif board.cells[3] == " " + "4" + elsif board.cells[5] == " " + "6" + elsif board.cells[7] == " " + "8" + end + + end + end +end \ No newline at end of file diff --git a/lib/players/human.rb b/lib/players/human.rb index e69de29bb2d..d2efcfc6da8 100644 --- a/lib/players/human.rb +++ b/lib/players/human.rb @@ -0,0 +1,9 @@ +module Players + class Human < Player + + def move(board) + puts "Please enter your selection." + gets.strip + end + end +end \ No newline at end of file diff --git a/spec/01_board_spec.rb b/spec/01_board_spec.rb index 4f15e0dd1e4..027bd4d9175 100644 --- a/spec/01_board_spec.rb +++ b/spec/01_board_spec.rb @@ -1,128 +1,128 @@ -require 'spec_helper' - -describe "Board" do - let(:board){Board.new} - - describe '#cells' do - it 'has an attribute to store the cells of the board' do - expect(board).to respond_to(:cells) - expect(board).to respond_to(:cells=) - - board.cells = [] - expect(board.cells).to match_array([]) - end - end - - describe '#reset!' do - it 'can reset the state of the cells in the board' do - expect(board).to respond_to(:reset!) - board.cells = ["X"] - board.reset! - expect(board.cells).to_not match_array(["X"]) - end - it 'sets the cells of the board to a 9 element array of " "' do - board.cells = ["X"] - board.reset! - expect(board.cells).to match_array(Array.new(9, " ")) - end - end - - describe '#initialize' do - it 'sets the cells of the board to a 9 element array of " "' do - board = Board.new - expect(board.cells).to match_array(Array.new(9, " ")) - end - end - - describe '#display' do - it 'prints the board' do - board.cells = ["X", "X", "X", "X", "O", "O", "X", "O", "O"] - - output = capture_puts{ board.display } - - expect(output).to include(" X | X | X ") - expect(output).to include("-----------") - expect(output).to include(" X | O | O ") - expect(output).to include("-----------") - expect(output).to include(" X | O | O ") - - - board.cells = ["X", "O", "X", "O", "X", "X", "O", "X", "O"] - - output = capture_puts{ board.display } - - expect(output).to include(" X | O | X ") - expect(output).to include("-----------") - expect(output).to include(" O | X | X ") - expect(output).to include("-----------") - expect(output).to include(" O | X | O ") - end - end - - describe '#position' do - it 'takes in user input and returns the value of the board cell' do - board.cells = ["O", " ", " ", " ", "X", " ", " ", " ", "X"] - - expect(board.position("1")).to eq("O") - expect(board.position("2")).to eq(" ") - expect(board.position("5")).to eq("X") - end - end - - describe '#full?' do - it 'returns true for a full board' do - board.cells = ["X", "O", "X", "O", "X", "X", "O", "X", "O"] - - expect(board.full?).to be_truthy - end - - it 'returns false for an in-progress game' do - board.cells = ["X", " ", "X", " ", "X", " ", "O", "O", " "] - - expect(board.full?).to be_falsey - end - end - - describe '#turn_count' do - it 'returns the amount of turns based on cell value' do - board.cells = ["O", " ", " ", " ", "X", " ", " ", " ", "X"] - - expect(board.turn_count).to eq(3) - end - end - - describe '#taken?' do - it 'returns true if the position is X or O' do - board.cells = ["X", " ", " ", " ", " ", " ", " ", " ", "O"] - - expect(board.taken?("1")).to be(true) - expect(board.taken?("9")).to be(true) - end - - it 'returns false if the position is empty or blank' do - board.cells = ["X", " ", " ", " ", " ", " ", " ", " ", "O"] - - expect(board.taken?("2")).to be(false) - expect(board.taken?("7")).to be(false) - end - end - - describe '#valid_move?' do - it 'returns true for user input between 1-9 that is not taken' do - board.cells = [" ", " ", " ", " ", "X", " ", " ", " ", " "] - - expect(board.valid_move?("1")).to be_truthy - expect(board.valid_move?("5")).to be_falsey - expect(board.valid_move?("invalid")).to be_falsey - end - end - - describe '#update' do - it 'updates the cells in the board with the player token according to the input' do - player = double("player", :token => "X") - - board.update("1", player) - expect(board.position("1")).to eq("X") - end - end -end +require 'spec_helper' + +describe "Board" do + let(:board){Board.new} + + describe '#cells' do + it 'has an attribute to store the cells of the board' do + expect(board).to respond_to(:cells) + expect(board).to respond_to(:cells=) + + board.cells = [] + expect(board.cells).to match_array([]) + end + end + + describe '#reset!' do + it 'can reset the state of the cells in the board' do + expect(board).to respond_to(:reset!) + board.cells = ["X"] + board.reset! + expect(board.cells).to_not match_array(["X"]) + end + it 'sets the cells of the board to a 9 element array of " "' do + board.cells = ["X"] + board.reset! + expect(board.cells).to match_array(Array.new(9, " ")) + end + end + + describe '#initialize' do + it 'sets the cells of the board to a 9 element array of " "' do + board = Board.new + expect(board.cells).to match_array(Array.new(9, " ")) + end + end + + describe '#display' do + it 'prints the board' do + board.cells = ["X", "X", "X", "X", "O", "O", "X", "O", "O"] + + output = capture_puts{ board.display } + + expect(output).to include(" X | X | X ") + expect(output).to include("-----------") + expect(output).to include(" X | O | O ") + expect(output).to include("-----------") + expect(output).to include(" X | O | O ") + + + board.cells = ["X", "O", "X", "O", "X", "X", "O", "X", "O"] + + output = capture_puts{ board.display } + + expect(output).to include(" X | O | X ") + expect(output).to include("-----------") + expect(output).to include(" O | X | X ") + expect(output).to include("-----------") + expect(output).to include(" O | X | O ") + end + end + + describe '#position' do + it 'takes in user input and returns the value of the board cell' do + board.cells = ["O", " ", " ", " ", "X", " ", " ", " ", "X"] + + expect(board.position("1")).to eq("O") + expect(board.position("2")).to eq(" ") + expect(board.position("5")).to eq("X") + end + end + + describe '#full?' do + it 'returns true for a full board' do + board.cells = ["X", "O", "X", "O", "X", "X", "O", "X", "O"] + + expect(board.full?).to be_truthy + end + + it 'returns false for an in-progress game' do + board.cells = ["X", " ", "X", " ", "X", " ", "O", "O", " "] + + expect(board.full?).to be_falsey + end + end + + describe '#turn_count' do + it 'returns the amount of turns based on cell value' do + board.cells = ["O", " ", " ", " ", "X", " ", " ", " ", "X"] + + expect(board.turn_count).to eq(3) + end + end + + describe '#taken?' do + it 'returns true if the position is X or O' do + board.cells = ["X", " ", " ", " ", " ", " ", " ", " ", "O"] + + expect(board.taken?("1")).to be(true) + expect(board.taken?("9")).to be(true) + end + + it 'returns false if the position is empty or blank' do + board.cells = ["X", " ", " ", " ", " ", " ", " ", " ", "O"] + + expect(board.taken?("2")).to be(false) + expect(board.taken?("7")).to be(false) + end + end + + describe '#valid_move?' do + it 'returns true for user input between 1-9 that is not taken' do + board.cells = [" ", " ", " ", " ", "X", " ", " ", " ", " "] + + expect(board.valid_move?("1")).to be_truthy + expect(board.valid_move?("5")).to be_falsey + expect(board.valid_move?("invalid")).to be_falsey + end + end + + describe '#update' do + it 'updates the cells in the board with the player token according to the input' do + player = double("player", :token => "X") + + board.update("1", player) + expect(board.position("1")).to eq("X") + end + end +end diff --git a/spec/02_player_spec.rb b/spec/02_player_spec.rb index cafa7c3e94b..04d48a2742f 100644 --- a/spec/02_player_spec.rb +++ b/spec/02_player_spec.rb @@ -1,21 +1,21 @@ -require 'spec_helper' - -describe 'Player' do - - describe '#initialize' do - it 'accepts a token to assign' do - player = Player.new("X") - expect(player.token).to eq("X") - end - end - - describe '#token' do - it 'cannot be changed once assigned in initialize' do - player = Player.new("O") - expect(player.token).to eq("O") - - expect{player.token = "O"}.to raise_error(NoMethodError) - expect(player).to_not respond_to(:token=) - end - end -end +require 'spec_helper' + +describe 'Player' do + + describe '#initialize' do + it 'accepts a token to assign' do + player = Player.new("X") + expect(player.token).to eq("X") + end + end + + describe '#token' do + it 'cannot be changed once assigned in initialize' do + player = Player.new("O") + expect(player.token).to eq("O") + + expect{player.token = "O"}.to raise_error(NoMethodError) + expect(player).to_not respond_to(:token=) + end + end +end diff --git a/spec/03_human_player_spec.rb b/spec/03_human_player_spec.rb index 4c9878da817..40f42720861 100644 --- a/spec/03_human_player_spec.rb +++ b/spec/03_human_player_spec.rb @@ -1,18 +1,18 @@ -require 'spec_helper' - -describe 'Players::Human' do - it 'inherits from Player' do - expect(Players::Human.ancestors).to include(Player) - end - - describe '#move' do - it 'asks the user for input and returns it' do - human = Players::Human.new("X") - allow($stdout).to receive(:puts) - - expect(human).to receive(:gets).and_return("1") - - expect(human.move(Board.new)).to eq("1") - end - end -end +require 'spec_helper' + +describe 'Players::Human' do + it 'inherits from Player' do + expect(Players::Human.ancestors).to include(Player) + end + + describe '#move' do + it 'asks the user for input and returns it' do + human = Players::Human.new("X") + allow($stdout).to receive(:puts) + + expect(human).to receive(:gets).and_return("1") + + expect(human.move(Board.new)).to eq("1") + end + end +end diff --git a/spec/04_game_spec.rb b/spec/04_game_spec.rb index 1dd2f1e3d25..8d33bfb296c 100644 --- a/spec/04_game_spec.rb +++ b/spec/04_game_spec.rb @@ -1,351 +1,351 @@ -require 'spec_helper' - -describe 'Game' do - describe '::WIN_COMBINATIONS' do - it 'defines a constant WIN_COMBINATIONS with arrays for each win combination' do - expect(Game::WIN_COMBINATIONS).to include_array([0,1,2]) - expect(Game::WIN_COMBINATIONS).to include_array([3,4,5]) - expect(Game::WIN_COMBINATIONS).to include_array([6,7,8]) - expect(Game::WIN_COMBINATIONS).to include_array([0,3,6]) - expect(Game::WIN_COMBINATIONS).to include_array([1,4,7]) - expect(Game::WIN_COMBINATIONS).to include_array([2,5,8]) - expect(Game::WIN_COMBINATIONS).to include_array([0,4,8]) - expect(Game::WIN_COMBINATIONS).to include_array([6,4,2]) - end - end - - describe '#board' do - it 'provides access to the board' do - game = Game.new - game.board = [] - expect(game.board).to eq([]) - end - end - - describe '#player_1' do - it 'provides access to player_1' do - game = Game.new - player_1 = Player.new("X") - game.player_1 = player_1 - expect(game.player_1).to eq(player_1) - end - end - - describe '#player_2' do - it 'provides access to player_2' do - game = Game.new - player_2 = Player.new("X") - game.player_2 = player_2 - expect(game.player_2).to eq(player_2) - end - end - - describe 'initialize' do - it 'accepts 2 players and a board' do - board = Board.new - player_1 = Player.new("X") - player_2 = Player.new("O") - - game = Game.new(player_1, player_2, board) - - expect(game.player_1).to eq(player_1) - expect(game.player_2).to eq(player_2) - expect(game.board).to eq(board) - end - - it 'defaults to two human players, X and O, with an empty board' do - game = Game.new - - expect(game.player_1).to be_a(Players::Human) - expect(game.player_1.token).to eq("X") - - expect(game.player_2).to be_a(Players::Human) - expect(game.player_2.token).to eq("O") - - expect(game.board.cells).to match_array(Array.new(9, " ")) - end - end - - describe '#current_player' do - it 'returns the correct player, X, for the third move' do - game = Game.new - game.board.cells = ["O", " ", " ", " ", "X", " ", " ", " ", " "] - - expect(game.current_player.token).to eq("X") - end - end - - describe '#won?' do - it 'returns false for a draw' do - game = Game.new - game.board.cells = ["X", "O", "X", "O", "X", "X", "O", "X", "O"] - - expect(game.won?).to be_falsey - end - - it 'returns the correct winning combination in the case of a win' do - game = Game.new - game.board.cells = ["X", "O", "X", - "O", "O", "X", - "O", "X", "X"] - - expect(game.won?).to contain_exactly(2, 5, 8) - end - - it "isn't hard-coded" do - game = Game.new - game.board.cells = ["O", "O", "O", - "X", "X", " ", - " ", " ", "X"] - - expect(game.won?).to contain_exactly(0, 1, 2) - end - end - - describe '#draw?' do - it 'returns true for a draw' do - game = Game.new - game.board.cells = ["X", "O", "X", "O", "X", "X", "O", "X", "O"] - - expect(game.draw?).to be_truthy - end - - it 'returns false for a won game' do - game = Game.new - game.board.cells = ["X", "O", "X", "O", "X", "X", "O", "O", "X"] - - expect(game.draw?).to be_falsey - end - - it 'returns false for an in-progress game' do - game = Game.new - game.board.cells = ["X", " ", "X", " ", "X", " ", "O", "O", "X"] - - expect(game.draw?).to be_falsey - end - end - - describe '#over?' do - it 'returns true for a draw' do - game = Game.new - game.board.cells = ["X", "O", "X", "O", "X", "X", "O", "X", "O"] - - expect(game.over?).to be_truthy - end - - it 'returns true for a won game' do - game = Game.new - game.board.cells = ["X", "O", "X", "O", "X", "X", "O", "O", "X"] - - expect(game.over?).to be_truthy - end - - it 'returns false for an in-progress game' do - game = Game.new - game.board.cells = ["X", " ", "X", " ", "X", " ", "O", "O", " "] - - expect(game.over?).to be_falsey - end - end - - describe '#winner' do - it 'returns X when X won' do - game = Game.new - game.board.cells = ["X", " ", " ", " ", "X", " ", " ", " ", "X"] - - expect(game.winner).to eq("X") - end - - it 'returns O when O won' do - game = Game.new - game.board.cells = ["X", "O", " ", " ", "O", " ", " ", "O", "X"] - - expect(game.winner).to eq("O") - end - - it 'returns nil when no winner' do - game = Game.new - game.board.cells = ["X", "O", " ", " ", " ", " ", " ", "O", "X"] - - expect(game.winner).to be_nil - end - end - - describe 'turn' do - it 'makes valid moves' do - game = Game.new - allow($stdout).to receive(:puts) - - expect(game.player_1).to receive(:gets).and_return("1") - - game.turn - end - - it 'asks for input again after a failed validation' do - game = Game.new - allow($stdout).to receive(:puts) - - expect(game.player_1).to receive(:gets).and_return("invalid") - expect(game.player_1).to receive(:gets).and_return("1") - - game.turn - end - - it 'changes to player 2 after the first turn' do - game = Game.new - allow($stdout).to receive(:puts) - - expect(game.player_1).to receive(:gets).and_return("1") - expect(game.player_2).to receive(:gets).and_return("2") - - game.turn - game.turn - end - end - - describe 'play' do - it 'asks for players input on a turn of the game' do - game = Game.new - allow($stdout).to receive(:puts) - allow(game).to receive(:over?).and_return(false, true) - - expect(game.player_1).to receive(:gets).at_least(:once).and_return("1") - - game.play - end - - it 'checks if the game is over after every turn' do - game = Game.new - allow($stdout).to receive(:puts) - allow(game.player_1).to receive(:gets).and_return("1", "2") - allow(game.player_2).to receive(:gets).and_return("4", "5") - - expect(game).to receive(:over?).at_least(:twice).and_return(false, false, true) - - game.play - end - - it 'plays the first turn of the game' do - game = Game.new - allow($stdout).to receive(:puts) - allow(game.player_1).to receive(:gets).and_return("1") - - allow(game).to receive(:over?).and_return(false, true) - - game.play - - expect(game.board.cells).to eq(["X", " ", " ", " ", " ", " ", " ", " ", " "]) - end - - it 'plays the first few turns of the game' do - game = Game.new - - allow($stdout).to receive(:puts) - allow(game.player_1).to receive(:gets).and_return("1", "2") - allow(game.player_2).to receive(:gets).and_return("4") - - allow(game).to receive(:over?).and_return(false, false, false, true) - - game.play - - expect(game.board.cells).to eq(["X", "X", " ", "O", " ", " ", " ", " ", " "]) - end - - it 'checks if the game is won after every turn' do - game = Game.new - allow($stdout).to receive(:puts) - allow(game.player_1).to receive(:gets).and_return("1", "2", "3") - allow(game.player_2).to receive(:gets).and_return("4", "5", "6") - allow(game).to receive(:winner).and_return("X") - - expect(game).to receive(:won?).at_least(:twice).and_return(false, false, true) - - game.play - end - - it 'checks if the game is a draw after every turn' do - game = Game.new - allow($stdout).to receive(:puts) - allow(game.player_1).to receive(:gets).and_return("1", "2") - allow(game.player_2).to receive(:gets).and_return("3", "4") - - expect(game).to receive(:draw?).at_least(:twice).and_return(false, false, true) - - game.play - end - - it 'stops playing if someone has won' do - game = Game.new - game.board.cells = ["X", "X", "X", " ", " ", " ", " ", " ", " "] - - allow($stdout).to receive(:puts) - - expect(game).to_not receive(:turn) - - game.play - end - - it 'congratulates the winner X' do - game = Game.new - game.board.cells = ["X", "X", "X", " ", " ", " ", " ", " ", " "] - allow($stdout).to receive(:puts) - - expect($stdout).to receive(:puts).with("Congratulations X!") - - game.play - end - - it 'congratulates the winner O' do - game = Game.new - game.board.cells = [" ", " ", " ", " ", " ", " ", "O", "O", "O"] - - allow($stdout).to receive(:puts) - - expect($stdout).to receive(:puts).with("Congratulations O!") - - game.play - end - - it 'stops playing in a draw' do - game = Game.new - game.board.cells = ["X", "O", "X", "O", "X", "X", "O", "X", "O"] - - allow($stdout).to receive(:puts) - - expect(game).to_not receive(:turn) - - game.play - end - - it 'prints "Cat\'s Game!" on a draw' do - game = Game.new - game.board.cells = ["X", "O", "X", "O", "X", "X", "O", "X", "O"] - - allow($stdout).to receive(:puts) - - expect($stdout).to receive(:puts).with("Cat's Game!") - - game.play - end - - it 'plays through an entire game' do - game = Game.new - allow($stdout).to receive(:puts) - - expect(game.player_1).to receive(:gets).and_return("1") - expect(game.player_2).to receive(:gets).and_return("2") - expect(game.player_1).to receive(:gets).and_return("3") - expect(game.player_2).to receive(:gets).and_return("4") - expect(game.player_1).to receive(:gets).and_return("5") - expect(game.player_2).to receive(:gets).and_return("6") - expect(game.player_1).to receive(:gets).and_return("7") - - expect($stdout).to receive(:puts).with("Congratulations X!") - - game.play - end - end - - describe 'start' do - end -end +require 'spec_helper' + +describe 'Game' do + describe '::WIN_COMBINATIONS' do + it 'defines a constant WIN_COMBINATIONS with arrays for each win combination' do + expect(Game::WIN_COMBINATIONS).to include_array([0,1,2]) + expect(Game::WIN_COMBINATIONS).to include_array([3,4,5]) + expect(Game::WIN_COMBINATIONS).to include_array([6,7,8]) + expect(Game::WIN_COMBINATIONS).to include_array([0,3,6]) + expect(Game::WIN_COMBINATIONS).to include_array([1,4,7]) + expect(Game::WIN_COMBINATIONS).to include_array([2,5,8]) + expect(Game::WIN_COMBINATIONS).to include_array([0,4,8]) + expect(Game::WIN_COMBINATIONS).to include_array([6,4,2]) + end + end + + describe '#board' do + it 'provides access to the board' do + game = Game.new + game.board = [] + expect(game.board).to eq([]) + end + end + + describe '#player_1' do + it 'provides access to player_1' do + game = Game.new + player_1 = Player.new("X") + game.player_1 = player_1 + expect(game.player_1).to eq(player_1) + end + end + + describe '#player_2' do + it 'provides access to player_2' do + game = Game.new + player_2 = Player.new("X") + game.player_2 = player_2 + expect(game.player_2).to eq(player_2) + end + end + + describe 'initialize' do + it 'accepts 2 players and a board' do + board = Board.new + player_1 = Player.new("X") + player_2 = Player.new("O") + + game = Game.new(player_1, player_2, board) + + expect(game.player_1).to eq(player_1) + expect(game.player_2).to eq(player_2) + expect(game.board).to eq(board) + end + + it 'defaults to two human players, X and O, with an empty board' do + game = Game.new + + expect(game.player_1).to be_a(Players::Human) + expect(game.player_1.token).to eq("X") + + expect(game.player_2).to be_a(Players::Human) + expect(game.player_2.token).to eq("O") + + expect(game.board.cells).to match_array(Array.new(9, " ")) + end + end + + describe '#current_player' do + it 'returns the correct player, X, for the third move' do + game = Game.new + game.board.cells = ["O", " ", " ", " ", "X", " ", " ", " ", " "] + + expect(game.current_player.token).to eq("X") + end + end + + describe '#won?' do + it 'returns false for a draw' do + game = Game.new + game.board.cells = ["X", "O", "X", "O", "X", "X", "O", "X", "O"] + + expect(game.won?).to be_falsey + end + + it 'returns the correct winning combination in the case of a win' do + game = Game.new + game.board.cells = ["X", "O", "X", + "O", "O", "X", + "O", "X", "X"] + + expect(game.won?).to contain_exactly(2, 5, 8) + end + + it "isn't hard-coded" do + game = Game.new + game.board.cells = ["O", "O", "O", + "X", "X", " ", + " ", " ", "X"] + + expect(game.won?).to contain_exactly(0, 1, 2) + end + end + + describe '#draw?' do + it 'returns true for a draw' do + game = Game.new + game.board.cells = ["X", "O", "X", "O", "X", "X", "O", "X", "O"] + + expect(game.draw?).to be_truthy + end + + it 'returns false for a won game' do + game = Game.new + game.board.cells = ["X", "O", "X", "O", "X", "X", "O", "O", "X"] + + expect(game.draw?).to be_falsey + end + + it 'returns false for an in-progress game' do + game = Game.new + game.board.cells = ["X", " ", "X", " ", "X", " ", "O", "O", "X"] + + expect(game.draw?).to be_falsey + end + end + + describe '#over?' do + it 'returns true for a draw' do + game = Game.new + game.board.cells = ["X", "O", "X", "O", "X", "X", "O", "X", "O"] + + expect(game.over?).to be_truthy + end + + it 'returns true for a won game' do + game = Game.new + game.board.cells = ["X", "O", "X", "O", "X", "X", "O", "O", "X"] + + expect(game.over?).to be_truthy + end + + it 'returns false for an in-progress game' do + game = Game.new + game.board.cells = ["X", " ", "X", " ", "X", " ", "O", "O", " "] + + expect(game.over?).to be_falsey + end + end + + describe '#winner' do + it 'returns X when X won' do + game = Game.new + game.board.cells = ["X", " ", " ", " ", "X", " ", " ", " ", "X"] + + expect(game.winner).to eq("X") + end + + it 'returns O when O won' do + game = Game.new + game.board.cells = ["X", "O", " ", " ", "O", " ", " ", "O", "X"] + + expect(game.winner).to eq("O") + end + + it 'returns nil when no winner' do + game = Game.new + game.board.cells = ["X", "O", " ", " ", " ", " ", " ", "O", "X"] + + expect(game.winner).to be_nil + end + end + + describe 'turn' do + it 'makes valid moves' do + game = Game.new + allow($stdout).to receive(:puts) + + expect(game.player_1).to receive(:gets).and_return("1") + + game.turn + end + + it 'asks for input again after a failed validation' do + game = Game.new + allow($stdout).to receive(:puts) + + expect(game.player_1).to receive(:gets).and_return("invalid") + expect(game.player_1).to receive(:gets).and_return("1") + + game.turn + end + + it 'changes to player 2 after the first turn' do + game = Game.new + allow($stdout).to receive(:puts) + + expect(game.player_1).to receive(:gets).and_return("1") + expect(game.player_2).to receive(:gets).and_return("2") + + game.turn + game.turn + end + end + + describe 'play' do + it 'asks for players input on a turn of the game' do + game = Game.new + allow($stdout).to receive(:puts) + allow(game).to receive(:over?).and_return(false, true) + + expect(game.player_1).to receive(:gets).at_least(:once).and_return("1") + + game.play + end + + it 'checks if the game is over after every turn' do + game = Game.new + allow($stdout).to receive(:puts) + allow(game.player_1).to receive(:gets).and_return("1", "2") + allow(game.player_2).to receive(:gets).and_return("4", "5") + + expect(game).to receive(:over?).at_least(:twice).and_return(false, false, true) + + game.play + end + + it 'plays the first turn of the game' do + game = Game.new + allow($stdout).to receive(:puts) + allow(game.player_1).to receive(:gets).and_return("1") + + allow(game).to receive(:over?).and_return(false, true) + + game.play + + expect(game.board.cells).to eq(["X", " ", " ", " ", " ", " ", " ", " ", " "]) + end + + it 'plays the first few turns of the game' do + game = Game.new + + allow($stdout).to receive(:puts) + allow(game.player_1).to receive(:gets).and_return("1", "2") + allow(game.player_2).to receive(:gets).and_return("4") + + allow(game).to receive(:over?).and_return(false, false, false, true) + + game.play + + expect(game.board.cells).to eq(["X", "X", " ", "O", " ", " ", " ", " ", " "]) + end + + it 'checks if the game is won after every turn' do + game = Game.new + allow($stdout).to receive(:puts) + allow(game.player_1).to receive(:gets).and_return("1", "2", "3") + allow(game.player_2).to receive(:gets).and_return("4", "5", "6") + allow(game).to receive(:winner).and_return("X") + + expect(game).to receive(:won?).at_least(:twice).and_return(false, false, true) + + game.play + end + + it 'checks if the game is a draw after every turn' do + game = Game.new + allow($stdout).to receive(:puts) + allow(game.player_1).to receive(:gets).and_return("1", "2") + allow(game.player_2).to receive(:gets).and_return("3", "4") + + expect(game).to receive(:draw?).at_least(:twice).and_return(false, false, true) + + game.play + end + + it 'stops playing if someone has won' do + game = Game.new + game.board.cells = ["X", "X", "X", " ", " ", " ", " ", " ", " "] + + allow($stdout).to receive(:puts) + + expect(game).to_not receive(:turn) + + game.play + end + + it 'congratulates the winner X' do + game = Game.new + game.board.cells = ["X", "X", "X", " ", " ", " ", " ", " ", " "] + allow($stdout).to receive(:puts) + + expect($stdout).to receive(:puts).with("Congratulations X!") + + game.play + end + + it 'congratulates the winner O' do + game = Game.new + game.board.cells = [" ", " ", " ", " ", " ", " ", "O", "O", "O"] + + allow($stdout).to receive(:puts) + + expect($stdout).to receive(:puts).with("Congratulations O!") + + game.play + end + + it 'stops playing in a draw' do + game = Game.new + game.board.cells = ["X", "O", "X", "O", "X", "X", "O", "X", "O"] + + allow($stdout).to receive(:puts) + + expect(game).to_not receive(:turn) + + game.play + end + + it 'prints "Cat\'s Game!" on a draw' do + game = Game.new + game.board.cells = ["X", "O", "X", "O", "X", "X", "O", "X", "O"] + + allow($stdout).to receive(:puts) + + expect($stdout).to receive(:puts).with("Cat's Game!") + + game.play + end + + it 'plays through an entire game' do + game = Game.new + allow($stdout).to receive(:puts) + + expect(game.player_1).to receive(:gets).and_return("1") + expect(game.player_2).to receive(:gets).and_return("2") + expect(game.player_1).to receive(:gets).and_return("3") + expect(game.player_2).to receive(:gets).and_return("4") + expect(game.player_1).to receive(:gets).and_return("5") + expect(game.player_2).to receive(:gets).and_return("6") + expect(game.player_1).to receive(:gets).and_return("7") + + expect($stdout).to receive(:puts).with("Congratulations X!") + + game.play + end + end + + describe 'start' do + end +end diff --git a/spec/05_computer_player_spec.rb b/spec/05_computer_player_spec.rb index fb8adba9edb..800e7fa932e 100644 --- a/spec/05_computer_player_spec.rb +++ b/spec/05_computer_player_spec.rb @@ -1,20 +1,20 @@ -require 'spec_helper' - -describe 'Players::Computer' do - it 'inherits from Player' do - expect(Players::Computer.ancestors).to include(Player) - end - - describe '#move' do - it 'returns a valid position for the computer to move' do - computer = Players::Computer.new("X") - board = Board.new - - valid_moves = ["1", "2", "3", "4", "5", "6", "7", "8", "9"] - - computer_move = computer.move(board) - - expect(valid_moves).to include(computer_move) - end - end -end +require 'spec_helper' + +describe 'Players::Computer' do + it 'inherits from Player' do + expect(Players::Computer.ancestors).to include(Player) + end + + describe '#move' do + it 'returns a valid position for the computer to move' do + computer = Players::Computer.new("X") + board = Board.new + + valid_moves = ["1", "2", "3", "4", "5", "6", "7", "8", "9"] + + computer_move = computer.move(board) + + expect(valid_moves).to include(computer_move) + end + end +end diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index 6245eb23a35..76e7f24d108 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -1,37 +1,37 @@ -require_relative "../config/environment.rb" - -RSpec.configure do |config| - config.order = :default -end - -RSpec::Matchers.define :include_array do |expected| - match do |actual| - actual.any?{|array| match_array(expected).matches?(array)} - end -end - -def run_file(file) - eval(File.read(file), binding) -end - -def get_variable_from_file(file, variable) - file_scope = binding - file_scope.eval(File.read(file)) - - begin - return file_scope.local_variable_get(variable) - rescue NameError - raise NameError, "local variable `#{variable}' not defined in #{file}." - end -end - -def capture_puts - begin - old_stdout = $stdout - $stdout = StringIO.new('','w') - yield - $stdout.string - ensure - $stdout = old_stdout - end -end +require_relative "../config/environment.rb" + +RSpec.configure do |config| + config.order = :default +end + +RSpec::Matchers.define :include_array do |expected| + match do |actual| + actual.any?{|array| match_array(expected).matches?(array)} + end +end + +def run_file(file) + eval(File.read(file), binding) +end + +def get_variable_from_file(file, variable) + file_scope = binding + file_scope.eval(File.read(file)) + + begin + return file_scope.local_variable_get(variable) + rescue NameError + raise NameError, "local variable `#{variable}' not defined in #{file}." + end +end + +def capture_puts + begin + old_stdout = $stdout + $stdout = StringIO.new('','w') + yield + $stdout.string + ensure + $stdout = old_stdout + end +end