Amazing-Python-Scripts

Форк
0
487 строк · 20.1 Кб
1
################################################### Scientific Calculator ###################################################
2
############################################### Contributed By Avdhesh Varshney #############################################
3
############################################ (https://github.com/Avdhesh-Varshney) ##########################################
4

5
# Importing Modules
6
import pygame
7

8
# Initialising pygame module
9
pygame.init()
10

11
# Setting Width and height of the Chess Game screen
12
WIDTH = 800
13
HEIGHT = 800
14

15
screen = pygame.display.set_mode([WIDTH, HEIGHT])
16
pygame.display.set_caption('Two-Player Chess Game')
17

18
font = pygame.font.Font('freesansbold.ttf', 20)
19
medium_font = pygame.font.Font('freesansbold.ttf', 40)
20
big_font = pygame.font.Font('freesansbold.ttf', 50)
21

22
timer = pygame.time.Clock()
23
fps = 60
24

25
# game variables and images
26
white_pieces = ['rook', 'knight', 'bishop', 'king', 'queen', 'bishop', 'knight', 'rook',
27
                'pawn', 'pawn', 'pawn', 'pawn', 'pawn', 'pawn', 'pawn', 'pawn']
28
white_locations = [(0, 0), (1, 0), (2, 0), (3, 0), (4, 0), (5, 0), (6, 0), (7, 0),
29
                   (0, 1), (1, 1), (2, 1), (3, 1), (4, 1), (5, 1), (6, 1), (7, 1)]
30
black_pieces = ['rook', 'knight', 'bishop', 'king', 'queen', 'bishop', 'knight', 'rook',
31
                'pawn', 'pawn', 'pawn', 'pawn', 'pawn', 'pawn', 'pawn', 'pawn']
32
black_locations = [(0, 7), (1, 7), (2, 7), (3, 7), (4, 7), (5, 7), (6, 7), (7, 7),
33
                   (0, 6), (1, 6), (2, 6), (3, 6), (4, 6), (5, 6), (6, 6), (7, 6)]
34

35
captured_pieces_white = []
36
captured_pieces_black = []
37

38
# 0 - whites turn no selection: 1-whites turn piece selected: 2- black turn no selection, 3 - black turn piece selected
39
turn_step = 0
40
selection = 100
41
valid_moves = []
42

43
# load in game piece images (queen, king, rook, bishop, knight, pawn) x 2
44
black_queen = pygame.image.load('./images/black queen.png')
45
black_queen = pygame.transform.scale(black_queen, (80, 80))
46
black_queen_small = pygame.transform.scale(black_queen, (45, 45))
47
black_king = pygame.image.load('./images/black king.png')
48
black_king = pygame.transform.scale(black_king, (80, 80))
49
black_king_small = pygame.transform.scale(black_king, (45, 45))
50
black_rook = pygame.image.load('./images/black rook.png')
51
black_rook = pygame.transform.scale(black_rook, (80, 80))
52
black_rook_small = pygame.transform.scale(black_rook, (45, 45))
53
black_bishop = pygame.image.load('./images/black bishop.png')
54
black_bishop = pygame.transform.scale(black_bishop, (80, 80))
55
black_bishop_small = pygame.transform.scale(black_bishop, (45, 45))
56
black_knight = pygame.image.load('./images/black knight.png')
57
black_knight = pygame.transform.scale(black_knight, (80, 80))
58
black_knight_small = pygame.transform.scale(black_knight, (45, 45))
59
black_pawn = pygame.image.load('./images/black pawn.png')
60
black_pawn = pygame.transform.scale(black_pawn, (65, 65))
61
black_pawn_small = pygame.transform.scale(black_pawn, (45, 45))
62
white_queen = pygame.image.load('./images/white queen.png')
63
white_queen = pygame.transform.scale(white_queen, (80, 80))
64
white_queen_small = pygame.transform.scale(white_queen, (45, 45))
65
white_king = pygame.image.load('./images/white king.png')
66
white_king = pygame.transform.scale(white_king, (80, 80))
67
white_king_small = pygame.transform.scale(white_king, (45, 45))
68
white_rook = pygame.image.load('./images/white rook.png')
69
white_rook = pygame.transform.scale(white_rook, (80, 80))
70
white_rook_small = pygame.transform.scale(white_rook, (45, 45))
71
white_bishop = pygame.image.load('./images/white bishop.png')
72
white_bishop = pygame.transform.scale(white_bishop, (80, 80))
73
white_bishop_small = pygame.transform.scale(white_bishop, (45, 45))
74
white_knight = pygame.image.load('./images/white knight.png')
75
white_knight = pygame.transform.scale(white_knight, (80, 80))
76
white_knight_small = pygame.transform.scale(white_knight, (45, 45))
77
white_pawn = pygame.image.load('./images/white pawn.png')
78
white_pawn = pygame.transform.scale(white_pawn, (65, 65))
79
white_pawn_small = pygame.transform.scale(white_pawn, (45, 45))
80

81
white_images = [white_pawn, white_queen, white_king,
82
                white_knight, white_rook, white_bishop]
83
small_white_images = [white_pawn_small, white_queen_small, white_king_small, white_knight_small,
84
                      white_rook_small, white_bishop_small]
85

86
black_images = [black_pawn, black_queen, black_king,
87
                black_knight, black_rook, black_bishop]
88
small_black_images = [black_pawn_small, black_queen_small, black_king_small, black_knight_small,
89
                      black_rook_small, black_bishop_small]
90

91
piece_list = ['pawn', 'queen', 'king', 'knight', 'rook', 'bishop']
92

93
# check variables/ flashing counter
94
counter = 0
95
winner = ''
96
game_over = False
97

98

99
# draw main game board
100
def draw_board():
101
    for i in range(32):
102
        column = i % 4
103
        row = i // 4
104
        if row % 2 == 0:
105
            pygame.draw.rect(screen, 'light gray', [
106
                             600 - (column * 200), row * 100, 100, 100])
107
        else:
108
            pygame.draw.rect(screen, 'light gray', [
109
                             700 - (column * 200), row * 100, 100, 100])
110
        pygame.draw.rect(screen, 'gray', [0, 800, WIDTH, 100])
111
        pygame.draw.rect(screen, 'gold', [0, 800, WIDTH, 100], 5)
112
        pygame.draw.rect(screen, 'gold', [800, 0, 200, HEIGHT], 5)
113
        status_text = ['White: Select a Piece to Move!', 'White: Select a Destination!',
114
                       'Black: Select a Piece to Move!', 'Black: Select a Destination!']
115
        screen.blit(big_font.render(
116
            status_text[turn_step], True, 'black'), (20, 820))
117
        for i in range(9):
118
            pygame.draw.line(screen, 'black', (0, 100 * i), (800, 100 * i), 2)
119
            pygame.draw.line(screen, 'black', (100 * i, 0), (100 * i, 800), 2)
120
        screen.blit(medium_font.render('FORFEIT', True, 'black'), (810, 830))
121

122

123
# draw pieces onto board
124
def draw_pieces():
125
    for i in range(len(white_pieces)):
126
        index = piece_list.index(white_pieces[i])
127
        if white_pieces[i] == 'pawn':
128
            screen.blit(
129
                white_pawn, (white_locations[i][0] * 100 + 22, white_locations[i][1] * 100 + 30))
130
        else:
131
            screen.blit(white_images[index], (white_locations[i]
132
                        [0] * 100 + 10, white_locations[i][1] * 100 + 10))
133
        if turn_step < 2:
134
            if selection == i:
135
                pygame.draw.rect(screen, 'red', [white_locations[i][0] * 100 + 1, white_locations[i][1] * 100 + 1,
136
                                                 100, 100], 2)
137

138
    for i in range(len(black_pieces)):
139
        index = piece_list.index(black_pieces[i])
140
        if black_pieces[i] == 'pawn':
141
            screen.blit(
142
                black_pawn, (black_locations[i][0] * 100 + 22, black_locations[i][1] * 100 + 30))
143
        else:
144
            screen.blit(black_images[index], (black_locations[i]
145
                        [0] * 100 + 10, black_locations[i][1] * 100 + 10))
146
        if turn_step >= 2:
147
            if selection == i:
148
                pygame.draw.rect(screen, 'blue', [black_locations[i][0] * 100 + 1, black_locations[i][1] * 100 + 1,
149
                                                  100, 100], 2)
150

151

152
# function to check all pieces valid options on board
153
def check_options(pieces, locations, turn):
154
    moves_list = []
155
    all_moves_list = []
156
    for i in range((len(pieces))):
157
        location = locations[i]
158
        piece = pieces[i]
159
        if piece == 'pawn':
160
            moves_list = check_pawn(location, turn)
161
        elif piece == 'rook':
162
            moves_list = check_rook(location, turn)
163
        elif piece == 'knight':
164
            moves_list = check_knight(location, turn)
165
        elif piece == 'bishop':
166
            moves_list = check_bishop(location, turn)
167
        elif piece == 'queen':
168
            moves_list = check_queen(location, turn)
169
        elif piece == 'king':
170
            moves_list = check_king(location, turn)
171
        all_moves_list.append(moves_list)
172
    return all_moves_list
173

174

175
# check king valid moves
176
def check_king(position, color):
177
    moves_list = []
178
    if color == 'white':
179
        enemies_list = black_locations
180
        friends_list = white_locations
181
    else:
182
        friends_list = black_locations
183
        enemies_list = white_locations
184
    # 8 squares to check for kings, they can go one square any direction
185
    targets = [(1, 0), (1, 1), (1, -1), (-1, 0),
186
               (-1, 1), (-1, -1), (0, 1), (0, -1)]
187
    for i in range(8):
188
        target = (position[0] + targets[i][0], position[1] + targets[i][1])
189
        if target not in friends_list and 0 <= target[0] <= 7 and 0 <= target[1] <= 7:
190
            moves_list.append(target)
191
    return moves_list
192

193

194
# check queen valid moves
195
def check_queen(position, color):
196
    moves_list = check_bishop(position, color)
197
    second_list = check_rook(position, color)
198
    for i in range(len(second_list)):
199
        moves_list.append(second_list[i])
200
    return moves_list
201

202

203
# check bishop moves
204
def check_bishop(position, color):
205
    moves_list = []
206
    if color == 'white':
207
        enemies_list = black_locations
208
        friends_list = white_locations
209
    else:
210
        friends_list = black_locations
211
        enemies_list = white_locations
212
    for i in range(4):  # up-right, up-left, down-right, down-left
213
        path = True
214
        chain = 1
215
        if i == 0:
216
            x = 1
217
            y = -1
218
        elif i == 1:
219
            x = -1
220
            y = -1
221
        elif i == 2:
222
            x = 1
223
            y = 1
224
        else:
225
            x = -1
226
            y = 1
227
        while path:
228
            if (position[0] + (chain * x), position[1] + (chain * y)) not in friends_list and \
229
                    0 <= position[0] + (chain * x) <= 7 and 0 <= position[1] + (chain * y) <= 7:
230
                moves_list.append(
231
                    (position[0] + (chain * x), position[1] + (chain * y)))
232
                if (position[0] + (chain * x), position[1] + (chain * y)) in enemies_list:
233
                    path = False
234
                chain += 1
235
            else:
236
                path = False
237
    return moves_list
238

239

240
# check rook moves
241
def check_rook(position, color):
242
    moves_list = []
243
    if color == 'white':
244
        enemies_list = black_locations
245
        friends_list = white_locations
246
    else:
247
        friends_list = black_locations
248
        enemies_list = white_locations
249
    for i in range(4):  # down, up, right, left
250
        path = True
251
        chain = 1
252
        if i == 0:
253
            x = 0
254
            y = 1
255
        elif i == 1:
256
            x = 0
257
            y = -1
258
        elif i == 2:
259
            x = 1
260
            y = 0
261
        else:
262
            x = -1
263
            y = 0
264
        while path:
265
            if (position[0] + (chain * x), position[1] + (chain * y)) not in friends_list and \
266
                    0 <= position[0] + (chain * x) <= 7 and 0 <= position[1] + (chain * y) <= 7:
267
                moves_list.append(
268
                    (position[0] + (chain * x), position[1] + (chain * y)))
269
                if (position[0] + (chain * x), position[1] + (chain * y)) in enemies_list:
270
                    path = False
271
                chain += 1
272
            else:
273
                path = False
274
    return moves_list
275

276

277
# check valid pawn moves
278
def check_pawn(position, color):
279
    moves_list = []
280
    if color == 'white':
281
        if (position[0], position[1] + 1) not in white_locations and \
282
                (position[0], position[1] + 1) not in black_locations and position[1] < 7:
283
            moves_list.append((position[0], position[1] + 1))
284
        if (position[0], position[1] + 2) not in white_locations and \
285
                (position[0], position[1] + 2) not in black_locations and position[1] == 1:
286
            moves_list.append((position[0], position[1] + 2))
287
        if (position[0] + 1, position[1] + 1) in black_locations:
288
            moves_list.append((position[0] + 1, position[1] + 1))
289
        if (position[0] - 1, position[1] + 1) in black_locations:
290
            moves_list.append((position[0] - 1, position[1] + 1))
291
    else:
292
        if (position[0], position[1] - 1) not in white_locations and \
293
                (position[0], position[1] - 1) not in black_locations and position[1] > 0:
294
            moves_list.append((position[0], position[1] - 1))
295
        if (position[0], position[1] - 2) not in white_locations and \
296
                (position[0], position[1] - 2) not in black_locations and position[1] == 6:
297
            moves_list.append((position[0], position[1] - 2))
298
        if (position[0] + 1, position[1] - 1) in white_locations:
299
            moves_list.append((position[0] + 1, position[1] - 1))
300
        if (position[0] - 1, position[1] - 1) in white_locations:
301
            moves_list.append((position[0] - 1, position[1] - 1))
302
    return moves_list
303

304

305
# check valid knight moves
306
def check_knight(position, color):
307
    moves_list = []
308
    if color == 'white':
309
        enemies_list = black_locations
310
        friends_list = white_locations
311
    else:
312
        friends_list = black_locations
313
        enemies_list = white_locations
314
    # 8 squares to check for knights, they can go two squares in one direction and one in another
315
    targets = [(1, 2), (1, -2), (2, 1), (2, -1),
316
               (-1, 2), (-1, -2), (-2, 1), (-2, -1)]
317
    for i in range(8):
318
        target = (position[0] + targets[i][0], position[1] + targets[i][1])
319
        if target not in friends_list and 0 <= target[0] <= 7 and 0 <= target[1] <= 7:
320
            moves_list.append(target)
321
    return moves_list
322

323

324
# check for valid moves for just selected piece
325
def check_valid_moves():
326
    if turn_step < 2:
327
        options_list = white_options
328
    else:
329
        options_list = black_options
330
    valid_options = options_list[selection]
331
    return valid_options
332

333

334
# draw valid moves on screen
335
def draw_valid(moves):
336
    if turn_step < 2:
337
        color = 'red'
338
    else:
339
        color = 'blue'
340
    for i in range(len(moves)):
341
        pygame.draw.circle(
342
            screen, color, (moves[i][0] * 100 + 50, moves[i][1] * 100 + 50), 5)
343

344

345
# draw captured pieces on side of screen
346
def draw_captured():
347
    for i in range(len(captured_pieces_white)):
348
        captured_piece = captured_pieces_white[i]
349
        index = piece_list.index(captured_piece)
350
        screen.blit(small_black_images[index], (825, 5 + 50 * i))
351
    for i in range(len(captured_pieces_black)):
352
        captured_piece = captured_pieces_black[i]
353
        index = piece_list.index(captured_piece)
354
        screen.blit(small_white_images[index], (925, 5 + 50 * i))
355

356

357
# draw a flashing square around king if in check
358
def draw_check():
359
    if turn_step < 2:
360
        if 'king' in white_pieces:
361
            king_index = white_pieces.index('king')
362
            king_location = white_locations[king_index]
363
            for i in range(len(black_options)):
364
                if king_location in black_options[i]:
365
                    if counter < 15:
366
                        pygame.draw.rect(screen, 'dark red', [white_locations[king_index][0] * 100 + 1,
367
                                                              white_locations[king_index][1] * 100 + 1, 100, 100], 5)
368
    else:
369
        if 'king' in black_pieces:
370
            king_index = black_pieces.index('king')
371
            king_location = black_locations[king_index]
372
            for i in range(len(white_options)):
373
                if king_location in white_options[i]:
374
                    if counter < 15:
375
                        pygame.draw.rect(screen, 'dark blue', [black_locations[king_index][0] * 100 + 1,
376
                                                               black_locations[king_index][1] * 100 + 1, 100, 100], 5)
377

378

379
def draw_game_over():
380
    pygame.draw.rect(screen, 'black', [200, 200, 400, 70])
381
    screen.blit(font.render(
382
        f'{winner} won the game!', True, 'white'), (210, 210))
383
    screen.blit(font.render(f'Press ENTER to Restart!',
384
                True, 'white'), (210, 240))
385

386

387
# main game loop
388
black_options = check_options(black_pieces, black_locations, 'black')
389
white_options = check_options(white_pieces, white_locations, 'white')
390
run = True
391
while run:
392
    timer.tick(fps)
393
    if counter < 30:
394
        counter += 1
395
    else:
396
        counter = 0
397
    screen.fill('dark gray')
398
    draw_board()
399
    draw_pieces()
400
    draw_captured()
401
    draw_check()
402
    if selection != 100:
403
        valid_moves = check_valid_moves()
404
        draw_valid(valid_moves)
405
    # event handling
406
    for event in pygame.event.get():
407
        if event.type == pygame.QUIT:
408
            run = False
409
        if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1 and not game_over:
410
            x_coord = event.pos[0] // 100
411
            y_coord = event.pos[1] // 100
412
            click_coords = (x_coord, y_coord)
413
            if turn_step <= 1:
414
                if click_coords == (8, 8) or click_coords == (9, 8):
415
                    winner = 'black'
416
                if click_coords in white_locations:
417
                    selection = white_locations.index(click_coords)
418
                    if turn_step == 0:
419
                        turn_step = 1
420
                if click_coords in valid_moves and selection != 100:
421
                    white_locations[selection] = click_coords
422
                    if click_coords in black_locations:
423
                        black_piece = black_locations.index(click_coords)
424
                        captured_pieces_white.append(black_pieces[black_piece])
425
                        if black_pieces[black_piece] == 'king':
426
                            winner = 'white'
427
                        black_pieces.pop(black_piece)
428
                        black_locations.pop(black_piece)
429
                    black_options = check_options(
430
                        black_pieces, black_locations, 'black')
431
                    white_options = check_options(
432
                        white_pieces, white_locations, 'white')
433
                    turn_step = 2
434
                    selection = 100
435
                    valid_moves = []
436
            if turn_step > 1:
437
                if click_coords == (8, 8) or click_coords == (9, 8):
438
                    winner = 'white'
439
                if click_coords in black_locations:
440
                    selection = black_locations.index(click_coords)
441
                    if turn_step == 2:
442
                        turn_step = 3
443
                if click_coords in valid_moves and selection != 100:
444
                    black_locations[selection] = click_coords
445
                    if click_coords in white_locations:
446
                        white_piece = white_locations.index(click_coords)
447
                        captured_pieces_black.append(white_pieces[white_piece])
448
                        if white_pieces[white_piece] == 'king':
449
                            winner = 'black'
450
                        white_pieces.pop(white_piece)
451
                        white_locations.pop(white_piece)
452
                    black_options = check_options(
453
                        black_pieces, black_locations, 'black')
454
                    white_options = check_options(
455
                        white_pieces, white_locations, 'white')
456
                    turn_step = 0
457
                    selection = 100
458
                    valid_moves = []
459
        if event.type == pygame.KEYDOWN and game_over:
460
            if event.key == pygame.K_RETURN:
461
                game_over = False
462
                winner = ''
463
                white_pieces = ['rook', 'knight', 'bishop', 'king', 'queen', 'bishop', 'knight', 'rook',
464
                                'pawn', 'pawn', 'pawn', 'pawn', 'pawn', 'pawn', 'pawn', 'pawn']
465
                white_locations = [(0, 0), (1, 0), (2, 0), (3, 0), (4, 0), (5, 0), (6, 0), (7, 0),
466
                                   (0, 1), (1, 1), (2, 1), (3, 1), (4, 1), (5, 1), (6, 1), (7, 1)]
467
                black_pieces = ['rook', 'knight', 'bishop', 'king', 'queen', 'bishop', 'knight', 'rook',
468
                                'pawn', 'pawn', 'pawn', 'pawn', 'pawn', 'pawn', 'pawn', 'pawn']
469
                black_locations = [(0, 7), (1, 7), (2, 7), (3, 7), (4, 7), (5, 7), (6, 7), (7, 7),
470
                                   (0, 6), (1, 6), (2, 6), (3, 6), (4, 6), (5, 6), (6, 6), (7, 6)]
471
                captured_pieces_white = []
472
                captured_pieces_black = []
473
                turn_step = 0
474
                selection = 100
475
                valid_moves = []
476
                black_options = check_options(
477
                    black_pieces, black_locations, 'black')
478
                white_options = check_options(
479
                    white_pieces, white_locations, 'white')
480

481
    if winner != '':
482
        game_over = True
483
        draw_game_over()
484

485
    pygame.display.flip()
486

487
pygame.quit()
488

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.