Player vs computer [closed] - ruby

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
Created this connect 4 game following a guide online but the guide didn't explain how to make it computer vs player it only explained how to make it player vs player. I've tried adding a computer variable that generated a random number 1..8 for the columns but it wasn't working was just sitting there asking player two to pick a location.
Here's the player code below how do i implement player vs computer ?
class Board
attr_accessor :board
attr_reader :turn, :identifier
def initialize
#board = [
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0]
]
#turn = 0
#identifier = 1
end
def choose_column(col)
7.downto(0) do |i|
if board[i][col-1] == 0
board[i][col-1] = identifier
break
end
end
false
end
def win?
return true if check_rows?
return true if check_columns?
return true if check_diagonal?
end
def check_validity(sum,num)
if num == 1
sum = 0 if sum < 0
sum += 1
elsif num == -1
sum = 0 if sum > 0
sum -= 1
else
sum = 0
end
end
def check_rows?
8.times do |i|
board[i].inject(0) do |sum, num|
sum = check_validity(sum,num)
return true if sum.abs == 4
sum
end
end
false
end
def check_columns?
8.times do |i|
column = []
board.each { |row| column.push(row[i]) }
column.inject(0) do |sum, num|
sum = check_validity(sum,num)
return true if sum.abs == 4
sum
end
end
false
end
def check_diagonal?
board[0..2].each_with_index do |row, row_i|
row.each_with_index do |column, col_i|
if col_i <=3
sum = board[row_i][col_i]
1.upto(3) { |i| sum += board[row_i+i][col_i+i] }
return true if sum.abs == 4
end
if col_i >= 3
sum = board[row_i][col_i]
1.upto(3) { |i| sum += board[row_i+i][col_i-i] }
return true if sum.abs == 4
end
end
end
false
end
def new_game
#turn = 1
end
def game_flow
new_game
while turn < 43
assign_player
player = #identifier == 1 ? 1 : 2
puts draw_board
print "Round #{#turn}. Player #{player}'s turn. Choose column (1-8): "
input = gets.chomp
while !validate_input(input) || check_full?(input)
print "Invalid Pick. Try again: "
input = gets.chomp
end
input = validate_input(input)
choose_column(input)
if win?
puts draw_board
puts "Congratulations. Player #{player} won"
break
end
#turn += 1
end
puts "Draw!" unless win?
return true
end
def assign_player
#identifier = #turn.odd? ? 1 : -1
end
def validate_input(input)
return input !~ /^[1-8]$/ ? false : input.to_i
end
def check_full?(column)
column = column.to_i
column -= 1
return board[0][column] != 0
end
def draw_board
print "1 2 3 4 5 6 7 8\n"
rep = { 0 => ".", 1 => "O", -1 => "X" }
board.each do |row|
print "#{rep[row[0]]} #{rep[row[1]]} #{rep[row[2]]} #{rep[row[3]]} #{rep[row[4]]} #{rep[row[5]]} #{rep[row[6]]} #{rep[row[7]]}\n"
end
print " "
end
end
board = Board.new
board.game_flow

Like Ken White says, if you want the computer to select a choice, you need to detect when it is the computer's turn. It looks like in your example this is encoded in the #player variable. You can have a simple if branch which only prompts for input when it is the human player's turn. Everything else could remain the same, but you would update your game_flow method to consider this other case:
if player == 1
print "Round #{#turn}. Player #{player}'s turn. Choose column (1-8): "
input = gets.chomp
while !validate_input(input) || check_full?(input)
print "Invalid Pick. Try again: "
input = gets.chomp
end
input = validate_input(input)
else
input = rand(1..8)
end
Hope this helps.

Related

Building tic tac toe game through scratch stuck while checking winning

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

How to correctly write a ruby method

i'm trying ruby. I want to make a program which can continue the sequence.
1
11
21
1211
111221
(which next line is a calculated each number of previous line)
For example last line is(see previous) one of 1, one of 2, and two of 1.
I make a code and it works fine:
5.times do
result_seq = []
count = 1
puts initial_seq.join
initial_seq.size.times do
if (value = initial_seq.shift) == initial_seq.first
count += 1
else
result_seq << count << value
count = 1
end
end
initial_seq = result_seq
end
But now I want to write a simple method called Next
I want to make:
sec = Sequence.new(1)
sec.next -> will return 11
sec.next.next -> will return 21
sec.next.next.next -> will return 1211
How can i write it correctly using my code?
UPD
I wrote the tests for it:
require "spec_helper"
require "sequence"
describe Sequence do
let(:sequence) { Sequence.new("1") }
describe "to_s" do
it "return initial value" do
expect(sequence.to_s).to eql "1"
end
end
describe "next" do
it "generate next state" do
expect(sequence.next.to_s).to eql "11"
end
it "return Sequence instance" do
expect(sequence.next).to be_an_instance_of(Sequence)
end
it "generate next state 2 times" do
expect(sequence.next.next.to_s).to eql "21"
end
it "generate next state 3 times" do
expect(sequence.next.next.next.to_s).to eql "1211"
end
end
end
class Sequence
attr_reader :initial_seq
def initialize(initial_seq = [])
#initial_seq = initial_seq
print_next
end
def print_next
result_seq = []
count = 1
puts initial_seq.join
initial_seq.size.times do
if (value = initial_seq.shift) == initial_seq.first
count += 1
else
result_seq << count << value
count = 1
end
end
#initial_seq = result_seq
self #<===== The most important part for being able to chain `print_next`
end
end
Usage:
Sequence.new([1]).print_next.print_next.print_next.print_next
1
11
21
1211
111221
edit
If you want to initialize it with integer argument, not array:
def initialize(number)
#initial_seq = [number]
print_next
end
Sequence.new(1).print_next.print_next
1
11
21
Or, if you do not want initialize to accept an argument (assuming, it will always start with 1):
def initialize
#initial_seq = [1]
print_next
end
Sequence.new.print_next.print_next
1
11
21
Ruby provides Enumerators, which behave almost like in OP. Leaving the original code almost unaltered:
seq = Enumerator.new do |yielder|
initial_seq = [1]
loop do #endless loop, but don't worry, its lazy
result_seq = []
count = 1
yielder << initial_seq.join
initial_seq.size.times do
if (value = initial_seq.shift) == initial_seq.first
count += 1
else
result_seq << count << value
count = 1
end
end
initial_seq = result_seq
end
end
5.times{puts seq.next}
puts seq.next

Building Tic Tac Toe game to learn OOP, but my game board isn't updating

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.

Display number of bytes in data set

I wrote a program to create histograms of IP addresses, URLs, error codes, and frequency of IP visits, and would like to obtain the size, in bytes, of the data collected for each histogram. I looked around and saw a bit about the bytes method, but can't seem to get it to function.
Any idea on how to do that to this bit of code? I'd like to add the "byte puts" line after displaying the filename in each method.
class CommonLog
def initialize(logfile)
#logfile = logfile
end
def readfile
#readfile = File.readlines(#logfile).map { |line|
line.split()
}
#readfile = #readfile.to_s.split(" ")
end
def ip_histogram
#ip_count = 0
#readfile.each_index { |index|
if (#readfile[index] =~ /\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/ )
puts #readfile[index]
puts #ip_count += 1
end
}
puts File.basename #logfile
end
def url_histogram
#url_count = 0
#readfile.each_index { |index|
if (#readfile[index] =~ /\/{1}(([a-z]{4,})|(\~{1}))\:{0}\S+/ )
puts #readfile[index]
puts #url_count += 1
end
}
puts File.basename #logfile
end
def requests_per_hour
#time_count2 = 0
#time_count3 = 0
#time_count4 = 0
#time_count5 = 0
#time_count6 = 0
#readfile.each_index { |index|
if (#readfile[index] =~ /\:\d{2}\:/ )
#new = #readfile[index].split(":")
if #new[1] == "02"
#time_count2 += 1
elsif #new[1] == "03"
#time_count3 += 1
elsif #new[1] == "04"
#time_count4 += 1
elsif #new[1] == "05"
#time_count5 += 1
elsif #new[1] == "06"
#time_count6 += 1
end
end
}
puts "#{#time_count2} instances during hour 2"
puts "#{#time_count3} instances during hour 3"
puts "#{#time_count4} instances during hour 4"
puts "#{#time_count5} instances during hour 5"
puts "#{#time_count6} instances during hour 6"
puts File.basename #logfile
end
def sorted_list
#codearray = Array.new
#http_code_count = 0
#count200 = 0
#count304 =0
#count301 = 0
#count403 = 0
#readfile.each_index { |index|
if #readfile[index] =~ /([2][0][0]")|([3][0][4])|([3][0][1])|([4][0][3])/
#codearray << #readfile[index]
#http_code_count += 1
if #readfile[index] == '200'
#count200 += 1
elsif #readfile[index] == "304"
#count304 += 1
elsif #readfile[index] == "301"
#count301 += 1
elseif #readfile[index] == "403"
#count403 += 1
end
end
}
#hash_count = 0
#frequencies = Hash.new(0)
#codearray.each { |word| #frequencies[word] += 1 }
#frequencies = #frequencies.sort_by { |a, b| a}
#frequencies.each { |word, frequency| #hash_count += frequency}
#frequencies.each { |key, value|
puts "Error #{key} : #{(value.to_f/#hash_count.to_f)*100}%"
}
puts File.basename #logfile
end
end
my_file = CommonLog.new("test_log")
my_file.readfile
my_file.ip_histogram
my_file.url_histogram
my_file.requests_per_hour
my_file.sorted_list
Assuming that the number of bytes processed is the entire size of each log file you could do something like this:
class CommonLog
attr_reader :bytes_read
def initialize(logfile)
#logfile = logfile
#bytes_read = File.size(logfile)
end
# ... now simply print "bytes_read" when desired ...

A very specific Conway's Game of Life (Ruby beginner)

Looking for feedback on obvious logic errors on this, not optimizing. I keep getting weird tick counts on the end game message (ex: 1 tick turns into 11 ticks)
The largest error I can spot while running the code is on the 2nd tick, a very large amount of alive cells appear. I am too new to this to understand why, but it seems like the #alive_cells is not resetting back to 0 after each check.
Here is my entire code, its large but it should be child's play to anyone with experience.
class CellGame
def initialize
puts "How big do you want this game?"
#size = gets.chomp.to_i
#cell_grid = Array.new(#size) { Array.new(#size) }
#grid_storage = Array.new(#size) { Array.new(#size) }
#tick_count = 0
fill_grid_with_random_cells
end
def fill_grid_with_random_cells
#cell_grid.each do |row|
row.map! do |cell|
roll = rand(10)
if roll > 9
"•"
else
" "
end
end
end
check_cells_for_future_state
end
def check_for_any_alive_cells
#cell_grid.each do |row|
if row.include?("•")
check_cells_for_future_state
break
else
end_game_print_result
end
end
end
def check_cells_for_future_state
#cell_grid.each_with_index do |row, row_index|
row.each_with_index do |cell, cell_index|
#live_neighbors = 0
add_row_shift = (row_index + 1)
if add_row_shift == #size
add_row_shift = 0
end
add_cell_shift = (cell_index + 1)
if add_cell_shift == #size
add_cell_shift = 0
end
def does_this_include_alive(cell)
if cell.include?("•")
#live_neighbors +=1
end
end
top_left_cell = #cell_grid[(row_index - 1)][(cell_index - 1)]
does_this_include_alive(top_left_cell)
top_cell = #cell_grid[(row_index - 1)][(cell_index)]
does_this_include_alive(top_cell)
top_right_cell = #cell_grid[(row_index - 1)][(add_cell_shift)]
does_this_include_alive(top_right_cell)
right_cell = #cell_grid[(row_index)][(add_cell_shift)]
does_this_include_alive(right_cell)
bottom_right_cell = #cell_grid[(add_row_shift)][(add_cell_shift)]
does_this_include_alive(bottom_right_cell)
bottom_cell = #cell_grid[(add_row_shift)][(cell_index)]
does_this_include_alive(bottom_cell)
bottom_left_cell = #cell_grid[(add_row_shift)][(cell_index - 1)]
does_this_include_alive(bottom_left_cell)
left_cell = #cell_grid[(row_index)][(cell_index - 1)]
does_this_include_alive(left_cell)
if #live_neighbors == 2 || #live_neighbors == 3
#grid_storage[row_index][cell_index] = "•"
else
#grid_storage[row_index][cell_index] = " "
end
end
end
update_cell_grid
end
def update_cell_grid
#cell_grid = #grid_storage
print_cell_grid_and_counter
end
def print_cell_grid_and_counter
system"clear"
#cell_grid.each do |row|
row.each do |cell|
print cell + " "
end
print "\n"
end
#tick_count += 1
print "\n"
print "Days passed: #{#tick_count}"
sleep(0.25)
check_for_any_alive_cells
end
def end_game_print_result
print "#{#tick_count} ticks were played, end of game."
exit
end
end
I couldn't see where your code went wrong. It does have a recursive call which can easily cause strange behavior. Here is what I came up with:
class CellGame
def initialize(size)
#size = size; #archive = []
#grid = Array.new(size) { Array.new(size) { rand(3).zero? } }
end
def lives_on?(row, col)
neighborhood = (-1..1).map { |r| (-1..1).map { |c| #grid[row + r] && #grid[row + r][col + c] } }
its_alive = neighborhood[1].delete_at(1)
neighbors = neighborhood.flatten.count(true)
neighbors == 3 || neighbors == 2 && its_alive
end
def next_gen
(0...#size).map { |row| (0...#size).map { |col| lives_on?(row, col) } }
end
def play
tick = 0; incr = 1
loop do
#archive.include?(#grid) ? incr = 0 : #archive << #grid
sleep(0.5); system "clear"; #grid = next_gen
puts "tick - #{tick += incr}"
puts #grid.map { |row| row.map { |cell| cell ? '*' : ' ' }.inspect }
end
end
end
cg = CellGame.new 10
cg.play
The tick count stops but the program keeps running through the oscillator at the end.
I wanted to revisit this and confidently say I have figured it out! Here is my new solution - still super beginner focused. Hope it helps someone out.
class Game
# Uses constants for values that won't change
LIVE = "🦄"
DEAD = " "
WIDTH = 68
HEIGHT = 34
def initialize
# Sets our grid to a new empty grid (set by method below)
#grid = empty_grid
# Randomly fills our grid with live cells
#grid.each do |row|
# Map will construct our new array, we use map! to edit the #grid
row.map! do |cell|
if rand(10) == 1
LIVE # Place a live cell
else
DEAD # Place a dead cell
end
end
end
# Single line implimentation
# #grid.each {|row|row.map! {|cell|rand(10) == 1 ? LIVE : DEAD}}
loop_cells #start the cycle
end
def empty_grid
Array.new(HEIGHT) do
# Creates an array with HEIGHT number of empty arrays
Array.new(WIDTH) do
# Fills each array with a dead cell WIDTH number of times
DEAD
end
end
# Single line implimentation
# Array.new(HEIGHT){ Array.new(WIDTH) { DEAD } }
end
def print_grid # Prints our grid to the terminal
system "clear" # Clears the terminal window
# Joins cells in each row with an empty space
rows = #grid.map do |row|
row.join(" ")
end
# Print rows joined by a new line
print rows.join("\n")
# Single line implimentation
# print #grid.map{|row| row.join(" ")}.join("\n")
end
def loop_cells
print_grid # Start by printing the current grid
new_grid = empty_grid # Set an empty grid (this will be the next life cycle)
# Loop through every cell in every row
#grid.each_with_index do |row, row_index|
row.each_with_index do |cell, cell_index|
# Find the cells friends
friends = find_friends(row_index, cell_index)
# Apply life or death rules
if cell == LIVE
state = friends.size.between?(2,3)
else
state = friends.size == 3
end
# Set cell in new_grid for the next cycle
new_grid[row_index][cell_index] = state ? LIVE : DEAD
end
end
# Replace grid and start over
#grid = new_grid
start_over
end
def find_friends(row_index, cell_index)
# Ruby can reach backwards through arrays and start over at the end - but it cannot reach forwards. If we're going off the grid, start over at 0
row_fix = true if (row_index + 1) == HEIGHT
cell_fix = true if (cell_index + 1) == WIDTH
# You'll see below I will use 0 if one of these values is truthy when checking cells to the upper right, right, lower right, lower, and lower left.
# Check each neighbor, use 0 if we're reaching too far
friends = [
#grid[(row_index - 1)][(cell_index - 1)],
#grid[(row_index - 1)][(cell_index)],
#grid[(row_index - 1)][(cell_fix ? 0 : cell_index + 1)],
#grid[(row_index)][(cell_fix ? 0 : cell_index + 1)],
#grid[(row_fix ? 0 : row_index + 1)][(cell_fix ? 0 : cell_index + 1)],
#grid[(row_fix ? 0 : row_index + 1)][(cell_index)],
#grid[(row_fix ? 0 : row_index + 1)][(cell_index - 1)],
#grid[(row_index)][(cell_index - 1)]
]
# Maps live neighbors into an array, removes nil values
friends.map{|x| x if x == LIVE}.compact
end
def start_over
sleep 0.1
loop_cells
end
end
# Start game when file is run
Game.new

Resources