Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@nanjizal
Last active January 12, 2021 13:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nanjizal/6614efcb878a8f4c62c78eb7b32c1e1b to your computer and use it in GitHub Desktop.
Save nanjizal/6614efcb878a8f4c62c78eb7b32c1e1b to your computer and use it in GitHub Desktop.
NextTo, assume MIT if used, ideal for slider puzzle.
#if useTypeDef
typedef NextToCore = {
var width: Int;
var item: Int;
var target: Int;
}
#else
@:structInit
class NextToCore {
public var width: Int;
public var item: Int;
public var target: Int;
public function new( width: Int, item: Int, target: Int ){
this.width = width;
this.item = item;
this.target = target;
}
}
#end
// usage
// trace(({ width: 7, item: 8, target: 9 }:NextTo).check() );
@:forward
abstract NextTo( NextToCore ) from NextToCore {
function new( nextToCore: NextToCore ){
this = nextToCore;
}
public inline
function check(): Bool {
var colItem = column( this.item );
var colTarget = column( this.target );
var rowItem = row( this.item, colItem );
var rowTarget = row( this.target, colTarget );
var sameCol = ( colItem == colTarget );
var sameRow = ( rowItem == rowTarget );
return if( sameCol ){
above1() || below1();
} else if( sameRow ){
left1() || right1();
} else {
return false;
}
}
inline
function column( val: Int ): Int {
return val % this.width;
}
inline
function row( val: Int, valColumn: Int ): Int {
return cast ( val - valColumn )/this.width;
}
inline
function above1(): Bool {
return difTarget() == -this.width;
}
inline
function below1(): Bool {
return difTarget() == this.width;
}
inline
function left1(): Bool {
return difTarget() == -1;
}
inline
function right1(): Bool {
return difTarget() == 1;
}
inline
function difTarget():Int {
return this.target - this.item;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment