我写的代码可能有点长,但是我想看看是否有错误,以便我可以将其提交到 dartbug.com 。如果没有错误,我想知道我做错了什么。
代码的想法是将点的位置与网格(分别为 Square 类和 Grid 类)同步。
Square.onPosChange 是一个发送前一个位置的 Stream。
当一个正方形被添加到网格(Grid.add)时,有一个对 onPosChange 的订阅,它所做的是改变正方形在网格中的位置;首先它将它从前一个位置删除(只是分配 null),然后将它分配给当前位置。
当我期望前一个位置为空时,我的测试失败了。现在下面是代码,请注意我认为可能是问题的注释行。
编辑:以防万一,这不是愚人节问题:P
import 'dart:async';
import 'package:unittest/unittest.dart';
void main() {
test('grid',(){
Square s = new Square(3, 5);
Grid g = new Grid(10,10);
g.add(s);
expect(g._cols[3].squares[5], s);//pass
s.x = 6;
expect(g._cols[6].squares[5], s);//pass
expect(g._cols[3].squares[5], isNull);//fails
});
}
class Grid{
List<GridCol> _cols;
int w, h;
Grid(this.w, this.h){
_cols = new List<GridCol>.filled(w, new GridCol(h));
}
add(Square square){
if(!isOut(square)){
//add square to grid
_cols[square.x].squares[square.y] = square;
//listen to onPosChanged event stream
square.onPosChanged.listen((Point previousPos){
//remove from previous position
_cols[previousPos.x].squares[previousPos.y] = null;
//if is not out of bounds, add in new position
if(!isOut(square)){
/*
* Up until this point, (3,5) is null, as was set earlier.
* (6,5) is also null since it was never set.
*
* But after the following line, strangely,
* both (3,5) and (6,5) are set to the square.
*/
_cols[square.x].squares[square.y] = square;
print("(3,5): ${_cols[3].squares[5]}");//(3,5): (6,5)
print("(6,5): ${_cols[6].squares[5]}");//(6,5): (6,5)
}
});
}
}
isOut(Point p) =>
p.x < 0 || p.y < 0 || p.x >= w || p.y >= h;
}
class GridCol{
List<Square> squares;
GridCol(int h): squares = new List<Square>(h);
}
class Square extends Point{
int get x => super.x;
set x (value){
var prev = super.x;
super.x = value;
_sc.add(p(prev, y));
}
int get y => super.y;
set y (value){
var prev = super.y;
super.y = value;
_sc.add(p(x,prev));
}
StreamController<Point> _sc;
Stream get onPosChanged => _sc.stream;
Square(x, y)
{
super.x = x;
super.y = y;
_sc = new StreamController<Point>.broadcast();
}
}
class Point{
int x = 0;
int y = 0;
Point([this.x, this.y]);
String toString() => '($x,$y)';
}
p(x, y) => new Point(x, y);