-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
267 lines (211 loc) · 10.1 KB
/
main.py
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
#Basic cross the road game using pygame
import sys, os, logging
import pygame
import highscore_sorting as hs
logging.basicConfig(level=logging.DEBUG,
filename='app.log',
filemode='w',
format='%(name)s - %(levelname)s - %(message)s')
os.environ['SDL_VIDEO_CENTERED'] = "1" #Centers game window in the middle of the screen
SCREEN_WIDHT = 800
SCREEN_HEIGHT = 800
SCREEN_TITLE = "Cross The Road"
WHITE_COLOR = (255, 255, 255)
BLACK_COLOR = (0, 0, 0)
clock = pygame.time.Clock()
pygame.font.init()
font = pygame.font.SysFont("comicsans", 75)
class Game:
TICK_RATE = 60 #Frame rate for the game
def __init__(self, image_path, title, width, height):
self.title = title
self.width = width
self.height = height
self.game_screen = pygame.display.set_mode((width, height))
self.game_screen.fill(WHITE_COLOR)
pygame.display.set_caption(title)
background_image = pygame.image.load(image_path)
self.image = pygame.transform.scale(background_image, (width, height))
def scores(self, player_name, score):
self.player_name = player_name
self.score = score
execution_path = os.getcwd()
f = open('highscore.txt','a')
write_msg = player_name, ",", str(score), "\n"
f.writelines(write_msg)
f.close()
def scoring(self, level_number, level_speed):
score_points = (level_number + level_speed) * 100
return score_points
def run_game_loop(self, level_speed, level_number, player_name):
is_game_over = False
did_win = False
direction = 0
self.player_name = player_name
player_character = PlayerCharacter("images/player.png", 375, 700, 50, 50)
enemy_0 = NonPlayerCharacter("images/enemy.png", 20, 600, 50, 50)
enemy_0.SPEED *= level_speed
enemy_1 = NonPlayerCharacter("images/enemy.png", self.width - 50, 400, 50, 50)
enemy_1.SPEED *= level_speed
enemy_2 = NonPlayerCharacter("images/enemy.png", 20, 200, 50, 50)
enemy_2.SPEED *= level_speed
treasure = GameObject("images/treasure.png", 375, 25, 50, 50)
while not is_game_over:
for event in pygame.event.get():
if event.type == pygame.QUIT:
is_game_over = True
elif event.type == pygame.KEYDOWN: #Event, when key is pressed
if event.key == pygame.K_ESCAPE:
pygame.quit()
quit()
elif event.key == pygame.K_SPACE:
#Display score on the screen when player press space button
text = font.render("Your Score: "+str(int(self.scoring(level_number, level_speed))), True, WHITE_COLOR)
self.game_screen.blit(text, (200, 300))
pygame.display.update()
clock.tick(1)
elif event.key == pygame.K_LSHIFT or event.key == pygame.K_RSHIFT:
#A funny message when player presses left or right shift key
text = font.render("This won't help you run faster!", True, WHITE_COLOR)
self.game_screen.blit(text, (25, 325))
pygame.display.update()
clock.tick(1)
elif event.key == pygame.K_TAB:
#Display highest scores when a player presses tab key
hs.main() #run the sorting file
from highscore_sorting import top_three_items
try_list = top_three_items
text1 = "Name|Score"
text2 = str(try_list[0]).translate(str.maketrans("","","[](),'")) #Remove
text3 = str(try_list[1]).translate(str.maketrans("","","[](),'")) #unnecassery
text4 = str(try_list[2]).translate(str.maketrans("","","[](),'")) #characters
display_text1 = font.render(text1, True, BLACK_COLOR)
display_text2 = font.render(text2, True, BLACK_COLOR)
display_text3 = font.render(text3, True, BLACK_COLOR)
display_text4 = font.render(text4, True, BLACK_COLOR)
self.game_screen.blit(display_text1, (250, 275))
self.game_screen.blit(display_text2, (250, 350))
self.game_screen.blit(display_text3, (250, 425))
self.game_screen.blit(display_text4, (250, 500))
pygame.display.update()
clock.tick(1)
elif event.key == pygame.K_UP:
direction = 1
elif event.key == pygame.K_DOWN:
direction = -1
elif event.type == pygame.KEYUP: #Event, when key is released
if event.key == pygame.K_UP or event.key == pygame.K_DOWN:
#Immediatly stop character from moving when a player releases the movement button
direction = 0
#logging.info(event) print all movements and key presses to the terminal
self.game_screen.fill(WHITE_COLOR) #Redraw the background image
self.game_screen.blit(self.image, (0, 0))
treasure.draw(self.game_screen)
player_character.move(direction, self.height)
player_character.draw(self.game_screen)
enemy_0.move(self.width)
enemy_0.draw(self.game_screen)
if level_number > 4: #Increasing difficulty, additional enemy
enemy_1.move(self.width)
enemy_1.draw(self.game_screen)
if level_number == 4: #Slow down speed when additional enemy appears
level_speed = 1
if level_number > 8: #Increasing difficulty, a total of 3 enemies
enemy_2.move(self.width)
enemy_2.draw(self.game_screen)
if level_number == 8: #Slow down speed when additional enemy appears
level_speed = 1
if player_character.detect_collision(enemy_0) == True:
is_game_over = True
did_win = False
text = font.render("You lost! Try again.", True, BLACK_COLOR)
self.game_screen.blit(text, (150, 300))
pygame.display.update()
clock.tick(1)
break
elif player_character.detect_collision(treasure):
is_game_over = True
did_win = True
text = font.render("You Win!", True, WHITE_COLOR)
self.game_screen.blit(text, (275, 300))
pygame.display.update()
clock.tick(1)
break
elif player_character.detect_collision(enemy_1) == True:
is_game_over = True
did_win = False
text = font.render("You lost! Don't rush!.", True, BLACK_COLOR)
self.game_screen.blit(text, (150, 300))
pygame.display.update()
clock.tick(1)
break
elif player_character.detect_collision(enemy_2) == True:
is_game_over = True
did_win = False
text = font.render("You lost! Almost there!.", True, BLACK_COLOR)
self.game_screen.blit(text, (150, 300))
pygame.display.update()
clock.tick(1)
break
pygame.display.update() #updates all game graphics
clock.tick(self.TICK_RATE)
if did_win:
self.run_game_loop(level_speed + 0.5, level_number + 1, self.player_name)
else:
self.scores(player_name, int(self.scoring(level_number, level_speed)))
hs.main() #run the sorting file
self.run_game_loop(1, 1, self.player_name)
class GameObject:
def __init__(self, image_path, x, y, width, height):
"""Path to image, coordinates on the screen, width and height of the object"""
object_image = pygame.image.load(image_path)
self.image = pygame.transform.scale(object_image, (width, height))
self.x_pos = x
self.y_pos = y
self.width = width
self.height = height
def draw(self, background):
background.blit(self.image, (self.x_pos, self.y_pos))
class PlayerCharacter(GameObject):
"""Character controled by a human player."""
SPEED = 8
def __init__(self, image_path, x, y, width, height):
super().__init__(image_path, x, y, width, height)
def move(self, direction, max_height):
if direction > 0: #Move up
self.y_pos -= self.SPEED
elif direction < 0: #Move down
self.y_pos += self.SPEED
if self.y_pos >= max_height - 50: #Do not allow to move out of screen
self.y_pos = max_height - 50
elif self.y_pos <= 0:
self.y_pos = 0
def detect_collision(self, another_entity):
"""Check if there's a collision with another entity"""
if self.y_pos > another_entity.y_pos + another_entity.height:
return False
elif self.y_pos + self.height < another_entity.y_pos:
return False
if self.x_pos > another_entity.x_pos + another_entity.width:
return False
elif self.x_pos + self.width < another_entity.x_pos:
return False
return True
class NonPlayerCharacter(GameObject):
SPEED = 5
def __init__(self, image_path, x, y, width, height):
super().__init__(image_path, x, y, width, height)
def move(self, max_width):
if self.x_pos <= 40:
self.SPEED = abs(self.SPEED)
elif self.x_pos >= max_width - 80:
self.SPEED = -abs(self.SPEED)
self.x_pos += self.SPEED
if __name__ == "__main__":
pygame.init()
new_game = Game("images/background.png", SCREEN_TITLE, SCREEN_WIDHT, SCREEN_HEIGHT)
score_points = 0
player_name = input("Enter your name:")
new_game.run_game_loop(1, 1, player_name)
pygame.quit()
quit()