參考內容網址如下:
https://bbs.egret.com/thread-47694-1-1.html?tdsourcetag=s_pcqq_aiomsg
https://www.jianshu.com/p/9d5f40603d8c
具體解釋
1、以麻將爲例
玩家A、B、C、D 座位如下
C 2
D 3 B1
A 0
首先獲取所有玩家的服務器位置:Index = 0,1,2,3
加入現在是B的視角
則:移位 = B.index 1 - 0 = 1 ,說明移動一個位置
新座位的序號:
B = B.index - 移位 = 1-1 = 0
C = C.index - 移位 = 2-1 = 1
D = D.index - 移位 = 3-1 = 2
A = A.index - 移位 = 0 - 1 = -1,如果是負數,則+總人數4:-1+4=3
同理:C的視角
移位= C.index 2-0 = 2
C = C.index - 移位 = 2-2 = 0
D = D.index - 移位 = 3-2 = 1
A = A.index - 移位 = 0 - 2 = -2,如果是負數,則+總人數4:-2+4=2
B = B.index - 移位 = 1 - 2 = -1,如果是負數,則+總人數4:-1+4=3
同理:D的視角
移位= D.index 3-0 = 3
D = D.index - 移位 = 3 - 3 = 0
A = A.index - 移位 = 0 - 3 = -3,如果是負數,則+總人數4:-3+4=1
B = B.index - 移位 = 1 - 3 = -2,如果是負數,則+總人數4:-2+4=2
C = C.index - 移位 = 2 - 3 = -1,如果是負數,則+總人數4:-1+4=3
2、鬥地主位置算法同理
C 2 B 1
A0
首先獲取所有玩家的服務器位置:Index = 0,1,2
加入現在是B的視角
則:移位 = B.index 1 - 0 = 1 ,說明移動一個位置
新座位的序號:
B = B.index - 移位 = 1-1 = 0
C = C.index - 移位 = 2-1 = 1
A = A.index - 移位 = 0 - 1 = -1,如果是負數,則+總人數3:-1+3=2
同理:C的視角
移位= C.index 2-0 = 2
C = C.index - 移位 = 2 - 2 = 0
A = A.index - 移位 = 0 - 2 = -2,如果是負數,則+總人數3:-2+3=1
B = B.index - 移位 = 1 - 2 = -1,如果是負數,則+總人數3:-1+3=2
另一種
我也來分享一個位置算法,一半所有的都能適用,思路和樓主的不同~ 假設五人場,服務器會首先返回自己的座位號:
我們的思路是服務器有服務器的座位號,我們客戶端有自己的座位號,只要做對應的映射就行。在視圖上自己的位置永遠是0
只要初始化一次table,然後每次服務器返回座位,根據映射找自己的位置就可以了
C#版
class Program
{
static int[] seatTable = { 0, 1, 2, 3 };
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
string str = "";
for (int i=0;i<seatTable.Length;i++) {
str = "";
seatTalbleInit(i);
for (int j = 0; j < seatTable.Length; j++)
{
str = str + "" + getViewSeat(j) + ',';
}
Console.WriteLine("-->"+ str);
}
}
static void seatTalbleInit(int selfSeat) {
for (int i = 0; i < seatTable.Length; i++)
{
if (i == 0)
{
seatTable[0] = selfSeat;
}
else {
seatTable[i] = seatTable[i - 1] + 1;
seatTable[i] = seatTable[i] % seatTable.Length;
}
}
}
static int getViewSeat(int xyseat) {
for (var i = 0; i < seatTable.Length; i++)
{
if (seatTable[i] == xyseat)
{
return i;
}
}
return -1;
}
}
js版
var seatTable = [0, 1, 2, 3,4]
function seatTalbleInit(selfSeat) {
seatTable.forEach((item, index) => {
if (index == 0) {
seatTable[0] = selfSeat;
} else {
seatTable[index] = seatTable[index - 1] + 1;
seatTable[index] = seatTable[index] % seatTable.length;
}
})
}
function getViewSeat(xyseat) {
for (var i = 0; i < seatTable.length; i++) {
if (seatTable[i] == xyseat) {
return i;
}
}
}
var str = '';
for(let i=0;i<seatTable.length;i++){
str = '';
seatTalbleInit(i)
for(let j=0;j<seatTable.length;j++){
str = str + '' + getViewSeat(j) + ','
}
console.log( '-->' + str );
}
第二種 js版
_maxNum 最大人數
i 自己所在座位
j 服務器座位
ret 本地位置
var seatTable2 = [0, 1, 2, 3]
var _maxNum = seatTable2.length
for(let i=0;i<seatTable2.length;i++){
str = '';
for(let j=0;j<seatTable2.length;j++){
let ret = (j - i + _maxNum) % _maxNum;
str = str + '' + ret + ','
}
console.log( '-->' + str );
}
參考四人
當myChairId == 0 時,// 0123
當myChairId == 1時,// 3012
當myChairId == 2 時,//2301
當myChairId == 3 時,//1230
證明公式是正確的