Copyright © 2015 François Terrier. JavaScript adaptation and original interface © 2026. Distributed under EPL-1.0-or-later. Source repository: https://github.com/fterrier/pylos/tree/f9283cf58a32000ed271e768ab6151ac081ed37d. This is an independent adaptation, not affiliated with the physical game publisher. Original source sections and full modified corresponding source follow. The new local rival uses reserve and square heuristics. Lessons and repetition draw are additions. No straight-line bonus. End-of-turn reserve exhaustion concedes the summit, matching the upstream engine termination rule.
Eclipse Public License 1.0 · Metadata tags: github-source, game
THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC
LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM
CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT.
1. DEFINITIONS
"Contribution" means:
a) in the case of the initial Contributor, the initial code and
documentation distributed under this Agreement, and
b) in the case of each subsequent Contributor:
i) changes to the Program, and
ii) additions to the Program;
where such changes and/or additions to the Program originate from and are
distributed by that particular Contributor. A Contribution 'originates' from
a Contributor if it was added to the Program by such Contributor itself or
anyone acting on such Contributor's behalf. Contributions do not include
additions to the Program which: (i) are separate modules of software
distributed in conjunction with the Program under their own license
agreement, and (ii) are not derivative works of the Program.
"Contributor" means any person or entity that distributes the Program.
"Licensed Patents" mean patent claims licensable by a Contributor which are
necessarily infringed by the use or sale of its Contribution alone or when
combined with the Program.
"Program" means the Contributions distributed in accordance with this
Agreement.
"Recipient" means anyone who receives the Program under this Agreement,
including all Contributors.
2. GRANT OF RIGHTS
a) Subject to the terms of this Agreement, each Contributor hereby grants
Recipient a non-exclusive, worldwide, royalty-free copyright license to
reproduce, prepare derivative works of, publicly display, publicly perform,
distribute and sublicense the Contribution of such Contributor, if any, and
such derivative works, in source code and object code form.
b) Subject to the terms of this Agreement, each Contributor hereby grants
Recipient a non-exclusive, worldwide, royalty-free patent license under
Licensed Patents to make, use, sell, offer to sell, import and otherwise
transfer the Contribution of such Contributor, if any, in source code and
object code form. This patent license shall apply to the combination of the
Contribution and the Program if, at the time the Contribution is added by the
Contributor, such addition of the Contribution causes such combination to be
covered by the Licensed Patents. The patent license shall not apply to any
other combinations which include the Contribution. No hardware per se is
licensed hereunder.
c) Recipient understands that although each Contributor grants the licenses
to its Contributions set forth herein, no assurances are provided by any
Contributor that the Program does not infringe the patent or other
intellectual property rights of any other entity. Each Contributor disclaims
any liability to Recipient for claims brought by any other entity based on
infringement of intellectual property rights or otherwise. As a condition to
exercising the rights and licenses granted hereunder, each Recipient hereby
assumes sole responsibility to secure any other intellectual property rights
needed, if any. For example, if a third party patent license is required to
allow Recipient to distribute the Program, it is Recipient's responsibility
to acquire that license before distributing the Program.
d) Each Contributor represents that to its knowledge it has sufficient
copyright rights in its Contribution, if any, to grant the copyright license
set forth in this Agreement.
3. REQUIREMENTS
A Contributor may choose to distribute the Program in object code form under
its own license agreement, provided that:
a) it complies with the terms and conditions of this Agreement; and
b) its license agreement:
i) effectively disclaims on behalf of all Contributors all warranties and
conditions, express and implied, including warranties or conditions of title
and non-infringement, and implied warranties or conditions of merchantability
and fitness for a particular purpose;
ii) effectively excludes on behalf of all Contributors all liability for
damages, including direct, indirect, special, incidental and consequential
damages, such as lost profits;
iii) states that any provisions which differ from this Agreement are offered
by that Contributor alone and not by any other party; and
iv) states that source code for the Program is available from such
Contributor, and informs licensees how to obtain it in a reasonable manner on
or through a medium customarily used for software exchange.
When the Program is made available in source code form:
a) it must be made available under this Agreement; and
b) a copy of this Agreement must be included with each copy of the Program.
Contributors may not remove or alter any copyright notices contained within
the Program.
Each Contributor must identify itself as the originator of its Contribution,
if any, in a manner that reasonably allows subsequent Recipients to identify
the originator of the Contribution.
4. COMMERCIAL DISTRIBUTION
Commercial distributors of software may accept certain responsibilities with
respect to end users, business partners and the like. While this license is
intended to facilitate the commercial use of the Program, the Contributor who
includes the Program in a commercial product offering should do so in a
manner which does not create potential liability for other Contributors.
Therefore, if a Contributor includes the Program in a commercial product
offering, such Contributor ("Commercial Contributor") hereby agrees to defend
and indemnify every other Contributor ("Indemnified Contributor") against any
losses, damages and costs (collectively "Losses") arising from claims,
lawsuits and other legal actions brought by a third party against the
Indemnified Contributor to the extent caused by the acts or omissions of such
Commercial Contributor in connection with its distribution of the Program in
a commercial product offering. The obligations in this section do not apply
to any claims or Losses relating to any actual or alleged intellectual
property infringement. In order to qualify, an Indemnified Contributor must:
a) promptly notify the Commercial Contributor in writing of such claim, and
b) allow the Commercial Contributor tocontrol, and cooperate with the
Commercial Contributor in, the defense and any related settlement
negotiations. The Indemnified Contributor may participate in any such claim
at its own expense.
For example, a Contributor might include the Program in a commercial product
offering, Product X. That Contributor is then a Commercial Contributor. If
that Commercial Contributor then makes performance claims, or offers
warranties related to Product X, those performance claims and warranties are
such Commercial Contributor's responsibility alone. Under this section, the
Commercial Contributor would have to defend claims against the other
Contributors related to those performance claims and warranties, and if a
court requires any other Contributor to pay any damages as a result, the
Commercial Contributor must pay those damages.
5. NO WARRANTY
EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS PROVIDED ON
AN "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER
EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR
CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A
PARTICULAR PURPOSE. Each Recipient is solely responsible for determining the
appropriateness of using and distributing the Program and assumes all risks
associated with its exercise of rights under this Agreement , including but
not limited to the risks and costs of program errors, compliance with
applicable laws, damage to or loss of data, programs or equipment, and
unavailability or interruption of operations.
6. DISCLAIMER OF LIABILITY
EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR ANY
CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION
LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE
EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY
OF SUCH DAMAGES.
7. GENERAL
If any provision of this Agreement is invalid or unenforceable under
applicable law, it shall not affect the validity or enforceability of the
remainder of the terms of this Agreement, and without further action by the
parties hereto, such provision shall be reformed to the minimum extent
necessary to make such provision valid and enforceable.
If Recipient institutes patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Program itself
(excluding combinations of the Program with other software or hardware)
infringes such Recipient's patent(s), then such Recipient's rights granted
under Section 2(b) shall terminate as of the date such litigation is filed.
All Recipient's rights under this Agreement shall terminate if it fails to
comply with any of the material terms or conditions of this Agreement and
does not cure such failure in a reasonable period of time after becoming
aware of such noncompliance. If all Recipient's rights under this Agreement
terminate, Recipient agrees to cease use and distribution of the Program as
soon as reasonably practicable. However, Recipient's obligations under this
Agreement and any licenses granted by Recipient relating to the Program shall
continue and survive.
Everyone is permitted to copy and distribute copies of this Agreement, but in
order to avoid inconsistency the Agreement is copyrighted and may only be
modified in the following manner. The Agreement Steward reserves the right to
publish new versions (including revisions) of this Agreement from time to
time. No one other than the Agreement Steward has the right to modify this
Agreement. The Eclipse Foundation is the initial Agreement Steward. The
Eclipse Foundation may assign the responsibility to serve as the Agreement
Steward to a suitable separate entity. Each new version of the Agreement will
be given a distinguishing version number. The Program (including
Contributions) may always be distributed subject to the version of the
Agreement under which it was received. In addition, after a new version of
the Agreement is published, Contributor may elect to distribute the Program
(including its Contributions) under the new version. Except as expressly
stated in Sections 2(a) and 2(b) above, Recipient receives no rights or
licenses to the intellectual property of any Contributor under this
Agreement, whether expressly, by implication, estoppel or otherwise. All
rights in the Program not expressly granted under this Agreement are
reserved.
This Agreement is governed by the laws of the State of New York and the
intellectual property laws of the United States of America. No party to this
Agreement will bring a legal action under this Agreement more than one year
after the cause of action arose. Each party waives its rights to a jury trial
in any resulting litigation.
Copyright © 2015 François Terrier. JavaScript adaptation and original interface © 2026. Distributed under EPL-1.0-or-later. Source repository: https://github.com/fterrier/pylos/tree/f9283cf58a32000ed271e768ab6151ac081ed37d. This is an independent adaptation, not affiliated with the physical game publisher. Original source sections and full modified corresponding source follow. The new local rival uses reserve and square heuristics. Lessons and repetition draw are additions. No straight-line bonus. End-of-turn reserve exhaustion concedes the summit, matching the upstream engine termination rule.
/* Original browser interface and local rival, EPL-1.0-or-later. */
'use strict';
const R=Pylos,$=id=>document.getElementById(id),KEY='ivory-rise-v1';let state,history=[],selected=null,busy=false,epoch=0,stats={wins:0,lessons:[]};
function initial(kind){let b=Array(30).fill(0);if(kind==='square'){[0,1,4].forEach(i=>b[i]=1);[10,15].forEach(i=>b[i]=2);}if(kind==='lift'){[0,5,15].forEach(i=>b[i]=1);[1,4].forEach(i=>b[i]=2);}if(kind==='finish')b=b.map((_,i)=>i<29?(i%2===0?2:1):0);return {b,player:1,phase:'place',removed:0,kind,mode:$('mode').value,turn:1,winner:0,draw:false,seen:[],message:kind==='square'?'Place Ivory at level 1, row 2, column 2 to complete a square.':kind==='lift'?'Select Ivory at level 1, row 4, column 4, then the open level 2 socket.':kind==='finish'?'All supports are ready. Place Ivory at the summit.':'Ivory begins. Place a reserve sphere in any open socket.'};}
function save(){try{localStorage.setItem(KEY,JSON.stringify({state,history,stats}));}catch{}}
function remember(){history.push(JSON.parse(JSON.stringify(state)));if(history.length>60)history.shift();}
function name(p){return p===1?'Ivory':'Jade';}
function lessonDone(){if(!stats.lessons.includes(state.kind))stats.lessons.push(state.kind);state.winner=1;state.message='Lesson complete · '+(state.kind==='square'?'A square replenishes your reserve.':state.kind==='lift'?'A lift saves a reserve sphere.':'You claimed the summit.');save();}
function endTurn(){selected=null;state.phase='place';if(state.kind!=='normal'){lessonDone();render();return;}const w=R.outcome(state.b);if(w){state.winner=w;state.message=name(w)+' wins · '+(state.b[29]?'the summit is claimed.':name(3-w)+' has spent the last reserve.');if(w===1)stats.wins++;save();render();return;}state.player=3-state.player;state.turn++;let key=state.b.join('')+state.player;state.seen.push(key);if(state.seen.filter(x=>x===key).length>=3){state.draw=true;state.message='A balanced table · three repeated positions. Draw.';}else state.message=name(state.player)+' to move · place from reserve or lift an exposed sphere.';save();render();runAI();}
function activate(i){if(busy||state.winner||state.draw||(state.mode==='ai'&&state.player===2))return;const p=state.player;if(state.phase==='reclaim'){if(state.b[i]!==p||!R.free(state.b,i)){state.message='Only your exposed spheres can return to reserve.';render();return;}state.b=R.remove(state.b,p,i);state.removed++;state.message='Reclaimed '+state.removed+' sphere'+(state.removed>1?'s.':'. You may reclaim one more or finish.');if(state.removed===2){endTurn();return;}save();render();return;}
if(state.b[i]){if(state.b[i]!==p){state.message='That sphere belongs to '+name(3-p)+'.';}else if(!R.free(state.b,i)){state.message='This sphere supports another. Choose an exposed sphere.';}else{selected=selected===i?null:i;state.message=selected===null?'Using a sphere from reserve.':'Lift selected · choose an open socket on a higher level.';}render();return;}
if(state.kind==='square'&&i!==5||state.kind==='lift'&&(selected!==15||i!==16)||state.kind==='finish'&&i!==29){state.message='Follow the lesson target described at the start. Use New table to try again.';render();return;}
if(!R.legal(state.b,p,selected,i)){state.message=selected!==null?'That lift needs a higher socket with all four supports still in place.':'That socket needs four supports below.';render();return;}remember();let n=R.place(state.b,p,selected,i);state.b=n.board;selected=null;if(i===29){if(state.kind!=='normal'){lessonDone();render();return;}endTurn();return;}if(n.square){state.phase='reclaim';state.removed=0;state.message='Square made! Reclaim up to two exposed '+name(p)+' spheres, or finish.';save();render();}else endTurn();}
function runAI(){if(state.mode!=='ai'||state.player!==2||state.winner||state.draw||busy)return;busy=true;render();let e=epoch;setTimeout(()=>{if(e!==epoch)return;try{let m=R.choose(state.b,2);if(!m){state.winner=1;state.message='Ivory wins · Jade has no legal move.';busy=false;save();render();return;}state.b=m.board;state.message='Jade '+(m.from!==null?'lifted a sphere':'placed from reserve')+(m.removed.length?' and reclaimed '+m.removed.length:'')+'.';busy=false;endTurn();}catch(err){busy=false;state.message='The local rival could not move. Undo or start a new table.';console.error(err);render();}},250);}
function render(){for(let p=1;p<=2;p++)$('r'+p).textContent=R.reserve(state.b,p);$('turn').textContent=state.winner?(state.kind==='normal'?name(state.winner)+' wins':'Lesson complete'):state.draw?'Draw':name(state.player)+(busy?' is thinking…':' · turn '+state.turn);$('stage').textContent=state.phase==='reclaim'?'RECLAIM / '+state.removed+' OF 2':selected!==null?'LIFT SELECTED':'PLACE / LIFT';$('message').textContent=state.message;$('end').disabled=state.phase!=='reclaim'||busy||!!state.winner;$('reserve').disabled=busy||state.phase==='reclaim'||!!state.winner||state.draw;$('reserve').textContent=selected===null?'Reserve selected':'Use reserve';$('undo').disabled=!history.length||busy;$('mode').value=state.mode;$('setup').value=state.kind;$('record').textContent=stats.wins+' full-table Ivory wins · '+stats.lessons.length+'/3 lessons';$('tip').textContent=state.phase==='reclaim'?'Tap one of your exposed spheres to recover it. Supported spheres stay on the table.':'Outlined sockets are ready. Select your exposed sphere to see higher lift destinations.';
let focused=document.activeElement?.dataset?.cell;const layers=$('layers');layers.replaceChildren();for(let z=0;z<4;z++){let section=document.createElement('section');section.className='layer';let h=document.createElement('h2');h.textContent='0'+(z+1)+' / '+['FOUNDATION','MIDDLE','CROWN','SUMMIT'][z];section.append(h);let grid=document.createElement('div');grid.className='grid';grid.style.gridTemplateColumns='repeat('+(4-z)+',1fr)';R.cells.forEach((c,i)=>{if(c.z!==z)return;let button=document.createElement('button'),v=state.b[i];button.dataset.cell=i;button.className='cell'+(v?' p'+v:'')+(v&&!R.free(state.b,i)||!v&&!R.open(state.b,i)?' blocked':'')+(i===selected?' selected':'');const available=!v&&R.legal(state.b,state.player,selected,i)&&state.phase==='place';if(available)button.classList.add('available');button.setAttribute('aria-label','Level '+(z+1)+' row '+(c.r+1)+' column '+(c.c+1)+': '+(v?name(v)+(R.free(state.b,i)?' exposed':' supporting'):(available?'open':'waiting for supports')));button.setAttribute('aria-pressed',i===selected?'true':'false');button.addEventListener('click',()=>activate(i));grid.append(button);});section.append(grid);layers.append(section);}if(focused!==undefined)document.querySelector('[data-cell="'+focused+'"]')?.focus();}
$('reserve').onclick=()=>{selected=null;state.message='Choose any open socket to spend one reserve sphere.';render();};$('end').onclick=()=>endTurn();$('new').onclick=()=>{epoch++;busy=false;history=[];selected=null;state=initial($('setup').value);save();render();};$('undo').onclick=()=>{epoch++;busy=false;state=history.pop();selected=null;save();render();runAI();};$('guide').onclick=()=>{const d=$('rules');d.open=!d.open;if(d.open)d.scrollIntoView({block:'start',behavior:'smooth'});};
try{let d=JSON.parse(localStorage.getItem(KEY));if(d&&d.state?.b?.length===30&&d.state.b.every(v=>[0,1,2].includes(v))){state=d.state;history=d.history||[];stats=d.stats||stats;}}catch{}if(!state)state=initial('normal');render();runAI();
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><rect width="64" height="64" rx="14" fill="#233f3c"/><g fill="#efe5c9"><circle cx="20" cy="43" r="11"/><circle cx="44" cy="43" r="11"/><circle cx="32" cy="23" r="11"/></g></svg>
<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Ivory Rise · Pylos</title><link rel="icon" href="./icon.svg"><link rel="stylesheet" href="./style.css"></head><body><main><header><a class="brand" href="./">IR <span>THE SMALL TABLE / Nº 04</span></a><button id="guide">How to play</button></header><section class="hero"><div><p class="eyebrow">THIRTY SPHERES. ONE SUMMIT.</p><h1>Ivory <em>Rise</em></h1><p class="intro">Build together. Save your own.<br>A quiet game of lifting, claiming, and thinking one level higher.</p></div><div class="sculpture" aria-hidden="true"><i></i><i></i><i></i><i></i><i></i><i></i></div></section><section class="toolbar"><label>Table<select id="mode"><option value="ai">You vs local computer</option><option value="two">Two people, one device</option></select></label><label>Start position<select id="setup"><option value="normal">A fresh pyramid</option><option value="square">Lesson 1 · Make a square</option><option value="lift">Lesson 2 · Lift a sphere</option><option value="finish">Lesson 3 · Claim the summit</option></select></label><button id="new">New table</button></section><section class="table"><div class="rail"><div class="player ivory"><span>IVORY / YOU</span><strong id="r1">15</strong><small>spheres in reserve</small></div><div class="player teal"><span>JADE / RIVAL</span><strong id="r2">15</strong><small>spheres in reserve</small></div><div class="action"><button id="reserve">Use reserve</button><button id="end" disabled>Finish reclaiming</button><button id="undo">Undo turn</button></div><p id="tip"></p><p class="record" id="record"></p></div><div class="play"><div class="turnline"><span id="turn"></span><span id="stage">PLACE / LIFT</span></div><p id="message" role="status" aria-live="polite"></p><div id="layers"></div><p class="legend"><span>○ available socket</span><span>● exposed sphere</span><span>◌ waiting for support</span></p></div></section><details id="rules"><summary>The art of keeping a sphere</summary><div class="guide"><p><b>1 / Place.</b> Ivory begins. Take a sphere from your reserve and place it in any open socket. Higher sockets need four occupied supports immediately below.</p><p><b>2 / Lift.</b> Instead of spending a reserve, select one of your exposed spheres, then an open socket on any higher level. You may never move a sphere that supports another, or remove a support needed by its destination.</p><p><b>3 / Reclaim.</b> Complete a 2×2 square of your color on any level to take back up to two of your exposed spheres, one at a time. You may take the sphere just placed. Finish reclaiming when ready. Straight lines do not earn a bonus in this edition.</p><p><b>4 / Win.</b> Keep spheres in reserve. If your reserve is empty at the end of your turn, your rival wins; the remaining reserve claims the summit. Placing the apex wins immediately. Three identical end-of-turn positions are a draw.</p><p><b>Controls.</b> Click or tap sockets and spheres. Tab through the board; Enter or Space activates a focused cell. “Use reserve” cancels a lift. Undo restores a whole turn, including the computer reply. Saves stay on this device. Lessons use curated positions and track separately from full games.</p><p>This independent Pylos adaptation uses the square-only rules from François Terrier’s open-source engine. The local computer uses a new small heuristic, not the upstream negamax. <a href="./source.html">Source, adaptations & license</a>.</p></div></details><footer><span>NO CLOCK. JUST A BETTER NEXT MOVE.</span><a href="./source.html">Open-source notes</a></footer></main><script src="./rules.js"></script><script src="./game.js"></script></body></html>
{
"title": "Ivory Rise \u00b7 Pylos",
"source": "https://github.com/fterrier/pylos",
"commit": "f9283cf58a32000ed271e768ab6151ac081ed37d",
"stars_observed": 5,
"license": "EPL-1.0-or-later",
"tags": [
"github-source",
"game"
],
"adaptation": "Static JavaScript port of board/static/move geometry and square-only rules, original interface and local heuristic rival. No server, WebSockets, Telegram, upstream UI artwork or negamax."
}/* Ivory Rise: JavaScript adaptation of pylos.board/static/move by François Terrier.
* Copyright 2015 François Terrier; adaptations 2026. EPL-1.0-or-later. */
(function(root){
const cells=[];for(let z=0;z<4;z++)for(let r=0;r<4-z;r++)for(let c=0;c<4-z;c++)cells.push({z,r,c});
const index=(z,r,c)=>cells.findIndex(p=>p.z===z&&p.r===r&&p.c===c);
const below=cells.map(p=>p.z?[index(p.z-1,p.r,p.c),index(p.z-1,p.r+1,p.c),index(p.z-1,p.r,p.c+1),index(p.z-1,p.r+1,p.c+1)]:[]);
const above=cells.map((p,i)=>cells.map((_,j)=>j).filter(j=>below[j].includes(i)));
const squares=[];for(let z=0;z<3;z++)for(let r=0;r<3-z;r++)for(let c=0;c<3-z;c++)squares.push([index(z,r,c),index(z,r+1,c),index(z,r,c+1),index(z,r+1,c+1)]);
const reserve=(b,p)=>15-b.filter(x=>x===p).length;
const free=(b,i)=>!!b[i]&&above[i].every(j=>!b[j]);
const open=(b,i)=>!b[i]&&below[i].every(j=>!!b[j]);
function legal(b,p,from,to){if(to<0||to>=30||b[to])return false;if(from===null)return reserve(b,p)>0&&open(b,to);if(b[from]!==p||!free(b,from)||cells[from].z>=cells[to].z)return false;let a=b.slice();a[from]=0;return open(a,to);}
function place(b,p,from,to){if(!legal(b,p,from,to))throw Error('Illegal placement');let a=b.slice();if(from!==null)a[from]=0;a[to]=p;return {board:a,square:squares.some(s=>s.includes(to)&&s.every(i=>a[i]===p))};}
function remove(b,p,i){if(b[i]!==p||!free(b,i))throw Error('Supported or foreign sphere');let a=b.slice();a[i]=0;return a;}
function options(b,p){let out=[];for(let to=0;to<30;to++){for(const from of [null,...cells.map((_,i)=>i).filter(i=>b[i]===p&&free(b,i))]){if(!legal(b,p,from,to))continue;let n=place(b,p,from,to);let variants=[{board:n.board,removed:[]}];if(n.square){for(let i=0;i<30;i++)if(n.board[i]===p&&free(n.board,i)){let a=remove(n.board,p,i);variants.push({board:a,removed:[i]});for(let j=0;j<30;j++)if(a[j]===p&&free(a,j))variants.push({board:remove(a,p,j),removed:[i,j]});}}for(let v of variants)if(v.board.join()!==b.join())out.push({...v,from,to,square:n.square});}}return out;}
function outcome(b){if(b[29])return b[29];if(reserve(b,1)===0)return 2;if(reserve(b,2)===0)return 1;return 0;}
function choose(b,p){let best=null,value=-Infinity;for(const m of options(b,p)){let winner=outcome(m.board);let v=(reserve(m.board,p)-reserve(m.board,3-p))*12+cells.reduce((s,c,i)=>s+(m.board[i]===p?c.z*2:0),0)+(winner===p?10000:winner?-10000:0);for(const s of squares){let own=s.filter(i=>m.board[i]===p).length,opp=s.filter(i=>m.board[i]===3-p).length;if(!opp)v+=own===3?4:own*.2;if(!own)v-=opp===3?5:opp*.2;}v+=m.to*.0001;if(v>value){value=v;best=m;}}return best;}
const api={cells,index,below,above,squares,reserve,free,open,legal,place,remove,options,outcome,choose};if(typeof module!=='undefined')module.exports=api;else root.Pylos=api;
})(typeof globalThis!=='undefined'?globalThis:this);
*{box-sizing:border-box}body{margin:0;background:#f2efe6;color:#233f3c;font-family:Arial,sans-serif}main{max-width:1220px;padding:24px 40px;margin:auto}button,select,summary{font:inherit}button,select{border:1px solid #aebbb0;border-radius:7px;padding:11px 14px;background:#fbfaf6;color:#233f3c}button{cursor:pointer}button:hover:not(:disabled){background:#e5eadf}button:disabled{opacity:.4;cursor:default}button:focus-visible,select:focus-visible,summary:focus-visible,a:focus-visible{outline:3px solid #c76e39;outline-offset:3px}header{display:flex;justify-content:space-between;align-items:center;border-bottom:1px solid #c8ccbd;padding-bottom:17px}.brand{font:bold 24px Georgia;color:inherit;text-decoration:none}.brand span{font:10px Arial;letter-spacing:2px;margin-left:18px}.hero{display:flex;align-items:center;justify-content:space-between;padding:40px 20px 30px}.eyebrow{font-size:11px;letter-spacing:3px;color:#6e7971}h1{font:76px/1 Georgia;margin:12px 0 18px;font-weight:normal}h1 em{color:#b06b42}.intro{font-size:16px;line-height:1.65;color:#5c6e64}.sculpture{position:relative;width:290px;height:180px;transform:rotate(-8deg)}.sculpture i{position:absolute;width:65px;height:65px;border-radius:50%;background:radial-gradient(circle at 30% 20%,#fcf8e9,#d3c6a7 65%,#a39070);box-shadow:10px 22px 20px #536c5830}.sculpture i:nth-child(1){left:30px;top:100px}.sculpture i:nth-child(2){left:98px;top:100px;background:radial-gradient(circle at 30% 20%,#80aca0,#2d675d 65%,#143e37)}.sculpture i:nth-child(3){left:166px;top:100px}.sculpture i:nth-child(4){left:64px;top:49px}.sculpture i:nth-child(5){left:132px;top:49px}.sculpture i:nth-child(6){left:98px;top:0;background:radial-gradient(circle at 30% 20%,#80aca0,#2d675d 65%,#143e37)}.toolbar{display:flex;align-items:end;gap:14px;padding:20px 0;border-top:1px solid #c8ccbd}label{font-size:11px;letter-spacing:1px;display:grid;gap:7px}select{font-size:13px;letter-spacing:0;max-width:100%}.table{display:grid;grid-template-columns:200px 1fr;background:#e3e8dd;border:1px solid #c9d0c2;border-radius:14px;overflow:hidden}.rail{padding:24px;border-right:1px solid #c7cebf}.player{padding:15px 0}.player span{display:block;font-size:10px;letter-spacing:1px}.player strong{font:44px Georgia;display:block;margin:6px 0}.player small{font-size:11px;color:#637367}.teal{color:#20685c}.action{display:grid;gap:8px;margin-top:20px}.action button{font-size:12px}#tip{font-size:12px;line-height:1.6;color:#647467}.record{font-size:11px;line-height:1.6}.play{padding:24px}.turnline{display:flex;justify-content:space-between;font-size:12px;letter-spacing:1px}#stage{color:#7e8a7b;font-size:10px}#message{min-height:40px;line-height:1.4;font-size:14px}#layers{display:grid;grid-template-columns:1.4fr 1fr;gap:15px}.layer{padding:15px;background:#eff1e8;border:1px solid #d0d6c8;border-radius:10px}.layer h2{font-size:10px;font-weight:normal;letter-spacing:2px;margin:0 0 15px;color:#75836f}.grid{display:grid;gap:7px;max-width:300px;margin:auto;aspect-ratio:1}.cell{border-radius:50%;padding:0;min-width:0;aspect-ratio:1;position:relative;background:#dce2d3;border:1px dashed #bbc6b0;box-shadow:inset 0 2px 5px #52674e12}.cell.available{border:2px solid #93aa8b;background:#f7f6eb}.cell.p1{background:radial-gradient(circle at 32% 25%,#fffef5,#daceaf 65%,#a99677);border:1px solid #beac8e;box-shadow:1px 5px 5px #344a3933}.cell.p2{background:radial-gradient(circle at 32% 25%,#90b8a7,#367c6a 60%,#1e5144);border:1px solid #376f60;box-shadow:1px 5px 5px #344a3944}.cell.selected{outline:3px solid #bd6c3e;outline-offset:2px}.cell.blocked::after{content:'·';font-size:28px;color:#566d55}.cell.p1.blocked::after,.cell.p2.blocked::after{content:'•';color:#fff8;font-size:15px}.cell.hint{outline:3px solid #bd6c3e;outline-offset:2px}.layer:nth-child(2) .grid{max-width:200px}.layer:nth-child(3) .grid{max-width:130px}.layer:nth-child(4) .grid{max-width:65px}.legend{display:flex;gap:15px;font-size:10px;color:#75836f;margin-bottom:0;flex-wrap:wrap}details{margin:24px 0;border-top:1px solid #c8ccbd;border-bottom:1px solid #c8ccbd;padding:19px 0}summary{cursor:pointer;font:21px Georgia}.guide{max-width:800px;font-size:14px;line-height:1.75}.guide a,a{color:#376c59}footer{display:flex;justify-content:space-between;font-size:10px;letter-spacing:1px;color:#7b8377;padding-bottom:20px}footer a{letter-spacing:0}@media(max-width:700px){main{padding:16px}.hero{padding:28px 0 18px}h1{font-size:60px}.sculpture{display:none}.toolbar{flex-wrap:wrap}.toolbar label{flex:1;min-width:145px}.toolbar button{width:100%}.table{grid-template-columns:1fr}.rail{border-right:0;border-bottom:1px solid #c7cebf;padding:14px;display:grid;grid-template-columns:1fr 1fr;gap:10px}.player{padding:0}.player strong{font-size:32px}.action{grid-column:1/-1;display:flex;flex-wrap:wrap;margin:4px 0}.action button{flex:1;padding:9px}#tip{grid-column:1/-1;margin:0}.record{grid-column:1/-1;margin:0}.play{padding:16px}#layers{gap:8px}.layer{padding:9px}.grid{gap:5px}.layer h2{font-size:9px;letter-spacing:1px}.brand span{font-size:8px;margin-left:8px}.turnline{font-size:11px}footer{font-size:8px;gap:10px}}
@media(max-width:700px){.toolbar{display:grid;grid-template-columns:1fr;gap:10px}.toolbar label{min-width:0}.toolbar select{width:100%;min-width:0}.hero{padding-top:18px}.hero h1{font-size:52px}.intro{font-size:14px}.eyebrow{font-size:9px;letter-spacing:2px}}
(ns pylos.board
(:require [pylos.static :refer [create-static-board-helpers]]))
;; ================
;; Pylos board protocols
(defrecord PylosBoard [board meta-board static-helpers])
(defrecord PylosMetaBoard [empty-positions balls-on-board removable-positions])
;; =================
;; private stuff
(declare square-corners cell removable-positions)
;; TODO move some of these to move.cljc ?
(defn- square-position-below [board position]
((:square-positions-below-map (:static-helpers board)) position))
(defn- positions-above-first-layer [board]
(:positions-above-first-layer (:static-helpers board)))
(defn- square-positions-at-position [board position]
"Returns a list of positions that are corners of squares
containing the given position in the given board"
((:square-positions-at-position-map (:static-helpers board)) position))
(defn- has-new-full-square-at-square-position [board square-position position color]
(let [square-corners (square-corners board square-position)
square-corners-without-position (disj square-corners position)]
(every? #(= color (cell board %)) square-corners-without-position)))
(defn- removable-balls [board position]
"Gives all balls that can be removed assuming the given position is filled."
(let [removable-positions (removable-positions board)
; we re-add the given position since it can be removed
removable-positions (conj removable-positions position)
square-position-below (square-position-below board position)]
(if (nil? square-position-below)
removable-positions
(apply disj removable-positions (square-corners board square-position-below)))))
;; ================
;; public pylos board stuff
(defn board-size [board]
(:size (:static-helpers board)))
(defn cell [board position]
(get (:board board) position))
(defn empty-positions [board]
(:empty-positions (:meta-board board)))
(defn number-of-balls-on-board [board]
(apply + (map #(count (second %)) (:balls-on-board (:meta-board board)))))
(defn removable-positions [board]
(:removable-positions (:meta-board board)))
(defn ind [board position]
((:positions-map (:static-helpers board)) position))
(defn number-of-positions-around [board]
(:number-of-positions-around (:static-helpers board)))
(defn positions-around [board position direction]
{:pre [(or (= :left-up direction) (= :right-down direction))]}
(let [static-helpers (:static-helpers board)
positions-around-map (case direction
:left-up (:positions-left-up-map static-helpers)
:right-down (:positions-right-down-map static-helpers))]
(positions-around-map position)))
(defn position-on-top [board position]
((:position-on-top-map (:static-helpers board)) position))
(defn positions-under-position [board position]
((:positions-under-position-map (:static-helpers board)) position))
(defn square-corners [board position]
(positions-around board position :right-down))
(defn number-of-positions [board]
(:number-of-positions (:static-helpers board)))
; Starting functions that access the state
(defn balls-on-board [board color]
(color (:balls-on-board (:meta-board board))))
(defn balls-remaining [board color]
(let [number-of-balls (/ (number-of-positions board) 2)]
(- number-of-balls (count (balls-on-board board color)))))
(defn has-ball [board position]
(let [cell (cell board position)]
(or (= :black cell) (= :white cell))))
(defn can-remove-ball [board position]
(contains? (removable-positions board) position))
(defn new-full-square-position [board position color]
"Checks whether the board would have a now full square if the
board would be filled with a ball of the given color at the given position"
(let [square-positions (square-positions-at-position board position)]
(some #(when (has-new-full-square-at-square-position board % position color) %) square-positions)))
(defn removable-candidates-under-position
"Gives all candidates under the given position that can be removed,
assuming the given position would be filled by the given color on the board."
[board color position]
(let [removable-balls (removable-balls board position)
positions-under (positions-under-position board position)]
(into #{} (filter #(and (contains? removable-balls %) (contains? positions-under %))
(balls-on-board board color)))))
(defn removable-candidates
"Gives all the candidates on the board that can be removed,
assuming the given position would be filled by the given color on the board."
[board color position-with-ball]
(let [removable-balls (removable-balls board position-with-ball)
removable-balls (into #{} (filter #(contains? removable-balls %) (balls-on-board board color)))]
; we conj the given position since it can be removed
(conj removable-balls position-with-ball)))
(defn change-cell
([board position new-cell]
"Changes a cell to a new cell"
(assoc-in board [:board position] new-cell))
([partial-board partial-position new-cell cell-to-replace]
"Changes a cell to a new cell only if the cell contains cell-to-replace"
(if (= cell-to-replace (cell partial-board partial-position))
(change-cell partial-board partial-position new-cell)
partial-board)))
(defn has-square [board position]
(let [positions-to-check (square-corners board position)]
(and (= 4 (count positions-to-check))
(every? #(has-ball board %) positions-to-check))))
(defn squares-at-position [board position]
(let [positions-to-try (square-positions-at-position board position)]
(into #{} (filter #(has-square board %) positions-to-try))))
(defn has-balls-to-play [board color]
(let [balls-per-player (/ (number-of-positions board) 2)
balls-of-color-in-play (count (balls-on-board board color))]
(not (= balls-per-player balls-of-color-in-play))))
(defn add-ball [board color position]
{:pre [(= :open (cell board position))
(has-balls-to-play board color)]}
(let [meta-infos (:meta-board board)
board-with-ball (change-cell board position color)
new-square-positions (squares-at-position board-with-ball position)
new-open-positions (map #(position-on-top board %) new-square-positions)
new-empty-positions (-> (apply conj (:empty-positions meta-infos) new-open-positions)
(disj position))
position-below (square-position-below board position)
removable-positions-to-remove (if-not (nil? position-below) (square-corners board-with-ball position-below) [])]
(assoc (reduce #(change-cell %1 %2 :open :no-acc) board-with-ball new-open-positions)
:meta-board (assoc meta-infos
:empty-positions new-empty-positions
:removable-positions (-> (apply disj (:removable-positions meta-infos) removable-positions-to-remove)
(conj position))
:balls-on-board (update (:balls-on-board meta-infos) color #(conj % position))))))
(defn removable-positions-below [board position]
"Gives the positions immediately below the given positions that can be removed
given that the given position is not any more filled on the board"
(let [position-below (square-position-below board position)
new-removable-positions (if-not (nil? position-below)
(remove (fn [position]
(let [positions-to-try (square-positions-at-position board position)]
(some #(has-ball board (position-on-top board %)) positions-to-try)))
(square-corners board position-below)) [])]
new-removable-positions))
(defn removable-positions-of-color-below [board position color]
(let [removable-positions-below (removable-positions-below board position)
balls-of-color (balls-on-board board color)]
(filter #(contains? balls-of-color %) removable-positions-below)))
(defn remove-ball [board color position]
{:pre [(= color (cell board position))
(can-remove-ball board position)]}
(let [meta-infos (:meta-board board)
board-without-ball (change-cell board position :open)
square-positions-to-remove (squares-at-position board position)
open-positions-to-remove (map #(position-on-top board %) square-positions-to-remove)
new-empty-positions (-> (apply disj (:empty-positions meta-infos) open-positions-to-remove)
(conj position))
new-removable-positions (removable-positions-below board-without-ball position)]
(assoc (reduce #(change-cell %1 %2 :no-acc :open) board-without-ball open-positions-to-remove)
:meta-board (assoc meta-infos
:empty-positions new-empty-positions
:removable-positions (-> (apply conj (:removable-positions meta-infos) new-removable-positions)
(disj position))
:balls-on-board (update (:balls-on-board meta-infos) color #(disj % position))))))
(defn can-remove-position? [board color position]
(and (can-remove-ball board position)
(= color (cell board position))))
(defn can-add-position? [board color position]
"Checks if the given add can be done, given that the move has not been
generated on the board."
(= :open (cell board position)))
;; =======================
;; Pylos board creation and visitors - PRIVATE
(defn- retrieve-empty-positions [board]
(into #{} (filter #(= :open (cell board %)) (range 0 (count (:board board))))))
(defn- retrieve-balls-on-board [board color]
(into #{} (filter #(= color (cell board %)) (range 0 (count (:board board))))))
(defn- can-remove-ball-no-meta [board position]
(and (has-ball board position)
(every? #(not (has-ball board (position-on-top board %))) (positions-around board position :left-up))))
(defn- retrieve-removable-positions [board]
(into #{} (filter #(can-remove-ball-no-meta board %) (range 0 (count (:board board))))))
(defn- create-meta-board [board]
{:empty-positions (retrieve-empty-positions board)
:balls-on-board {:black (retrieve-balls-on-board board :black)
:white (retrieve-balls-on-board board :white)}
:removable-positions (retrieve-removable-positions board)})
(defn- create-board
([board size static-board-helpers]
(let [board-with-static {:board board :static-helpers static-board-helpers}
meta-board (create-meta-board board-with-static)]
(map->PylosBoard {:static-helpers static-board-helpers
:board board
:meta-board meta-board}))))
(defn- create-initial-board-vector [size number-of-positions]
(into [] (map (fn [ind] (if (< ind (* size size)) :open :no-acc))
(range number-of-positions))))
;; ========================
;; Pylos board creation and visitors public interface
(defn new-pylos-board
([board size]
"Create all meta data for a board and attach to it"
(create-board board size (create-static-board-helpers size)))
([size]
"Creates a new board with initial position"
(let [static-board-helpers (create-static-board-helpers size)
board (create-initial-board-vector
size (:number-of-positions static-board-helpers))]
(create-board board size static-board-helpers))))
(defn visit-board [board visit-fn]
(let [size (board-size board)
positions-map (:positions-map (:static-helpers board))]
(into []
(for [layer (range 0 size)]
(into []
(for [row (range 0 (- size layer))]
(into []
(for [col (range 0 (- size layer))]
(visit-fn [layer row col] (get positions-map [(inc layer) (inc row) (inc col)]))))))))))
(ns pylos.move
"game is {:player _ :board _ :past-moves _}
move is {:board _ :move _}"
#?@(:clj
[(:require
[pylos.board
:refer
[add-ball
can-add-position?
can-remove-position?
empty-positions
has-balls-to-play
new-full-square-position
number-of-positions-around
positions-under-position
removable-candidates
removable-candidates-under-position
removable-positions-of-color-below
remove-ball]])]
:cljs
[(:require
[pylos.board
:refer
[add-ball
can-add-position?
can-remove-position?
positions-under-position
empty-positions
has-balls-to-play
new-full-square-position
number-of-positions-around
removable-candidates
removable-candidates-under-position
removable-positions-of-color-below
remove-ball]])]))
(declare make-move-on-board)
(defn- all-tails [col]
(map reverse (remove empty? (reductions conj [] col))))
(defn is-move-allowed [board {:keys [color type position low-position positions original-move] :as move}]
(case type
:add (can-add-position? board color position)
:rise (and (can-remove-position? board color low-position)
(contains? (positions-under-position board position) low-position)
(can-add-position? (remove-ball board color low-position) color position))
:square (and (is-move-allowed board original-move)
(reduce #(if-not (can-remove-position? %1 color %2) (reduced false) (remove-ball %1 color %2)) (make-move-on-board board original-move) positions))))
(defn make-move-on-board [board {:keys [color type position original-move low-position positions] :as move}]
"Returns the board that is generated by making the given move"
{:pre [(is-move-allowed board move)]}
(case type
:add (add-ball board color position)
:rise (-> board
(remove-ball color low-position)
(add-ball color position))
:square (reduce #(remove-ball %1 color %2)
(make-move-on-board board original-move) positions)))
(defn move-square [original-move positions-to-remove square-position]
(let [color (:color original-move)]
{:type :square
:original-move original-move
:positions positions-to-remove
:square-position square-position
:color color}))
(defn move-add [color position]
{:type :add
:position position
:color color})
(defn move-rise [color low-position high-position]
{:type :rise
:low-position low-position
:position high-position
:color color})
(defn- remove-balls-when-square [{:keys [position type] :as move} board color new-square-position]
"Generates all possible ball removal possibilities given taht there is a square
of the same color as player at the given position
Assumes the given move has not been generated on the given board."
(let [removable-balls (removable-candidates board color position)
removable-balls (if (= :rise type) (disj removable-balls (:low-position move)) removable-balls) ; we remove the low position if rise
moves-with-one-ball-removed (map (fn [position] (move-square move [position] new-square-position)) removable-balls)
moves-with-two-balls-removed (mapcat (fn [[position & new-removable-balls :as stuff]]
(concat
(map (fn [second-position] (move-square move #{position second-position} new-square-position)) new-removable-balls)
(map (fn [second-position] (move-square move [position second-position] new-square-position)) (removable-positions-of-color-below board position color))))
(all-tails removable-balls))]
(concat moves-with-two-balls-removed moves-with-one-ball-removed)))
(defn calculate-next-moves [{:keys [board player]} empty-position]
(let [move-with-ball-added (move-add player empty-position)
moves-with-ball-risen (map #(move-rise player % empty-position)
(removable-candidates-under-position board player empty-position))
next-moves (reduce (fn [all-moves {:keys [position type] :as move}]
(let [new-square-position (new-full-square-position board position player)]
(if (nil? new-square-position) (conj all-moves move)
(concat all-moves (remove-balls-when-square move board player new-square-position)))))
[] (conj moves-with-ball-risen move-with-ball-added))]
(into [] next-moves)))
(defn generate-all-moves [game-position]
(mapcat #(calculate-next-moves game-position %) (empty-positions (:board game-position))))
(defn- compare-positions [board position1 position2]
(let [number-of-positions-around (number-of-positions-around board)]
(- (number-of-positions-around position2)
(number-of-positions-around position1))))
(defn- compare-moves [board]
(fn [{type1 :type :as move1} {type2 :type :as move2}]
(if (= type1 type2)
; we order by position
(cond
; except if square, then we put the 2 before the ones
(= type1 :square) (let [positions1 (:positions move1)
positions2 (:positions move2)]
(if (= (count positions1) (count positions2))
(compare-positions board
(:position (:original-move move1))
(:position (:original-move move2)))
(if (= 2 (count positions1)) -1 1)))
:else (compare-positions board (:position move1) (:position move2)))
; we order by type
(cond
(= type1 :square) -1
(= type2 :square) 1
(= type1 :rise) -1
(= type2 :rise) 1
;; impossible state
:else 0))))
(defn order-moves [board moves]
(sort (compare-moves board) moves))
(defn game-over? [board]
(or (not (has-balls-to-play board :white))
(not (has-balls-to-play board :black))))
(defn winner [board]
; {:pre [(game-over? board)]}
(if (has-balls-to-play board :white) :white :black))
(ns pylos.static
#?(:clj (:require [clojure.math.numeric-tower :as math])))
(defrecord PylosStaticBoardHelpers [number-of-positions size
positions-right-down-map
positions-left-up-map
position-on-top-map
square-positions-below-map
square-positions-at-position-map
number-of-positions-around
positions-above-first-layer
positions-under-position-map
positions-map all-positions])
(defn- calculate-all-positions [size]
"Returns an array of [layer row col] positions in their order in the board."
(into [] (apply concat (for [layer (range 1 (+ 1 size))]
(let [max-size (+ 2 (- size layer))]
(for [x (range 1 max-size)
y (range 1 max-size)]
[layer x y]))))))
(defn- calculate-positions-around [positions-map [layer row col :as position] ind]
(remove #(nil? (positions-map %)) [[layer (+ row ind) (+ col ind)]
[layer (+ row ind) col]
[layer row (+ col ind)]
[layer row col]]))
(defn- calculate-square-positions-at-position [positions-left-up positions-right-down position]
"Returns a list of positions that are corners of squares
containing the given position in the given board"
(let [positions-to-try (positions-left-up position)
positions-to-try (filter #(= 4 (count (positions-right-down %))) positions-to-try)]
positions-to-try))
;; TODO maybe have this function return something else when calling on the top position
(defn- calculate-position-on-top [position]
(update position 0 inc))
;; TODO maybe have this function return something else when calling on the bottom layer
(defn- calculate-square-positions-below [position]
"Returns the position below or nil if we are at first layer"
(let [position-below (update position 0 dec)]
(if (< (position-below 0) 1) nil position-below)))
(defn- calculate-positions-under-position [all-positions [layer _ _ :as position]]
(apply concat (for [layer-to-check (range 1 layer)]
(filter (fn [[layer _ _]] (= layer layer-to-check)) all-positions))))
(defn- calculate-positions-above-first-layer [all-positions]
(filter (fn [[layer _ _]] (> layer 1)) all-positions))
(defn- calculate-empty-positions [all-positions]
(filter (fn [[layer _ _]] (= 1 layer)) all-positions))
(defn- ceil [value]
#?(:clj (math/ceil value) :cljs (. js/Math ceil value)))
(defn- calculate-middle-positions [positions-right-down size]
(let [middle-positions (for [layer (range 1 (- size 1))]
(let [size-of-layer (- size (- layer 1))
middle (ceil (/ size-of-layer 2))
one-ball (= 1 (mod size-of-layer 2))]
(if one-ball [[layer middle middle]]
(positions-right-down [layer middle middle]))))
middle-positions (apply concat middle-positions)]
middle-positions))
(defn- calculate-all-positions-around [position positions-left-up positions-right-down]
(apply conj (positions-left-up position) (positions-right-down position)))
(defn- vec-from-map [m size]
(into [] (let [ind (range 0 size)]
(map #(m %) ind))))
;; optimize data structure
(defn- create-position-map [fun positions positions-map]
(vec-from-map
(into {} (map (fn [position] [(positions-map position) (into #{} (map positions-map (fun position)))]) positions))
(count positions-map)))
;; optimize data structure
(defn- create-position-map-one [fun positions positions-map]
(vec-from-map
(into {} (map (fn [position] [(positions-map position) (positions-map (fun position))]) positions))
(count positions-map)))
;; optimize data structure
(defn- create-position-set [positions positions-map]
(into #{} (map positions-map positions)))
(defn create-static-board-helpers [size]
(let [all-positions (calculate-all-positions size)
number-of-positions (count all-positions)
positions-map (into {} (map (fn [ind] [(all-positions ind) ind]) (range number-of-positions)))
positions-above-first-layer-no-ind (calculate-positions-above-first-layer all-positions)
positions-right-down-no-ind (into {} (map (fn [position] [position (calculate-positions-around positions-map position 1)]) all-positions))
positions-left-up-no-ind (into {} (map (fn [position] [position (calculate-positions-around positions-map position -1)]) all-positions))
positions-above-first-layer (create-position-set positions-above-first-layer-no-ind positions-map)
positions-right-down-map (create-position-map #(calculate-positions-around positions-map % 1) all-positions positions-map)
positions-left-up-map (create-position-map #(calculate-positions-around positions-map % -1) all-positions positions-map)
square-positions-below-map (create-position-map-one #(calculate-square-positions-below %) all-positions positions-map)
square-positions-at-position-map (create-position-map #(calculate-square-positions-at-position positions-left-up-no-ind positions-right-down-no-ind %) all-positions positions-map)
positions-under-position-map (create-position-map #(calculate-positions-under-position all-positions %) positions-above-first-layer-no-ind positions-map)
position-on-top-map (create-position-map-one #(calculate-position-on-top %) all-positions positions-map)
positions-around (create-position-map #(calculate-all-positions-around % positions-left-up-no-ind positions-right-down-no-ind)
all-positions positions-map)]
(map->PylosStaticBoardHelpers
{:size size
:number-of-positions number-of-positions
:positions-right-down-map positions-right-down-map
:positions-left-up-map positions-left-up-map
:position-on-top-map position-on-top-map
:square-positions-below-map square-positions-below-map
:square-positions-at-position-map square-positions-at-position-map
:positions-above-first-layer positions-above-first-layer
:positions-under-position-map positions-under-position-map
:number-of-positions-around (into [] (map (fn [positions-around] (count positions-around)) positions-around))
;; this map is only used to translate a position in coordinates into the integer
:positions-map positions-map
:all-positions all-positions})))
[](https://travis-ci.org/fterrier/pylos)
# Board Game Engine for Pylos
This is a board game engine and AI implementation in Clojure for 2-player games. At the moment, the board game [Pylos](https://boardgamegeek.com/boardgame/1419/pylos) in Clojure.
TODO screenshot
# Getting started
## Running the project in the REPL
```bash
git clone git@github.com:fterrier/pylos.git
cd pylos
lein repl
```
The project uses Stuart Sierra's components library. In the REPL, then use this to start (and restart) the system:
```bash
(user/go) # start system
(user/stop) # stop system
```
Open `http://localhost:8888`. To enter a CLJS REPL connection to the browser, run:
```bash
(user/cljs)
```
You can then play around with the app running in the browser. Try for instance:
```
# TODO output reconciler app-state
```
## Running the project standalone
### With an uberjar
```
lein uberjar
java -jar target/pylos.jar
```
Open `http://localhost:8080`
### With docker
```
lein uberimage
docker run -p 4000:8080 <generated-docker-image-id>
```
Open `http://<docker-machine-ip>:4000`
# Basic concepts
The engine can be extended to support multiple strategies. For now, those strategies are implemented :
| Name | Description |
|---|---|
| NegamaxStrategy | The negamax algorithm with alpha-beta pruning and transposition tables |
| RandomStrategy | Plays randomly |
| ChannelStrategy | Accepts move input from a channel |
More will be added in the future so we can let them play against each other.
TODO explain strategies, game and output functions.
# Useful REPL commands
TODO
In the REPL, you can call the following shortcut commands:
```bash
(-> (new-game)
(add-negamax 8 :white)
(add-negamax 8 :black)
(output-game pylos.pprint/print-pylos-game)
(start-game))
```
You should see stuff like this:
```
====================
Board after move of :black
====================
Move: {:type :add, :position 20, :color :black}
Time: 772.270422
o o o o - - - - - -
o w b o - b - - -
o b w o - - -
o o o o
Balls remaining :
- :white 13
- :black 12
{:negamax-values {:best-possible-score 1/2, :outcome nil}, :stats {:calculated-moves 14176, :lookup-moves 16234}}
Calculated moves per ms: 18.35626432938798
```
# TODO (incomplete)
- [] Use test.check to test the game algorithm, game and game server
- [] Handle timeouts, errors, etc...
- [] Persist game - CRDTs?
- [] Implement chess and create nicer abstractions for UI
- [] Scalability - what happens when game runner runs on more servers?
# Bugs
Open Github issue and don't hesitate to PR.
# License
Copyright © 2015 François Terrier
Distributed under the Eclipse Public License either version 1.0 or (at
your option) any later version.