Ruby instance variable changes unexpectedly - ruby

In the code below, a cluster has many points.
class Cluster
attr_accessor :centroid, :points
def initialize(centroid, *points)
#centroid = centroid
#points = points
end
end
class Point
attr_accessor :x, :y
def initialize(x = 0, y = 0)
#x = x
#y = y
end
end
An example of a Cluster object (lets us call this c):
#<Cluster:0x007ff5c123c210
#centroid=#<Point:0x007ff5c123c288 #x=25, #y=125>,
#points=
[#<Point:0x007ff5c123c238 #x=25, #y=125>,
#<Point:0x007ff5c1020120 #x=28, #y=145>]>
I am trying to calculate the mean of the points, and update #centroid without changing #points.
Let's say I have:
class Point
def +(point)
#x = #x + point.x
#y = #y + point.y
self
end
def /(num)
#x = #x/num
#y = #y/num
self
end
end
and to calculate the mean of all the points, I run:
c.centroid = c.points.reduce(&:+)/c.points.length
Then, c changes to:
#<Cluster:0x007ff5c123c210
#centroid=#<Point:0x007ff5c1515ec8 #x=26, #y=135>,
#points=
[#<Point:0x007ff5c1515ec8 #x=26, #y=135>,
#<Point:0x007ff5c1020120 #x=28, #y=145>]>
Note that first element of the #points is changed. Any suggestions?

Your + method in Point modifies the point's members #x and #y. You need to return a new point with the calculated values instead:
def +(point)
Point.new(#x + point.x, #y + point.y)
end
def /(num)
Point.new(#x/num, #y/num)
end

Since you did not pass an initial value to reduce, the first point became modified. You can pass a new point as the initial value to reduce, which will be modified and returned.
c.centroid = c.points.reduce(Point.new, &:+)/c.points.length

I think the problem is caused by the + method modifying the point #x and #y values.
Try changing the + method to:
def +(point)
x = #x + point.x
y = #y + point.y
self.class.new(x, y)
end

Related

Trouble making random spawning enemies shoot bullets

I have figured out how to randomly spawn enemies in different locations, but I cant figure out to make some of the enemies randomly fire bullets.
I created a Bullet class and a Enemy class. I use attr_reader to locate the enemies and call the x and y locations in the new Bullet method, but it fails to find where the enemy is located.
require 'gosu'
require_relative 'player'
require_relative 'enemy'
require_relative 'bullet'
class Proto < Gosu::Window
WIDTH = 1000
HEIGHT = 800
ENEMY_FREQUENCY = 0.03
attr_reader :x, :y, :radius, :angle
def initialize
super(WIDTH,HEIGHT)
self.caption = "Proto"
#player = Player.new(self)
#enemies = []
#bullets = []
#framecounter = 0
end
def update
#framecounter += 1
#player.turn_left if button_down?(Gosu::KbLeft)
#player.turn_right if button_down?(Gosu::KbRight)
#player.accelerate if button_down?(Gosu::KbUp)
#player.backward if button_down?(Gosu::KbDown)
#player.move
if rand < ENEMY_FREQUENCY
#enemies.push Enemy.new(self)
end
#enemies.each do |enemy|
enemy.move
if #framecounter % 60 == 0 && #enemies[3]
#bullets.push Bullet.new(self, #enemy.x, #enemy.y, #enemy.angle)
end
end
#bullets.each do |bullet|
bullet.move
end
end
def draw
#player.draw
#enemies.each do |enemy|
enemy.draw
end
#bullets.each do |bullet|
bullet.draw
end
end
end
window = Proto.new
window.show
class Enemy
SPEED = 1
attr_reader :x, :y, :radius, :angle
def initialize(window)
#radius = 20
#x = rand(window.width - 2 * #radius) + #radius
#y = 0
#image = Gosu::Image.new('ima/tile000.png')
end
def move
#y += SPEED
end
def draw
#image.draw(#x - #radius, #y - #radius, 2)
end
end
require_relative 'enemy'
class Bullet
SPEED = 5
def initialize(window, x, y, angle)
#x = x
#y = y
#direction = angle
#image = Gosu::Image.new('ima/tile000.png')
#imaget = Gosu::Image.new('ima/tile000.png')
#radius = 3
#window = window
end
def move
#y += SPEED
end
def draw
#image.draw(#x - #radius, #y - #radius, 1)
#imaget.draw(#enemy.x - radius, #enemy.y - #radius, 1)
end
end
I expect random enemies to fire bullets.
As discussed in the comments, the issue was that you had
#enemies.each do |enemy|
#enemy.draw
end
instead of
#enemies.each do |enemy|
enemy.draw
end

Keeping track of the path, Knights travel

So far my shortest path method will stop when it reaches the goal position, printing out everything it did along the way. I would like to know how I could go about implementing parent positions so I can print the path along with the goal. This is an assignment.
class Knight
attr_accessor :x, :y, :prev_position, :moves
def initialize(position)
#x = position[0]
#y = position[1]
#prev_position = nil
#moves = [
[-1,-2],
[-2,-1],
[-2,+1],
[-1,+2],
[+1,-2],
[+2,-1],
[+2,+1],
[+1,+2]]
end
def possible
move_list = Array.new
#moves.each do |moves|
x = #x + moves[0]
y = #y + moves[1]
if x.between?(0,7)
if y.between?(0,7)
move_list << [x,y]
end
end
end
move_list
end
end
def shortest_path(position,goal)
paths = Array.new
#start_knight = Knight.new(position)
until #start_knight.x == goal[0] and
#start_knight.y == goal[1]
#start_knight.possible.each do |p| paths << p end
shifted = paths.shift
#start_knight.x = shifted[0]
#start_knight.y = shifted[1]
puts "[#{#start_knight.x},#{#start_knight.y}]"
end
end
shortest_path([0,0],[7,7])

ruby gosu moving image to the direction is pointed at

i have been trying to make an image move to the direction it is pointed at.
however it just keeps moving in random directions :(
cant figure out why...
here's the code:
require 'gosu'
class Game < Gosu::Window
def initialize
super(1280, 720, true)
#image = Gosu::Image.from_text ':', 100
#ang = 1
#x = 640 - #image.width
#y = 360 - #image.height
end
def update
#sngX = (10.0/Math.cos(#ang.to_f)).to_i
#sngY = (10.0/Math.sin(#ang.to_f)).to_i
#n = Gosu::Image.from_text #ang.to_s, 50
end
def draw
#image.draw_rot #x, #y, 0, #ang
#n.draw 0, 0, 0
end
def button_down id
close if id == Gosu::KbEscape
if id == Gosu::KbE
#ang += 10
end
if id == Gosu::KbQ
#ang -= 10
end
if id == Gosu::KbW
#x += #sngX
#y += #sngY
end
end
end
Game.new.show
It definitely does not behave random.
I'd bet the issue is with Math trigonometric functions expect values in radians not grads, so #sngX and #sngY are assigned extreme results.
From the Ruby docs to Math::cos:
Computes the cosine of x (expressed in radians). Returns a Float in the range -1.0..1.0
Hope you know how to convert grads to radians.

Setting method local variables from a proc

If I have a class with two instance variables #x and #y, I can change them from a proc using self.instance_exec:
class Location
attr_accessor :x, :y
def initialize
#x = 0
#y = 0
end
def set &block
self.instance_exec(&block)
end
end
location = Location.new
location.set do
#x = rand(100)
#y = rand(100)
end
puts location.x
puts location.y
If I have a class with a method set with two local variables x and y, I can use proc return values to set them:
class Location
def set &block
x = 0;
y = 0;
x, y = block.call()
# do something with x and y
puts x
puts y
end
end
location = Location.new
location.set do
x = rand(100)
y = rand(100)
[x, y]
end
Is there a way to access the set method local variables x and y from the proc without using return values?
You can do it, sort of, but it isn't pretty
There is a way for block to set a variable in a calling method, but it isn't pretty. You can pass in a binding, then eval some code using the binding:
def foo(binding)
binding.eval "x = 2"
end
x = 1
foo(binding)
p x # => 2
Blocks also carry with them the binding in which they were defined, so if a block is being passed, then:
def foo(&block)
block.binding.eval "x = 2"
end
x = 1
foo {}
p x # => 2
What's in the block doesn't matter, in this case. It's just being used as a carrier for the binding.
Other ways to achieve the same goal
Yield an object
A more pedestrian way for a block to interact with it's caller is to pass an object to the block:
class Point
attr_accessor :x
attr_accessor :y
end
class Location
def set
point = Point.new
yield point
p point.x # => 10
p point.y # => 20
end
end
location = Location.new
location.set do |point|
point.x = 10
point.y = 20
end
This is often preferred to fancier techniques: It's easy to understand both its implementation and its use.
instance_eval an object
If you want to (but you probably shouldn't want to), the block's caller can use instance_eval/instance_exec to call the block. This sets self to the object, for that block.
class Location
def set(&block)
point = Point.new
point.instance_eval(&block)
p point.x # => 10
p point.y # => 20
end
end
location = Location.new
location.set do
self.x = 10
self.y = 20
end
You see that the block had to use use self. when calling the writers, otherwise new, local variables would have been declared, which is not what is wanted here.
Yield or instance_eval an object
Even though you still probably shouldn't use instance_eval, sometimes it's useful. You don't always know when it's good, though, so let's let the method's caller decide which technique to use. All the method has to do is to check that the block has parameters:
class Location
def set(&block)
point = Point.new
if block.arity == 1
block.call point
else
point.instance_eval(&block)
end
p point.x
p point.y
end
end
Now the user can have the block executed in the scope of the point:
location = Location.new
location.set do
self.x = 10
self.y = 20
end
# => 10
# => 20
or it can have the point passed to it:
location.set do |point|
point.x = 30
point.y = 40
end
# => 30
# => 40

question on overriding + operator in ruby

A recent convert to Ruby here. The following question isn't really practical; it's more of a question on how the internals of Ruby works. Is it possible to override the standard addition operator to accept multiple inputs? I'm assuming that the answer is no, given that the addition operator is a standard one, but i wanted to make sure i wasn't missing something.
Below is the code I wrote up quick to verify my thoughts. Note, it's completely trivial/contrived.
class Point
attr_accessor :x, :y
def initialize(x,y)
#x, #y = x, y
end
def +(x,y)
#x += x
#y += y
end
def to_s
"(#{#x}, #{#y})"
end
end
pt1 = Point.new(0,0)
pt1 + (1,1) # syntax error, unexpected ',', expecting ')'
You should not mutate the object when implementing + operator. Instead return a new Point Object:
class Point
attr_accessor :x, :y
def initialize(x,y)
#x, #y = x, y
end
def +(other)
Point.new(#x + other.x, #y + other.y)
end
def to_s
"(#{#x}, #{#y})"
end
end
ruby-1.8.7-p302:
> p1 = Point.new(1,2)
=> #<Point:0x10031f870 #y=2, #x=1>
> p2 = Point.new(3, 4)
=> #<Point:0x1001bb718 #y=4, #x=3>
> p1 + p2
=> #<Point:0x1001a44c8 #y=6, #x=4>
> p3 = p1 + p2
=> #<Point:0x1001911e8 #y=6, #x=4>
> p3
=> #<Point:0x1001911e8 #y=6, #x=4>
> p1 += p2
=> #<Point:0x1001877b0 #y=6, #x=4>
> p1
=> #<Point:0x1001877b0 #y=6, #x=4>
You can define the + method like that, but you'll only be able to call it using normal method call syntax:
pt1.+(1,1)
You can achieve something similar using arrays:
def +(args)
x, y = args
#x += x
#y += y
end
and later use it as:
pt1 + [1, 1]
You can also combine it with Chandra's solution, to accept both arrays and Points as arguments.

Resources