我想创建一些游戏。我对这个游戏的看法必须像对模块的看法那样好吗?这意味着,在我想运行我的游戏的其他网站上的任何地方,我都将放置模块。
因此,如果我们将“我的观点”想象成类,会看起来像这样吗?
class Mario {
// Whole game module
class Game {
// Game properties
class Player {
}
class Card {
}
}
class Init {
// This take care about gui etc.
class Gui {
show_cards() {
}
}
}
start() {
var init = new Init();
something to init Gui and run method show_cards();
}
}
var mario = new Mario();
mario.start();
我对吗?
但是这种语法在JavaScript中正确吗,甚至有可能吗?
感谢帮助!
答案 0 :(得分:0)
如果您希望获得HTML元素的额外帮助,可以将其放入页面中以保存游戏代码,可以制作一个custom element,但我敢打赌,只要使用{{3} }。
就您的代码结构而言,这应该会对您有所帮助。这是一个Game
类模板,它使用单独的Player
和Resource
类-我为您在顶部停留在GameHandler
类中(就像您的Mario类)
编码愉快!
class GameHandler {
constructor(){
this.handlerSetup();
const gameResources = [ // Array of resource objects for setResources method
{
type: "card",
number: 1,
},
{
type: "card",
number: 2,
options: { category: "A", description:"special" }
}
];
this.game = new Game(4, gameResources); // This can go in a loop to allow sequential games
}
handlerSetup(){ /* Do setup tasks here */ }
}
class Game {
constructor(playerCount, resourcesArray){
this.players = this.setPlayers(playerCount);
this.resources = this.setResources(resourcesArray);
this.winnerIfAny = null;
this.turnNumber = 0;
this.output("Ready to play");
// Main loop
while(this.winnerIfAny === null){
this.winnerIfAny = this.nextTurn(++this.turnNumber);
}
this.output(`Game over -- Player number ${this.winnerIfAny.number} wins`);
}
setPlayers(count){
let i = 0, players = [];
while(i < count){
players.push(new Player(i++));
}
this.output(`${count} players added`)
return players;
}
setResources(resourcesProvided){
let resources = [];
for(let resource of resourcesProvided){
resources.push(new Resource(resource));
}
this.output(`${resources.length} resources added`)
return resources;
}
nextTurn(turnNumber){
this.output("Taking turn...");
let winnerFound = null;
// Turn loop code goes here
// (eg switch to next player, take turn, check for winner
// This demo game is not very interesting -- it randomly assigns a winner
let rand = (Math.floor(Math.random() * (11 - turnNumber * 2)));
if (turnNumber > 1 && rand < 4) { winnerFound = this.players[rand]; }
if(winnerFound){ return winnerFound; }
return null;
}
output(text){ document.querySelector("#outputDiv").innerHTML += `${text}<br/>`; }
}
class Player {
constructor(number){
this.number = number;
//etc...
}
}
class Resource {
constructor(type, number, options){
this.number = number;
//etc...
}
}
new GameHandler();
<div id="outputDiv"></div>