javascript - Have a simple in-browser JS game need it to work with a Ruby script on the 'backend' -
my 'frontend' js script loads html5 canvas , draws x * y grid, draws alien @ default (x,y) coordinate in grid.
i have ruby classes define how alien moves. now, it's +- on x,y plane. want able click on 'move forward' button in browser, , send request ruby script calculate new position , send response coordinates.
could point me in right direction? can't logic around doing this. i've read sinatra, ajax, templates, , on nothing helping.
edit
app.rb
require 'sinatra' require_relative 'alien' '/' haml :home end '/new_alien' @alien = alien.new 1,1,:n # create new alien @x = @alien.x # set x coordinate @y = @alien.y # set y coordinate %q|{ "x":#{@x}, "y":#{@y} }| # return string coordinates end
home.haml
!!! %html %head %link{:rel => :stylesheet, :type => :"text/css", :href => "/css/main.css"} %body .wrapper %script(src="http://code.jquery.com/jquery-2.1.1.min.js") %script(src="/js/grid.js")
when /
path loaded, home.haml should load , x
, y
values passed js script uses these coordinates draw image. i'm not sure how exactly.
1) use javascript intercept button click installing onclick event handler
on button.
2) onclick event handler
function should use javascript(or jquery) send ajax request server. ajax request should include relevant data server side ruby script needs produce calculation. ajax request specify url, e.g.
"/calculate_new_position?x=10&y=20"
3) sinatra app, located on server, can simple this:
require 'sinatra' '/calculate_new_positon' x_coord = params[:x] #=> 10 y_coord = params[:y] #=> 20 #do calculation here: new_x = x_coord * 20 new_y = y_coord - 3 #the following string response: %q|{ "new_x":#{new_x}, "new_y":#{new_y} }| end
when server receives request url /calculate_new_position?x=10&y=20
, cause code above execute. sinatra automatically insert (or post) variables in hash called params
. return value of block the response
sent browser.
4) javascript ajax code include function called when the response
server received. function contain this:
obj = json.parse(json_str); //--> obj = {"new_x":22, "new_y":-3}; new_x = obj["new_x"]; new_y = obj["new_y"]; #use javascript move figures new coordinates.
here example:
~/ruby_programs/sinatra_4app$ tree . ├── models │ └── alien.rb ├── public │ └── js │ └── grid.js ├── routes.rb └── views └── home.haml 4 directories, 4 files
home.haml:
!!! 5 %html %body %button#forward_button move forward %script{:type => "text/javascript", :src => "http://code.jquery.com/jquery-2.1.1.min.js"} %script{:type => "text/javascript", :src => "/js/grid.js"}
the result after sinatra executes home.haml:
<!doctype html> <html> <body> <button id='forward_button'>move forward</button> <script src='http://code.jquery.com/jquery-2.1.1.min.js' type='text/javascript'></script> <script src='/js/grid.js' type='text/javascript'></script> </body> </html>
routes.rb:
require 'sinatra' require_relative 'models/alien' '/' haml :home, :format => :html5 #sinatra automatically looks templates in 'views' directory, line above looks file: views/home.haml end '/new_alien' alien = alien.new 1,1,:n alien.calculate_new_position new_x = alien.x new_y = alien.y %q|{ "new_x":#{new_x}, "new_y":#{new_y} }| #return string in json format containing new coordinates end
alien.rb:
class alien attr_accessor :x, :y, :direction def initialize(x, y, direction) @x = x @y = y @direction = direction end def calculate_new_position self.x += 2 #changes @x using accessor method rather changing @x directly, considered practice. self.y -= 2 end end
grid.js:
$(document).ready(function() { #this function executes when html elements exist, i.e. when #the document 'ready'--you can't search element until exists. #search element id="forward_button" , install event handler function #for onclick event: $("#forward_button").click(function() { #this function executes when button clicked #get current x, y coords somehow.... var x = 10; var y = 20; var url = "/new_alien?x=" + x + "&y=" + y; $.getjson(url, function(js_obj) { #this specialized version of $.ajax() #this function called when browser #receives response returned server new_x = js_obj["new_x"]; new_y = js_obj["new_y"]; #do new_x , new_y... console.log( "response received!" ); console.log( "new_x= " + new_x); console.log( "new_y= " + new_y); }); }); });
note js comments start //, code above cause errors if don't replace # //. i'm using # light gray shading, makes code easier read.
1) start server:
~/ruby_programs/sinatra_4app$ ruby routes.rb
2) enter following url in browser:
http://localhost:4567/
3) open console window whatever browser using. in firefox, console window under:
tools>web developer>web console
in chrome, it's:
view>developer>javascript console
4) click on "move forward" button; check output in console window.
Comments
Post a Comment