/** 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