-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
143 lines (99 loc) · 2.86 KB
/
main.py
File metadata and controls
143 lines (99 loc) · 2.86 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
import pygame
import random
pygame.init()
#creating game window
gameWindow =pygame.display.set_mode((900,600))
pygame.display.set_caption("Snakes!!")
clock=pygame.time.Clock()
font=pygame.font.Font(None,55)
# functions
def screen_text (text,colour,size,x,y):
font=pygame.font.Font(None,size)
screen_text=font.render(text,True,colour)
gameWindow.blit(screen_text,(x,y))
def plot_snake (gameWindow,colour,snake_list,snake_size):
for x,y in snake_list:
pygame.draw.rect(gameWindow,colour,[x,y,snake_size,snake_size])
#main game loop
def game_loop():
#game variables
white=(255,255,255)
green=(0,255,0)
red=(255,0,0)
black=(0,0,0)
exit_game=False
game_over=False
snake_x,snake_y=450,300
snake_size=30
vel_x,vel_y=0,0
food_x,food_y=random.randint(20,850),random.randint(20,550)
snake_list=[]
snake_length=1
score=0
fps=35
while not exit_game:
for event in pygame.event.get():
if event.type==pygame.QUIT:
exit_game=True
if event.type==pygame.KEYDOWN:
if not game_over:
if event.key==pygame.K_d:
vel_x=2
vel_y=0
if event.key==pygame.K_a:
vel_x=-2
vel_y=0
if event.key==pygame.K_w:
vel_y=-2
vel_x=0
if event.key==pygame.K_s:
vel_y=2
vel_x=0
else:
if event.key==pygame.K_RETURN:
exit_game=True
return exit_game
if game_over==True:
gameWindow.fill(white)
screen_text("Game Over!!",red,100,270,260)
screen_text("Press 'enter' to restart",black,40,300,320)
pygame.display.update()
clock.tick(fps)
continue
if abs(snake_x-food_x)<25 and abs(snake_y-food_y)<25:
score +=10
food_x=random.randint(20,850)
food_y=random.randint(20,550)
snake_length+=5
fps=min(35+(score//20)*5,60)
if snake_x==0 or snake_x==900 or snake_y==0 or snake_y==600:
score -=20
snake_x = vel_x + snake_x
snake_y+=vel_y
if snake_x<0:
snake_x=899
elif snake_x>900:
snake_x=1
if snake_y<0:
snake_y=599
elif snake_y>600:
snake_y=1
gameWindow.fill(white)
#snake tail growth
head=[snake_x,snake_y]
snake_list.append(head)
if len(snake_list)>snake_length:
del snake_list[0]
plot_snake(gameWindow,green,snake_list,snake_size)
pygame.draw.rect(gameWindow,red,[food_x,food_y,snake_size,snake_size])
if head in snake_list[:-1]:
game_over=True
if not game_over:
screen_text(("Score:"+str(score)),black,55,30,20)
pygame.display.update()
clock.tick(fps)
running=True
while running:
running=game_loop()
pygame.quit()
quit()