I am trying to get this Ruby game I made to loop after the first round, and end with a "game over" if the player hits a mine. I have it to where it will build the board, which is a pre-built layout in a .txt file, and it will loop, but the game doesn't end. Here is my code
def load_board
mine_field = []
File.open("mines.txt", 'r') do |f|
f.gets
f.each_line do |line|
mine_field.push line.chomp.split('')
end
end
return mine_field
end
def create_hint_board(board)
hint = Array.new
for i in (0..board.size-1)
hint[i] = []
for j in (0..board[i].size-1)
hint
if board[i][j] == '*'
hint[i].push '*'
else
bombs = 0
for x in (-1..1)
for y in (-1..1)
if i-x >= 0 &&
i-x < board.size &&
j-y >= 0 &&
j-y < board[i].size &&
board [i-x][j-y] == '*'
bombs += 1
end
end
end
hint[i][j] = bombs
end
end
end
return hint
end
def print_board (board)
board.each do |row|
p row
end
end
def pp_board (board)
puts Array.new(board[0].size*2+1, '-').join('')
board.each do |row|
puts "|" + row.join('|') + "|"
puts Array.new(row.size*2+1, '-').join('')
end
end
def copy_to_blank(board)
blank = Array.new
for i in 0..(board.size-1)
blank << Array.new(board[i].size, '.')
end
blank
end
def play(board)
puts "Welcome to Minesweeper!"
puts
puts
puts
hint = create_hint_board(board)
game = copy_to_blank(board)
puts "Starting"
pp_board game
#copy coords user puts in
coords = gets.chomp.split(' ')
i = coords[0].to_i
j = coords[1].to_i
game[i][j] =
hint[i][j]
pp_board game
puts
puts "Hint"
pp_board hint
end
end
#start the game
play load_board
Also, mines.txt looks like this...
4 3
*...
..*.
....
I would appreciate any feedback you can give.
This will get you looping:
# start while loop
while true
coords = gets.chomp.split
i = coords[0].to_i
j = coords[1].to_i
if hint[i][j] == "*"
puts "you lose"
break
end
game[i][j] = hint[i][j]
pp_board game
puts "\nHint"
pp_board hint
end
#end while loop
Ctrl-c to bust out. You can also use break to exit the loop:
break if game_over?
Related
I can play the game. Switch the player all working fine but not getting result who won the game.
def initialize_board
#count = 9
#player = PLAYER_ONE #current_player
#board = Array.new(3){ Array.new(3, " ") }
end
def play
inputs = get_inputs
return false if !inputs
update_board(inputs)
print_board
end
def switch_player
if(#player == PLAYER_ONE)
#player = PLAYER_TWO
else
#player = PLAYER_ONE
end
end
def game_over?
# #count = #count - 1
# #count <= 0
if check_winner
puts "#{#player} won "
end
end
def check_winner
WIN_COMBINATIONS.find do |indices|
binding.pry
values = #board.values_at(*indices)
values.all?('X') || values.all?('O')
end
end
Here I am getting indices [0,1,2] in all cases while debugging.
The main reason why you're not getting the winner is because your 'values = #board.values_at(*indices)' statement returns an array of arrays. And values.all?('X') || values.all?('O') checks not an 'X' or 'O' pattern but an array object. So you need to flatten an array first.
values.flatten!
Stefan already answered similar question , but his board was one-dimensional because of %w expression, you can read about it here
I'm having difficulty in adding underscores in my program. Also what is troubling me is that I can't seem to figure out how to remove the underscores when the user inputs the correct letter.
class Game
attr_reader :guess_count, :is_over, :word_length
def initialize (secret_word)
#secret_word = secret_word
#guess_count = 0
#is_over = false
#word_length = secret_word.length
end
def check_word(guess)
#guess_count += 1
if #secret_word == guess
puts "Congratulations!"
#is_over = true
else
#is_over = false
puts "Sorry, try again!"
end
end
def subtract_guess_count
counter = #word_length - #guess_count
end
end
puts "User 1, What is your secret word?"
secret_word = gets.chomp
anything = Game.new(secret_word)
while !anything.is_over
puts "User 2, Guess the secret word"
guess = gets.chomp
anything.check_word(guess)
if anything.subtract_guess_count == 0
puts "You lose! the correct word was #{secret_word}"
exit!
end
if anything.is_over == false
puts "You have #{anything.subtract_guess_count} left!"
end
end
Major Edit
To create a string of underscores you can do this:
word = ""
1.upto(#secret_word.length) do
word << "_"
end
To replace a character with an underscore (and vice versa) in a ruby string you can use the syntax:
word[i] = "_"
To print a word with spaces between each letter you can use the following:
array = word.split(//)
array.join(" ")
For your code a check_letter function could be useful:
def check_letter (guess)
if (#secret_word[guess])
for i in 0..((#secret_word.length) -1 )
if #secret_word[i] == guess
#progress[i] = guess
end
end
end
show_progress
check_word(#progress)
end
Working code
#! /usr/bin/env ruby
#
class Game
attr_reader :guess_count, :is_over, :word_length, :progress
def initialize (secret_word)
#secret_word = secret_word
#guess_count = 0
#is_over = false
#word_length = secret_word.length
#progress = ""
1.upto(secret_word.length) do
#progress << "_"
end
end
def check_word(guess)
if #secret_word == guess
puts "Congratulations!"
#is_over = true
else
#is_over = false
puts "Sorry, try again!"
end
end
def check_letter (guess)
if (#secret_word[guess])
for i in 0..((#secret_word.length) -1 )
if #secret_word[i] == guess
#progress[i] = guess
end
end
end
show_progress
check_word(#progress)
end
def show_progress
array = #progress.split(//)
word = ""
array.each do |letter|
word << letter + " "
end
puts word
end
def one_less_guess
#guess_count += 1
end
def subtract_guess_count
counter = #word_length - #guess_count
end
end
puts "User 1, What is your secret word?"
secret_word = gets.chomp
anything = Game.new(secret_word)
while !anything.is_over
puts "User 2, Guess the secret word"
guess = gets.chomp
anything.one_less_guess
if guess.length == 1
anything.check_letter(guess)
else
anything.check_word(guess)
end
if anything.subtract_guess_count == 0
puts "You lose! the correct word was #{secret_word}"
exit!
end
if anything.is_over == false
puts "You have #{anything.subtract_guess_count} left!"
end
end
These are incomplete codes, but it should at least update the game board until it fills up and error out. I don't know why its not updating the board. It definitely is registering my inputs as well as the computer's since the game does print my coordinates. Can someone please help me figure out what I'm doing wrong?
class Board
attr_reader :grid
def initialize
#grid = Array.new(3) { Array.new(3) }
#human = HumanPlayer.new
#computer = ComputerPlayer.new
#game = Game.new
end
def place_mark(pos)
if (pos[0] < 0 || pos[0] > 2) || (pos[1] < 0 || pos[1] > 2)
puts "Invalid coordinates! Please try again!"
#game.play
elsif empty?(pos)
if #game.current_player == "human"
puts "Player 1 goes: #{pos}"
#grid[pos[0]][pos[1]] = 'X'
elsif #game.current_player == "computer"
puts "Computer goes: #{pos}"
#grid[pos[0]][pos[1]] = "O"
end
if winner
puts "Congratulations! #{#game.current_player} wins!"
else
#game.switch_players!
end
else
puts "Space Taken! Please Try Again!"
#game.play
end
end
def empty?(pos)
#grid[pos[0]][pos[1]].nil?
end
def winner
#Need to set winning combinations
false
end
def over?
false #for now, it will go until all spaces are filled. Still need to set end game condition.
end
end
class HumanPlayer
def display
p Board.new.grid
end
def get_move
puts "Please enter your the quadrant you wish to place your mark."
pos = gets.chomp.scan(/[0-9]/).map!(&:to_i)
Board.new.place_mark(pos)
end
end
class ComputerPlayer
def get_move
x = rand(3).round
y = rand(3).round
Board.new.place_mark([x,y])
end
end
class Game
##turn_tracker = 0
def current_player
##turn_tracker.even? ? "human" : "computer"
end
def switch_players!
##turn_tracker += 1
play
end
def play_turn
if current_player == "human"
HumanPlayer.new.display
Board.new.place_mark(HumanPlayer.new.get_move)
elsif current_player == "computer"
ComputerPlayer.new.get_move
end
end
def play
play_turn until ##turn_tracker == 9 #Still need to set win conditions
end
end
board = Game.new
board.play
1) Game Initiates with Game#new#play
2) #play will run the game until 9 turns have passed (temporary
condition). It is passed to #play_turn
3) #play_turn figures out whose turn it is by using the
current_player.
4) It is then passed to HumanPlayer.get_move or
ComputerPlayer#get_move. These two will determine the moves of each
player and pass it to Board#place_mark.
5) #place_mark will determine if the move is valid using #empty? If
valid, it SHOULD update the grid. Then passes to the
Game#switch_players!
6)#switch_players! will change the player and passes back to #play.
7) It should iterate through this loop.
You always generate a new board, which then of course is again initalized with the starting position:
class HumanPlayer
def display
p Board.new.grid
end
...
end
As you want to learn something, I don't present you a solution.
I'm getting the error:
minesweeper.rb:32:in '|': can't convert Fixnum into Array (TypeError)
from minesweeper.rb:32:in 'block in create_hint_board'
from minesweeper.rb:31:in 'each_index'
from minesweeper.rb:31:in 'create_hint_board'
from minesweeper.rb:68:in '(main)'
when attempting to check a 2D array for a value, and adding 1 to all cells adjacent to that index location. The error occurs at subarray2 = board|i|. I'm trying to iterate over the entire 2D array
The entire code is
#def load_board(file)
# gameboard = File.readlines(file)[1..-1]
# gameboard.map! do |line|
# line.split.map(&:to_s)
# end
# $globalarray = gameboard
#end
$globalarray = [['*','.','.','.'],['.','.','*','.'],['.','.','.','.']]
def pp_board(board)
puts Array.new(board[0].size*2+1, '-').join('')
board.each do |row|
puts "|" + row.join("|") + "|"
puts Array.new(row.size*2+1, '-').join('')
end
end
def create_hint_board(board)
board = $globalarray
$globalarray.each_index do |i|
subarray = $globalarray[i]
subarray.each_index do |j|
if $globalarray[i][j] != '*'
board[i][j].to_i
board[i][j] = 0
end
puts "#{String(i)},#{String(j)} is #{board[i][j]}"
end
end
board.each_index do |i|
subarray2 = board|i|
subarray2.each_index do |j|
if board[i][j] == '*'
board[i+1][j] = board[i+1][j]+1
board[i+1][j+1] = board[i+1][j+1]+1
board[i+1][j-1] = board[i+1][j-1]+1
board[i][j-1] = board[i][j-1]+1
board[i][j+1] = board[i][j+1]+1
board[i-1][j] = board[i-1][j]+1
board[i-1][j+1] = board[i-1][j+1]+1
board[i-1][j-1] = board[i-1][j-1]+1
end
end
end
puts "new array is "
puts board
end
=begin
#def copy_to_blank(board)
# $newarrayblank = $newarray
# $newarrayblank.each_index do |i|
# subarray = $newarrayblank[i]
# subarray.each_index do |j|
# $newarrayblank[i][j] = '.'
# puts "#{String(i)},#{String(j)} is #{$newarrayblank[i][j]}"
# end
# end
#end
#load_board("mines.txt")
blank = [[]]
=end
puts "Original array is"
puts $globalarray
create_hint_board($globalarray)
#pp_board($globalarray)
#create_hint_board($globalarray)
#puts "new array is"
#pp_board($newarray)
#puts "new blank board is"
#copy_to_blank(blank)
#puts $newarrayblank
#pp_board($newarrayblank)
=begin
puts "Input Guess"
value1 = gets.split(" ")
row_guess = value1[0].to_i
col_guess = value1[1].to_i
puts $newarray[row_guess][col_guess]
while $newarray[row_guess][col_guess] != '*'
if $newarray[row_guess][col_guess] != '*'
puts "You guessed row #{row_guess} and column #{col_guess}."
puts $newarray[row_guess][col_guess]
#$newarrayblank[row_guess][col_guess] = $newarray[row_guess][col_guess]
#pp_board($newarrayblank)
puts "Input your guess in coordinates, separated by a blank space, or press q to quit."
value1 = gets.split(" ")
row_guess = value1[0].to_i
col_guess = value1[1].to_i
elsif $newarray[row_guess][col_guess] == '*'
puts "You guessed row #{row_guess} and column #{col_guess}."
puts "You hit a mine!"
puts "Game Over"
end
end
=end
The area giving me trouble is
board.each_index do |i|
subarray2 = board|i|
subarray2.each_index do |j|
if board[i][j] == '*'
board[i+1][j] = board[i+1][j]+1
board[i+1][j+1] = board[i+1][j+1]+1
board[i+1][j-1] = board[i+1][j-1]+1
board[i][j-1] = board[i][j-1]+1
board[i][j+1] = board[i][j+1]+1
board[i-1][j] = board[i-1][j]+1
board[i-1][j+1] = board[i-1][j+1]+1
board[i-1][j-1] = board[i-1][j-1]+1
end
end
end
I've also tried moving the addition section above, as an elsif statement below the if, like so
def create_hint_board(board)
board = $globalarray
$globalarray.each_index do |i|
subarray = $globalarray[i]
subarray.each_index do |j|
if $globalarray[i][j] != '*'
board[i][j].to_i
board[i][j] = 0
elsif board[i][j] == '*'
board[i+1][j] = board[i+1][j]+1
board[i+1][j+1] = board[i+1][j+1]+1
board[i+1][j-1] = board[i+1][j-1]+1
board[i][j-1] = board[i][j-1]+1
board[i][j+1] = board[i][j+1]+1
board[i-1][j] = board[i-1][j]+1
board[i-1][j+1] = board[i-1][j+1]+1
board[i-1][j-1] = board[i-1][j-1]+1
end
end
puts "#{String(i)},#{String(j)} is #{board[i][j]}"
end
end
This results in the error message:
minesweeper.rb:28:in '+': can't convert Fixnum into String (TypeError)
from minesweeper.rb:28:in 'block (2 levels) in create_hint_board'
from minesweeper.rb:28:in 'each_index'
from minesweeper.rb:28:in 'block in create_hint_board'
from minesweeper.rb:28:in 'each_index'
from minesweeper.rb:28:in 'create_hint_board'
from minesweeper.rb:28:in '(main')
The issue is at following line
subarray2 = board|i|
You are doing:
board.each_index do |i|
And in following line you are trying to get the value of board at that index. To achive this you should do:
subarray2 = board[i]
At last, there is a better way to achieve this by using each_with_index.
Eg:
board.each_with_index do |v, i|
subarray2 = v
...
end
I'm new to programming in Ruby and I decided to learn to build a hangman game, but I have a problem when comparing two strings, one that comes from a gets (If I do it for me code works normal) and one that is defined.
this is my codes:
this is my 'main':
require_relative("Ahorcado")
juego = Ahorcado.new()
juego.decirPalabra
while juego.hayVidas?
juego.imprimir
lectura = gets
lectura = lectura.to_s;
juego.preguntar lectura
end
puts juego.resultado
And the Ahorcado.rb
class Ahorcado
def loadVariables
#palabras = ["java","ruby","python","go"]
#adivinados = []
#gano = false
#vidas = 7
end
def initialize
loadVariables();
#palabra = #palabras[rand(#palabras.length)].split("")
puts "Se ha iniciado un juego"
#tamano = #palabra.length
puts "Existen #{#tamano} letras"
iniciar
end
def decirPalabra
puts #palabra
end
def preguntar letra
#vidas -= 1
letra = letra.to_s
temp = #palabra.join
puts temp.eql?(letra) # -> Allways false
if letra == #palabra.join then
#gano = true
puts "gano"
else
for i in 0...#tamano
if letra.eql?(#palabra[i]) then #Allways false
#adivinados[i] = true
#vidas += 1
else
puts "Incorrecto intente otra vez"
end
end
end
end
def comparar letra
#temp = letra;
puts #temp == #palabra[0]
end
def iniciar
for i in (0...#tamano)
#adivinados[i] = false;
end
end
def hayVidas?
return #vidas > 0
end
def resultado
#gano;
end
def imprimir
for i in (0...#tamano)
if #adivinados[i] then
print #palabra[i]+" "
else
print "_ "
end
end
puts
end
end
Thanks for yours answers, and sorry if i wrote bad some sentences, i don't speak english
When you do a "gets", lectura contains newline character in the end. Trying doing a "chomp" on lectura :-
lectura = lectura.chomp
and try again. So that all the newline characters are removed. You can also use "bytes" to see the exact characters in your string for debugging purposes.
puts lectura.bytes
Refer:- http://ruby-doc.org/core-2.0/String.html#method-i-chomp