Posted by King_Critter on Fri 12th Feb 02:53
download | new post | report as spam
- #! /usr/bin/python
- import random
- class Snake:
- def __init__(self):
- self.x = 5
- self.y = 5
- # self.score = 0
- # def eat(self): #eat function added
- # if self.x == Food().x and self.y == Food().y:
- # self.score += Food().points
- # Food().eaten()#calls eat func but eat func doesn't do anything
- def move(self, direction):
- if "up" in direction: self.y -= 1
- if "down" in direction: self.y += 1
- if "right" in direction: self.x += 1
- if "left" in direction: self.x -= 1
- if self.y > maxgrid: self.y = 1
- if self.y < 1: self.y = maxgrid
- if self.x > maxgrid: self.x = 1
- if self.x < 1: self.x = maxgrid
- # self.eat()
- def sleep(self):
- pass
- class Badguy:
- def __init__(self):
- self.x = 2
- self.y = 2
- def chase(self):
- if self.x == player.x:
- if self.y < player.y: self.y += 1
- if self.y > player.y: self.y -= 1
- elif self.y == player.y:
- if self.x < player.x: self.x += 1
- if self.x > player.x: self.x -= 1
- else:
- self.wander()
- self.check()
- def wander(self):
- self.x += random.choice((-1, 0, 1))
- self.y += random.choice((-1, 0, 1))
- self.check()
- def check(self):
- if self.y > maxgrid: self.y = 1
- if self.y < 1: self.y = maxgrid
- if self.x > maxgrid: self.x = 1
- if self.x < 1: self.x = maxgrid
- # class Food: #food class declared
- # def __init__(self): #for some reason keeps re-calling init
- # self.x = 4
- # self.y = 4
- # self.points = random.randint(1, 9)
- # def eaten(self): #doesn't work
- # self.x = random.randint(1, maxgrid)
- # self.y = random.randint(1, maxgrid)
- # self.points = random.randint(1, 9)
- def show_field():
- bookends = ("| {0}|".format(" - "*maxgrid))
- print(bookends)
- for y in range(maxgrid):
- line = ""
- for x in range(maxgrid):
- if x == vader.x-1 and y == vader.y-1:
- line += " C "
- elif x == player.x-1 and y == player.y-1:
- line += " P "
- # elif x == berry.x-1 and y == berry.y-1:
- # line += (" {0} ").format(Food().points)
- else:
- line = line + " . "
- print("| {0}|".format(line))
- print(bookends)
- maxgrid = int(input("Size of square grid?"))
- player = Snake()
- # berry = Food()
- vader = Badguy()
- while True:
- show_field()
- query = input("What direction? ").lower() #added for flexibility
- vader.chase()
- player.move(query)
Submit a correction or amendment below (click here to make a fresh posting)
After submitting an amendment, you'll be able to view the differences between the old and new posts easily
.After submitting an amendment, you'll be able to view the differences between the old and new posts easily
