353. Design Snake Game

Source: Internet
Author: User

        /** 353. Design Snake Game * 2016-7-12 by Mingyang*/        classSnakegame {//2D Position info is encoded to 1D and stored as the copiesSet<integer> set;//This copy are good for fast loop-up for eating body caseDeque<integer> body;//This copy are good for updating tail            intscore; int[] food; intFoodindex; intwidth; intheight;  PublicSnakegame (intWidthintHeightint[] food) {                 This. width =width;  This. Height =height;  This. Food =Food ; Set=NewHashset<>(); Set.add (0);//intially at [0][0]BODY =NewLinkedlist<>(); Body.offerlast (0); }                           Public intMove (String direction) {//Case 0:game already over:do nothing                if(Score = =-1) {                    return-1; }                                //Compute new Head                intRowhead = Body.peekfirst ()/width; intColhead = Body.peekfirst ()%width; Switch(direction) { Case"U": rowhead--;  Break;  Case"D": rowhead++;  Break;  Case"L": colhead--;  Break; default: colhead++; }                intHead = Rowhead * width +Colhead; //Case 1:out of boundary or eating bodySet.remove (Body.peeklast ());//new head is legal to being in the old tail ' s position, remove from set temporarily                if(Rowhead < 0 | | rowhead = = Height | | Colhead < 0 | | colhead = = Width | |Set.contains (head)) {                    returnScore =-1; }                                //add head for Case2 and Case3Set.add (head);                                Body.offerfirst (head); //case2:eating food, keep tail, add head                if(Foodindex < food.length && Rowhead = = Food[foodindex][0] && Colhead = = food[foodindex][1]) {Set.add (Body.peeklast ());//Old Tail does no change, so add it back to setfoodindex++; return++score; }                                //case3:normal Move, remove tail, add headBody.polllast (); returnscore; }        }

353. Design Snake Game

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.