我。不創造單獨的頁面。頁面是使用組件的上下文,應用程序。 Javascript允許你創建類(不要與CSS類混淆)。您可以創建每個類的實例。所以如果你有一個Car類,你可以實例化其中的兩個,並讓它們與頁面交互。例如:
// Javascript is a prototyped language. A class is defined as a function:
function Car()
{
// Some initialization of properties by assigning to this.propname
this.x = 0; this.y = 0;
this.direction = 0;
this.velocity = 0;
}
// Add methods by extending the prototype
Car.prototype.show = function()
{
// For each Car object, create and remember a DOM element.
// This is what makes your car visible.
this.DOMelement = document.createElement('div');
// Set style properties to position the car.
// Add sub-elements to make the case visible (images?)
}
Car.prototype.move = function()
{
// Update this.x and this.y
// Move/update the related DOM element accordingly.
}
現在,您可以創建兩個汽車:
var Car1 = new Car();
var Car2 = new Car();
Car1.show(); // Show the first.
您還需要捕獲鍵。我沒有經常這樣做,但可能有很多例子。
您可以使控制鍵成爲汽車的一個屬性,因此您可以創建汽車並指定其按鍵。汽車可以告訴遊戲需要哪個鍵。遊戲可以處理所有輸入並將其發送到正確的汽車。
之後,您將不得不創建某種類型的循環來添加動畫。
//Instead of an actual loop, you can create a function to render a single frame
function tick()
{
// Handle input and redirect it to the appropriate cars
// Call .move of all the cars
}
// Call the tick function repeatedly every 10 ms.
setInterval('tick', 10);
當然你也可以創建一個類來保存所有這些遊戲信息。這樣你就不會混亂你的窗口對象(所有的全局變量和函數實際上都會成爲窗口對象的一部分),並且將遊戲嵌入到現有站點中會更容易。您甚至可以在單個頁面中運行兩個獨立的遊戲!雖然他們會爭奪鑰匙。
無論如何,還有很多需要填補的空白,但我希望這能給你一個想法。