Julac Ontina Julac Ontina -5 years ago 134
Ruby Question

Ruby Basic Collision Detection using text

I'm trying to make a simple text-based ruby game that is basically a maze. I've already planned where to put the "walls" in the area I've built. The only problem is that whenever I try to check to see if the "player" or an entity collides, it doesn't. It just goes on as if there weren't any walls put up.
Here's the code:

#Maze Preset 1 Testing
wallpos = [5,1],[1,2],[3,2],[4,2],[2,4],[3,4],[5,4],[3,5]
puts wallpos
x = gets
y = gets
pos = Array[x,y]
if pos == wallpos
puts ""
puts "Intersect"
puts ""
puts "Nope."

Notes: I placed a puts wallpos and puts pos so I could see if the values I got are correct.

Answer Source

As Petr said, you need to process your input correctly:

x = gets.chomp.to_i
y = gets.chomp.to_i

Also, you are using the equality operator (==) incorrectly. A single coordinate pair cannot ever be equal to an array of coordinates. Instead, you should use Array#include? to check if the coordinates are found in the array. The code would look like this:

if wallpos.include?(pos)

By the way, the p method is great for debugging. If you are not sure of a value in your program (say, foo) you can print it out by adding:

p foo

which is short for

puts foo.inspect
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download