Advertisement
ClearCode

snake-powershell

Apr 6th, 2022
1,552
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.00 KB | None | 0 0
  1. from pytimedinput import timedInput
  2. from random import randint
  3. import os
  4. from colorama import Fore, init
  5.  
  6. def print_field():
  7.     for cell in CELLS:
  8.         if cell in snake_body:
  9.             print(Fore.GREEN + 'X', end = '')
  10.         elif cell == apple_pos:
  11.             print(Fore.RED + 'a',end = '')
  12.         elif cell[1] in (0, FIELD_HEIGHT - 1) or cell[0] in (0, FIELD_WIDTH - 1):
  13.             print(Fore.CYAN + '#', end = '')
  14.         else:
  15.             print(' ', end = '')
  16.  
  17.         if cell[0] == FIELD_WIDTH - 1:
  18.             print('')
  19.  
  20. def update_snake():
  21.     global eaten
  22.     new_head = snake_body[0][0] + direction[0], snake_body[0][1] + direction[1]
  23.     snake_body.insert(0,new_head)
  24.     if not eaten:
  25.         snake_body.pop(-1)
  26.     eaten = False
  27.  
  28. def apple_collision():
  29.     global apple_pos, eaten
  30.  
  31.     if snake_body[0] == apple_pos:
  32.         apple_pos = place_apple()
  33.         eaten = True
  34.  
  35. def place_apple():
  36.     col = randint(1,FIELD_WIDTH - 2)
  37.     row = randint(1,FIELD_HEIGHT - 2)
  38.     while (col, row) in snake_body:
  39.         col = randint(1,FIELD_WIDTH - 2)
  40.         row = randint(1,FIELD_HEIGHT - 2)
  41.     return (col,row)
  42.  
  43. init(autoreset=True)
  44.  
  45. # settings
  46. FIELD_WIDTH = 32
  47. FIELD_HEIGHT = 16
  48. CELLS = [(col,row) for row in range(FIELD_HEIGHT) for col in range(FIELD_WIDTH)]
  49.  
  50. # snake
  51. snake_body = [
  52.     (5,FIELD_HEIGHT // 2),
  53.     (4,FIELD_HEIGHT // 2),
  54.     (3,FIELD_HEIGHT // 2)]
  55. DIRECTIONS = {'left':(-1,0),'right': (1,0),'up': (0,-1),'down': (0,1)}
  56. direction = DIRECTIONS['right']
  57. eaten = False
  58. apple_pos = place_apple()
  59.  
  60. while True:
  61.     # clear field
  62.     os.system('cls')
  63.    
  64.     # draw field
  65.     print_field()
  66.  
  67.     # get input
  68.     txt,_ = timedInput('',timeout = 0.3)
  69.     match txt:
  70.         case 'w': direction = DIRECTIONS['up']
  71.         case 'a': direction = DIRECTIONS['left']
  72.         case 's': direction = DIRECTIONS['down']
  73.         case 'd': direction = DIRECTIONS['right']
  74.         case 'q':
  75.             os.system('cls')
  76.             break
  77.  
  78.     # update game
  79.     update_snake()
  80.     apple_collision()
  81.  
  82.     # check death
  83.     if snake_body[0][1] in (0, FIELD_HEIGHT - 1) or \
  84.        snake_body[0][0] in (0,FIELD_WIDTH - 1) or\
  85.        snake_body[0] in snake_body[1:]:
  86.         os.system('cls')
  87.         break
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement