Advertisement
Guest User

Snake_Game

a guest
Dec 9th, 2019
146
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.37 KB | None | 0 0
  1. import math
  2. import random
  3. import pygame
  4. import tkinter as tk
  5. from tkinter import messagebox
  6.  
  7. class cube(object):
  8.     rows = 20
  9.     w = 500
  10.     def __init__(self,start,dirnx=1,dirny=0,color=(255,0,0)):
  11.         self.pos = start
  12.         self.dirnx = 1
  13.         self.dirny = 0
  14.         self.color = color
  15.  
  16.        
  17.     def move(self, dirnx, dirny):
  18.         self.dirnx = dirnx
  19.         self.dirny = dirny
  20.         self.pos = (self.pos[0] + self.dirnx, self.pos[1] + self.dirny)
  21.  
  22.     def draw(self, surface, eyes=False):
  23.         dis = self.w // self.rows
  24.         i = self.pos[0]
  25.         j = self.pos[1]
  26.  
  27.         pygame.draw.rect(surface, self.color, (i*dis+1,j*dis+1, dis-2, dis-2))
  28.         if eyes:
  29.             centre = dis//2
  30.             radius = 3
  31.             circleMiddle = (i*dis+centre-radius,j*dis+8)
  32.             circleMiddle2 = (i*dis + dis -radius*2, j*dis+8)
  33.             pygame.draw.circle(surface, (0,0,0), circleMiddle, radius)
  34.             pygame.draw.circle(surface, (0,0,0), circleMiddle2, radius)
  35.        
  36.  
  37.  
  38.  
  39. class snake(object):
  40.     body = []
  41.     turns = {}
  42.     def __init__(self, color, pos):
  43.         self.color = color
  44.         self.head = cube(pos)
  45.         self.body.append(self.head)
  46.         self.dirnx = 0
  47.         self.dirny = 1
  48.  
  49.     def move(self):
  50.         for event in pygame.event.get():
  51.             if event.type == pygame.QUIT:
  52.                 pygame.quit()
  53.  
  54.             keys = pygame.key.get_pressed()
  55.  
  56.             for key in keys:
  57.                 if keys[pygame.K_LEFT]:
  58.                     self.dirnx = -1
  59.                     self.dirny = 0
  60.                     self.turns[self.head.pos[:]] = [self.dirnx, self.dirny]
  61.  
  62.                 elif keys[pygame.K_RIGHT]:
  63.                     self.dirnx = 1
  64.                     self.dirny = 0
  65.                     self.turns[self.head.pos[:]] = [self.dirnx, self.dirny]
  66.  
  67.                 elif keys[pygame.K_UP]:
  68.                     self.dirnx = 0
  69.                     self.dirny = -1
  70.                     self.turns[self.head.pos[:]] = [self.dirnx, self.dirny]
  71.  
  72.                 elif keys[pygame.K_DOWN]:
  73.                     self.dirnx = 0
  74.                     self.dirny = 1
  75.                     self.turns[self.head.pos[:]] = [self.dirnx, self.dirny]
  76.  
  77.         for i, c in enumerate(self.body):
  78.             p = c.pos[:]
  79.             if p in self.turns:
  80.                 turn = self.turns[p]
  81.                 c.move(turn[0],turn[1])
  82.                 if i == len(self.body)-1:
  83.                     self.turns.pop(p)
  84.             else:
  85.                 if c.dirnx == -1 and c.pos[0] <= 0: c.pos = (c.rows-1, c.pos[1])
  86.                 elif c.dirnx == 1 and c.pos[0] >= c.rows-1: c.pos = (0,c.pos[1])
  87.                 elif c.dirny == 1 and c.pos[1] >= c.rows-1: c.pos = (c.pos[0], 0)
  88.                 elif c.dirny == -1 and c.pos[1] <= 0: c.pos = (c.pos[0],c.rows-1)
  89.                 else: c.move(c.dirnx,c.dirny)
  90.        
  91.  
  92.     def reset(self, pos):
  93.         self.head = cube(pos)
  94.         self.body = []
  95.         self.body.append(self.head)
  96.         self.turns = {}
  97.         self.dirnx = 0
  98.         self.dirny = 1
  99.  
  100.  
  101.     def addCube(self):
  102.         tail = self.body[-1]
  103.         dx, dy = tail.dirnx, tail.dirny
  104.  
  105.         if dx == 1 and dy == 0:
  106.             self.body.append(cube((tail.pos[0]-1,tail.pos[1])))
  107.         elif dx == -1 and dy == 0:
  108.             self.body.append(cube((tail.pos[0]+1,tail.pos[1])))
  109.         elif dx == 0 and dy == 1:
  110.             self.body.append(cube((tail.pos[0],tail.pos[1]-1)))
  111.         elif dx == 0 and dy == -1:
  112.             self.body.append(cube((tail.pos[0],tail.pos[1]+1)))
  113.  
  114.         self.body[-1].dirnx = dx
  115.         self.body[-1].dirny = dy
  116.        
  117.  
  118.     def draw(self, surface):
  119.         for i, c in enumerate(self.body):
  120.             if i ==0:
  121.                 c.draw(surface, True)
  122.             else:
  123.                 c.draw(surface)
  124.  
  125.  
  126. def drawGrid(w, rows, surface):
  127.     sizeBtwn = w // rows
  128.  
  129.     x = 0
  130.     y = 0
  131.     for l in range(rows):
  132.         x = x + sizeBtwn
  133.         y = y + sizeBtwn
  134.  
  135.         pygame.draw.line(surface, (255,255,255), (x,0),(x,w))
  136.         pygame.draw.line(surface, (255,255,255), (0,y),(w,y))
  137.        
  138.  
  139. def redrawWindow(surface):
  140.     global rows, width, s, snack
  141.     surface.fill((0,0,0))
  142.     s.draw(surface)
  143.     snack.draw(surface)
  144.     drawGrid(width,rows, surface)
  145.     pygame.display.update()
  146.  
  147.  
  148. def randomSnack(rows, item):
  149.  
  150.     positions = item.body
  151.  
  152.     while True:
  153.         x = random.randrange(rows)
  154.         y = random.randrange(rows)
  155.         if len(list(filter(lambda z:z.pos == (x,y), positions))) > 0:
  156.             continue
  157.         else:
  158.             break
  159.        
  160.     return (x,y)
  161.  
  162.  
  163. def message_box(subject, content):
  164.     root = tk.Tk()
  165.     root.attributes("-topmost", True)
  166.     root.withdraw()
  167.     messagebox.showinfo(subject, content)
  168.     try:
  169.         root.destroy()
  170.     except:
  171.         pass
  172.  
  173.  
  174. def main():
  175.     global width, rows, s, snack
  176.     width = 500
  177.     rows = 20
  178.     win = pygame.display.set_mode((width, width))
  179.     s = snake((255,0,0), (10,10))
  180.     snack = cube(randomSnack(rows, s), color=(0,255,0))
  181.     flag = True
  182.  
  183.     clock = pygame.time.Clock()
  184.    
  185.     while flag:
  186.         pygame.time.delay(50)
  187.         clock.tick(10)
  188.         s.move()
  189.         if s.body[0].pos == snack.pos:
  190.             s.addCube()
  191.             snack = cube(randomSnack(rows, s), color=(0,255,0))
  192.  
  193.         for x in range(len(s.body)):
  194.             if s.body[x].pos in list(map(lambda z:z.pos,s.body[x+1:])):
  195.                 print(\'Score: \', len(s.body))
  196.                message_box(\'You Lost!\', \'Play again...\')
  197.                s.reset((10,10))
  198.                break
  199.  
  200.            
  201.        redrawWindow(win)
  202.  
  203.        
  204.    pass
  205.  
  206.  
  207.  
  208. main()
  209.  
  210.  
  211. PS C:\Users\17041758\Desktop\Python> & C:/Python/Python38-32/python.exe c:/Users/17041758/Desktop/Python/snake.py
  212. & : The term 'C:/Python/Python38-32/python.exe' is not recognized as the name of a cmdlet, function, script file, or operable
  213. program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
  214. At line:1 char:3
  215. + & C:/Python/Python38-32/python.exe c:/Users/17041758/Desktop/Python/s ...
  216. +   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  217.    + CategoryInfo          : ObjectNotFound: (C:/Python/Python38-32/python.exe:String) [], CommandNotFoundException
  218.    + FullyQualifiedErrorId : CommandNotFoundException
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement