Write a snake in Python

Source: Internet
Author: User
Tags case statement switch case

Recently learning Python, want to do something to practice practiced hand, command line of the snake is generally c practiced hand project, but in a moment to find nothing else, first do a snake to practice simple grammar.

Because Python listens to the keyboard is troublesome, does not have the C language Kbhit (), therefore this snake does not move itself, the operation effect is as follows:

  

Requirements: With # for the border, with * for food, O for the body of the snake, O for the snake head, using Wsad to move

Python version: 3.6.1

System Environment: WIN10

Class:

Board: Chess board, game area

Snake: A snake that records the state of a snake by recording each point of the body

Game: Games Class

Originally wanted a food class, but food only needed a coordinate, and a new one, so simply use list to save the coordinates, new food in the game, the logic is not too much problem

Source

#Write by Guobao#2017/4//7##Greedy Snake#use # To do the border, * make food, o do the body and head#python 3.6.1ImportCopyImportRandomImportOSImportMSVCRT#the Board class, used to put everythingclassBoard:__points=[]    def __init__(self): self.__points. Clear () forIinchRange (22): Line= []            ifi = = 0ori = = 21:                 forJinchRange (22): Line.append ('#')            Else: Line.append ('#')                 forJinchRange (20): Line.append (' ') Line.append ('#') self.__points. Append (line)defGetPoint (self, location):returnSelf.__points[Location[0]] [Location[1]]    defClear (self): self.__points. Clear () forIinchRange (22): Line= []            ifi = = 0ori = = 21:                 forJinchRange (22): Line.append ('#')            Else: Line.append ('#')                 forJinchRange (20): Line.append (' ') Line.append ('#') self.__points. Append (line)defPut_snake (Self, snake_locations):#Clear the Boardself.clear ()#put the snake points         forXinchsnake_locations:self.__points[X[0]] [X[1]] ='o'        #The headx = Snake_locations[len (snake_locations)-1] Self.__points[X[0]] [X[1]] ='O'    defPut_food (Self, food_location): Self.__points[Food_location[0]] [Food_location[1]] ='*'    defShow (self): Os.system ("CLS")         forIinchRange (22):             forJinchRange (22):                Print(self.)__pointsI [j], end="')            Print()#The Snake classclassSnake:__points= []    def __init__(self): forIinchRange (1, 6): Self.__points. append ([1, I]) defgetpoints (self):returnSelf.__points    #move to the next position    #give the next head    defMove (self, next_head): Self.__points. Pop (0) self.__points. Append (next_head)#Eat The food    #give the next head    defeat (Self, next_head): Self.__points. Append (next_head)#Calc the next state    #and return the direction    defNext_head (Self, direction='default'):        #need to change the value, so copy itHead = Copy.deepcopy (self.__points[Len (self.__points)-1])        #Calc The "default" direction        ifDirection = ='default': Neck= self.__points[Len (self.__points)-2]            ifNeck[0] >head[0]: direction=' up'            elifNeck[0] <head[0]: direction=' Down'            elifNECK[1] > Head[1]: Direction=' Left'            elifNECK[1] < head[1]: Direction=' Right'        ifDirection = =' up': head[0]= Head[0]-1elifDirection = =' Down': head[0]= Head[0] + 1elifDirection = =' Left': head[1] = head[1]-1elifDirection = =' Right': head[1] = head[1] + 1returnHead#The gameclassGame:board=Board () Snake=Snake () food=[] Count=0def __init__(self): Self.new_food () self.board.clear () Self.board.put_snake (self.snake.getPoints ()) SE Lf.board.put_food (Self.food)defNew_food (self): while1: Line= Random.randint (1, 20) Column= Random.randint (1, 20)            ifSelf.board.getPoint ([column, line]) = =' ': Self.food=[column, line]return    defShow (self): Self.board.clear () Self.board.put_snake (Self.snake.getPoints ()) Self.board.put_food ( Self.food) self.board.show ()defRun (self): Self.board.show ()#The ' W a s d ' is the directionsOperation_dict = {b'W':' up'B'W':' up'B's':' Down'B'S':' Down'B'a':' Left'B'A':' Left'B'D':' Right'B'D':' Right'} op=Msvcrt.getch () whileOp! = b'Q':            ifOp not inchOperation_dict:op=Msvcrt.getch ()Else: New_head=Self.snake.next_head (Operation_dict[op])#Get The food                ifSelf.board.getPoint (new_head) = ='*': Self.snake.eat (new_head) Self.count= Self.count + 1ifSelf.count >= 15: Self.show ()Print("Good Job")                         Break                    Else: Self.new_food () self.show ()#reverse a Q-day fairy                elifNew_head = = Self.snake.getPoints () [Len (Self.snake.getPoints ())-2]:                    Pass                #Rush The Wall                elifSelf.board.getPoint (new_head) = ='#' orSelf.board.getPoint (new_head) = ='o':                    Print('GG')                     Break                #Normal Move                Else: Self.snake.move (New_head) self.show () op=Msvcrt.getch () game (). Run ()

Notes:

1.Python without a switch case statement, you can use dirt to implement

The 2.Python = number is copy, copy reference, deep copy needs to use Copy's Deepcopy () function to implement

3. Even within member functions, you need to use self to access member variables, which is very different from C + +, Java

Write a snake in Python

Related Article

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.