コード例 #1
0
ファイル: wall.go プロジェクト: ivan1993spb/clever-snake
func CreateLongWall(pg *playground.Playground) (Wall, error) {
	if pg == nil {
		return nil, playground.ErrNilPlayground
	}

	var (
		pgW, pgH = pg.GetSize()
		err      error
		dots     playground.DotList
	)

	switch playground.RandomDirection() {
	case playground.DIR_NORTH, playground.DIR_SOUTH:
		dots, err = pg.GetEmptyField(1, pgH)
	case playground.DIR_EAST, playground.DIR_WEST:
		dots, err = pg.GetEmptyField(pgW, 1)
	default:
		err = playground.ErrInvalidDirection
	}

	if err != nil {
		return nil, err
	}

	return CreateWall(pg, dots)
}
コード例 #2
0
ファイル: snake.go プロジェクト: ivan1993spb/clever-snake
// CreateSnake creates new snake
func CreateSnake(pg *playground.Playground, cxt context.Context,
) (*Snake, error) {

	if pg == nil {
		return nil, &errCreateObject{playground.ErrNilPlayground}
	}
	if err := cxt.Err(); err != nil {
		return nil, &errCreateObject{err}
	}

	var (
		dir  = playground.RandomDirection()
		dots playground.DotList
		err  error
	)

	switch dir {
	case playground.DIR_NORTH, playground.DIR_SOUTH:
		dots, err = pg.GetEmptyField(1, uint8(_SNAKE_START_LENGTH))
	case playground.DIR_EAST, playground.DIR_WEST:
		dots, err = pg.GetEmptyField(uint8(_SNAKE_START_LENGTH), 1)
	}

	if err != nil {
		return nil, &errCreateObject{err}
	}

	if dir == playground.DIR_SOUTH || dir == playground.DIR_EAST {
		dots = dots.Reverse()
	}

	// Parent context stores in snake to pass it to corpse when snake
	// will be died. Snakes context are passed in run func
	scxt, cncl := context.WithCancel(cxt)

	snake := &Snake{pg, dots, _SNAKE_START_LENGTH, dir, time.Now(),
		cxt, cncl}

	if err = pg.Locate(snake); err != nil {
		return nil, &errCreateObject{err}
	}

	if err := snake.run(scxt); err != nil {
		pg.Delete(snake)
		return nil, &errCreateObject{err}
	}

	return snake, nil
}