1
0

0х.py 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. import telebot
  2. import random
  3. import os
  4. TOKEN = "7030023448:AAFRdU_uwxpgT0K-mYy_UtohgkRnhpjE3IM"
  5. bot = telebot.TeleBot(TOKEN)
  6. DATABASE_FILE = "users.txt"
  7. EMPTY = "⬜"
  8. CROSS = "❌"
  9. CIRCLE = "⭕"
  10. def register_user(chat_id):
  11. with open(DATABASE_FILE, "a") as f:
  12. f.write(f"{chat_id},0,0\n")
  13. print(f"User {chat_id} registered.")
  14. def get_user_data(chat_id):
  15. with open(DATABASE_FILE, "r") as f:
  16. for line in f:
  17. data = line.strip().split(",")
  18. if int(data[0]) == chat_id:
  19. return {
  20. "chat_id": int(data[0]),
  21. "win_bot": int(data[1]),
  22. "balance": int(data[2])
  23. }
  24. return None
  25. def update_user_data(chat_id, win_bot=None, balance=None):
  26. lines = []
  27. with open(DATABASE_FILE, "r") as f:
  28. for line in f:
  29. data = line.strip().split(",")
  30. if int(data[0]) == chat_id:
  31. if win_bot is not None:
  32. data[1] = str(win_bot)
  33. if balance is not None:
  34. data[2] = str(balance)
  35. lines.append(",".join(data) + "\n")
  36. with open(DATABASE_FILE, "w") as f:
  37. f.writelines(lines)
  38. print(f"User {chat_id} data updated.")
  39. # --- Игровые функции ---
  40. def create_board():
  41. return [EMPTY] * 9
  42. def print_board(board):
  43. row1 = board[0:3]
  44. row2 = board[3:6]
  45. row3 = board[6:9]
  46. return f'{row1[0]}{row1[1]}{row1[2]}\n{row2[0]}{row2[1]}{row2[2]}\n{row3[0]}{row3[1]}{row3[2]}'
  47. def check_winner(board, player):
  48. # Проверка строк, столбцов и диагоналей
  49. for i in range(0, 9, 3):
  50. if board[i] == board[i+1] == board[i+2] == player:
  51. return True
  52. for i in range(3):
  53. if board[i] == board[i+3] == board[i+6] == player:
  54. return True
  55. if board[0] == board[4] == board[8] == player:
  56. return True
  57. if board[2] == board[4] == board[6] == player:
  58. return True
  59. return False
  60. def is_board_full(board):
  61. return EMPTY not in board
  62. def bot_move(board):
  63. # 1. Проверка возможности выигрыша для бота
  64. for i in range(9):
  65. if board[i] == EMPTY:
  66. temp_board = board[:]
  67. temp_board[i] = CIRCLE
  68. if check_winner(temp_board, CIRCLE):
  69. return i
  70. # 2. Проверка возможности выигрыша для игрока и блокировка
  71. for i in range(9):
  72. if board[i] == EMPTY:
  73. temp_board = board[:]
  74. temp_board[i] = CROSS
  75. if check_winner(temp_board, CROSS):
  76. return i
  77. # 3. Выбор случайной пустой клетки (стратегически)
  78. corners = [0, 2, 6, 8]
  79. available_corners = [i for i in corners if board[i] == EMPTY]
  80. if available_corners:
  81. return random.choice(available_corners)
  82. center = 4
  83. if board[center] == EMPTY:
  84. return center
  85. edges = [1, 3, 5, 7]
  86. available_edges = [i for i in edges if board[i] == EMPTY]
  87. if available_edges:
  88. return random.choice(available_edges)
  89. return None # Доска заполнена, и нет доступных ходов
  90. def create_board_markup(board):
  91. markup = telebot.types.InlineKeyboardMarkup(row_width=3)
  92. buttons = []
  93. for i in range(9):
  94. buttons.append(telebot.types.InlineKeyboardButton(board[i], callback_data=f"move_{i}"))
  95. markup.add(*buttons)
  96. return markup
  97. # --- Обработчики ---
  98. @bot.message_handler(commands=["start"])
  99. def start(message):
  100. chat_id = message.chat.id
  101. user_data = get_user_data(chat_id)
  102. if user_data is None:
  103. register_user(chat_id)
  104. bot.send_message(chat_id, "Вы успешно зарегистрированы!")
  105. markup = telebot.types.InlineKeyboardMarkup(row_width=2)
  106. item_profile = telebot.types.InlineKeyboardButton("Профиль", callback_data="profile")
  107. item_play = telebot.types.InlineKeyboardButton("Играть", callback_data="play")
  108. markup.add(item_profile, item_play)
  109. with open("zastavka.jpg", "rb") as photo:
  110. bot.send_photo(chat_id, photo, caption="Выберите действие:", reply_markup=markup)
  111. # Обработчик inline кнопок
  112. @bot.callback_query_handler(func=lambda call: True)
  113. def callback_inline(call):
  114. chat_id = call.message.chat.id
  115. message_id = call.message.message_id
  116. if call.data == "profile":
  117. bot.delete_message(chat_id, message_id)
  118. show_profile(chat_id)
  119. elif call.data == "play":
  120. bot.delete_message(chat_id, message_id)
  121. start_game(chat_id)
  122. elif call.data.startswith("move_"):
  123. handle_move(call)
  124. else:
  125. pass
  126. def handle_move(call):
  127. chat_id = call.message.chat.id
  128. message_id = call.message.message_id
  129. move = int(call.data.split("_")[1])
  130. game_data = games.get(chat_id)
  131. if not game_data:
  132. bot.send_message(chat_id, "Игра не найдена.")
  133. return
  134. board = game_data["board"]
  135. if board[move] != EMPTY:
  136. bot.send_message(chat_id, "Эта клетка уже занята!")
  137. return
  138. # Ход человека
  139. board[move] = CROSS
  140. if check_winner(board, CROSS):
  141. user_data = get_user_data(chat_id)
  142. if user_data:
  143. update_user_data(chat_id, win_bot=int(user_data["win_bot"]) + 1, balance=int(user_data["balance"]) + 10)
  144. with open("pobeda.jpg", "rb") as photo:
  145. bot.send_photo(chat_id, photo, caption="Вы выйграли!\n+10 монет")
  146. bot.delete_message(chat_id, message_id)
  147. del games[chat_id]
  148. show_menu(chat_id)
  149. return
  150. if is_board_full(board):
  151. with open("niza.jpg", "rb") as photo:
  152. bot.send_photo(chat_id, photo, caption="Ничья!")
  153. bot.delete_message(chat_id, message_id)
  154. del games[chat_id]
  155. show_menu(chat_id)
  156. return
  157. # Ход бота
  158. bot_choice = bot_move(board)
  159. if bot_choice is not None:
  160. board[bot_choice] = CIRCLE
  161. else:
  162. with open("niza.jpg", "rb") as photo:
  163. bot.send_photo(chat_id, photo, caption="Ничья!")
  164. bot.delete_message(chat_id, message_id)
  165. del games[chat_id]
  166. show_menu(chat_id)
  167. return
  168. if check_winner(board, CIRCLE):
  169. with open("lose.jpg", "rb") as photo:
  170. bot.send_photo(chat_id, photo, caption="Вы проиграли!")
  171. bot.delete_message(chat_id, message_id)
  172. del games[chat_id]
  173. show_menu(chat_id)
  174. return
  175. if is_board_full(board):
  176. with open("niza.jpg", "rb") as photo:
  177. bot.send_photo(chat_id, photo, caption="Ничья!")
  178. bot.delete_message(chat_id, message_id)
  179. del games[chat_id]
  180. show_menu(chat_id)
  181. return
  182. game_data["board"] = board
  183. games[chat_id] = game_data
  184. bot.delete_message(chat_id, message_id)
  185. send_board(chat_id, board)
  186. def show_profile(chat_id):
  187. user_data = get_user_data(chat_id)
  188. if user_data:
  189. profile_info = (
  190. f"Имя аккаунта: {chat_id}\n"
  191. f"Побед с ботом: {user_data['win_bot']}\n"
  192. f"Баланс: {user_data['balance']} серебра"
  193. )
  194. with open("profil.jpg", "rb") as photo:
  195. bot.send_photo(chat_id, photo, caption=profile_info)
  196. else:
  197. bot.send_message(chat_id, "Произошла ошибка при получении данных профиля.")
  198. show_menu(chat_id)
  199. def start_game(chat_id):
  200. board = create_board()
  201. game_data = {"board": board}
  202. games[chat_id] = game_data
  203. send_board(chat_id, board)
  204. def send_board(chat_id, board):
  205. markup = create_board_markup(board)
  206. bot.send_message(chat_id, print_board(board), reply_markup=markup)
  207. def show_menu(chat_id):
  208. markup = telebot.types.InlineKeyboardMarkup(row_width=2)
  209. item_profile = telebot.types.InlineKeyboardButton("Профиль", callback_data="profile")
  210. item_play = telebot.types.InlineKeyboardButton("Играть", callback_data="play")
  211. markup.add(item_profile, item_play)
  212. with open("zastavka.jpg", "rb") as photo:
  213. bot.send_photo(chat_id, photo, caption="Выберите действие:", reply_markup=markup)
  214. games = {}
  215. bot.polling(none_stop=True)