import
Foundation
struct
Matrix
{
let
rows:
Int
, columns:
Int
var
grid: [
Int
]
init
(rows:
Int
, columns:
Int
) {
self
.rows = rows
self
.columns = columns
grid =
Array
(count: rows * columns, repeatedValue: 0)
}
func
indexIsValidForRow(row:
Int
, column:
Int
) ->
Bool
{
return
row >= 0 && row < rows && column >= 0 && column < columns
}
subscript(row:
Int
, column:
Int
) ->
Int
{
get
{
assert(indexIsValidForRow(row, column: column),
"超出范围"
)
return
grid[(row * columns) + column]
}
set
{
assert(indexIsValidForRow(row, column: column),
"超出范围"
)
grid[(row * columns) + column] = newValue
}
}
}
class
GameModelMatrix
{
var
dimension:
Int
= 0
var
tiles:
Matrix
init
(dimension:
Int
)
{
self
.dimension = dimension
self
.tiles =
Matrix
(rows:
self
.dimension, columns:
self
.dimension)
}
func
emptyPositions()-> [
Int
]
{
var
emptytiles =
Array
<
Int
>()
for
row
in
0..<
self
.dimension
{
for
col
in
0..<
self
.dimension
{
var
val = tiles[row,col]
if
(val == 0)
{
emptytiles.append(tiles[row, col])
}
}
}
return
emptytiles
}
func
setPosition(row:
Int
, col:
Int
, value:
Int
) ->
Bool
{
assert(row >= 0 && row < dimension)
assert(col >= 0 && col < dimension)
var
val = tiles[row,col]
if
(val > 0)
{
println
(
"该位置(\(row), \(col))已经有值了"
)
return
false
}
printTiles()
tiles[row, col] = value
printTiles()
return
true
}
func
isFull()->
Bool
{
if
(emptyPositions().count == 0)
{
return
true
}
return
false
}
func
printTiles()
{
println
(tiles)
println
(
"输出数据模型数据"
)
for
row
in
0..<
self
.dimension
{
for
col
in
0..<
self
.dimension
{
print
(
"\(tiles[row, col])\t"
)
}
println
(
""
)
}
println
(
""
)
}
}
请发表评论