简体   繁体   English

有一个简单的浏览器内JS游戏,需要它与“后端”上的Ruby脚本一起使用

[英]Have a simple in-browser JS game need it to work with a Ruby script on the 'backend'

My 'frontend' is a JS script that loads a HTML5 canvas and draws a X * Y grid, it then draws an alien at some default (X,Y) coordinate in the grid. 我的“前端”是一个JS脚本,该脚本加载HTML5画布并绘制X * Y网格,然后在网格中的某个默认(X,Y)坐标处绘制外星人。

I have some ruby classes that define how this alien moves. 我有一些定义该外星人如何移动的红宝石类。 For now, it's just +- on the X,Y plane. 现在,它在X,Y平面上只是+-。 I want to be able to click on a 'move forward' button in the browser, and for that to send a request to the ruby script which will then calculate the new position and send a response with the coordinates. 我希望能够在浏览器中单击“前进”按钮,并将其发送到红宝石脚本,然后该脚本将计算新位置并发送带有坐标的响应。

Could somebody point me in the right direction? 有人能指出我正确的方向吗? I can't get the logic around doing this. 我无法理解这样做的逻辑。 I've read into Sinatra, AJAX, templates, and so on but nothing is helping. 我已经阅读了Sinatra,AJAX,模板等,但是没有任何帮助。

Edit 编辑

app.rb app.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

home.haml 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 the / path is loaded, home.haml should load and I would like for the x and y values to be passed to a JS script which uses these coordinates to draw an image. 加载/路径后,应加载home.haml,我希望将xy值传递给使用这些坐标绘制图像的JS脚本。 I'm not sure how to do this exactly. 我不确定如何确切地做到这一点。

1) Use javascript to intercept the button click by installing an onclick event handler on the button. 1)通过在按钮上安装onclick event handler ,使用javascript拦截按钮单击。

2) The onclick event handler function should use javascript(or jquery) to send an AJAX request to the server. 2) onclick event handler函数应使用javascript(或jquery)将AJAX请求发送到服务器。 The AJAX request should include any relevant data that your server side ruby script needs to produce its calculation. AJAX请求应包含服务器端ruby脚本进行计算所需的所有相关数据。 Your AJAX request will specify a certain url, eg 您的AJAX请求将指定某个网址,例如

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

3) Your Sinatra app, which is located on the server, can be as simple as this: 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

When your server receives a GET request for the url /calculate_new_position?x=10&y=20 , it will cause the code above to execute. 当您的服务器收到针对url /calculate_new_position?x=10&y=20的GET请求时,它将导致上述代码执行。 Sinatra will automatically insert any GET (or POST) variables in a Hash called params . Sinatra将自动在称为params的哈希中插入任何GET(或POST)变量。 The return value of the block will be the response that is sent back to the browser. 该块的返回值将是发送回浏览器the response

4) Your javascript AJAX code will include a function that is called when the response from the server is received. 4)您的javascript AJAX代码将包含一个函数,当收到服务器the responsethe response调用该函数。 The function will contain something like 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 to move figures to new coordinates.

Here is an example: 这是一个例子:

~/ruby_programs/sinatra_4app$ tree
.
├── models
│   └── alien.rb
├── public
│   └── js
│       └── grid.js
├── routes.rb
└── views
    └── home.haml

4 directories, 4 files

home.haml: 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: 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>

routes.rb: routes.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

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

grid.js: grid.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);
    });

  });

});

Note that js comments start with //, so the code above will cause errors if you don't replace the # with //. 请注意,js注释以//开头,因此如果您不将#替换为//,则上面的代码将导致错误。 I'm using the # to get the light gray shading, which makes the code easier to read. 我正在使用#来获得浅灰色阴影,这使代码更易于阅读。

1) Start the server: 1)启动服务器:

~/ruby_programs/sinatra_4app$ ruby routes.rb 

2) Then enter the following url in your browser: 2)然后在浏览器中输入以下网址:

http://localhost:4567/

3) Then open the Console window for whatever browser you are using. 3)然后为正在使用的任何浏览器打开“控制台”窗口。 In Firefox, the console window is under: 在Firefox中,控制台窗口位于以下位置:

Tools>Web Developer>Web Console

In Chrome, it's: 在Chrome中,它是:

View>Developer>Javascript Console

4) Click on the "Move forward" button; 4)点击“前进”按钮; then check the output in the Console window. 然后在“控制台”窗口中检查输出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM