javascript - 有一个简单的浏览器内 JS 游戏需要它在 'backend' 上使用 Ruby 脚本

标签 javascript ruby html sinatra

我的“前端”是一个 JS 脚本,它加载 HTML5 Canvas 并绘制 X * Y 网格,然后在网格中的某个默认 (X,Y) 坐标处绘制一个外星人。

我有一些定义这个外星人如何移动的 ruby 类。现在,它只是 X,Y 平面上的 +-。我希望能够单击浏览器中的“向前移动”按钮,并为此向 ruby​​ 脚本发送请求,然后该脚本将计算新位置并发送带有坐标的响应。

有人能给我指出正确的方向吗?我无法理解这样做的逻辑。我已经阅读了 Sinatra、AJAX、模板等,但没有任何帮助。

编辑

应用.rb

require 'sinatra'
require_relative 'alien'

get '/' do
  haml :home
end

get '/new_alien' do
  @alien = Alien.new 1,1,:N       # create a new alien
  @x = @alien.x                  # set the x coordinate
  @y = @alien.y                  # set the y coordinate
  %Q|{ "x":#{@x}, "y":#{@y} }|  # return a string with the coordinates
end

主页.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")

当加载 / 路径时,home.haml 应该加载,我希望将 xy 值传递给使用这些坐标绘制图像的 JS 脚本。我不确定该怎么做。

最佳答案

1) 通过在按钮上安装 onclick 事件处理程序,使用 javascript 拦截按钮点击。

2) onclick 事件处理程序 函数应该使用 javascript(或 jquery)向服务器发送 AJAX 请求。 AJAX 请求应包含服务器端 ruby​​ 脚本生成其计算所需的任何相关数据。您的 AJAX 请求将指定一个特定的 url,例如

"/calculate_new_position?x=10&y=20"

3) 您位于服务器上的 Sinatra 应用可以像这样简单:

 require 'sinatra'

 get '/calculate_new_positon' do

    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 is the response:
    %Q|{ "new_x":#{new_x}, "new_y":#{new_y} }| 

 end

当您的服务器收到对 url /calculate_new_position?x=10&y=20 的 GET 请求时,它会导致上面的代码执行。 Sinatra 将自动在名为 params 的哈希中插入任何 GET(或 POST)变量。该 block 的返回值将是发送回浏览器的响应

4) 您的 javascript AJAX 代码将包含一个函数,该函数在收到来自服务器的响应 时调用。该函数将包含如下内容:

obj = JSON.parse(json_str);  //--> obj = {"new_x":22, "new_y":-3};
new_x = obj["new_x"];
new_y = obj["new_y"];

#Use javascript to move figures to new coordinates.

这是一个例子:

~/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"}

sinatra执行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>

路线.rb:

require 'sinatra'
require_relative 'models/alien'

get '/' do
  haml :home, :format => :html5
  #Sinatra automatically looks for templates in a 'views' directory, so the line above looks for the file: views/home.haml
end

get '/new_alien' do
  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 a string in json format containing the new coordinates
end

外星人.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 the accessor method rather than changing @x directly, which is considered good practice.
    self.y -= 2
  end
end

网格.js:

$(document).ready(function() {
                  #This function executes when all the html elements exist, i.e. when
                  #the document is 'ready'--you can't search for an element until it exists.

  #Search for an element whose id="forward_button" and install an event handler function 
  #for its onclick event:
  $("#forward_button").click(function() {
                             #This function executes when the button is 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 is a specialized version of $.ajax()
                   #This function is called when the browser
                   #receives the response returned by the server

      new_x = js_obj["new_x"];
      new_y = js_obj["new_y"];
      #Do something with new_x and new_y...

      console.log( "Response received!" );
      console.log( "new_x= " + new_x);
      console.log( "new_y= " + new_y);
    });

  });

});

注意js注释是以//开头的,所以上面的代码如果不把#换成//就会报错。我使用 # 来获得浅灰色阴影,这使代码更易于阅读。

1) 启动服务器:

~/ruby_programs/sinatra_4app$ ruby routes.rb 

2) 然后在浏览器中输入以下网址:

http://localhost:4567/

3) 然后打开您正在使用的任何浏览器的控制台窗口。在 Firefox 中,控制台窗口位于:

Tools>Web Developer>Web Console

在 Chrome 中,它是:

View>Developer>Javascript Console

4) 点击“前进”按钮;然后在控制台窗口中检查输出。

关于javascript - 有一个简单的浏览器内 JS 游戏需要它在 'backend' 上使用 Ruby 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25366669/

相关文章:

ruby-on-rails - "one, two, and three"是否存在 Rails 助手?

ruby - Shotgun 上的 Sinatra 和 Ruby 1.9.2 问题

javascript - 为什么输出是01122?

javascript - Angularjs 将 json 响应合并为一个

javascript - 当通过load() ajax函数提交表单时,如何清除文本框中的文本

javascript - 在应用 CSS 和 Javascript 之前,如何防止导航呈现为列表?

ruby - 如何在 ruby​​ watir 中选择下拉值选项?

javascript - 使用 toDataURL ("image/png")时如何捕获 HTML5 Canvas 的背景?

javascript - 如何修改多级菜单以与 *ngFor 和 querySelectorAll 一起使用?

javascript - 解析数组内的 JSON 数组并与 pdfmake 绑定(bind)