VitalyD

Untitled

Jun 19th, 2018
161
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 10.06 KB | None | 0 0
  1. # импорт библиотек
  2. import random
  3. import os
  4.  
  5. # размер поля
  6. size = 10
  7. monitoring = False
  8.  
  9. # виды кораблей
  10. s_buffer = "^"
  11. s_ship = "A"
  12. s_space = "."
  13. s_hit = "x"
  14. s_destroyed = "W"
  15. s_miss = "*"
  16.  
  17. # Available ships (quantity, size):
  18. ships_list = [[1, 4], [2, 3], [3, 2], [4, 1]]
  19.  
  20.  
  21.  
  22. # Класс корабля
  23. class Board(object):
  24.  
  25.     def __init__(self):
  26.         self.board = []
  27.         # Here will be containing spawned ships information:
  28.         self.spawned = []
  29.  
  30.     # создание корабля
  31.     def create(self):
  32.         for row in range(size):
  33.             self.board.append([s_space] * size)
  34.    
  35.     # его спавн в рандомной позиции
  36.     def random(self):
  37.  
  38.         for ship in ships_list:
  39.             for unit in range(ship[0]):
  40.  
  41.                 spawning = True
  42.                 while spawning:
  43.  
  44.                     # Define the refer of ship (0 - x, 1 - y):
  45.                     global refer
  46.                     refer = random.randrange(2)
  47.                     if refer == 0:
  48.                         location_y = random.randrange(size)
  49.                         location_x = random.randrange(size - (ship[1] - 1))
  50.                     else:
  51.                         location_y = random.randrange(size - (ship[1] - 1))
  52.                         location_x = random.randrange(size)
  53.  
  54.                     # Testing if ship has own space on the board:
  55.                     offset = 0
  56.                     for testing in range(ship[1]):
  57.                         if refer == 0 and self.board[location_y][location_x + offset] != s_space:
  58.                             continue
  59.                         elif refer == 1 and self.board[location_y + offset][location_x] != s_space:
  60.                             continue
  61.                         offset += 1
  62.                         if offset == ship[1]:
  63.                             spawning = False
  64.  
  65.                 # Creating ship body:
  66.                 offset = 0
  67.                 current_ship = []
  68.                 for marker in range(ship[1]):
  69.                     if refer == 0:
  70.                         self.board[location_y][location_x + offset] = s_ship
  71.                         current_ship.append([location_y, location_x + offset])
  72.                     else:
  73.                         self.board[location_y + offset][location_x] = s_ship
  74.                         current_ship.append([location_y + offset, location_x])
  75.                     offset += 1
  76.                 self.spawned.append(current_ship)
  77.  
  78.                 # Creating buffer zone for unit:
  79.                 for unit_point in current_ship:
  80.                     for buffer_point in ([0, 1], [0, -1], [1, 0], [-1, 0], [1, 1], [1, -1], [-1, 1], [-1, -1]):
  81.                         b_point_y = unit_point[0] + buffer_point[0]
  82.                         b_point_x = unit_point[1] + buffer_point[1]
  83.                         if b_point_y in range(size) and b_point_x in range(size):
  84.                             if self.board[b_point_y][b_point_x] == s_space:
  85.                                 self.board[b_point_y][b_point_x] = s_buffer
  86.     # обновления поля
  87.     def updating(self, ship):
  88.         # Creating buffer zone for unit:
  89.         for unit in ship:
  90.             for buffer_point in ([0, 0], [0, 1], [0, -1], [1, 0], [-1, 0], [1, 1], [1, -1], [-1, 1], [-1, -1]):
  91.                 b_point_y = unit[0] + buffer_point[0]
  92.                 b_point_x = unit[1] + buffer_point[1]
  93.                 if b_point_y in range(size) and b_point_x in range(size):
  94.                     if self.board[b_point_y][b_point_x] == s_buffer:
  95.                         self.board[b_point_y][b_point_x] = s_miss
  96.                     elif self.board[b_point_y][b_point_x] == s_hit:
  97.                         self.board[b_point_y][b_point_x] = s_destroyed
  98.  
  99. # печать поля
  100. def print_boards():
  101.     # Printing top of the scale:
  102.     print("\n    Your board" + (" " * (size + 5)) + "Enemy board")
  103.     print("    " + (" ".join(str(i) for i in list(range(size)))), end=(" " * 2))
  104.     print("    " + (" ".join(str(i) for i in list(range(size)))))
  105.     print("   " + (" |" * size), end=(" " * 2))
  106.     print("   " + (" |" * size))
  107.     # Printing left part of scale and board:
  108.     n = 0
  109.     for i in range(size):
  110.         if monitoring:
  111.             print(str(n) + " - " + " ".join(str(i) for i in player.board[n]), end=(" " * 2))
  112.             print(str(n) + " - " + " ".join(str(i) for i in ai.board[n]))
  113.         else:
  114.             print(str(n) + " - " + " ".join(str(i) for i in player.board[n]).replace(s_buffer, s_space), end=(" " * 2))
  115.             print(str(n) + " - " + " ".join(str(i) for i in ai.board[n]).replace(s_ship, s_space).replace(s_buffer, s_space))
  116.         n += 1
  117.  
  118. # обработка нажить энтера
  119. def press_ent():
  120.     input("Press the Enter bottom to continue.\n")
  121.  
  122. # проверка состояния кораблей (уничтожены или нет)
  123. def state_of_ships(enemy):
  124.     global destroy
  125.     destroy = False
  126.     # Checking state of all ships:
  127.     for d_ship in enemy.spawned:
  128.         damage = 0
  129.         for d_unit in d_ship:
  130.             if enemy.board[d_unit[0]][d_unit[1]] == s_hit:
  131.                 damage += 1
  132.         # If the current ship was destroyed:
  133.         if damage == len(d_ship):
  134.             enemy.updating(d_ship)
  135.             enemy.spawned.remove(d_ship)
  136.             destroy = True
  137.  
  138. # ход компьютера
  139. def ai_pass():
  140.     ai_guessing = True
  141.     while ai_guessing:
  142.  
  143.         # Probability of AI intuition (zero is enable):
  144.         ai_intuition = random.randrange(size * 5)
  145.  
  146.         # AI intuition (dishonest searching for enemy valid ship):
  147.         if ai_intuition == 0:
  148.             ai_int_ship = random.randrange(len(player.spawned))  # Choosing for ship.
  149.             ai_int_unit = random.randrange(len(player.spawned[ai_int_ship]))  # Choosing for unit.
  150.             ai_guess_y = player.spawned[ai_int_ship][ai_int_unit][0]
  151.             ai_guess_x = player.spawned[ai_int_ship][ai_int_unit][1]
  152.  
  153.         # AI random guessing:
  154.         else:
  155.             ai_guess_y = random.randrange(size)
  156.             ai_guess_x = random.randrange(size)
  157.  
  158.         # Checking. If hit:
  159.         if player.board[ai_guess_y][ai_guess_x] == s_ship:
  160.             player.board[ai_guess_y][ai_guess_x] = s_hit
  161.             state_of_ships(player)
  162.             if destroy:
  163.                 print("\nAI has destroyed your ship (X: %s, Y: %s)." % (ai_guess_x, ai_guess_y))
  164.             else:
  165.                 print("\nAI has damaged your ship (X: %s, Y: %s)." % (ai_guess_x, ai_guess_y))
  166.             break
  167.  
  168.         # Checking. If miss:
  169.         elif player.board[ai_guess_y][ai_guess_x] == s_space or player.board[ai_guess_y][ai_guess_x] == s_buffer:
  170.             player.board[ai_guess_y][ai_guess_x] = s_miss
  171.             print("\nAI has miss (X: %s, Y: %s)." % (ai_guess_x, ai_guess_y))
  172.             break
  173.  
  174.         # Checking. Otherwise restart guessing:
  175.         else:
  176.             continue
  177.  
  178. # очистка поля
  179. def clear():
  180.     # Clearing of previous board and text:
  181.     os.system('cls' if os.name == 'nt' else 'clear')
  182.  
  183. # приветствие
  184. print("Welcome to \"Sea Battle\" BETA version by Aunmag!\n")
  185. press_ent()
  186.  
  187. # создание бота
  188. ai = Board()
  189. ai.create()
  190. ai.random()
  191.  
  192. # создание игрока
  193. while True:
  194.     clear()
  195.     player = Board()
  196.     player.create()
  197.     player.random()
  198.     print("\nHIT: Here will be printing information about enemy.")
  199.     print_boards()
  200.     print("\nLook at your board (by left side).")
  201.     print("Press the Enter button to change spawn of your ships again (random).")
  202.     regenerate = input("Or if you're ready enter \"c\" letter here to continue: ")
  203.     if str(regenerate.lower()) != "c":
  204.         continue
  205.     else:
  206.         break
  207.  
  208. # начало игры
  209. print("\nOk! AI is going to start first. Get ready!\n")
  210. press_ent()
  211.  
  212.  
  213. game = True
  214. while game:
  215.  
  216.     clear()
  217.     ai_pass()
  218.     print_boards()
  219.  
  220.     guessing = True
  221.     while guessing:
  222.  
  223.         # информация о том, кто проиграл
  224.         print("\nEnemy ships remain: " + str(len(ai.spawned)) + ". ", end="")
  225.         print("Your ships remain: " + str(len(player.spawned)) + ".")
  226.  
  227.         # координаты выстрела
  228.         guess_x = input("Choose X (column) position to strike: ")
  229.         guess_y = input("Choose Y (line) position to strike: ")
  230.  
  231.         # если выходят за пределы поля
  232.         if not guess_x.isdigit() or not guess_y.isdigit():
  233.             print("\nError! You've entered wrong coordinates! Change your choose.")
  234.             continue
  235.         guess_x = int(guess_x)
  236.         guess_y = int(guess_y)
  237.  
  238.         if not (guess_x in range(size)) or not (guess_y in range(size)):
  239.             print("\nError! This location is too far to hit it! Change your choose.")
  240.             continue
  241.  
  242.         # Если попал
  243.         elif ai.board[guess_y][guess_x] == s_ship:
  244.             ai.board[guess_y][guess_x] = s_hit
  245.             state_of_ships(ai)
  246.             if destroy:
  247.                 print("\nYou've destroyed enemy ship!", end=" ")
  248.             else:
  249.                 print("\nYou've damaged enemy ship!", end=" ")
  250.             press_ent()
  251.             break
  252.  
  253.         # Если промахнулся
  254.         elif ai.board[guess_y][guess_x] == s_space or ai.board[guess_y][guess_x] == s_buffer:
  255.             ai.board[guess_y][guess_x] = s_miss
  256.             print("\nYou've missed.", end=" ")
  257.             press_ent()
  258.  
  259.         # Checking. If hit the same palace again:
  260.         else:
  261.             print("\nYou've already hit to this location, change your choose.")
  262.             continue
  263.  
  264.         # Проверка окончания игры
  265.         break
  266.  
  267.     if len(ai.spawned) == 0:
  268.         input("You are WINNER! You've destroyed all enemy units! Press the Enter to end this game.")
  269.         break
  270.  
  271.     if len(player.spawned) == 0:
  272.         print("You are LOSER! All your units were destroyed.")
  273.         input("Total enemy ships remain: " + str(len(ai.spawned)) + ".")
  274.         break
Advertisement
Add Comment
Please, Sign In to add comment