拥有一个简单的浏览器内JS游戏,需要它与后端'Ruby脚本一起工作
Have a simple in-browser JS game need it to work with a Ruby script on the 'backend'
我的'frontend'是一个JS脚本,它加载一个HTML5画布并绘制一个X * Y网格,然后在网格中的一些默认(X,Y)坐标绘制一个外星人。
我有一些ruby类来定义这个外星人如何移动。现在,它在xy平面上是+-。我希望能够在浏览器中单击"向前移动"按钮,并为此向ruby脚本发送请求,然后计算新位置并发送带有坐标的响应。
谁能给我指个正确的方向?我搞不懂这样做的逻辑。我读过Sinatra、AJAX、模板等等,但是没有任何帮助。编辑
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
!!!
%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应该加载,我想将x
和y
值传递给使用这些坐标绘制图像的JS脚本。我不知道该怎么做。
1)使用javascript拦截按钮点击,在按钮上安装onclick event handler
。
2) onclick event handler
函数应该使用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
的Hash中插入任何GET(或POST)变量。块的返回值将是发送回浏览器的the response
。
4)你的javascript AJAX代码将包括一个函数,当从服务器接收到the response
时调用。该函数将包含如下内容:
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>
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:
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:
$(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)然后在浏览器中输入以下url:
http://localhost:4567/
3)然后打开控制台窗口为您正在使用的浏览器。在Firefox中,控制台窗口位于:
Tools>Web Developer>Web Console
在Chrome中,它是:
View>Developer>Javascript Console
4)点击"前进"按钮;然后检查控制台窗口中的输出
- 未能从后端触发javascript
- 检查浏览器'在asp.net的后端代码中启用或禁用了s JS
- Ajax登录技术(后端php)
- 将Rails后端添加到JS/HTML/CSS应用程序时,正确的文件位置是什么
- 视图没有't在模拟后端时加载
- 是否可以在不使用外部后端的情况下编写grafana数据源插件
- 如何将Angular 2用于各种网站&使用PHP作为后端的模块
- 如何在不重新加载URL的情况下查询Node.Js的后端并更新页面
- 从后端检查Open Social小工具中的用户身份验证
- 如何使用python后端和web前端提供braintree客户端令牌
- 某些Magento后端管理按钮已停止工作
- 构建一个HTML小部件来嵌入付费内容-如何确保与后端的通信安全
- 为什么Express.js后端的CORS设置不起作用
- 调用后端、多路径变量、Ext Js
- 如何断言后端端点已被调用
- 骨干关系是否需要后端
- 与带下划线的后端同步时,转换为 CamelCase 以在 JavaScript 中使用
- 使用 Node 后端设置 webpack 热开发服务器以进行生产
- 拥有一个简单的浏览器内JS游戏,需要它与后端'Ruby脚本一起工作
- 是否有一种方法来连接值(如枚举)从前端(JS)到后端(PHP/Ruby)没有重复