簡體   English   中英

如何將數據從類傳遞到貓鼬模型?

[英]How to pass data from a class into a Mongoose model?

我將介紹解決該問題的方法。

  1. 有一個空板( 在這里 )。
  2. 您可以將騎士片放置在板上的任何位置。
  3. 您必須選擇所需的位置。
  4. 游戲應返回到達所需位置所需的最短距離的坐標
  5. 例如。 讓我們將騎士放在A1上。 我想去C5。 將返回的坐標為: A1,B3,C5。

容易嗎?

  • 本場比賽必須使用同一個的NodeJS RESTful的API來設計
  • 沒有界面 它純粹是后端。
  • 我正在使用國際象棋庫,因為我發現很難創建自己的棋盤(等)。您可以在這里找到它: https : //github.com/jhlywa/chess.js

我做了什么來解決這個問題?

我創建了控制器和板類

該代碼不起作用,但顯示為模擬我想要實現的功能:

(從技術上講我是業余愛好者)。

我的控制器:

app.post("/", (req, res) => {
  var board = new Board(chess = new Chess());
  // The post request creates a board
  board.clearBoard();
  // This clears the board of existing pieces
  board.placeFirstPosition(position);
  // This adds the knight to the board
  board.endPosition(position);
  // This method in the class here will handle the logic of moving the knight to the end position 
// This logic needs to be passed into the model 
  var move = new Move({
  coordinate: (all_the_coordinates)
  })
  // This data (coordinates) will be passed into the model (via mongoose)
  move.save().then((doc) => {
    res.send(doc);
  }, (e) => {
    res.status(400).send(e);
  });
  // Finally these moves will be saved to the database and will be returned to the server
});

我的董事會班級:

var Chess = require('../../node_modules/chess.js').Chess;

function Board(chess = new Chess()) {
  this._chess = chess;
}

Board.prototype.clearBoard = function() {
  this._chess.clear();
}

Board.prototype.placeFirstPosition = function(position) {
  this._chess.put({ type: 'k', color: 'w' }, position)
}

Board.prototype.endPosition = function(position) {
 // logic calculating the sequence of coordinates
}

Board.prototype.showBoard = function() {
  return this._chess.ascii();
}

module.exports = {Board};
  • 我添加了這個可以顯示棋盤的國際象棋庫,似乎有點麻煩,但這是我唯一的選擇,因為我不確定如何創建其他象棋。

我的問題:

問題是:

  • 如何將坐標從類中的方法傳遞到移動模型中? 隨后將其保存在數據庫中。
  • 如何在不進行硬編碼的情況下將所需位置傳遞給POST中的函數? board.placeFirstPosition('a1');
  • 稍后我將處理邏輯,您會建議哪種路線?
  • 我不能使用郵差在類正在這樣做時傳遞任何數據。
  • 是否需要數據庫 我的想法是,否則必須如何才能知道到達該位置所需的坐標?

你的建議:

  • 如果您能想到一種更好的方法來達到這一最終結果,我很想聽聽您的建議。

假設我正確了,您的條件是:

  • 選擇初始位置
  • 選擇目的地位置
  • 發出HTTP請求並返回最快的路徑。

階段將是

創建算法以匹配您的邏輯

function findBestPath(initPosX, initPosY, destPosX, destPosY)

創建使用此功能的路線

const express = require('express');
const app = express();
const bodyParser = require('bodyParser');
app.use(bodyParser.json());

app.post('/getBestPath', (req, res) => {
    let initPosX = req.body.initPosX,
        initPosY = req.body.initPosY,
        destPosX = req.body.destPosX,
        destPosY = req.body.destPosY;

    res.send(findBestPath(initPosX, initPosY, destPosX, destPoxY));
};

app.listen(3000, () => console.log('Example app listening on port 3000!'))

完成后,您可以從可以想到的任何接口(包括郵遞員)中使用POST HTTP請求來調用此函數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM