Giter Club home page Giter Club logo

ttt-5-move-rb's Introduction

Tic Tac Toe CLI: Adding Player Movement to the Game Board

Objectives

  1. Define a method to convert a user's input to an array index.
  2. Define a method that updates an array passed to it.
  3. Define a method with a default value.
  4. Use a method in a CLI.
  5. Accept user input via gets.
  6. Use user input in a method.

Overview

In this lab we'll be adding a input_to_index method and a move method to Tic Tac Toe to update the board with a player's token. The input_to_index method will take the user's input ("1"-"9") and convert it to the index of the board array (0-8). The move method represents a user moving into a position, like the middle cell, in Tic Tac Toe. We already have a method, #display_board, that prints out the tic tac toe board to the console and maps each location of the board to an array index. Then, we'll build a CLI that asks the player for the position on the board that they like to fill out with an "X" or an "O", convert the position to an index, update the board, and displays the updated board.

Project Structure

In previous exercises, we've learned to build programs that the user interacts with via the command line. Such interaction is considered to occur through the CLI, or command line interface. Conventionally, CLI programs have a bin directory which contains an executable file. This file contains the code that is responsible for running the program.

Take a look at the file structure of this project, mapped out below:

bin
  |–– move
lib
  |–– move.rb
spec
  |–– 01_input_to_index_spec.rb
  |–– 02_move_spec.rb
  |–– 03_cli_spec.rb
  |–– spec_helper.rb
...

We have our bin directory and it contains our executable file, move. Remember that executable files conventionally are not given a file extension like .rb.

Open up bin/move and take a look at the following code:

#!/usr/bin/env ruby

require_relative '../lib/move.rb'

First, we have our shebang line that tells the terminal which interpreter to use to execute the remainder of the file. Second, we are requiring the move.rb file, from within the lib directory. This gives our executable file access to whatever code we write in the move.rb file.

We'll be writing our #display_board, #input_to_index and #move methods in lib/move.rb and writing the code that interacts with the command line in the bin/move file.

Desired Behavior

Now that we understand the broad strokes of what we're trying to accomplish, as well as where we'll be writing our code, let's take a look at an example of the functionality:

When we run our executable file with ruby bin/move in the terminal, inside the directory of this project, we should see something like the following:

Welcome to Tic Tac Toe!
Where would you like to go?
2
   | X |   
-----------
   |   |   
-----------
   |   |   

Our program will:

  1. Print out a welcome message.
  2. Ask the user to input the position on the board they would like to fill.
  3. Convert the input to an array index.
  4. Fill out that position with either an "X" or an "O".
  5. Print the updated board.

Okay, we're ready to start coding!

Instructions

Part I: Defining our Methods

The first part of this lab is test-driven. Run learn to get started and use the test output to guide you in defining the move method.

Notice that we've already given you the #display_board method, since we've already built that out in a previous exercise.

#input_to_index

Your #input_to_index method must take one argument, the user's input (should be a string that is "1" - "9").

Regarding the player's input: if the user's input is "5", the player wants to fill out position 5 with their character. This means that your method must fill out the correct array index with the player's character.

The player's input is the string '5'. The first thing you'll need to do is convert the string to its integer value, because array indexes are always integers (think '5' vs 5). Give #to_i a try, as in '5'.to_i.

Also remember, from the player's point of view, the board contains spaces 1-9. An array's indexes start their count at 0. This has been accounted for if you use input_to_index in your move implementation to return the converted value and use that as the index. In this one case, make sure to put spaces between the elements you type; something like 5 + 1 - not 5+1 or 5 +1. There is an edge case which might come up and break your code if you forget the spaces.

So if the player types in a "2", what index in the board array do you want to access?

harrison ford 1

That's right, we would want to access index 1 of the board array.

#move

Your #move method must take in three arguments, the board array, the index in the board array that the player would like to fill out with an "X" or an "O", and the player's character (either "X" or "O"). The third argument, the player's character, should have a default of "X".

#move should also return the modified array with the updated index corresponding to the player's token. Don't create a new local variable for the board array, modify the one passed in as the argument and return it.

Part of your #move method will mean updating the board Array passed into it.

board = [" ", " ", " "]
def update_array_at_with(array, index, value)
  array[index] = value
end

update_array_at_with(board, 0, "X")
# The element at index 0 of array 'board' is set to the value "X"
board #=> ["X", " ", " "]

When collection objects are passed into methods, and those collection objects are changed within those methods, the change is made to the collection directly. The change is not made to a copy of what's passed in — which is exactly what happens when a Number is passed into a method. As an example, a test script should prove to you the oddity:

def number_adder(n)
  n += 10
end

def array_adder(a)
  a << "new thing at the end of the array"
end

x = 10
puts "Before call #{x}"
number_adder(x)
puts "After call: #{x}: Holy moly, unchanged!"

z = [1, 'hi', "Byron"]
puts "Before call #{z}"
array_adder(z)
puts "After call #{z}: Holy moly, *changed*!"

Once you have the tests passing, move on to part II.

Part II: The CLI

Open up bin/move. We're ready to code the executable portion of this program.

  1. Our program should first welcome the player by outputting a friendly message to the terminal: "Welcome to Tic Tac Toe!".
  2. Next, establish the starting state of the game, i.e. the empty board. Create a new board by setting a variable board equal to instantiating a new array with 9 elements, each of which is a blank space, " ".
  3. Now, ask the user for input by outputting "Where would you like to go?" to the terminal.
  4. We need to store the user's input. Use gets.strip to store their input to a variable, input.
  5. Now we want to convert the user's input to an array index using our #input_to_index method and store this as the variable index.
  6. Now we're ready to call our #move method. Do so with the arguments of the board, the index the user wants to access and the default player of "X".
  7. Lastly, display the board by calling the #display_board method, passing in the necessary arguments required to run this method.

Now, run your program by typing ruby bin/move in the terminal. Have fun playing (one round of) tic tac toe!

View Tic Tac Toe CLI: Adding Player Movement to the Game Board on Learn.co and start learning to code for free.

ttt-5-move-rb's People

Contributors

annjohn avatar aturkewi avatar aviflombaum avatar gj avatar jonbf avatar loganhasson avatar maxwellbenton avatar mendelb avatar pajamaw avatar peterbell avatar sammarcus avatar sgharms avatar sophiedebenedetto avatar

Stargazers

 avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ttt-5-move-rb's Issues

Failed test

The board is defined as an array in ../bin/move, everything works in IRB, but there's still one failure:
rspec ./spec/03_cli_spec.rb:4 # ../bin/move executing a CLI Application defines a board variable

I've even checked that board is an array, so everything's fine there as well.

Hi, instructor

I have a program that does what's ask. Made it to 16 examples, 4 failures. But my program does doCLI ask a user for input, pass the user input, calls display. If you can llok at the code give some feedback, would appreciate.

All 03_cli_spec checks fail if you forget to input argument for display_board

Howdy,

I was working through this module and ran into an issue where my 03_cli_spec.rb check gave me errors on all 8 examples when forgetting to define the display_board(#) argument.

It caused an issue because as I knew I had some examples that worked (i.e. defines board variable) in the beginning and wasn't sure what caused everything to go belly-up. I would've thought the "calls display_board passing the modified board" would've been the error to specifically call out.

Screenshots for reference.
cli module error

Was never told how to convert string to integer

I was surprised to learn that I had to cast the the string I get from the gets to an integer in order to use it as an index into the array. I don't think the material to date has covered to_i? But even if it did previously, I've probably forgotten and lab should remind me to think about this, else I predict this will be a common error.

Tic Tac Toe Move

Spec expects conversion of input -> index - 1 in input to index, however in the lesson you state "You'll have to account for that in your #move method by doing some math."

Nitrous open

Hei,
Nitrous open button in the top right corner of the page does not work for me, it races an issues when i press it.

Confusion

This paragraph really confused me and held up my progress:

Regarding the player's input: if the user's input is "5", the player wants to fill out position 5 with their character. This means that your method must fill out the correct array index with the player's character.
The player's input is the string '5'. The first thing you'll need to do is convert the string to its integer value, because array indexes are always integers (think '5' vs 5). Give #to_i a try, as in '5'.to_i.

I interpreted this as the input literally was a string, and we would need to convert it first. Maybe I was just missing the point, as I knew the input is actually a variable, but this paragraph convinced me otherwise.

learn IDE bug

Does not open the needed files for the questions. Shows the correct learn directory, but there are no files in the labs folder. This is a constant issue I have been dealing with the previous questions as well. I usually have to manually unfork, fork, clone..etc a number of times, through git commands to get it to work.

Might want to clarify pass by reference for arrays

I originally wrote my move function to:

  1. take an array as input
  2. change one of its values
  3. and then end by returning the now-changed array

but this messed up the CLI test suite because apparently arrays in Ruby behave in a 'pass by reference' way, which i didn't know.

Not sure if/how to make that clearer here, or if it's necessary but just noting my trouble point.

Intro to ruby seset

I had to take an extended break from the intro to Ruby. Is there any way I can start over/have it reset?

Thank you

tests break when variable overwritten

worked with a student today who had the following in her /bin/move which is not incorrect ruby but it was breaking the get_variable_from_file method in the helper
tried to pry in and found that file_scope.eval wasn't liking that but i don't know a fix
below code passes all tests with board = move(board, position, player = "X") changed to move(board, position, player = "X")

#!/usr/bin/env ruby
require_relative '../lib/move.rb'
require 'pry'

# Code your CLI Here
  puts "Welcome to Tic Tac Toe!"
  board = [" ", " ", " ", " ", " ", " ", " ", " ", " "]
  display_board(board)

  # while board[0..8].include?(" ")

    puts "Where do you want to go?"
    puts "Please enter a whole number from one to nine inclusive"
    input = gets.strip
      # break if input == "stop"

    position = input_to_index(input)
    if position != -1
      board = move(board, position, player = "X")
      display_board(board)
    end
  # end

Where to start...

Hello!

I have read the tutorial but the last part titled "Continuing to Solve Fizzbuzz" is confusing. Am I supposed to copy that code?

I tried this:

def fizzbuzz(int)
if int % 3 == 0 # if the number int is divisible by 3
"Fizz"
end

def fizzbuzz(int)
if int % 5 == 0
"Buzz"
end

def fizzbuzz(int)
if int % 3 == 0
elsif int % 5 == 0
"Fizzbuzz"
end

And when running learn I got in the terminal:

// ♥ learn
/usr/local/rvm/gems/ruby-2.3.1/gems/rspec-core-3.4.4/lib/rspec/core/configuration.rb:1361:in load': /home/creative-kernel-3560/rspec -fizzbuzz-online-web-sp-000/fizzbuzz.rb:18: syntax error, unexpected end-of-input, expecting keyword_end (SyntaxError) from /usr/local/rvm/gems/ruby-2.3.1/gems/rspec-core-3.4.4/lib/rspec/core/configuration.rb:1361:in block in load_spec_files'
from /usr/local/rvm/gems/ruby-2.3.1/gems/rspec-core-3.4.4/lib/rspec/core/configuration.rb:1359:in each' from /usr/local/rvm/gems/ruby-2.3.1/gems/rspec-core-3.4.4/lib/rspec/core/configuration.rb:1359:in load_spec_files'
from /usr/local/rvm/gems/ruby-2.3.1/gems/rspec-core-3.4.4/lib/rspec/core/runner.rb:106:in setup' from /usr/local/rvm/gems/ruby-2.3.1/gems/rspec-core-3.4.4/lib/rspec/core/runner.rb:92:in run'
from /usr/local/rvm/gems/ruby-2.3.1/gems/rspec-core-3.4.4/lib/rspec/core/runner.rb:78:in run' from /usr/local/rvm/gems/ruby-2.3.1/gems/rspec-core-3.4.4/lib/rspec/core/runner.rb:45:in invoke'
from /usr/local/rvm/gems/ruby-2.3.1/gems/rspec-core-3.4.4/exe/rspec:4:in `<top (required)>'

I'm not sure what this means..

Not Getting Credit for "Tic Tac Toe Move" Lab

Hello. I completed this lab, but it does not show like I passed it under my "Curriculum". It's causing to not let me pass my "Command Line Application" section. Please help. Thank you!

Pass by value

arr1=[1,2,3]
arr2=arr1
arr2<<4
print arr1
If Ruby passed by value then arr1=[1,2,3] but
it doesn't. arr1=[1,2,3,4]
Ruby passes by reference value.

Have the method argument stubs not be typed or be less specific

Student ran into an issue converting the position to an integer too early and got:

1) ./bin/move executing a CLI Application calls move passing the user input
Failure/Error: run_file("./bin/move")
# received :move with unexpected arguments
expected: (anything, "1", *(any args))
got: ([" ", " ", " ", " ", " ", " ", " ", " ", " "], 1, "X")

We can change that stub to be less specific...

Having an issue with Tic Tac Toe Move

Receiving the following message: ./bin/move executing a CLI Application
defines a board variable
prints "Welcome to Tic Tac Toe!"
asks the user for input
converts the users input to an index
calls move passing the index (FAILED - 1)
Failures:

  1. ./bin/move executing a CLI Application calls move passing the index
    Failure/Error: run_file("./bin/move")
    #RSpec::ExampleGroups::BinMoveExecutingACLIApplication:0x00000003016960 received :move with unexpected arguments
    expected: (anything, 0, *(any args))
    got: ([" ", " ", " ", " ", " ", " ", " ", " ", " "], 1, "X")

    ./spec/spec_helper.rb:17:in `run_file'

    ./spec/spec_helper.rb:6:in `eval'

    ./spec/spec_helper.rb:6:in `run_file'

    ./spec/03_cli_spec.rb:48:in `block (2 levels) in <top (required)>'

Finished in 0.03516 seconds (files took 0.11825 seconds to load)
17 examples, 1 failure
Failed examples:
rspec ./spec/03_cli_spec.rb:41 # ./bin/move executing a CLI Application calls move passing the index

Here is my code:

puts "Welcome to Tic Tac Toe!"
board = [" ", " ", " "," ", " ", " "," ", " ", " "]
puts "Where would you like to go?"

input = gets.strip
index = input_to_index(input)
move(board, index)
display_board(board)

Quiz problem

Hi,

This quiz already had some answers selected and isn't allowing me to choose any answers. I've also tried to reload the site and the problem is persisting.

Convert to CLI Lab

Make this into a CLI lab that simply:

  1. Welcomes them
  2. Prints the board
  3. Asks for input from 1-9
  4. Updates the board with move
  5. Displays the accurate filled in move.

Instructions inaccurate

Lab says "It doesn't matter whether you choose "X" or "O"

In fact, in order to get the CLI tests to pass, you have to pass X. So we either need to clarify the instruction or make the tests more generic.

incorrect expectation in test?

In 02_cli_spec.rb you have

it 'calls move passing the user input' do

which has

expect(self).to receive(:move).with(anything, '1', any_args), "Make sure `bin/move` is passing the user input to the `#move` method."

Not sure why we'd want to pass a string to #move after changing it to an integer after getting it from the user. It'd have to be turned into an integer again to be used in the array index adjustment. So maybe something like

with(anything, 1, any_args)

would work better instead.

Anyway, it just didn't make sense to me as to why we'd have to address that test in a roundabout way when the instructions would suggest otherwise (unless I missed something).

learn open not cd to current lesson in Nitrous

While the learn open function is properly forking the lesson, it doesn't change into the appropriate directory after doing so. On my Nitrous IDE, I just executed learn open which should have brought me into the "ttt-5-move-rb folder," but instead it dropped me into "interpolation-super-power-q-000."

how do you store the result as the variable index

require_relative '../lib/move.rb'

Hi, I have a question on "step 5 - Now we want to convert the user's input to an array index using our #input_to_index method and store this as the variable index. " how do you store the result as the variable index?
Below is my code under folder "bin":

#!/usr/bin/env ruby

require_relative '../lib/move.rb'

puts "Welcome to Tic Tac Toe!"
board=[" ", " ", " ", " ", " ", " ", " ", " ", " "]
puts "Where would you like to go?"
input = gets.strip
input_to_index(input)
#I actually hard-code it rather than store the value of "index"
index = input.to_i - 1

move(board, index)
display_board(board)

Potential typos

Hello my dears! I am hoping to enrich the program by finding the small tidbits I missed the first time round. I believe there are some missing words in one of the instructions under the #move method instructions on the following page: https://learn.co/tracks/full-stack-web-development-v6/intro-to-ruby-development/command-line-applications/tic-tac-toe-move?batch_id=306&track_id=43149

I believe the text should say: When collection objects are passed into methods, and those collection objects are changed within those methods the change is made to the collection directly.

Also: It is not made to a copy like what happens when a Number is passed.

Aysan requested I raise the issue to have this resolved. Thank you very kindly for your efforts, they're super appreciated!

Best!

Dana

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.