Bmorr

Snake Royale with Replays

Feb 27th, 2019
201
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 12.21 KB | None | 0 0
  1. #SnakeVs.py
  2. import pygame
  3. import os
  4. import math
  5. from random import randint
  6. from pygame.locals import *
  7. import time
  8. import datetime
  9. import copy
  10. import glob
  11. import moviepy.editor as mpy
  12.  
  13. pygame.init()
  14.  
  15. width = 800
  16. height = 650
  17. size = 10
  18.  
  19. gifPath = "/Users/20morrisonb/Desktop/Snake Images/"
  20.  
  21. win = pygame.display.set_mode((width, height))
  22. pygame.display.set_caption("Snake Royale")
  23.  
  24. PATH = os.path.abspath(__file__)
  25. PATH = PATH[0:-16] #-16 to chop off SnakeVsRoyale.py
  26. font = pygame.font.SysFont('', 24)
  27. bigFont = pygame.font.SysFont('', 30)
  28.  
  29. clock = pygame.time.Clock()
  30.  
  31. length = 1
  32.  
  33. class Snake:
  34.     global length
  35.     def __init__(self, pos, dir, name):
  36.         self.bod = [pos] #Lists [[x,y], [x,y]...]
  37.         self.dir = dir #String 'direction'
  38.         self.pos = pos.copy() #List [x,y]
  39.         self.name = name #Name 'Chris'
  40.         self.length = 1
  41.         self.kills = 0
  42.         self.alive = True
  43.         self.color = (randint(100,255),randint(100,255),randint(100,255)) #Start at 100 so it's not black or dark
  44.     def getInfo(self):
  45.         return [self.bod.copy(), self.dir, self.pos.copy()]
  46.     def getEndInfo(self):
  47.         return [self.name, self.length, self.kills]
  48.     def setDir(self, info):
  49.         self.dir = getattr(playerUpdates, self.name)(self.pos.copy(), self.bod.copy(), self.dir, info.copy())
  50.     def update(self, win):
  51.         if self.alive:
  52.             if self.dir == 'right':
  53.                 self.pos[0]+=size
  54.             elif self.dir == 'left':
  55.                 self.pos[0]-=size
  56.             elif self.dir == 'up':
  57.                 self.pos[1]-=size
  58.             elif self.dir == 'down':
  59.                 self.pos[1]+=size
  60.             else:
  61.                 print("No direction set", self.name)
  62.  
  63.             # CHANGED IF TO WHILE
  64.             while len(self.bod) > length: #length is global, self.length is the class variable
  65.                 self.bod.pop(0)
  66.         if self.alive:
  67.             for i in self.bod:
  68.                 pygame.draw.rect(win, self.color, pygame.Rect(i[0], i[1], size, size))
  69.  
  70.             nameText = font.render(self.name, True, (255,255,255))
  71.             loc = nameText.get_rect()
  72.             loc.center = (self.pos[0]+10, self.pos[1]-14)
  73.             w, h = loc.size
  74.             # pygame.draw.rect(win, (255,255,255), pygame.Rect(loc.x, loc.y, w, h))
  75.             win.blit(nameText, loc)
  76.             # CHANGED TO LOWER DOWN
  77.             self.bod.append([self.pos[0], self.pos[1]])
  78.         else:
  79.             self.bod = []
  80.             self.pos =[-100,-100]
  81.  
  82.  
  83.  
  84. def generateGif(killId, path):
  85.     gif_name = killId
  86.     fps = 15
  87.     os.scandir(path)
  88.     glob.glob(path)
  89.     file_list = glob.glob(path + killId + "/" + '*.png') # Get all the pngs in the current directory
  90.     list.sort(file_list, key=lambda x: int(x.split('_')[1].split('.png')[0])) # Sort the images by #, this may need to be tweaked for your use case
  91.     clip = mpy.ImageSequenceClip(file_list, fps=fps)
  92.     clip.write_gif(path + '{}.gif'.format(gif_name), fps=fps)
  93.  
  94.  
  95. def draw(data):
  96.     snakeList, feed = data[0], data[1]
  97.     pygame.draw.rect(win, (0, 0, 0), pygame.Rect(0, 0, width, height))
  98.     for i in snakeList:
  99.         i.update(win)
  100.     ycounter = 20
  101.     for i in feed:
  102.         text = bigFont.render(i[0], True, (0, 0, 0))
  103.         loc = text.get_rect()
  104.         loc.topleft = (20, ycounter)
  105.         w, h = loc.size
  106.         pygame.draw.rect(win, (255, 255, 255), pygame.Rect(loc.x - 5, loc.y - 5, w + 10, h + 10))
  107.         win.blit(text, loc)
  108.         ycounter += h + 15
  109.         i[1] += 2
  110.         if i[1] > 200:
  111.             feed.remove(i)
  112.     # pygame.draw.rect(win, (255, 255, 255), pygame.Rect(0, 0, width, height), 1)  # White border
  113.     pygame.display.update()
  114.     # print("drawing!")
  115.  
  116.  
  117. def main():
  118.     global length
  119.     players = ["Chris", "Chris", "Chris", "Chris"]
  120.     snakeList = []
  121.     tickRate = 30
  122.     feed = []
  123.  
  124.     # CHANGE
  125.     ticks = 0
  126.     kills = []
  127.     frames = []
  128.     tempFrames = []
  129.     frameRecorderCounter = 0
  130.  
  131.     dirs = ['right', 'left', 'up', 'down']
  132.     for i in players:
  133.         snake = Snake([randint(1, (width/size)-2) * size, randint(1, (height/size)-2)*size], dirs[randint(0, 3)], i)
  134.         snakeList.append(snake)
  135.  
  136.     end = True
  137.     playing = True
  138.     tStart = time.time()
  139.  
  140.     while playing:
  141.         clock.tick(tickRate)
  142.         for event in pygame.event.get():
  143.             if event.type == QUIT:
  144.                 playing = False
  145.                 end = False
  146.  
  147.         info = []
  148.         for i in snakeList:
  149.             info.append(i.getInfo())
  150.         for i in snakeList:
  151.             i.setDir(info.copy())
  152.         #Check hit
  153.         for i in snakeList:
  154.             if i.alive:
  155.                 loc = i.getInfo()[2]
  156.                 for x in info:
  157.                     if loc in x[0]:
  158.                         if loc == x[0][-1]: #Checks if it is itself
  159.                             temp = x[0].copy()
  160.                             temp.remove(loc)
  161.                             if loc in temp: #Checks to see if the value is in the list twice
  162.                                 i.alive = False
  163.                                 feed.append([i.name+' is out (Hit itself)', 0])
  164.                         else: #Makes sure it isn't current position
  165.                             i.alive = False
  166.                             feed.append([i.name+' is out (Hit Snake)', 0])
  167.                 if loc[0] < 0 or loc[0]>=width or loc[1]<0 or loc[1]>=height:
  168.                     i.alive = False
  169.                     feed.append([i.name+' is out (Border)', 0])
  170.             else:
  171.                 # CHANGE
  172.                 for l in frames:
  173.                     tempFrames.append(l.copy())
  174.                 frameRecorderCounter = 20
  175.                 snakeList.remove(i)
  176.                 print('snake dead, new length:', str(len(snakeList)))
  177.  
  178.         if (time.time()-tStart) > 1:
  179.             length += 1
  180.             tStart = time.time()
  181.         tickRate = (math.ceil(length / 30) + 1) * 30
  182.         # if ticks % 100 == 0:
  183.         #     print("tickRate: " + str(tickRate))
  184.         if tickRate >= 100 and snakeList.__len__() > 0:
  185.             # snakeList[0].alive = False
  186.             s = 1
  187.  
  188.         keys = pygame.key.get_pressed()
  189.         for i in keys:
  190.             if i:
  191.                 end = False
  192.                 playing = False
  193.         if frameRecorderCounter <= 0 and snakeList.__len__() <= 0:
  194.             playing = False
  195.             print("playing = False")
  196.  
  197.         #Draw everything
  198.  
  199.         # CHANGE
  200.         if len(frames) > 60:
  201.             # print("Length " + str(len(frames)) + " is too long!")
  202.             frames.remove(frames[0])
  203.  
  204.         if frameRecorderCounter > 0:
  205.             frameRecorderCounter -= 1
  206.             tempFrames.append(frames[len(frames) - 1].copy())
  207.         elif len(tempFrames) > 0:
  208.             kills.append(tempFrames.copy())
  209.             tempFrames.clear()
  210.  
  211.  
  212.         data = [snakeList, feed]
  213.         draw(data)
  214.         # print("OG: " + str(data))
  215.         dataCopy = [copy.deepcopy(snakeList), copy.deepcopy(feed)]
  216.         # print("NEW: " + str(dataCopy))
  217.         frames.append(dataCopy)
  218.         ticks += 1
  219.  
  220.     while end: #This is just so it doesn't immediately close after someone loses
  221.         clock.tick(tickRate)
  222.         for event in pygame.event.get():
  223.             if event.type == QUIT:
  224.                 end = False
  225.         #Draw everything
  226.         # pygame.draw.rect(win, (255,0,0), pygame.Rect(0,0,width,height)) #Background
  227.         end = False
  228.         pygame.display.update()
  229.  
  230.     for kill in kills:
  231.         clock.tick(tickRate)
  232.  
  233.         killId = ""
  234.  
  235.         for i in range(0, 15):
  236.             killId += str(randint(0, 9))
  237.             # print(killId)
  238.  
  239.         killId = 'kill-{date:%Y-%m-%d %H:%M:%S}'.format(date=datetime.datetime.now())
  240.  
  241.         print("Kill ID: #" + killId)
  242.         path = gifPath + killId + "/"
  243.  
  244.         succ = False
  245.  
  246.         try:
  247.             os.mkdir(path)
  248.         except OSError:
  249.             print("Creation of the directory %s failed" % path)
  250.         else:
  251.             succ = True
  252.             print("Successfully created the directory %s " % path)
  253.  
  254.         for frame in kill:
  255.             clock.tick(tickRate)
  256.             draw(frame)
  257.             # print("Drew frame")
  258.             # print(str(frame))
  259.  
  260.             fnum = kill.index(frame)
  261.  
  262.             if 0 <= fnum - 45 <= 74:
  263.  
  264.                 scopeNum = str(fnum - 45)
  265.  
  266.                 if fnum - 45 < 10:
  267.                     scopeNum = "0" + scopeNum
  268.  
  269.                 myimage = pygame.image.load(gifPath + "Quickscope/quickscope" + scopeNum + ".png")
  270.                 imagerect = myimage.get_rect()
  271.  
  272.                 win.blit(myimage, ((width / 2) - (imagerect[2] / 2), height - imagerect[3]))
  273.                 # pygame.display.flip()
  274.                 pygame.display.update()
  275.  
  276.             fname = path + "frame_" + str(fnum) + ".png"
  277.             # pygame.display.update()
  278.             # print("Updated display")
  279.             pygame.image.save(win, fname)
  280.         if succ:
  281.             generateGif(killId, gifPath)
  282.  
  283.         for frame in kill:
  284.             clock.tick(tickRate)
  285.             draw(frame)
  286.  
  287.             # print("Drew frame")
  288.             # print(str(frame))
  289.  
  290.             fname = path + "frame_" + str(kill.index(frame)) + ".png"
  291.             # pygame.display.update()
  292.             # print("Updated display")
  293.             try:
  294.                 os.remove(fname)
  295.             except OSError:
  296.                 s = 1
  297.                 # print("Deletion of the file %s failed" % fname)
  298.             else:
  299.                 s = 1
  300.                 # print("Successfully deleted the file %s " % fname)
  301.  
  302.         try:
  303.             os.rmdir(path)
  304.         except OSError:
  305.             print("Deletion of the directory %s failed" % path)
  306.         else:
  307.             print("Successfully deleted the directory %s " % path)
  308.  
  309.     pygame.quit()
  310.  
  311.  
  312. class playerUpdates:
  313.     #pos is [x,y] bod is [[x,y],[x,y]...]
  314.     #info is [[bod, dir, pos], [bod, dir, pos]...]
  315.     def Chris(pos, bod, dir, info):
  316.         def hit(dirr, info, bod, pos):
  317.             newX, newY = pos[0], pos[1]
  318.             if dirr == 'right':
  319.                 newX += size
  320.             if dirr == 'left':
  321.                 newX -= size
  322.             if dirr == 'up':
  323.                 newY -= size
  324.             if dirr == 'down':
  325.                 newY += size
  326.             if newX >= width or newX < 0 or newY >= height or newY < 0:
  327.                 return True
  328.             for i in info:
  329.                 badX, badY = i[2][0], i[2][1]
  330.                 if i[1] == 'right':
  331.                     badX += size
  332.                 if i[1] == 'left':
  333.                     badX -= size
  334.                 if i[1] == 'up':
  335.                     badY -= size
  336.                 if i[1] == 'down':
  337.                     badY += size
  338.  
  339.                 if [newX, newY] in i[0]:
  340.                     return True
  341.                 if [newX, newY] == [badX, badY]:
  342.                     return True
  343.             return False
  344.         if not(hit(dir, info, bod, pos)):
  345.             return dir
  346.         else:
  347.             dirs = ['right', 'left', 'up', 'down']
  348.             for i in range(0,3):
  349.                 newDir = dirs.pop(randint(0,len(dirs)-1))
  350.                 if not(hit(newDir, info, bod, pos)):
  351.                     return newDir
  352.             return dir
  353.  
  354.         newX, newY = pos[0], pos[1]
  355.         if dir == 'right':
  356.             newX += size
  357.         if dir == 'left':
  358.             newX -= size
  359.         if dir == 'up':
  360.             newY -= size
  361.         if dir == 'down':
  362.             newY += size
  363.  
  364.         if newX >= width:
  365.             return 'up'
  366.         if newX < 0:
  367.             return 'down'
  368.         if newY >= height:
  369.             return 'right'
  370.         if newY < 0:
  371.             return 'left'
  372.         return dir
  373.  
  374.  
  375.     def Person(pos, bod, dir, info):
  376.         newX, newY = pos[0], pos[1]
  377.         if dir == 'right':
  378.             newX += size
  379.         if dir == 'left':
  380.             newX -= size
  381.         if dir == 'up':
  382.             newY -= size
  383.         if dir == 'down':
  384.             newY += size
  385.  
  386.         if newX >= width:
  387.             return 'up'
  388.         if newX < 0:
  389.             return 'down'
  390.         if newY >= height:
  391.             return 'right'
  392.         if newY < 0:
  393.             return 'left'
  394.         return dir
  395.  
  396.  
  397. main()
Advertisement
Add Comment
Please, Sign In to add comment