Amazing-Python-Scripts

Форк
0
172 строки · 3.7 Кб
1
from tkinter import *
2
import random
3

4
GAME_WIDTH = 600
5
GAME_HEIGHT = 600
6
SPEED = 100
7
SPACE_SIZE = 20
8
BODY_PARTS = 3
9
SNAKE_COLOUR = "#00FF00"
10
FOOD_COLOUR = "#FF0000"
11
BACKGROUND_COLOUR = "#000000"
12

13

14
class Snake:
15

16
    def __init__(self):
17
        self.body_size = BODY_PARTS
18
        self.coordinates = []
19
        self.squares = []
20

21
        for i in range(0, BODY_PARTS):
22
            self.coordinates.append([0, 0])
23

24
        for x, y in self.coordinates:
25
            square = canvas.create_rectangle(
26
                x, y, x + SPACE_SIZE, y + SPACE_SIZE, fill=SNAKE_COLOUR, tag="snake")
27
            self.squares.append(square)
28

29

30
class Food:
31

32
    def __init__(self):
33

34
        x = random.randint(0, (GAME_WIDTH/SPACE_SIZE)-1) * SPACE_SIZE
35
        y = random.randint(0, (GAME_HEIGHT/SPACE_SIZE)-1) * SPACE_SIZE
36

37
        self.coordinates = [x, y]
38

39
        canvas.create_oval(x, y, x + SPACE_SIZE, y+SPACE_SIZE,
40
                           fill=FOOD_COLOUR, tag="food")
41

42

43
def next_turn(snake, food):
44

45
    x, y = snake.coordinates[0]
46

47
    if direction == 'up':
48
        y -= SPACE_SIZE
49

50
    elif direction == 'down':
51
        y += SPACE_SIZE
52

53
    elif direction == 'left':
54
        x -= SPACE_SIZE
55

56
    elif direction == 'right':
57
        x += SPACE_SIZE
58

59
    snake.coordinates.insert(0, (x, y))
60

61
    square = canvas.create_rectangle(
62
        x, y, x + SPACE_SIZE, y + SPACE_SIZE, fill=SNAKE_COLOUR)
63

64
    snake.squares.insert(0, square)
65

66
    if x == food.coordinates[0] and y == food.coordinates[1]:
67

68
        global score
69

70
        score += 1
71

72
        label.config(text="Score: {}".format(score))
73

74
        canvas.delete("food")
75

76
        food = Food()
77

78
    else:
79
        del snake.coordinates[-1]
80

81
        canvas.delete(snake.squares[-1])
82

83
        del snake.squares[-1]
84

85
    if check_collisons(snake):
86
        game_over()
87

88
    else:
89
        window.after(SPEED, next_turn, snake, food)
90

91

92
def change_direction(new_direction):
93

94
    global direction
95

96
    if new_direction == 'left':
97
        if direction != 'right':
98
            direction = new_direction
99

100
    elif new_direction == 'right':
101
        if direction != 'left':
102
            direction = new_direction
103

104
    if new_direction == 'up':
105
        if direction != 'down':
106
            direction = new_direction
107

108
    if new_direction == 'down':
109
        if direction != 'up':
110
            direction = new_direction
111

112

113
def check_collisons(snake):
114
    x, y = snake.coordinates[0]
115

116
    if x < 0 or x >= GAME_WIDTH:
117
        return True
118
    elif y < 0 or y >= GAME_HEIGHT:
119
        return True
120

121
    for body_part in snake.coordinates[1:]:
122
        if x == body_part[0] and y == body_part[1]:
123
            return True
124

125
    return False
126

127

128
def game_over():
129
    # canvas.delete(ALL)
130
    canvas.create_text(canvas.winfo_width()/2, canvas.winfo_height()/2,
131
                       font=('consolas', 70), text="GAME OVER", fill="red", tag="gameover")
132

133
    reset_button = Button(text="Restart", font=('consolas', 20), command=reset)
134
    canvas.create_window(300, 400, window=reset_button)
135

136

137
def reset():
138
    score = 0
139
    label.config(text="Score:{}".format(score))
140
    canvas.delete(ALL)
141

142
    snake = Snake()
143
    food = Food()
144
    next_turn(snake, food)
145

146

147
window = Tk()
148
window.title("Snake Game")
149
window.resizable(False, False)
150

151
score = 0
152
direction = 'down'
153

154
label = Label(window, text="Score:{}".format(score), font=('consolas', 40))
155
label.pack()
156

157
canvas = Canvas(window, bg=BACKGROUND_COLOUR,
158
                height=GAME_HEIGHT, width=GAME_WIDTH)
159
canvas.pack()
160

161
window.bind('<Left>', lambda event: change_direction('left'))
162
window.bind('<Right>', lambda event: change_direction('right'))
163
window.bind('<Up>', lambda event: change_direction('up'))
164
window.bind('<Down>', lambda event: change_direction('down'))
165

166
snake = Snake()
167

168
food = Food()
169

170
next_turn(snake, food)
171

172
window.mainloop()
173

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

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

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

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