[译]Pixelreka! -使用TogetherJS JavaScript库进行实时游戏
By robot-v1.0
本文链接 https://www.kyfws.com/applications/pixelreka-real-time-game-with-togetherjs-javascrip-zh/
版权声明 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
- 12 分钟阅读 - 5727 个词 阅读量 0[译]Pixelreka! -使用TogetherJS JavaScript库进行实时游戏
原文地址:https://www.codeproject.com/Articles/700528/Pixelreka-Real-Time-Game-with-TogetherJS-JavaScrip
原文作者:Marcelo Ricardo de Oliveira
译文由本站 robot-v1.0 翻译
前言
Build a collaborative game (or any other app) with Mozilla’s Real Time Collaboration Library 使用Mozilla的实时协作库构建协作游戏(或任何其他应用)
介绍(Introduction)
几个月前,Mozilla Foundation发布了功能强大的协作工具TogetherJS:一个JavaScript库,该JavaScript库一旦添加到您的网站中,便可以实时建立用户之间的连接.(A few months ago, Mozilla Foundation released TogetherJS, a powerful collaboration tool: a JavaScript library which, once added to your website, could establish connections between users in real time.) 尽管这项技术不是新技术(仅举几例,但自几年前以来,(Although the technology is not new (just to name a few, since few years ago we have) 网络插座(Web Sockets) 用于全双工通信通道和(for full-duplex communication channels and) SignalR.Net(SignalR.Net) 当网络套接字不可用时也可以使用),(which also works when web sockets are not available),) TogetherJS(TogetherJS) 为实时协作提供了丰富的即用型功能,例如标准化的对话框,更改您的姓名和头像的功能以及内置的聊天功能.因此,我立即意识到了这种库的潜力,这就是Pixelreka游戏的构想.(provides a rich set of out-of-the-box features for real-time collaboration, such as the standardized dialogs, the ability to change your name and avatar and also a built-in chat. So, Immediately I recognized the potential of such library and that’s how the Pixelreka game was conceived.)
系统要求(System Requirements)
由于该项目仅依赖JavaScript,因此无需编译代码.如果您想对其进行修改和测试,那么任何好的代码编辑器就足够了,例如(Since this project relies solely on JavaScript, there will be no need for compiling code. If you want to modify and test it, then any good code editor will be enough, such as) 记事本++(Notepad++) ,(,) 崇高文字(Sublime Text) 甚至(or even) Visual Studio Express 2012 Web版(Visual Studio Express 2012 for Web) .(.)
TogetherJS(TogetherJS)
TogetherJS入门就像在HTML页面中包含以下脚本标记一样简单:(Getting started with TogetherJS is as easy as including the following script tag in your HTML page:)
<script src="https://togetherjs.com/togetherjs-min.js"></script>
可以这么简单吗?是的,它可以.您可以将上述标记放在HTML中的任何位置.(Can it be that simple? Yes, it can. And you can put the above tag anywhere in your HTML.)
TogetherJS的核心是(The centerpiece of TogetherJS is the)枢纽(hub).使用(. Using) WebSocket(WebSocket) 根据协议,集线器是客户端连接到的服务器,并接收和广播来自/传递到同一会话中连接的客户端的消息.这样,消息将在到达时完全保留并重新分发.(protocol, the hub is a server to which the clients are connected, and which receives and broadcasts messages coming from/delivered to the clients connected in the same session. In doing so, the messages are preserved and redistributed exactly as they arrive.) TogetherJS的工作原理是通过集线器重新分发参与同一会话的浏览器传递的消息. TogetherJS不需要客户端停留在完全相同的页面中,但是由于Pixelreka是单页面应用程序,因此您可能会认为不是.(TogetherJS works by redistributing messages passed by the browsers participating in the same session through the hub. TogetherJS doesn’t require clients to stay in the exactly same page, but since Pixelreka is a single-page application, you might think otherwise.)
在客户端浏览器和(Once the connection is established between the client browsers and the)枢纽(hub),一些开箱即用的实时功能会自动生效.例如,每当一位客户参与者移动浏览器时,就会通过websocket向集线器发送一条消息,而集线器又将未触及的消息广播给其他客户参与者.(, some out-of-the-box real-time features are automatically put to action. For example, whenever one of the client participants move the browser, a message is sent via websockets to the hub, which in turn broadcasts that message untouched to the other client participants.)
既然我们已经设法在代码中引用TogetherJS JavaScript库,则需要每个客户端都同意连接.它可以由我们的应用程序自动完成,并且对用户透明,但是相反,我们创建了一个邀请用户加入游戏的按钮.(Now that we managed to reference the TogetherJS JavaScript library in our code, it is required that each client agrees with the connection. It could be done automatically by our application and transparent to the user, but instead we create a button inviting the user to join the game.)
<input type="button" class="start-togetherjs btn btn-large btn-success" onclick="initializeTogetherJS(); return false;"
style="display: none;" value="Start Pixelreka!" />
function initializeTogetherJS() {
TogetherJS(this);
}
当用户启动Pixelreka时,他或她进入单页应用程序,显示中央面板,其中包含大尺寸像素绘图板,以及左侧的调色板,底部的质询字词和"随机"按钮.在这个像素画板上,他(她)必须(猜测是什么?)画一些代表挑战词的图片,以便其他参与者必须正确猜出它.如果玩家发现很难绘制或不知道单词的含义,则为后备按钮,因此可以立即拿起另一个挑战单词.(When the user starts Pixelreka, he or she enters the single page application, showing the central panel containg the big-sized pixel drawing board, along with the color palette at the left, the challenge word in the bottom, and a “shuffle” button. In this pixel drawing board he or she will have to (guess what?) draw some picture representing the challenge word, so that other participants will have to guess it correctly. The suffle button if for when the player finds it very difficult to draw or doesn’t know the meaning of the word, so another challenge word can be immediately picked up.)
您可以看到上面的图片在右边缘显示了一个面板,并且由TogetherJS自动为您的页面提供.它有四个按钮,它们的详细信息如下:(You can see that the above picture shows a panel at the right edge, and that is automatically provided by TogetherJS for your page. It has four buttons and they are detailed as follows:)
- 这是你(This is you):您可以在此处配置您的姓名,头像(即您的照片),向Mozilla基金会提供反馈并退出TogetherJS会话.(: this is where you configure your name, avatar (i.e. your photo), provide feedback to Mozilla foundation and exit the TogetherJS session.)
- 邀请朋友(Invite a friend):一旦按下,此按钮将显示一个托盘,该托盘带有您要发送给朋友的网址,以便您可以一起玩.(: once pushed, this button will display a tray with a url that you would like to send to a friend so that you both could play together.)
- 语音聊天(Audio Chat):使用麦克风/扬声器通过Web RTC技术与其他会话参与者通信. Web RTC是一个不错的功能,但仅由Chrome和Firefox实现(到目前为止,尚未支持Internet Explorer).(: use microphone/speakers to communicate with other session participants through the Web RTC technology. Web RTC is a nice feature, but only implemented by Chrome and Firefox (no Internet Explorer support so far).)
- 聊天室(Chat):定期且简单的文字聊天.(: a regular and simple text chat.)
更新头像非常容易.只需在本地文件系统中选择一个文件即可.(Updating an avatar is quite easy. Just chose a file in your local file system and you’re done.)
邀请朋友参加您的会议只需要复制和粘贴TogetherJS提供的url.查看会话身份如何嵌入到URL的末尾.(Inviting a friend for your session requires you only a copy-and-paste of the url provided by TogetherJS. See how the session identity is embedded at the end of the url.)
当您的朋友收到游戏会话的网址时,他或她将立即看到带有您的头像的游戏面板,并被要求加入正在进行的会话.(When your friend receives the url of the game session, he or she will immediately see the game board with your avatar, and will be asked to join the ongoing session.)
配置通讯(Configuring Communication)
得知TogetherJS会为您提供通信所需的所有基础架构,我们感到很欣慰.我们要做的就是精确配置(It’s a relief to know that TogetherJS will help you us with all the infrastructure needed for communication. All we have to do is configure exactly)什么消息(what messages)将在会议参与者之间传递,并且(are to be passed between the session participants and)什么功能(what functions)接收到此类消息时将调用它们.(are to be invoked when receiving such messages.) 的(The) Pixelreka(Pixelreka)
- 编辑开始(editor-started):当新的"编辑器"开始绘制时,将触发此消息.这意味着接收消息的参与者是那些必须正确猜出图纸的参与者.该消息包含以下组件:(: this message is triggered when a new “editor” starts drawing. This means that the participants receiving the message are those ones who have to guess the drawing correctly. The message has the following components:)
- userId,userIdentityId(userId, userIdentityId):由TogetherJS基础结构生成的编辑者ID.(: the editor’s IDs generated by TogetherJS infrastructure.)
- 头像(avatar):编辑者用户的图片网址.(: the image URL of the editor user.)
- 名称(name):编辑者的姓名.(: the editor’s name.)
- 类别(category):编辑者必须绘制的单词类别.(: the category of the word the editor must draw.)
- 像素集(pixel-set):每当编辑器更改绘图画布中的像素颜色时,都会发送此消息.每个会话都包含很多图,因此该消息将被广播多次.这是参与游戏的人们开始猜测的地方.(: this message is sent everytime the editor changes a pixel color in the drawing canvas. Every session includes a lot of drawing, so this message is expected to be broadcast many, many times. This is where people participating in the game start guessing.)
- pixelId(pixelId):像素ID,范围从0到255.此像素表示像素化绘图画布中的位图位置.(: the pixel id, varying from 0 to 255. This pixel refers to the bitmap position in the pixelated drawing canvas.)
- colorIndex(colorIndex):颜色索引,由图形调色板定义.(: the color index, defined by the drawing color palette.)
- 新猜测(new-guess):随着图纸变得更加完整和清晰,参与者将开始猜测,并使用以下参数发送此消息:(: as the drawing becomes more complete and clear, the participants will start guessing, and this message is sent with the following parameters:) 用户身份(userId):进行猜测的用户的ID.(: the id of the user making the guess.) 猜测(guess):被猜中的单词.(: the word being guessed.)
请注意,以上列表仅指(It should be noticed that the above list refers only to the)习俗(custom)为了使我们的应用程序正常工作,我们必须进行的通信.同时,通过Together JS中枢,参与者之间还会有更多的消息来往,例如鼠标移动,点击,文本框更改,但是这些都是现成的,并且由TogetherJS库自动提供,因此我们不必担心它们.(communication that we have to set up for our application to work correctly. At th same time there are many more messages coming and going between participants via the Together JS hub, such as mouse movements, clicks, text box changes, but these ones are provided out-of-the-box and automatically by the TogetherJS library so that we don’t have to worry about them.) 以下代码显示了如何设置这些消息:(The following code shows how to set up these messages:)
setupCommunication: function () {
var self = this;
TogetherJS.hub.on("editor-started", function (msg) {
if (self.currentPlayerIdentityId() != msg.userIdentityId) {
var guessUser = TogetherJS.require("peers").getPeer(msg.userId);
self.currentPlayerIdentityId(guessUser.userIdentityId);
self.currentPlayerName(guessUser.name);
self.currentPlayerAvatar(guessUser.avatar);
}
});
TogetherJS.hub.on("pixel-set", function (msg) {
self.pixels()[msg.pixelId].colorIndex(msg.colorIndex);
});
TogetherJS.hub.on("new-guess", function (msg) {
var guessUser = TogetherJS.require("peers").getPeer(msg.userId);
var callback = function () {
};
newGuess(guessUser, msg.guess, callback)
});
},
“编辑器启动"消息(The “editor-started” message)
如上所示,当设置了新的编辑器(在游戏画布上绘制内容的人)时,将广播"编辑开始"消息.发送此消息时有两种情况.第一个是当玩家单击"开始"按钮并初始化TogetherJS会话时:(As seen above, the “editor-started” message is broadcast when the new editor (the person to draw something on the game canvas) is set. There is a couple of situations when this message is sent. The first one is when the player clicks “Start” button and the TogetherJS session is initialized:)
cmdStart: function () {
this.startEditor();
},
当用户重新加载页面时,将调用第二个页面,因此他/她将自动重新进入TogetherJS会话.注意如何声明 TogetherJSConfig_on_ready函数来处理参与者的重新进入:(The second one is invoked when the user reloads the page, thus he/she is automatically reentered in the TogetherJS session. Notice how the TogetherJSConfig_on_ready function is declared to handle the reentering of the participant:)
TogetherJSConfig_on_ready = function () {
startGame();
};
.
.
.
var Game = function () {
this.initialize();
}
$.extend(Game.prototype, {
...
initialize: function () {
...
this.viewModel.startEditor();
...
},
...
});
最后是 startEditor类本身,该类除其他事项外,还通过TogetherJS对象的 send方法发送消息.(And finally the startEditor class itself, which among other things sends the message via the send method of the TogetherJS object.)
startEditor: function () {
TogetherJS.send({
type: 'editor-started',
userId: TogetherJS.require("peers").Self.id,
userIdentityId: TogetherJS.require("peers").Self.identityId,
avatar: TogetherJS.require("peers").Self.avatar,
name: TogetherJS.require("peers").Self.name,
category: self.category
});
this.currentPlayerIdentityId(TogetherJS.require("peers").Self.identityId);
this.currentPlayerName(TogetherJS.require("peers").Self.name);
this.currentPlayerAvatar(TogetherJS.require("peers").Self.avatar);
},
“像素集"消息(The “pixel-set” message)
“像素设置"消息使其他参与者能够看到绘图过程.(The “pixel-set” message is what enables other participants to see the drawing process.) 用户单击绘图画布时,他或她触发 PixelViewModel的 setPixel函数.然后,该消息将被广播,通知正在绘制的对象以及在给定颜色下绘制在画布上的位置.(When the user clicks the drawing canvas, he or she triggers the setPixel function of the PixelViewModel. The message is then broadcast, informing who is drawing and where in the drawing canvas the given color is being painted.)
var PixelViewModel = function (index, col, row, even, colorIndex) {
this.initialize(index, col, row, even, colorIndex);
};
$.extend(PixelViewModel.prototype, {
.
.
.
setPixel: function (colorIndex) {
var self = this;
if (gameViewModel.isMouseDown) {
if (self.colorIndex() != colorIndex) {
self.colorIndex(colorIndex);
if (!game)
startGame();
TogetherJS.send({
type: 'pixel-set',
userId: TogetherJS.require("peers").Self.id,
userIdentityId: TogetherJS.require("peers").Self.identityId,
pixelId: self.index(),
colorIndex: colorIndex
});
}
}
}
});
“新猜测"消息(The “new-guess” message)
随着图纸变得更加清晰,玩家将开始猜测,然后(As the drawing becomes more clear, the players will start making guesses, and the)新猜测(new-guess)当用户填写 txtGuess输入框并按下(message is sent when the users fills in the txtGuess input box and pushes the)发送(Send)按钮.(button.)
cmdSend: function () {
this.send();
},
send: function () {
var self = this;
TogetherJS.send({
type: 'new-guess',
userId: TogetherJS.require("peers").Self.id,
userIdentityId: TogetherJS.require("peers").Self.identityId,
guess: self.txtGuess()
});
},
游戏玩法(Game Play)
在参与者之间建立连接后,编辑器播放器准备开始绘制,其他参与者准备开始猜测.一侧的图几乎立即在其他浏览器上显示.(As the connections are established between participants, the editor player is ready to start drawing and the other participants are ready to start guessing. The drawing in one side is shown almost immediately on the other browsers.) 在下面的示例中,(In the example below,)柯密特(Kermit)和(and)动物(Animal)都进入了同一会话.(have both entered the same session.)
请注意,它们在TogetherJS提供的右侧面板中如何互相看到:(Notice how they see one another in the right panel that is provied by TogetherJS:)
但是绘图板对于两者都有些不同. Animal在左板上画图,这就是为什么他拿着画笔,而Kermit试图猜测他的画图时,他看到右上角的化身表明这是Animal来画画了:(But the drawing board is a bit different for the both of them. Animal is drawing on the left board, and that’s why he’s holding a brush, while Kermit is trying to guess his drawing, and he sees a top right avatar indicating that it’s Animal’s turn to draw:)
然后Animal开始绘制图形,而Kermit立即在他的浏览器中看到该图形发生的情况:(Then Animal starts drawing and Kermit immediately sees that drawing happening in his browser:)
即使绘图板是低分辨率的16x16位图,有时也需要使用一个像素宽的画笔进行大量工作,尤其是在填充区域(例如绘制大象)时.在这些情况下,更宽的画笔会更方便地完成任务:(Even though the drawing board is a low-res, 16x16 bitmap, sometimes using a brush as wide as one pixel is a lot of work, especially when filling regions (such as painting an elephant). In these occasions, a wider brush would be much more convenient for the task:)
使用不同的颜色还有助于使图形更清晰:(Using different colors also help making the drawing more clear:)
现在,Kermit终于弄清了Animal的画作是关于什么的,他填写了” guess"文本框:(Now that Kermit finally figured out what Animal’s drawing was about, he fills in the “guess” text box:)
当Kermit发出猜测时,这就是Animal的浏览器中弹出的内容.(When Kermit sends his guess, this is what is popped up on Animal’s browser.)
由于游戏尚未完成,因此到此结束.我知道,您想要更多.但是对于演示TogetherJS的目标来说,这可能就足够了.您可以自由扩展游戏,记分牌,实施回合管理,徽章,在Facebook和Twitter上共享游戏结果以及您的想象力.(Since the game is not complete, it ends here. I know, you wanted more. But for the goal of demonstrating TogetherJS, this might be enough. You are free to extend the game, implement scoreboards, implement turn management, badges, sharing game results on Facebook and Twitter and what else your imagination allows.)
最后考虑(Final Considerations)
基于Web的实时通信比以往任何时候都功能强大.不久的将来,基础设施通信技术将会商品化,不久前,这种技术仅适用于高级开发人员.我们应该感谢TogetherJS团队为使我们拥有如此高级工具而做出的努力,从而使我们节省了时间并专注于我们自己的核心应用程序功能.(Web based real-time communication is getting more powerful than ever. Very soon there will be in the landscape a commoditization of infrastructure communication technologies that not long ago were available only for the advanced developer. We should be thankful to the efforts made by TogetherJS team to bring us such high level tools, allowing us to save time and focus on our own core application features.) 非常感谢您的阅读,请随时对本文和随附的代码发表评论.(Thanks a lot for the reading, and please feel free to leave a comment regarding the article and the accompanying code.)
历史(History)
- 2013-12-22:初始版本.(2013-12-22: Initial version.)
许可
本文以及所有相关的源代码和文件均已获得The Code Project Open License (CPOL)的许可。
Javascript Dev 新闻 翻译