我們?cè)?Bitcoin SV 上實(shí)現(xiàn)了一個(gè)數(shù)獨(dú)游戲智能合約,利用之前介紹過(guò)的一種合約范式可以將游戲中尋找解題方案的過(guò)程外包上鏈。因?yàn)榍蠼鈹?shù)獨(dú)問(wèn)題的計(jì)算工作量會(huì)隨著其行列數(shù)快速增長(zhǎng),實(shí)際上它也是一個(gè) NP-完全 問(wèn)題。不過(guò)我們可以借由比特幣智能合約巧妙地尋求答案,只需要驗(yàn)證答案提供者所給出的解答是否滿足要求即可,這樣即可以將復(fù)雜的求解計(jì)算過(guò)程實(shí)現(xiàn)鏈下外包。
import "util.scrypt";
import "array.scrypt";
contract Sudoku {
bytes board;
static const int N = 9;
static bytes EMPTY = b'00';
constructor(bytes board) {
this.board = board;
}
function merge(bytes solution) : bytes {
bytes newBoard = this.board;
int i = 0;
loop (N) {
int j = 0;
loop (N) {
int value = this.readValue(newBoard, i, j);
int inputValue = this.readValue(solution, i, j);
if (value == 0) {
require(inputValue = 9);
newBoard = this.setValue(newBoard, i, j, inputValue);
} else {
require(value == inputValue);
}
j++;
}
i++;
}
return newBoard;
}
public function solve(bytes solution) {
require(len(solution) == Sudoku.N * Sudoku.N);
bytes newBord = this.merge(solution);
Array rowArray = new Array();
Array colArray = new Array();
Array squareArray = new Array();
int i = 0;
loop (N) {
int j = 0;
loop (N) {
// check for duplicate
// in a row
int rowElem = this.readValue(newBord, i, j);
require(rowArray.indexOf(rowElem) == -1);
rowArray.push(rowElem);
// in a column
int colElem = this.readValue(newBord, j, i);
require(colArray.indexOf(colElem) == -1);
colArray.push(colElem);
// in a subgrid
int squareElem = this.readSquareValue(newBord, i, j);
require(squareArray.indexOf(squareElem) == -1);
squareArray.push(squareElem);
j++;
}
rowArray.clear();
colArray.clear();
squareArray.clear();
i++;
}
require(true);
}
static function readValue(bytes board, int i, int j): int {
return Util.fromLEUnsigned(Util.getElemAt(board, Sudoku.index(i, j)));
}
static function setValue(bytes board, int i, int j, int value): bytes {
return Util.setElemAt(board, this.index(i, j), Util.toLEUnsigned(value, 1));
}
static function readSquareValue(bytes board, int i, int j): int {
return Util.fromLEUnsigned(Util.getElemAt(board, Sudoku.indexSquare(i, j)));
}
static function index(int row, int col) : int {
return row * Sudoku.N + col;
}
static function indexSquare(int i, int j) : int {
int row = i / 3 * 3 + j / 3;
int col = i % 3 * 3 + j % 3;
return Sudoku.index(row, col);
}
}
到此這篇關(guān)于比特幣上的數(shù)獨(dú)游戲合約的實(shí)現(xiàn)代碼的文章就介紹到這了,更多相關(guān)比特幣數(shù)獨(dú)游戲合約內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!