- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
Latest commit
350 lines (277 loc) · 11.4 KB
/
Copy pathmain.py
File metadata and controls
350 lines (277 loc) · 11.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
importmath
importtkinterastk
importnumpyasnp
importtime
classConstants:
"""Game configuration constants"""
WINDOW_WIDTH=800
WINDOW_HEIGHT=800
# Rendering settings
NUM_RAYS=800
FOV=math.pi/3# 60 degrees field of view
RENDER_DISTANCE=20
# Movement settings
MOVEMENT_SPEED=0.15
ROTATION_SPEED=0.08
# Visual settings
WALL_HEIGHT_SCALE=600
MIN_BRIGHTNESS=0.2
# Colors
SKY_COLOR="#87CEEB"
FLOOR_COLOR="#D2B48C"
WALL_BASE_COLOR="#D3D3D3"
classPlayer:
"""Handles player position, rotation and movement"""
def__init__(self, x=2.0, y=2.0, direction=math.pi/4):
self.x=x
self.y=y
self.direction=direction
defmove(self, dx, dy):
"""Move player by delta x and y"""
self.x+=dx
self.y+=dy
defrotate(self, angle_delta):
"""Rotate player by angle delta"""
self.direction+=angle_delta
# Keep angle in 0-2π range
self.direction=self.direction% (2*math.pi)
classGameMap:
"""Handles map data and collision detection"""
def__init__(self, arena_data):
self.arena=arena_data
self.height=len(arena_data)
self.width=len(arena_data[0]) ifself.height>0else0
defis_wall(self, x, y):
"""Check if position contains a wall"""
try:
grid_x, grid_y=int(x), int(y)
if0<=grid_x<self.heightand0<=grid_y<self.width:
returnself.arena[grid_x][grid_y] !=0
returnTrue# Consider out-of-bounds as walls
except (IndexError, ValueError):
returnTrue
defis_valid_position(self, x, y):
"""Check if position is valid for player movement"""
returnnotself.is_wall(x, y)
classRaycastRenderer:
"""Handles all rendering operations"""
def__init__(self, canvas, width, height):
self.canvas=canvas
self.width=width
self.height=height
defclear_screen(self):
"""Clear the canvas and draw sky/floor"""
self.canvas.delete("all")
# Draw sky
self.canvas.create_rectangle(
0, 0, self.width, self.height//2,
fill=Constants.SKY_COLOR, outline=""
)
# Draw floor
self.canvas.create_rectangle(
0, self.height//2, self.width, self.height,
fill=Constants.FLOOR_COLOR, outline=""
)
defcast_ray(self, game_map, start_x, start_y, angle):
"""Cast a single ray and return distance to wall"""
ray_dx=math.cos(angle)
ray_dy=math.sin(angle)
distance=0.0
step_size=0.05
x, y=start_x, start_y
whiledistance<Constants.RENDER_DISTANCE:
x+=ray_dx*step_size
y+=ray_dy*step_size
distance+=step_size
ifgame_map.is_wall(x, y):
returndistance
returnConstants.RENDER_DISTANCE
defcalculate_wall_brightness(self, distance):
"""Calculate wall brightness based on distance"""
ifdistance<=0:
return1.0
brightness=1.0- (distance/Constants.RENDER_DISTANCE)
returnmax(Constants.MIN_BRIGHTNESS, brightness)
defget_wall_color(self, brightness):
"""Get wall color based on brightness level"""
base_color=0x69# Base gray value
color_value=int(base_color*brightness)
returnf"#{color_value:02x}{color_value:02x}{color_value:02x}"
defdraw_wall_slice(self, x, wall_height, distance):
"""Draw a single vertical wall slice"""
brightness=self.calculate_wall_brightness(distance)
wall_color=self.get_wall_color(brightness)
# Calculate wall position
wall_top= (self.height-wall_height) //2
wall_bottom= (self.height+wall_height) //2
# Draw the wall slice
slice_width=self.width//Constants.NUM_RAYS
self.canvas.create_rectangle(
x, wall_top, x+slice_width, wall_bottom,
fill=wall_color, outline=""
)
defrender_scene(self, player, game_map):
"""Render the complete 3D scene"""
self.clear_screen()
# Calculate ray angles
start_angle=player.direction-Constants.FOV/2
angle_step=Constants.FOV/Constants.NUM_RAYS
foriinrange(Constants.NUM_RAYS):
ray_angle=start_angle+i*angle_step
# Cast ray and get distance
distance=self.cast_ray(game_map, player.x, player.y, ray_angle)
# Apply fish-eye correction
corrected_distance=distance*math.cos(ray_angle-player.direction)
# Calculate wall height
ifcorrected_distance>0:
wall_height=Constants.WALL_HEIGHT_SCALE/corrected_distance
else:
wall_height=Constants.WALL_HEIGHT_SCALE
# Limit wall height to screen
wall_height=min(wall_height, self.height)
# Draw wall slice
x_position=i* (self.width//Constants.NUM_RAYS)
self.draw_wall_slice(x_position, wall_height, corrected_distance)
classInputHandler:
"""Handles continuous input for smooth movement"""
def__init__(self, root):
self.root=root
self.keys_pressed=set()
self.setup_key_bindings()
defsetup_key_bindings(self):
"""Setup key press and release event handlers"""
self.root.bind('<KeyPress>', self.on_key_press)
self.root.bind('<KeyRelease>', self.on_key_release)
self.root.focus_set() # Ensure window has focus for key events
defon_key_press(self, event):
"""Handle key press events"""
self.keys_pressed.add(event.keysym.lower())
defon_key_release(self, event):
"""Handle key release events"""
self.keys_pressed.discard(event.keysym.lower())
defis_key_pressed(self, key):
"""Check if a specific key is currently pressed"""
returnkey.lower() inself.keys_pressed
classGame:
"""Main game class that orchestrates everything"""
def__init__(self):
# Initialize game components
self.setup_window()
self.setup_game_objects()
self.setup_input()
# Game loop control
self.running=True
self.last_update_time=time.time()
self.target_fps=60
defsetup_window(self):
"""Initialize the tkinter window and canvas"""
self.root=tk.Tk()
self.root.title("Enhanced 2.5D Raycasting Engine")
self.root.geometry(f"{Constants.WINDOW_WIDTH}x{Constants.WINDOW_HEIGHT}")
self.root.resizable(False, False)
self.canvas=tk.Canvas(
self.root,
width=Constants.WINDOW_WIDTH,
height=Constants.WINDOW_HEIGHT,
bg=Constants.SKY_COLOR
)
self.canvas.pack()
defsetup_game_objects(self):
"""Initialize game objects"""
# Game map
arena_data= [
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 1, 1, 1, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 1, 0, 1],
[1, 0, 0, 1, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 1, 0, 0, 0, 0, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
]
self.game_map=GameMap(arena_data)
self.player=Player(2.0, 2.0, math.pi/4)
self.renderer=RaycastRenderer(
self.canvas, Constants.WINDOW_WIDTH, Constants.WINDOW_HEIGHT
)
defsetup_input(self):
"""Setup input handling"""
self.input_handler=InputHandler(self.root)
# Bind escape key to quit
self.root.bind('<Escape>', lambdae: self.quit_game())
defupdate_player_movement(self):
"""Update player position based on currently pressed keys"""
moved=False
# Movement keys
ifself.input_handler.is_key_pressed('w'):
dx=math.cos(self.player.direction) *Constants.MOVEMENT_SPEED
dy=math.sin(self.player.direction) *Constants.MOVEMENT_SPEED
self.try_move_player(dx, dy)
moved=True
ifself.input_handler.is_key_pressed('s'):
dx=-math.cos(self.player.direction) *Constants.MOVEMENT_SPEED
dy=-math.sin(self.player.direction) *Constants.MOVEMENT_SPEED
self.try_move_player(dx, dy)
moved=True
ifself.input_handler.is_key_pressed('a'):
dx=math.sin(self.player.direction) *Constants.MOVEMENT_SPEED
dy=-math.cos(self.player.direction) *Constants.MOVEMENT_SPEED
self.try_move_player(dx, dy)
moved=True
ifself.input_handler.is_key_pressed('d'):
dx=-math.sin(self.player.direction) *Constants.MOVEMENT_SPEED
dy=math.cos(self.player.direction) *Constants.MOVEMENT_SPEED
self.try_move_player(dx, dy)
moved=True
# Rotation keys
ifself.input_handler.is_key_pressed('left'):
self.player.rotate(-Constants.ROTATION_SPEED)
moved=True
ifself.input_handler.is_key_pressed('right'):
self.player.rotate(Constants.ROTATION_SPEED)
moved=True
returnmoved
deftry_move_player(self, dx, dy):
"""Attempt to move player with collision detection"""
new_x=self.player.x+dx
new_y=self.player.y+dy
# Check collision for new position
ifself.game_map.is_valid_position(new_x, new_y):
self.player.move(dx, dy)
defupdate(self):
"""Main game update loop"""
current_time=time.time()
# Update player movement
moved=self.update_player_movement()
# Render scene if something changed or enough time has passed
ifmovedor (current_time-self.last_update_time) > (1.0/self.target_fps):
self.renderer.render_scene(self.player, self.game_map)
self.last_update_time=current_time
# Schedule next update
ifself.running:
self.root.after(16, self.update) # ~60 FPS
defquit_game(self):
"""Quit the game"""
self.running=False
self.root.quit()
defrun(self):
"""Start the game loop"""
# Initial render
self.renderer.render_scene(self.player, self.game_map)
# Start update loop
self.update()
# Start tkinter main loop
self.root.mainloop()
defmain():
"""Main entry point"""
try:
game=Game()
game.run()
exceptKeyboardInterrupt:
print("\nGame interrupted by user")
exceptExceptionase:
print(f"Game error: {e}")
if__name__=="__main__":
main()