unsigned int AutoPolygon::getSquareValue(const unsigned int& x, const unsigned int& y, const Rect& rect, const float& threshold)
{
    /*
     checking the 2x2 pixel grid, assigning these values to each pixel, if not transparent
     +---+---+
     | 1 | 2 |
     +---+---+
     | 4 | 8 | <- current pixel (curx,cury)
     +---+---+
     */
    unsigned int sv = 0;
    //NOTE: due to the way we pick points from texture, rect needs to be smaller, otherwise it goes outside 1 pixel
    auto fixedRect = Rect(rect.origin, rect.size-Size(2,2));
    
    Vec2 tl = Vec2(x-1, y-1);
    sv += (fixedRect.containsPoint(tl) && getAlphaByPos(tl) > threshold)? 1 : 0;
    Vec2 tr = Vec2(x, y-1);
    sv += (fixedRect.containsPoint(tr) && getAlphaByPos(tr) > threshold)? 2 : 0;
    Vec2 bl = Vec2(x-1, y);
    sv += (fixedRect.containsPoint(bl) && getAlphaByPos(bl) > threshold)? 4 : 0;
    Vec2 br = Vec2(x, y);
    sv += (fixedRect.containsPoint(br) && getAlphaByPos(br) > threshold)? 8 : 0;
    CCASSERT(sv != 0 && sv != 15, "square value should not be 0, or 15");
    return sv;
}
Beispiel #2
0
void PropertyField::initTouchThings()
{
    static bool touch_moved = false;
    auto listener = EventListenerTouchOneByOne::create();

    listener->onTouchBegan = [this](Touch* touch, Event* event){
        auto point = touch->getLocation();
        auto rect = DDConfig::propertyAreaRect();
        touch_moved = false;
        return !DDPropertyFieldProtocal::flagIsTappingExclusive && rect.containsPoint(point) && _tappingEnable && _showState==SS_AGENT;
    };

    listener->onTouchMoved = [this](Touch* touch, Event* event){
        touch_moved = true;
    };

    listener->onTouchEnded = [this](Touch* touch, Event* event){
        auto rect = DDConfig::propertyAreaRect();
        if (rect.containsPoint(touch->getLocation()) && touch_moved == false) {

            auto point = touch->getLocation();
            // 遍历各个propNode

            // 5个常规node
            for (int i= 0; i < NUM_PROPERTY_MAX; i++) {
                auto node = &_propertyNodes[i];
                if (node->enable && node->clickable && help_checkIfPointInNode(node->image, point)) {
                    // 常规属性升级
                    if (node->cost <= DDMapData::s()->_cntGasLeft) {
                        ansClickAgentUpgrade(_battleAgentAid, node->propType);
                    } else {
                        ansClickGasRunOut();
                    }
                    return;
                }
            }

            // 五行
            if (_elementTypeNode.enable && _elementTypeNode.clickable && help_checkIfPointInNode(_elementTypeNode.image, point)) {
                ansClickElementIcon(_battleAgentAid, _elementTypeNode.propType);
                return;
            }

            // 移除按钮
            if (_removeNode.enable && _removeNode.clickable && help_checkIfPointInNode(_removeNode.image, point)) {
                ansClickRemoveIcon(_battleAgentAid, _removeNode.propType);
                return;
            }
        }
    };

    listener->onTouchCancelled = [this](Touch* touch, Event* event){
    };

    _propertyLayer->getEventDispatcher()->addEventListenerWithSceneGraphPriority(listener, _propertyLayer);
}
void BuildingField::init(cocos2d::Layer *buildingLayer)
{
    static bool touch_moved = false;
    _buildingLayer = buildingLayer;

    _buildingImage = Sprite::create("images/template_buildings.png");
    _buildingImage->setPosition(DDConfig::buildingAreaCenter());
    auto rect = DDConfig::buildingAreaRect();
    _buildingImage->setScale(rect.size.width/_buildingImage->getContentSize().width);
    _buildingImage->setZOrder(Z_BUILDING_IMAGE);
    _buildingLayer->addChild(_buildingImage);

    _selectionIcon = Sprite::create("images/template_buildings_select_icon.png");
    _selectionIcon->setScale(rect.size.height/_selectionIcon->getContentSize().height);
    _selectionIcon->setVisible(false);
    _selectionIcon->setZOrder(Z_SELECT_ICON);
    _buildingLayer->addChild(_selectionIcon);


    auto listener = EventListenerTouchOneByOne::create();

    listener->onTouchBegan = [this](Touch* touch, Event* event){
        auto point = touch->getLocation();
        auto rect = DDConfig::buildingAreaRect();
        touch_moved = false;
        return rect.containsPoint(point);
    };

    listener->onTouchMoved = [this](Touch* touch, Event* event){
        touch_moved = true;
    };

    listener->onTouchEnded = [this](Touch* touch, Event* event){
        auto rect = DDConfig::buildingAreaRect();
        if (rect.containsPoint(touch->getLocation()) && touch_moved == false) {
            //算出选中了哪一个
            auto point = touch->getLocation();
            float diffX = point.x - rect.origin.x;
            float widthStep = DDConfig::buildingAreaSelectionWidth();
            int which = diffX / widthStep;
            CCLOG("buildingfiled select %d", which);
            _selectionIcon->setVisible(true);
            _selectionIcon->setPosition(rect.origin + Vec2{widthStep*which + widthStep*0.5f, rect.size.height*0.5f});
        }
    };

    listener->onTouchCancelled = [this](Touch* touch, Event* event){
    };

    _buildingLayer->getEventDispatcher()->addEventListenerWithSceneGraphPriority(listener, _buildingLayer);

}
Beispiel #4
0
        bool Brush::containsEntity(const Entity& entity) const {
            BBoxf theirBounds = entity.bounds();
            if (!bounds().contains(theirBounds))
                return false;

            Vec3f point = theirBounds.min;
            if (!containsPoint(point))
                return false;
            point[0] = theirBounds.max[0];
            if (!containsPoint(point))
                return false;
            point[1] = theirBounds.max[1];
            if (!containsPoint(point))
                return false;
            point[0] = theirBounds.min[0];
            if (!containsPoint(point))
                return false;
            point = theirBounds.max;
            if (!containsPoint(point))
                return false;
            point[0] = theirBounds.min[0];
            if (!containsPoint(point))
                return false;
            point[1] = theirBounds.min[1];
            if (!containsPoint(point))
                return false;
            point[0] = theirBounds.max[0];
            if (!containsPoint(point))
                return false;
            return true;
        }
Beispiel #5
0
bool CheckBox::handleMouse( UINT uMsg, POINT pt, WPARAM wParam, LPARAM lParam )
{
    if( !_enabled || !visible() )
        return false;

    switch( uMsg )
    {
        case WM_LBUTTONDOWN:
        case WM_LBUTTONDBLCLK:
        {
            if (containsPoint( pt ))
            {
                // Pressed while inside the control
                _pressed = true;
                // mdavidson come back to
                SetCapture (_dialog->windowHandle());

                if( !_hasFocus )
                    _dialog->RequestFocus (this);

                return true;
            }

            break;
        }

        case WM_LBUTTONUP:
        {
            if( _pressed )
            {
                _pressed = false;
                ReleaseCapture();

                // Button click
                if( containsPoint( pt ) )
                {
                    SetCheckedInternal( !m_bChecked, true );

                }

                return true;
            }

            break;
        }
    };
    
    return false;
}
Beispiel #6
0
double RS_Image::getDistanceToPoint(const RS_Vector& coord,
                                    RS_Entity** entity,
                                    RS2::ResolveLevel /*level*/,
                                                                        double /*solidDist*/) const{
    if (entity) {
        *entity = const_cast<RS_Image*>(this);
    }

    RS_VectorSolutions corners = getCorners();

    //allow selecting image by clicking within images, bug#3464626
	if(containsPoint(coord)){
		//if coord is on image

		RS_SETTINGS->beginGroup("/Appearance");
		bool draftMode = (bool)RS_SETTINGS->readNumEntry("/DraftMode", 0);
		RS_SETTINGS->endGroup();
		if(!draftMode) return double(0.);
	}
    //continue to allow selecting by image edges
    double minDist = RS_MAXDOUBLE;

	for (size_t i = 0; i < corners.size(); ++i){
		size_t const j = (i+1)%corners.size();
		RS_Line const l{corners.get(i), corners.get(j)};
		double const dist = l.getDistanceToPoint(coord, nullptr);
		minDist = std::min(minDist, dist);
	}

    return minDist;
}
Beispiel #7
0
void ClickText::handleMouseMove(const Common::Point &point) {
	if (containsPoint(point)) {
		_curVisual = _visualActive;
	} else {
		_curVisual = _visualPassive;
	}
}
Beispiel #8
0
bool ScrollPane<T>::mouseDownSelf(float mx, float my, int button, int mod)
{
	if(!containsPoint(mx,my))
		return false;
	
	// Click on scrollbar
	if(haveScrollbar() && mx>x+width-scrollPaneScrollbarWidth && mx<x+width)
	{
		// Top scroll button?
		if(my < y+scrollButtonHeight) {
			if(scrollPos>0)
				scrollPos--;
		}
		// Bottom scroll button?
		else if(my > y+height-scrollButtonHeight) {
			if(scrollPos<maxScroll)
				scrollPos++;
		}
		// Elsewhere on scrollbar?
		else {
			// TODO
		}
	}
	else
	{
		int index = (my-y)/lineHeight + scrollPos;
		if(index == lastClickIndex && lastClickTime+doubleClickDelay>getTime())
			activate();
		lastClickTime = getTime();
		lastClickIndex = index;
		if(index>=0 && index<elements.size())
			selection = index;
	}
	return true;
}
Beispiel #9
0
RS_Vector RS_Image::getNearestPointOnEntity(const RS_Vector& coord,
        bool onEntity, double* dist, RS_Entity** entity) const{

    if (entity!=NULL) {
        *entity = const_cast<RS_Image*>(this);
    }

    RS_VectorSolutions corners =getCorners();
    //allow selecting image by clicking within images, bug#3464626
    if(containsPoint(coord)){
        //if coord is within image
        if(dist!=NULL) *dist=0.;
        return coord;
    }
    RS_VectorSolutions points(4);

    RS_Line l[] =
        {
            RS_Line(NULL, RS_LineData(corners.get(0), corners.get(1))),
            RS_Line(NULL, RS_LineData(corners.get(1), corners.get(2))),
            RS_Line(NULL, RS_LineData(corners.get(2), corners.get(3))),
            RS_Line(NULL, RS_LineData(corners.get(3), corners.get(0)))
        };

    for (int i=0; i<4; ++i) {
        points.set(i, l[i].getNearestPointOnEntity(coord, onEntity));
    }

    return points.getClosest(coord, dist);
}
Beispiel #10
0
bool UIWidget::setRect(const Rect& rect)
{
    /*
    if(rect.width() > 8192 || rect.height() > 8192) {
        g_logger.error(stdext::format("attempt to set huge rect size (%s) for %s", stdext::to_string(rect), m_id));
        return false;
    }
    */
    // only update if the rect really changed
    Rect oldRect = m_rect;
    if(rect == oldRect)
        return false;

    m_rect = rect;

    // updates own layout
    updateLayout();

    // avoid massive update events
    if(!m_updateEventScheduled) {
        UIWidgetPtr self = static_self_cast<UIWidget>();
        g_dispatcher.addEvent([self, oldRect]() {
            self->m_updateEventScheduled = false;
            if(oldRect != self->getRect())
                self->onGeometryChange(oldRect, self->getRect());
        });
        m_updateEventScheduled = true;
    }

    // update hovered widget when moved behind mouse area
    if(containsPoint(g_window.getMousePosition()))
        g_ui.updateHoveredWidget();

    return true;
}
Beispiel #11
0
void SudokuBox::onItemDragedAtPoint(const Vec2& point, int numberIndex) {
//	log("SudokuBox::onItemDragedAtPoint with numberIndex is %d", numberIndex);
	//check if this point in the box at first.
	if (!containsPoint(point))
		return;

	//calculate the position in box for this point.
	int pos = m_iCols * (m_iRows - ((int)point.y / CELL_SIZE) - 1) + ((int) point.x / CELL_SIZE);
//	log("calculated the pos is %d", pos);
	if (m_pOrgData[pos] <= 0) {
		// if not changed, return
		if (m_pData[pos] == numberIndex + 1)
			return;

		operation op;
		op.pos = pos;
		op.oldValue = m_pData[pos];
		op.value = numberIndex + 1;

		setNumber(pos, numberIndex + 1);
		m_vctOps.push_back(op);
	} else {
		//its a original cell, ignore
//		log("position %d is a original cell", pos);
	}
}
Beispiel #12
0
/*!
 * The step of the control mode.
 */
ControlTargetPtr FollowGroup::step()
{
    PositionMeters previousTargetPosition = m_targetPosition;
    m_targetPosition = computeTargetPosition();
    // check if the target position is inside the model area
    if (!containsPoint(m_targetPosition)) {
        // switch to the previous target
        m_targetPosition = previousTargetPosition;
    }

    if (m_targetPosition.isValid()) {
        PositionMeters robotPosition = m_robot->state().position();
        QString status;
        if (robotPosition.isValid()) {
            status = QString("group distance %1 m")
                    .arg(robotPosition.distance2dTo(m_targetPosition), 0, 'f', 3);
        } else {
            status = QString("group distance unknown");
        }
        emit notifyControlModeStatus(status);
        return ControlTargetPtr(new TargetPosition(m_targetPosition));
    } else {
        // otherwise the robot doesn't move
        emit notifyControlModeStatus("target undefined");
        return ControlTargetPtr(new TargetSpeed(0, 0));
    }
}
Beispiel #13
0
bool FloatQuad::intersectsCircle(const FloatPoint& center, float radius) const
{
    return containsPoint(center) // The circle may be totally contained by the quad.
        || lineIntersectsCircle(center, radius, m_p1, m_p2)
        || lineIntersectsCircle(center, radius, m_p2, m_p3)
        || lineIntersectsCircle(center, radius, m_p3, m_p4)
        || lineIntersectsCircle(center, radius, m_p4, m_p1);
}
/**
 * locate is the main location function.  It handles both single-element
 * and multi-element Geometries.  The algorithm for multi-element Geometries
 * is more complex, since it has to take into account the boundaryDetermination rule
 */
int
SimplePointInAreaLocator::locate(const Coordinate& p, const Geometry *geom)
{
	if (geom->isEmpty()) return Location::EXTERIOR;
	if (containsPoint(p,geom))
		return Location::INTERIOR;
	return Location::EXTERIOR;
}
Beispiel #15
0
NavPoly* NavMesh::getPolygon(point_t coord) {
	//todo: use better datastructure for this.
	for (auto it = polygon.begin(); it != polygon.end(); it++) {
		if (it->containsPoint(coord))
			return &*it;
	}
	return nullptr;
}
Beispiel #16
0
bool Polygon::nearSegment(const Segment& seg, float threshold) const {
    if (containsPoint(seg.pt[0]) || containsPoint(seg.pt[1])) {
        return true;
    }

    unsigned int i = vertices.size() - 1;
    for (unsigned int j = 0; j < vertices.size(); ++j) {
        Segment edge(vertices[i], vertices[j]);
        if (edge.nearSegment(seg, threshold)) {
            return true;
        }

        i = j;
    }

    return false;
}
void HelloWorld::onMouseMove(Event* event) {
	EventMouse* e = (EventMouse*)event;
	CCPoint mousePosition = CCPoint(e->getCursorX(), e->getCursorY() + 640);

	auto block1 = startMenuItem->getBoundingBox();
	if (block1.containsPoint(mousePosition)) largerItem(startMenuItem, 1);
	else largerItem(NULL, 0);
}
Beispiel #18
0
void HoleDemo::onTouchesBegan(const std::vector<Touch*>& touches, Event* event)
{
	Touch *touch = (Touch *)touches[0];
	Vec2 point = _outerClipper->convertToNodeSpace(Director::getInstance()->convertToGL(touch->getLocationInView()));
    auto rect = Rect(0, 0, _outerClipper->getContentSize().width, _outerClipper->getContentSize().height);
    if (!rect.containsPoint(point)) return;
    this->pokeHoleAtPoint(point);
}
Beispiel #19
0
bool KRTriangle3::sphereCast(const KRVector3 &start, const KRVector3 &dir, float radius, KRVector3 &hit_point, float &hit_distance) const
{
    // Dir must be normalized
    const float SMALL_NUM = 0.001f;     // anything that avoids division overflow
    
    KRVector3 tri_normal = calculateNormal();
    
    float d = KRVector3::Dot(tri_normal, m_c[0]);
    float e = KRVector3::Dot(tri_normal, start) - radius;
    float cotangent_distance = e - d;
    
    KRVector3 plane_intersect;
    float plane_intersect_distance;
    
    float denom = KRVector3::Dot(tri_normal, dir);
    
    if(denom > -SMALL_NUM) {
        return false; // dir is co-planar with the triangle or going in the direction of the normal; no intersection
    }

    // Detect an embedded plane, caused by a sphere that is already intersecting the plane.
    if(cotangent_distance <= 0 && cotangent_distance >= -radius * 2.0f) {
        // Embedded plane - Sphere is already intersecting the plane.
        // Use the point closest to the origin of the sphere as the intersection
        plane_intersect = start - tri_normal * (cotangent_distance + radius);
        plane_intersect_distance = 0.0f;
    } else {
        // Sphere is not intersecting the plane
        // Determine the first point hit by the swept sphere on the triangle's plane
        
        plane_intersect_distance = -(cotangent_distance / denom);
        plane_intersect = start + dir * plane_intersect_distance - tri_normal * radius;
    }
    
    if(plane_intersect_distance < 0.0f) {
        return false;
    }
    
    if(containsPoint(plane_intersect)) {
        // Triangle contains point
        hit_point = plane_intersect;
        hit_distance = plane_intersect_distance;
        return true;
    } else {
        // Triangle does not contain point, cast ray back to sphere from closest point on triangle edge or vertice
        KRVector3 closest_point = closestPointOnTriangle(plane_intersect);
        float reverse_hit_distance;
        if(_intersectSphere(closest_point, -dir, start, radius, reverse_hit_distance)) {
            // Reverse cast hit sphere
            hit_distance = reverse_hit_distance;
            hit_point = closest_point;
            return true;
        } else {
            // Reverse cast did not hit sphere
            return false;
        }
    }
}
Beispiel #20
0
void ScrollViewDemo::onTouchesBegan(const std::vector<Touch*>& touches, Event  *event)
{
	Touch *touch = touches[0];
    auto clipper = this->getChildByTag(kTagClipperNode);
	Vec2 point = clipper->convertToNodeSpace(Director::getInstance()->convertToGL(touch->getLocationInView()));
    auto rect = Rect(0, 0, clipper->getContentSize().width, clipper->getContentSize().height);
    _scrolling = rect.containsPoint(point);
    _lastPoint = point;
}
Beispiel #21
0
bool Polygon::containsVertex(const Polygon& other) const {
    for (unsigned int i = 0; i < other.vertices.size(); ++i) {
        if (containsPoint(other.vertices[i])) {
            return true;
        }
    }

    return false;
}
Beispiel #22
0
MessageType BattleScene::UIcontainsPoint(Vec2 position)
{//check if the UILayer contains the touchPoint
	MessageType message;

	auto rectKnight = uiLayer->KnightPngFrame->getBoundingBox();
	auto rectArcher = uiLayer->ArcherPngFrame->getBoundingBox();
	auto rectMage = uiLayer->MagePngFrame->getBoundingBox();

	if (rectKnight.containsPoint(position) && uiLayer->KnightAngry->getPercentage() == 100)
		message = MessageType::SPECIAL_KNIGHT;
	else if (rectArcher.containsPoint(position) && uiLayer->ArcherAngry->getPercentage() == 100)
		message = MessageType::SPECIAL_ARCHER;
	else if (rectMage.containsPoint(position) && uiLayer->MageAngry->getPercentage() == 100)
		message = MessageType::SPECIAL_MAGE;
	else
		return MessageType::NullMessageType;
	return message;
}
Beispiel #23
0
XBOOL XXObjectRectangle::SysCallMethod(int id,XSWFCONTEXT*pCnt,XXVARLIST&list)
{
	switch(id)
	{
	case _SYSID(clone):
		 pCnt->pStack->Push(Clone());
		 return XTRUE;
	case _SYSID(contains):
		 contains(*pCnt,list);
		 return XTRUE;
	case _SYSID(containsPoint):
		 containsPoint(*pCnt,list);
		 return XTRUE;
	case _SYSID(containsRectangle):
		 containsRectangle(*pCnt,list);
		 return XTRUE;
	case _SYSID(equals):
		 equalsRect(*pCnt,list);
		 return XTRUE;
	case _SYSID(inflate):
		 inflate(*pCnt,list);
		 return XTRUE;
	case _SYSID(inflatePoint):
		 inflatePoint(*pCnt,list);
		 return XTRUE;
	case _SYSID(intersection):
		 intersection(*pCnt,list);
		 return XTRUE;
	case _SYSID(intersects):
		 intersects(*pCnt,list);return XTRUE;
	case _SYSID(isEmpty):
		 pCnt->pStack->PushBool((width==0&&height==0));
		 return XTRUE;
	case _SYSID(offset):
		 offsetRect(*pCnt,list);
		 return XTRUE;
	case _SYSID(offsetPoint):
		 offsetPoint(*pCnt,list);
		 return XTRUE;
	case _SYSID(setEmpty):
		 left=top=0;
		 width=height=0;
		 pCnt->pStack->PushConst(XOCT_UNDEFINE);
		 return XTRUE;
	case _SYSID(toString):
		{
			XXVar var;
			GetString(var);
			pCnt->pStack->Push(var);
		}return XTRUE;
	case _SYSID(union):
		unionRect(*pCnt,list);
		return XTRUE;
	}
	return XXObject::SysCallMethod(id,pCnt,list);
}
Beispiel #24
0
int main (int argc, char **argv) {
    char buf[512];
    int sum = 0;
    while(gets(buf)) {
        int ax, ay, bx, by, cx, cy;
        sscanf(buf, "%d,%d,%d,%d,%d,%d", &ax, &ay, &bx, &by, &cx, &cy);
        sum += containsPoint(ax, ay, bx, by, cx, cy, 0, 0);
    }
    printf("%d\n", sum);
}
Beispiel #25
0
bool Segment2d::intersectsLine(const Line2d &line, Vector2d *pos) {
	Vector2d p;
	if (getLine().intersectsLine(line, &p) && containsPoint(p)) {
		if (pos)
			*pos = p;
		return true;
	}

	return false;
}
bool UIBuyBuildingLayer::isTouchEdge(Touch* touch)
{
	Point local = convertToNodeSpace(touch->getLocation());
	auto rect = Rect(0,317 + 100,Director::getInstance()->getWinSize().width,Director::getInstance()->getWinSize().height - 417);
	if (rect.containsPoint(local))
	{   
		return true;
	}
	return false;
}
/**
 * Marks elements inside and outside the box
 */
Marker::MarkerValue
OrientedBoxMarker::computeElementMarker()
{
    Point centroid = _current_elem->centroid();

    if (containsPoint(centroid))
        return _inside;

    return _outside;
}
Beispiel #28
0
void Fish::setFastMove()
{
    this->unscheduleUpdate();
    if (m_light) {
        m_light->removeFromParent();
    }
    auto viewsize = WinSize;
    auto point = this->getPosition();
    auto rect1 = Rect(0, 0, viewsize.width/2, viewsize.height/2);
    auto rect2 = Rect(viewsize.width/2, 0, viewsize.width/2, viewsize.height/2);
    auto rect3 = Rect(0, viewsize.height/2, viewsize.width/2, viewsize.height/2);
    auto rect4 = Rect(viewsize.width/2, viewsize.height/2, viewsize.width/2, viewsize.height/2);
    auto callfunc = [=]{this->removeFromParent();};
    Vec2 targetpoint;
    
    auto rect = Rect(0, 0, viewsize.width, viewsize.height);
    if (rect.containsPoint(point)) {
        if (rect1.containsPoint(point)) {
            targetpoint = Vec2(-200, -200);
        }
        else if(rect2.containsPoint(point))
        {
            targetpoint = Vec2(viewsize.width+200, -200);
        }
        else if(rect3.containsPoint(point))
        {
            targetpoint = Vec2(-200, viewsize.height+200);
        }
        else if(rect4.containsPoint(point))
        {
            targetpoint = Vec2(viewsize.width+200, viewsize.height+200);
        }
        auto paction = Sequence::create(MoveTo::create(2.f, targetpoint), FadeTo::create(0.5f, 0), CallFunc::create(callfunc), NULL);
        auto angle = GameDataMgr::getInstance()->getAngleByTwoPoint(targetpoint, point);
        this->setRotation(angle);
        this->runAction(paction);
    }
    else
    {
        auto paction = Sequence::createWithTwoActions(FadeTo::create(0.5f, 0), CallFunc::create(callfunc));
        this->runAction(paction);
    }
}
Beispiel #29
0
void HelloWorld::testEat(){
    auto head_size = this->snake.at(0)->getContentSize();
    auto head_point = this->snake.at(0)->getPosition();
    auto head_rect = Rect(head_point.x,head_point.y,20 ,20);
    auto apple_point = this->apple->getPosition();
    auto ap = Point(apple_point.x+10,apple_point.y+10);
    if(head_rect.containsPoint(ap)){
        log("Good eat!!");
        
        auto body = Sprite::create("bo.png");
        body->setAnchorPoint(Point(0,0));
        body->setColor(Color3B(0,255,0));
        this->snake.pushBack(body);
        this->addChild(this->snake.at(this->snake.size()-1));
        body->setPosition(this->snake.at(this->snake.size()-2)->getPosition());
        
        //random set apple
        auto winsize = Director::getInstance()->getVisibleSize();
        auto x_l = winsize.width/20-1;
        auto y_l = winsize.height/20-1;
        while (true) {
            srand((int)time(NULL)+(int)time(0));
            this->apple->setPosition(Point( (rand() % ((int)x_l+1)) *20,(rand() % ((int)y_l+1))*20));
            bool b = true;
            for (auto i=0; i<this->snake.size(); i++) {
                auto body_size = this->snake.at(i)->getContentSize();
                auto body_point = this->snake.at(i)->getPosition();
                auto body_rect = Rect(body_point.x,body_point.y,20 ,20);
                auto apple_ppoint = this->apple->getPosition();
                auto app = Point(apple_ppoint.x+10,apple_ppoint.y+10);
                if(body_rect.containsPoint(app)){
                    b=false;
                }
            }
            if (b)
                break;
        }
        
        
        
        testGameisOver(false);
    }
}
Beispiel #30
0
void HelloWorld::testGameisOver(bool b){
    auto winsize = Director::getInstance()->getVisibleSize();
    if (b) {
        //失败情况 1.撞墙 2.吃到自己 (移动后检测)
        
        bool b = false;
        if (snake.size()>2) {
            for (auto i=1; i<this->snake.size(); i++) {
                auto body_size = this->snake.at(i)->getContentSize();
                auto body_point = this->snake.at(i)->getPosition();
                auto body_rect = Rect(body_point.x,body_point.y,20 ,20);
                auto head_point = this->snake.at(0)->getPosition();
                auto app = Point(head_point.x+10,head_point.y+10);
                if(body_rect.containsPoint(app)){
                    b=true;
                }
            }
        }
        
        if (this->snake.at(0)->getPositionX() >= winsize.width || this->snake.at(0)->getPositionX() < 0 ||
            this->snake.at(0)->getPositionY() >= winsize.height || this->snake.at(0)->getPositionY() < 0 || b)
        {
            //game over
            unschedule(schedule_selector(HelloWorld::up_date));
            _eventDispatcher->removeEventListenersForType(EventListener::Type::TOUCH_ONE_BY_ONE);
            auto label = LabelTTF::create("GAME OVER", "Arial", 50);
            label->setPosition(Point(winsize.width/2,winsize.height/2));
            this->addChild(label, 1);
            label->setScale(0);
            label->runAction(ScaleTo::create(3, 1.5));
            label->setOpacity(0);
            label->runAction(FadeTo::create(1.5, 255));
            this->runAction(Sequence::create(DelayTime::create(5),CallFunc::create([]{Director::getInstance()->replaceScene(HelloWorld::createScene());}), NULL));
            
        }
        
    }else{
        //胜利情况 长度到达40 (吃东西后检测)
        if (this->snake.size() == 50) {
            //game win
            unschedule(schedule_selector(HelloWorld::up_date));
            _eventDispatcher->removeEventListenersForType(EventListener::Type::TOUCH_ONE_BY_ONE);
            auto label = LabelTTF::create("U WIN", "Arial", 50);
            label->setPosition(Point(winsize.width/2,winsize.height/2));
            this->addChild(label, 1);
            label->setScale(0);
            label->runAction(ScaleTo::create(3, 1.5));
            label->setOpacity(0);
            label->runAction(FadeTo::create(1.5, 255));
            this->runAction(Sequence::create(DelayTime::create(5),CallFunc::create([]{Director::getInstance()->replaceScene(HelloWorld::createScene());}), NULL));
        }
        
    }
    
}