Adam D. Bell
Adam D. Bell

Reputation: 167

Case statement issues with ruby

I'm working on a tic-tac-toe problem for a ruby project. I'd like to have one method control and report who is the current player. For move zero I'd like to randomly pick who goes. After that it will alternate between the two players evenly. Here is my code so far

def current_player (move_counter = 0)
  case move_counter
  when move_counter = 0 
    player_on_deck = rand() > 0.5 ? "Computer" : @player
  when move_counter > 0
    player_on_deck == "Computer" ? @player : "Computer"
  end

  move_counter +=1 
  return player_on_deck move_counter
end

I think I'm messing up the implementation the move_counter to give me a switch for when to do what. Every time this method is called it starts from zero. Do i need to make a new method that only tracks moves and pass that value into this method? Or is there away to make move_counter stay up to date inside of this method?

Upvotes: 0

Views: 249

Answers (2)

eebbesen
eebbesen

Reputation: 5148

You are setting the value of move_counter in the when clause: when move_counter = 0 should be when move_counter == 0. Also, you have the reverse problem when trying to define player_on_deck for the second time -- you are using == but should be using =.

Here's what I think you are really trying to do:

def current_player (move_counter = 0)
  case move_counter
  when move_counter == 0 
    player_on_deck = rand() > 0.5 ? "Computer" : @player
  when move_counter > 0
    player_on_deck = "Computer" ? @player : "Computer"
  end

  return player_on_deck
end

Upvotes: 2

dax
dax

Reputation: 11017

I think you just need to decide between passing the count as an argument and incrementing it inside the method (which isn't the best)

Try something like this:

def current_player (move_counter = 0)
  case move_counter
  when move_counter == 0 
    player_on_deck = rand() > 0.5 ? "Computer" : @player
  when move_counter > 0
    player_on_deck == "Computer" ? @player : "Computer"
  end

  return player_on_deck
end

and increment the move_counter at the bottom of your game loop.

the first time is taken care of via the default argument, and anytime past that will be dealt with by the counter you define at the bottom of your game loop.

**also as eebbesen has said, the move counter isn't being evaluated in your case statement, it's being reset.

Upvotes: 1

Related Questions