-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgame15.py
More file actions
416 lines (394 loc) · 26.4 KB
/
Copy pathgame15.py
File metadata and controls
416 lines (394 loc) · 26.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
import telebot
from telebot import types
import time
import random
import sqlite3
bot = telebot.TeleBot('TOKEN') #PUT YOUR TOKEN
chanel = '-1003480826321'
@bot.message_handler(commands=['start'])
def start(message):
if message.chat.type == 'private':
conn = sqlite3.connect('rating.db')
cur = conn.cursor()
cur.execute('SELECT user_id FROM users')
is_registr = False
while True:
search = cur.fetchone()
if search == None:
break
if search[0] == message.chat.id:
is_registr = True
break
if is_registr == False:
if message.chat.last_name != None:
cur.execute("INSERT INTO users (user_id, score, nickname, username) VALUES ('%s', '%s', '%s', '%s')" % (message.chat.id, 0, message.chat.first_name + ' ' + message.chat.last_name, message.chat.username))
else:
cur.execute("INSERT INTO users (user_id, score, nickname, username) VALUES ('%s', '%s', '%s', '%s')" % (message.chat.id, 0, message.chat.first_name, message.chat.username))
conn.commit()
cur.close()
conn.close()
bot.send_message(message.chat.id, 'Добро пожаловать в игру "15"!')
markup = types.InlineKeyboardMarkup()
markup1 = types.InlineKeyboardButton('📰Подписаться на канал', url='https://t.me/lupikprojects')
markup2 = types.InlineKeyboardButton('✅Проверить подписку', callback_data='subscription')
markup.add(markup1).row(markup2)
bot.send_message(message.chat.id, 'Для использования бота необходимо быть подписанным на канал.',
reply_markup=markup)
@bot.callback_query_handler(func=lambda call: True)
def callback(call):
if call.message:
if call.data == 'subscription':
chat_member = bot.get_chat_member(chanel, call.message.chat.id)
if chat_member.status in ['member', 'creator']:
markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
button1 = types.KeyboardButton('🕹Начать игру')
button2 = types.KeyboardButton('❓Как играть?')
button3 = types.KeyboardButton('🏆Рейтинг')
button4 = types.KeyboardButton('⚙️Настройки')
markup.add(button1).row(button2, button3).row(button4)
bot.delete_message(call.message.chat.id, call.message.message_id)
bot.send_message(call.message.chat.id,'Спасибо за подписку!', reply_markup=markup)
else:
bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.id, text= 'Вы не подписались')
time.sleep(1)
markup = types.InlineKeyboardMarkup()
markup1 = types.InlineKeyboardButton('📰Подписаться на канал', url='https://t.me/lupikprojects')
markup2 = types.InlineKeyboardButton('✅Проверить подписку', callback_data='subscription')
markup.add(markup1).row(markup2)
bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.id, text= 'Для использования бота необходимо быть подписанным на канал.',reply_markup=markup)
elif call.data == 'close':
bot.delete_message(call.message.chat.id, call.message.message_id)
elif call.data == 'nick':
msg = bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.id, text='Введите новый никнейм:')
bot.register_next_step_handler(msg, new_nickname)
elif call.data == 'see_nick':
markup = types.InlineKeyboardMarkup(row_width=2)
button1 = types.InlineKeyboardButton('🟢Вкл', callback_data='on_see')
button2 = types.InlineKeyboardButton('🔴Выкл', callback_data='off_see')
markup.add(button1, button2)
bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.id,
text='Включить или выключить гиперссылку?\n\n'
'По умолчанию: вкл\n\n'
'P.s. если у вас нет айди в телеграмме, то и ссылки на ваш профиль тоже не будет, даже если вы ее попытаетесь включить.', reply_markup=markup)
elif call.data == 'on_see':
conn = sqlite3.connect('rating.db')
cur = conn.cursor()
cur.execute('UPDATE users SET username = ? WHERE user_id = ?', (call.message.chat.username, call.message.chat.id))
conn.commit()
cur.close()
conn.close()
bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.id,
text='Гиперссылка включена')
elif call.data == 'off_see':
conn = sqlite3.connect('rating.db')
cur = conn.cursor()
cur.execute('UPDATE users SET username = ? WHERE user_id = ?',('None', call.message.chat.id))
conn.commit()
cur.close()
conn.close()
bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.id,
text='Гиперссылка выключена')
@bot.message_handler(content_types=['text'])
def bot_message(message):
if message.chat.type == 'private':
if bot.get_chat_member(chanel, message.chat.id).status in ['member', 'creator']:
if message.text == '🕹Начать игру':
markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
up = types.KeyboardButton('⬆️')
left = types.KeyboardButton('⬅️')
right = types.KeyboardButton('➡️')
down = types.KeyboardButton('⬇️')
game_ower = types.KeyboardButton('💥Завершить игру')
markup.add(up).row(left,right).row(down).row(game_ower)
msg = bot.send_message(message.chat.id, 'Генерирую комбинацию...', reply_markup=markup)
game = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,' ']
for i in range(80):
storona = random.randint(1,4) #1 - влево, 2 - вверх, 3 - вправо, 4 - вниз
pyst = game.index(' ')
if storona == 1:
if game.index(' ') - 1 not in [-1,3,7,11]:
game[pyst], game[pyst - 1] = game[pyst - 1], game[pyst]
elif storona == 2:
if game.index(' ') - 4 not in [-4, -3, -2, -1]:
game[pyst], game[pyst - 4] = game[pyst - 4], game[pyst]
elif storona == 3:
if game.index(' ') + 1 not in [4,8,12,16]:
game[pyst], game[pyst + 1] = game[pyst + 1], game[pyst]
else:
if game.index(' ') + 4 not in [16,17,18,19]:
game[pyst], game[pyst + 4] = game[pyst + 4], game[pyst]
markup2 = types.InlineKeyboardMarkup(row_width=4)
for i in range(0,16,4):
markup2.add(types.InlineKeyboardButton(f'{game[i]}', callback_data=f'{i}'),
types.InlineKeyboardButton(f'{game[i+1]}', callback_data=f'{i+1}'),
types.InlineKeyboardButton(f'{game[i+2]}',callback_data=f'{i+2}'),
types.InlineKeyboardButton(f'{game[i+3]}',callback_data=f'{i+3}'))
msg = bot.send_message(message.chat.id, 'Игра началась!', reply_markup=markup2)
bot.register_next_step_handler(msg, steps, game, msg)
elif message.text == '❓Как играть?':
markup = types.InlineKeyboardMarkup()
markup.add(types.InlineKeyboardButton('❎Закрыть меню', callback_data='close'))
bot.send_message(message.chat.id, '<b>Игра в 1️⃣5️⃣ (пятнашки)</b>\n\n'
'Игра в 15 — это головоломка с квадратной доской 4x4, где расставлены 15 пронумерованных плиток (от 1 до 15) и один пустой квадрат.\n\n'
'Цель — привести плитки в порядок по возрастанию (слева направо, сверху вниз), передвигая по одной плитке на пустое место.\n\n'
'Основные моменты:\n\n'
'- Можно двигать только плитки, соседствующие с пустым местом.\n'
'- Изначальная расстановка плиток случайная (но решаемая).\n'
'- Победа достигается, когда все цифры выстроены по порядку, а пустое место оказывается внизу справа.\n\n\n'
'<b>Особенности игры (в боте):</b>\n\n'
'<u>Управление</u>:\n'
'Интуитивно понятное, но все же.\n'
'⬆️ - сдивает цифру, которая находится ниже пустой клетки вверх.\n'
'⬇️ - сдивает цифру, которая находится выше пустой клетки вниз.\n'
'➡️ - сдивает цифру, которая находится левее пустой клетки вправо.\n'
'⬅️ - сдивает цифру, которая находится правее пустой клетки влево.\n\n'
'<u>Теория пятнашек</u>:\n'
'Оригинальная игра в 15 (с произвольного порядка) может закончиться двумя развязками. Либо у вас получится поставить все числа в нужном порядке, либо числа 14 и 15 всегда будут стоять на местах друг друга. В оригинальной версии игры нужно было вытащить эти 2 последние цифры и вставить в нужном порядке. В боте же, <code>все комбинации являются победными</code>. Если у вас что-то не получается - пытайтесь еще)'
'', parse_mode='HTML', reply_markup=markup)
elif message.text == '🏆Рейтинг':
markup = types.InlineKeyboardMarkup(row_width=1)
close = types.InlineKeyboardButton('❎Закрыть меню', callback_data='close')
markup.add(close)
conn = sqlite3.connect('rating.db')
cur = conn.cursor()
cur.execute('SELECT user_id, score, nickname, username FROM users')
base = []
while True:
idd = cur.fetchone()
if idd == None: break
base.append(idd)
base.sort(key=lambda x: x[1])
vivod = ''
for i in range(1,11):
if len(base)+1 == i:
break
element = base[len(base)-i]
if element[3] != 'None':
vivod += f'{i}. <a href="t.me/{element[3]}">{element[2]}</a> - ⚜️{element[1]}\n'
else:
vivod += f'{i}. {element[2]} - ⚜️{element[1]}\n'
for i in range(len(base)):
if base[i][0] == message.chat.id:
position = i
break
vivod += f'\n Ваша позиция в топе: {len(base)-position}'
bot.send_message(message.chat.id, vivod, parse_mode='HTML', disable_web_page_preview=True, reply_markup=markup)
elif message.text == '⚙️Настройки':
markup = types.InlineKeyboardMarkup(row_width=1)
button1 = types.InlineKeyboardButton('✏️Изменить никнейм', callback_data='nick')
button2 = types.InlineKeyboardButton('👓Гиперссылка', callback_data='see_nick')
button3 = types.InlineKeyboardButton('❎Закрыть меню', callback_data='close')
markup.add(button1,button2,button3)
bot.send_message(message.chat.id, '⚙️Настройки:\n\n'
'✏️Изменить никнейм - поменять никнейм в таблице рейтинга.\n\n'
'👓Гиперссылка - можно <a href="https://t.me/lupikprojects">вкл</a>/выкл отображение никнейма с ссылкой на ваш тг профиль.', reply_markup=markup,
parse_mode='HTML', disable_web_page_preview=True)
else:
markup = types.InlineKeyboardMarkup()
markup1 = types.InlineKeyboardButton('📰Подписаться на канал', url='https://t.me/lupikprojects')
markup2 = types.InlineKeyboardButton('✅Проверить подписку', callback_data='subscription')
markup.add(markup1).row(markup2)
bot.send_message(message.chat.id, 'Для использования бота необходимо быть подписанным на канал.', reply_markup=markup)
def steps(message, game, msg):
bot.delete_message(message.chat.id, message.message_id)
if message.text == '⬆️':
if game.index(' ') + 4 < 16:
a = game.index(' ')
b = game.index(' ') + 4
game[a], game[b] = game[b], game[a]
markup2 = types.InlineKeyboardMarkup(row_width=4)
for i in range(0, 16, 4):
markup2.add(types.InlineKeyboardButton(f'{game[i]}', callback_data=f'{i}'),
types.InlineKeyboardButton(f'{game[i + 1]}', callback_data=f'{i + 1}'),
types.InlineKeyboardButton(f'{game[i + 2]}', callback_data=f'{i + 2}'),
types.InlineKeyboardButton(f'{game[i + 3]}', callback_data=f'{i + 3}'))
msg = bot.edit_message_text(chat_id=msg.chat.id, message_id=msg.id, text='Последний шаг: ⬆️',
reply_markup=markup2)
if game == [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, ' ']:
conn = sqlite3.connect('rating.db')
cur = conn.cursor()
cur.execute('SELECT user_id, score FROM users')
while True:
idd = cur.fetchone()
if idd == None:
break
if idd[0] == message.chat.id:
schet = idd[1]
break
cur.execute('UPDATE users SET score = ? WHERE user_id = ?', (schet + 1, message.chat.id))
conn.commit()
cur.close()
conn.close()
markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
button1 = types.KeyboardButton('🕹Начать игру')
button2 = types.KeyboardButton('❓Как играть?')
button3 = types.KeyboardButton('🏆Рейтинг')
button4 = types.KeyboardButton('⚙️Настройки')
markup.add(button1).row(button2, button3).row(button4)
bot.send_message(message.chat.id, 'Поздравляю! Вы выйграли!\n'
'Ваш рейтинг увеличен на 1.\n'
'Игра автоматически закроется через 3 секунды', reply_markup=markup)
time.sleep(3)
bot.delete_message(msg.chat.id, msg.message_id)
else:
bot.register_next_step_handler(msg, steps, game, msg)
elif message.text == '⬇️':
if game.index(' ') - 4 > -1:
a = game.index(' ')
b = game.index(' ')-4
game[a], game[b] = game[b], game[a]
markup2 = types.InlineKeyboardMarkup(row_width=4)
for i in range(0, 16, 4):
markup2.add(types.InlineKeyboardButton(f'{game[i]}', callback_data=f'{i}'),
types.InlineKeyboardButton(f'{game[i + 1]}', callback_data=f'{i + 1}'),
types.InlineKeyboardButton(f'{game[i + 2]}', callback_data=f'{i + 2}'),
types.InlineKeyboardButton(f'{game[i + 3]}', callback_data=f'{i + 3}'))
msg = bot.edit_message_text(chat_id=msg.chat.id, message_id=msg.id, text='Последний шаг: ⬇️',
reply_markup=markup2)
if game == [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, ' ']:
conn = sqlite3.connect('rating.db')
cur = conn.cursor()
cur.execute('SELECT user_id, score FROM users')
while True:
idd = cur.fetchone()
if idd == None:
break
if idd[0] == message.chat.id:
schet = idd[1]
break
cur.execute('UPDATE users SET score = ? WHERE user_id = ?', (schet + 1, message.chat.id))
conn.commit()
cur.close()
conn.close()
markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
button1 = types.KeyboardButton('🕹Начать игру')
button2 = types.KeyboardButton('❓Как играть?')
button3 = types.KeyboardButton('🏆Рейтинг')
button4 = types.KeyboardButton('⚙️Настройки')
markup.add(button1).row(button2, button3).row(button4)
bot.send_message(message.chat.id, 'Поздравляю! Вы выйграли!\n'
'Ваш рейтинг увеличен на 1.\n'
'Игра автоматически закроется через 3 секунды', reply_markup=markup)
time.sleep(3)
bot.delete_message(msg.chat.id, msg.message_id)
else:
bot.register_next_step_handler(msg, steps, game, msg)
elif message.text == '➡️':
if game.index(' ') - 1 not in [-1,3,7,11]:
a = game.index(' ')
b = game.index(' ') - 1
game[a], game[b] = game[b], game[a]
markup2 = types.InlineKeyboardMarkup(row_width=4)
for i in range(0, 16, 4):
markup2.add(types.InlineKeyboardButton(f'{game[i]}', callback_data=f'{i}'),
types.InlineKeyboardButton(f'{game[i + 1]}', callback_data=f'{i + 1}'),
types.InlineKeyboardButton(f'{game[i + 2]}', callback_data=f'{i + 2}'),
types.InlineKeyboardButton(f'{game[i + 3]}', callback_data=f'{i + 3}'))
msg = bot.edit_message_text(chat_id=msg.chat.id, message_id=msg.id, text='Последний шаг: ➡️',
reply_markup=markup2)
if game == [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, ' ']:
conn = sqlite3.connect('rating.db')
cur = conn.cursor()
cur.execute('SELECT user_id, score FROM users')
while True:
idd = cur.fetchone()
if idd == None:
break
if idd[0] == message.chat.id:
schet = idd[1]
break
cur.execute('UPDATE users SET score = ? WHERE user_id = ?', (schet + 1, message.chat.id))
conn.commit()
cur.close()
conn.close()
markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
button1 = types.KeyboardButton('🕹Начать игру')
button2 = types.KeyboardButton('❓Как играть?')
button3 = types.KeyboardButton('🏆Рейтинг')
button4 = types.KeyboardButton('⚙️Настройки')
markup.add(button1).row(button2, button3).row(button4)
bot.send_message(message.chat.id, 'Поздравляю! Вы выйграли!\n'
'Ваш рейтинг увеличен на 1.\n'
'Игра автоматически закроется через 3 секунды', reply_markup=markup)
time.sleep(3)
bot.delete_message(msg.chat.id, msg.message_id)
else:
bot.register_next_step_handler(msg, steps, game, msg)
elif message.text == '⬅️':
if game.index(' ') + 1 not in [4,8,12,16]:
a = game.index(' ')
b = game.index(' ') + 1
game[a], game[b] = game[b], game[a]
markup2 = types.InlineKeyboardMarkup(row_width=4)
for i in range(0, 16, 4):
markup2.add(types.InlineKeyboardButton(f'{game[i]}', callback_data=f'{i}'),
types.InlineKeyboardButton(f'{game[i + 1]}', callback_data=f'{i + 1}'),
types.InlineKeyboardButton(f'{game[i + 2]}', callback_data=f'{i + 2}'),
types.InlineKeyboardButton(f'{game[i + 3]}', callback_data=f'{i + 3}'))
msg = bot.edit_message_text(chat_id=msg.chat.id, message_id=msg.id, text='Последний шаг: ⬅️',
reply_markup=markup2)
if game == [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, ' ']:
conn = sqlite3.connect('rating.db')
cur = conn.cursor()
cur.execute('SELECT user_id, score FROM users')
while True:
idd = cur.fetchone()
if idd == None:
break
if idd[0] == message.chat.id:
schet = idd[1]
break
cur.execute('UPDATE users SET score = ? WHERE user_id = ?', (schet + 1, message.chat.id))
conn.commit()
cur.close()
conn.close()
markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
button1 = types.KeyboardButton('🕹Начать игру')
button2 = types.KeyboardButton('❓Как играть?')
button3 = types.KeyboardButton('🏆Рейтинг')
button4 = types.KeyboardButton('⚙️Настройки')
markup.add(button1).row(button2, button3).row(button4)
bot.send_message(message.chat.id, 'Поздравляю! Вы выйграли!\n'
'Ваш рейтинг увеличен на 1.\n'
'Игра автоматически закроется через 3 секунды', reply_markup=markup)
time.sleep(3)
bot.delete_message(msg.chat.id, msg.message_id)
else:
bot.register_next_step_handler(msg, steps, game, msg)
elif message.text == '💥Завершить игру':
markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
yes = types.KeyboardButton('✅Да')
no = types.KeyboardButton('🚫Нет')
markup.add(yes, no)
bot.send_message(message.chat.id, 'Вы уверены, что хотите сдаться?', reply_markup=markup)
bot.register_next_step_handler(msg, steps, game, msg)
elif message.text == '✅Да':
bot.delete_message(msg.chat.id, msg.message_id)
markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
button1 = types.KeyboardButton('🕹Начать игру')
button2 = types.KeyboardButton('❓Как играть?')
button3 = types.KeyboardButton('🏆Рейтинг')
button4 = types.KeyboardButton('⚙️Настройки')
markup.add(button1).row(button2, button3).row(button4)
bot.send_message(message.chat.id, 'Игра окончена.\nВы сдались(', reply_markup=markup)
elif message.text == '🚫Нет':
markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
up = types.KeyboardButton('⬆️')
left = types.KeyboardButton('⬅️')
right = types.KeyboardButton('➡️')
down = types.KeyboardButton('⬇️')
game_ower = types.KeyboardButton('💥Завершить игру')
markup.add(up).row(left, right).row(down).row(game_ower)
bot.send_message(message.chat.id, 'Продолжайте игру!', reply_markup = markup)
bot.register_next_step_handler(msg, steps, game, msg)
else:
bot.register_next_step_handler(msg, steps, game, msg)
def new_nickname(message):
conn = sqlite3.connect('rating.db')
cur = conn.cursor()
cur.execute('UPDATE users SET nickname = ? WHERE user_id = ?', (message.text, message.chat.id))
conn.commit()
cur.close()
conn.close()
bot.send_message(message.chat.id, 'Никнейм изменен.')
bot.polling(none_stop=True)