Source

Squish the Bugs / roguelike / main.py

Full commit
  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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
'''
Created: Aug 4, 2013
Last modified: Aug 11, 2013 
'''

import pygame
import math
import sys
import random


######################################################################## engine

def get_stick(joy, axisX, axisY):
	state = ( joy.get_axis(axisX), joy.get_axis(axisY) )
	
	magSq = magnitudeSq2d(state)
	
	### The MadCatz controller reports a vector magnitude of >1 when the sticks
	### are tilted towards the corners, which seems to be because of a dead
	### zone around the outside. Normalizing the vector whenever its magnitude
	### is >1 seems to fix this.
	if magSq > 1:
		return normalize2d(state)
	
	dead_zone_radius = .2
	
	### Circular dead zone
	if magSq < dead_zone_radius ** 2:
		return (0, 0)
	
	### Scale usable input space so it goes from 0->1 instead of abruptly
	### jumping to the hardware's representation of the edge of the dead zone.
	mag = math.sqrt(magSq)
	max_mag = 1 - dead_zone_radius
	#new_mag = max_mag / mag
	new_mag = (mag - dead_zone_radius) / max_mag
	
	return mag_scale_to_2d(state, new_mag)

def sum2d(a, b):
	return (a[0] + b[0], a[1] + b[1])
def dif2d(a, b):
	return (a[0] - b[0], a[1] - b[1])

def sum3d(a, b):
	return (a[0] + b[0], a[1] + b[1], a[2] + b[2])

def magnitudeSq2d(vec):
	return vec[0] ** 2 + vec[1] ** 2
def magnitude2d(vec):
	return math.sqrt(magnitudeSq2d(vec))

def normalize2d(vec):
	return mag_scale_2d(vec, 1 / magnitude2d(vec))

def int2d(vec):
	return (int(vec[0]), int(vec[1]))

def mag_scale_2d(vec, scalar):
	return (vec[0] * scalar, vec[1] * scalar)
def mag_scale_to_2d(vec, scalar):
	if not math.isfinite(scalar):
		raise Exception() # because this was probably not intended
	#try:
	return mag_scale_2d(vec, scalar / magnitude2d(vec))
	#except:
	#	return (NaN, NaN)
	### Just let it throw when the vector has a magnitude of zero; there's no
	### real way to klodge that into a usable number because it would require
	### a direction.
	### A real programming language would allow this function to have
	### preconditions.

def flipY2d(vec):
	return (vec[0], -vec[1])
def flip2d(vec):
	return (-vec[0], -vec[1])

def scale2d(vec, scalar):
	return (vec[0] * scalar, vec[1] * scalar)
def basic_product_2d(a, b):
	return (a[0] * b[0], a[1] * b[1])
def negate2d(vec):
	return (-vec[0], -vec[1])

def negate3d(vec):
	return (-vec[0], -vec[1], -vec[2])


EVENT_DRAW = 100

event_handlers = [] # contains: (predicate:function, callback:function)
next_event_handlers = []
def proc_event(event):
	global event_handlers, next_event_handlers
	
	event_handlers = next_event_handlers
	next_event_handlers = list(event_handlers)
	for handler in event_handlers:
		#if handler == None: continue
		
		if handler[0](event):
			handler[1](event)
			
def proc_events():
	for event in pygame.event.get():
		proc_event(event)
		
def event_loop():
	while True:
		proc_events()
		proc_event(pygame.event.Event(EVENT_DRAW))
		#pygame.display.update()
		pygame.display.flip()

def on_event(predicate, callback):
	### TODO: take priorty as parameter so screen flip and hud drawing can be
	### registered in any order
	
	### TODO: what about attaching events to other events?
	
	removed = False
	def invoke(event):
		if removed: return
		
		callback(event)
	
	def remove(): ### TODO: Use linked list
		nonlocal removed
		if removed: return
		removed = True
		
		next_event_handlers.remove(handler)
	
	handler = (predicate, invoke)
	next_event_handlers.append(handler)
	return remove

def on_event_once(predicate, callback):
	stop = on_event(predicate, lambda a: (callback(a), stop()))


########################################################################### app

pygame.init()
#pygame.mouse.set_visible(False)
surface_screen = pygame.display.set_mode(
	#(0, 0),
	#(600, 400),
	(1024, 768),
	#(1280, 720),
	#(1440, 900),
	#(1600, 1200),
	#pygame.FULLSCREEN# |
	#| pygame.DOUBLEBUF
	#| pygame.HWSURFACE
)
pygame.display.set_caption('Roguelike v0.0.6')


class AppEvent:
	INPUT_DIRECTION, BLOCK_MOVED = range(1000, 1002)
class Direction:
	NORTH, EAST, SOUTH, WEST = range(4)

on_event(
	lambda a: a.type == pygame.KEYDOWN and a.key == pygame.K_UP,
	lambda a: proc_event(pygame.event.Event(AppEvent.INPUT_DIRECTION, direction=Direction.NORTH))
)
on_event(
	lambda a: a.type == pygame.KEYDOWN and a.key == pygame.K_DOWN,
	lambda a: proc_event(pygame.event.Event(AppEvent.INPUT_DIRECTION, direction=Direction.SOUTH))
)
on_event(
	lambda a: a.type == pygame.KEYDOWN and a.key == pygame.K_RIGHT,
	lambda a: proc_event(pygame.event.Event(AppEvent.INPUT_DIRECTION, direction=Direction.EAST))
)
on_event(
	lambda a: a.type == pygame.KEYDOWN and a.key == pygame.K_LEFT,
	lambda a: proc_event(pygame.event.Event(AppEvent.INPUT_DIRECTION, direction=Direction.WEST))
)

previous_hat = (0, 0)
def hat_to_direction4(event):
	global camera, previous_hat
	if event.value[0] != previous_hat[0]:
		if event.value[0] == 1:
			#proc_event(pygame.event.Event(AppEvent.EAST))
			proc_event(pygame.event.Event(AppEvent.INPUT_DIRECTION))
		elif event.value[0] == -1:
			#proc_event(pygame.event.Event(AppEvent.WEST))
			proc_event(pygame.event.Event(AppEvent.INPUT_DIRECTION))
	if event.value[1] != previous_hat[1]:
		if event.value[1] == 1:
			#proc_event(pygame.event.Event(AppEvent.NORTH))
			proc_event(pygame.event.Event(AppEvent.INPUT_DIRECTION))
		elif event.value[1] == -1:
			#proc_event(pygame.event.Event(AppEvent.SOUTH))
			proc_event(pygame.event.Event(AppEvent.INPUT_DIRECTION))
	previous_hat = event.value
on_event(lambda a: a.type == pygame.JOYHATMOTION, lambda a: hat_to_direction4(a))


on_event(lambda a: a.type == EVENT_DRAW, lambda a: surface_screen.fill(colorBG))
on_event(lambda a: a.type == pygame.QUIT, lambda a: sys.exit())
on_event(lambda a: a.type == pygame.KEYDOWN and a.key == pygame.K_ESCAPE, lambda a: sys.exit())

def draw_joy_input(event):
	#for joy in range(len(joysticks)):
	for joyIndex, joy in enumerate(joysticks):
		for button in range(joy.get_numbuttons()):
			pygame.draw.rect(
				surface_screen,
				(colorDebugToggleOn if joy.get_button(button) else colorDebugToggleOff),
				pygame.Rect(button * 40 + 5, joyIndex * 50 + 10, 30, 30)
			)
		#print(str(joy) + ': ' + str(joysticks[joy].get_axis(0)))
		
		sticks = [ (0, 1), (4, 3) ]
		for i in range(len(sticks)):
			axes = sticks[i]
			stick_center = ((joy.get_numbuttons() + i) * 40 + 5 + 15, joyIndex * 50 + 10 + 15)
			pygame.draw.circle(surface_screen, colorDebug0, stick_center, 15)
			pygame.draw.line(
				surface_screen, colorDebug1, stick_center,
				int2d(sum2d(stick_center, mag_scale_2d(get_stick(joy, axes[0], axes[1]), 15))),
				3
			)
		
		trigger_height = 30 * joy.get_axis(2)
		pygame.draw.rect(
			surface_screen,
			colorDebug0,
			pygame.Rect((joy.get_numbuttons() + i) * 40 + 5 + 40, joyIndex * 50 + 10, 30, 30)
		)
		if trigger_height > 0:
			pygame.draw.rect(
				surface_screen,
				colorDebugToggleOn,
				pygame.Rect((joy.get_numbuttons() + i) * 40 + 5 + 40, joyIndex * 50 + 10 + (30 - trigger_height), 30, trigger_height)
			)
		
		### so... pygame won't detect the right-side trigger?
		pygame.draw.rect(
			surface_screen,
			colorDebug0,
			pygame.Rect((joy.get_numbuttons() + i) * 40 + 5 + 80, joyIndex * 50 + 10, 30, 30)
		)
		
		for hat in range(joy.get_numhats()):
			hat_center = ((joy.get_numbuttons() + i) * 40 + 5 + 40 + 80 + 15, joyIndex * 50 + 10 + 15)
			pygame.draw.rect(
				surface_screen,
				colorDebug0,
				pygame.Rect((joy.get_numbuttons() + i) * 40 + 5 + 40 + 80, joyIndex * 50 + 10, 30, 30),
				3
			)
			pygame.draw.line(
				surface_screen, colorDebug1, hat_center,
				int2d(sum2d(hat_center, flipY2d(mag_scale_2d(joy.get_hat(hat), 15)))),
				3
			)
#on_event(lambda a: a.type == EVENT_DRAW, draw_joy_input)

colorBG = pygame.Color(255, 220, 255)
colorDebug0 = pygame.Color(190, 170, 170)
colorDebug1 = pygame.Color(150, 0, 0)
colorDebugToggleOn = pygame.Color(20, 170, 20)
colorDebugToggleOff = pygame.Color(160, 0, 0)
color_HUD = pygame.Color(255, 255, 255)
color_HUD_outline = pygame.Color(0, 0, 0)

joysticks = [pygame.joystick.Joystick(x) for x in range(pygame.joystick.get_count())]
for joy in joysticks:
	joy.init()




camera = ((0, 0, 0), 7) # ((x, y, z), view_height) ~~~ width depends on screen
#def move_camera(delta):
#	global camera
#	camera = (sum3d(camera[0], delta), camera[1])
### not used? ^

def move_camera_to(dest):
	if len(dest) != 3: raise Exception() 
	global camera
	camera = (dest, camera[1])
#def zoom_camera(delta):
#	global camera
#	camera = (camera[0], max(1, camera[1] + delta))


blocks = [] # contains: ((x, y, z), tile)
position_to_blocklist = {}
def update_blocks():
	blocks.sort(key=lambda a: a[0][2] * 10000 + a[0][1] + a[1][4] + (100000000 if a[1][5] else 0))
	position_to_blocklist.clear()
	for block in blocks:
		position = block[0]
		if position not in position_to_blocklist:
			position_to_blocklist[position] = []
		position_to_blocklist[position].append(block)

def remove_block(block):
	position_to_blocklist[block[0]].remove(block)
	if len(position_to_blocklist[block[0]]) == 0:
		del position_to_blocklist[block[0]]
	blocks.remove(block)
	proc_event(pygame.event.Event(AppEvent.BLOCK_MOVED, block=block, dest=None))
	
def is_block_at(position):
	return position in position_to_blocklist and len(position_to_blocklist[position]) > 0

def move_block_to(block, dest):
	block[0] = dest
	update_blocks()
	proc_event(pygame.event.Event(AppEvent.BLOCK_MOVED, block=block, dest=dest))
	
def move_block(block, delta):
	move_block_to(block, sum3d(block[0], delta))

def get_block_types_at(position):
	for block in get_blocks_at(position):
		yield block[2]
def get_blocks_at(position):
	if position in position_to_blocklist:
		#yield from position_to_blocklist[position]
		for block in position_to_blocklist[position]:
			yield block
def is_block_type_at(position, block_type):
	#for a in get_block_types_at(position):
	#	if a == block_type:
	#		return True
	#return False
	return block_type in get_block_types_at(position)
	
def move_player(block, delta):
	def is_obstacle_type(block_type):
		return block_type in (BlockType.BUG, BlockType.ROCK, BlockType.TREE, BlockType.FILLER)
	def is_obstacle_at(position):
		return len([x for x in get_block_types_at(position) if is_obstacle_type(x)]) > 0
	def on_fail():
		bubble = make_block(block[0], tile_speech, BlockType.SPEECH)
		on_event_once(lambda a: a.type == AppEvent.INPUT_DIRECTION, lambda a: remove_block(bubble))
		
		question = make_block(block[0], tile_question, BlockType.SPEECH)
		on_event_once(lambda a: a.type == AppEvent.INPUT_DIRECTION, lambda a: remove_block(question))
	
	dest = sum3d(block[0], delta)
	above = sum3d(dest, (0, 1, 0))
	
	if is_obstacle_at(dest):
		if is_obstacle_at(above):
			on_fail()
			return
		for block_type in get_block_types_at(dest):
			if block_type == BlockType.FILLER:
				move_block(block, sum3d(delta, (0, 1, 0)))
				return
		on_fail()
		return
	else:
		for i in range(1, 5):
			below = sum3d(dest, (0, -i, 0))
			
			for other_block in get_blocks_at(below):
				block_type = other_block[2]
				
				if block_type in (BlockType.FILLER, BlockType.ROCK):
					move_block(block, sum3d(delta, (0, 1 - i, 0)))
					return
				elif block_type == BlockType.BUG:
					other_block[1] = tile_bug_dead
					other_block[2] = BlockType.BUG_DEAD
					move_block(block, sum3d(delta, (0, -i, 0)))
					return
				elif is_obstacle_type(block_type):
					on_fail()
					return
				else:
					continue
		on_fail()

def can_bug_move(block, delta):
	if len(list(get_blocks_at(sum3d(block[0], (0, 1, 0))))) > 0: # something on top, usually another bug
		return False # let other bug move off first so odd behavior doesn't commence
	
	def is_obstacle(block_type):
		return block_type in (BlockType.PLAYER, BlockType.BUG, BlockType.ROCK, BlockType.TREE, BlockType.FILLER)
	def is_obstacle_at(position):
		return len([x for x in get_block_types_at(position) if is_obstacle(x)]) > 0
	
	dest = sum3d(block[0], delta)
	
	if is_obstacle_at(dest):
		return False
	else:
		below = sum3d(dest, (0, -1, 0))
		
		for other_block in get_blocks_at(below):
			block_type = other_block[2]
			
			if block_type in (BlockType.FILLER, BlockType.ROCK, BlockType.BUG):
				return True
			elif not is_obstacle(block_type):
				continue
			return False
	
def move_bug(block, delta):
	if can_bug_move(block, delta):
		move_block(block, delta)

#def ai_bug(block):
#	if block[2] == BlockType.BUG_DEAD: return
#	
#	options = [x for x in ((1, 0, 0), (-1, 0, 0), (0, 0, 1), (0, 0, -1)) if can_bug_move(block, x)]
#	if len(options) > 0:
#		move_bug(block, random.choice(options))

def make_bug(position):
	last_move = None
	def do_ai(event):
		nonlocal last_move
		
		if block[2] == BlockType.BUG_DEAD: return
		
		deltas = [(1, 0, 0), (-1, 0, 0), (0, 0, 1), (0, 0, -1)]
		
		reverse_move = (None if last_move == None else negate3d(last_move))
		if last_move != None:
			deltas.remove(reverse_move) ### avoid about-face when possible 
		
		options = [x for x in deltas if can_bug_move(block, x)]
		if len(options) > 0:
			option = random.choice(options)
			move_bug(block, option)
			last_move = option
		else:
			### attempt about-face when all else fails
			if reverse_move != None and can_bug_move(block, reverse_move):
				move_bug(block, reverse_move)
				last_move = reverse_move
		
		
		
	
	block = make_block(position, tile_bug, BlockType.BUG)
	on_event(lambda a: a.type == AppEvent.BLOCK_MOVED and a.block == block_player, do_ai)
	### TODO: Remove event binding when bug-death event fires


#def center_camera_on_block(block):
#	move_camera_to(block[0])
#def center_camera_on_player():
#	move_camera_to(sum3d(block_player[0], (0, -1, 0)))
#on_event(lambda a: a.type == AppEvent.BLOCK_MOVED and a.block == block_player, lambda a: center_camera_on_player())


TILE_W = 1
TILE_L = .8
TILE_H = .4

# tile: (surface, (reg_x, reg_y), reg_width, is_filler, relative_layer, hud)
tile_gray = (pygame.image.load('Plain Block.png').convert_alpha(), (50, 90), 100, True, 0, False)
tile_dirt = (pygame.image.load('Dirt Block.png').convert_alpha(), (50, 90), 100, True, 0, False)
tile_grass = (pygame.image.load('Grass Block.png').convert_alpha(), (50, 90), 100, True, 0, False)
tile_water = (pygame.image.load('Water Block.png').convert_alpha(), (50, 90), 100, True, -1, False)
tile_rock = (pygame.image.load('Rock.png').convert_alpha(), (50, 90), 100, False, 0, False)
tile_tree = (pygame.image.load('Tree Tall.png').convert_alpha(), (50, 90), 100, False, 0, False)
tile_player = (pygame.image.load('Character Cat Girl.png').convert_alpha(), (50, 90), 100, False, 0, False)
tile_player_in_water = (pygame.image.load('Character Cat Girl In Water.png').convert_alpha(), (50, 90), 100, False, 0, False)
tile_bug = (pygame.image.load('Enemy Bug.png').convert_alpha(), (50, 90), 100, False, 0, False)
tile_bug_dead = (pygame.image.load('Enemy Bug Squished.png').convert_alpha(), (50, 90), 100, False, -1, False)
tile_speech = (pygame.image.load('SpeechBubble.png').convert_alpha(), (-35, 190), 100, False, 0, True)
tile_wood = (pygame.image.load('Wood Block.png').convert_alpha(), (50, 90), 100, True, 0, False)
tile_question = (pygame.image.load('Question.png').convert_alpha(), (-35, 190), 100, False, 1, True) ### Uses font Palatino Linotype
tile_bush_0 = (pygame.image.load('Tree Short.png').convert_alpha(), (50, 90), 100, False, 0, False)
tile_bush_1 = (pygame.image.load('Tree Ugly.png').convert_alpha(), (50, 90), 100, False, 0, False)

shadow_e = (pygame.image.load('Shadow East.png'), (50, 90), 100)
shadow_w = (pygame.image.load('Shadow West.png'), (50, 90), 100)
shadow_s = (pygame.image.load('Shadow South.png'), (50, 90), 100)
shadow_n = (pygame.image.load('Shadow North Clipped.png'), (50, 90), 100)
shadow_side_w = (pygame.image.load('Shadow Side West.png'), (50, 90), 100)
shadow_se = (pygame.image.load('Shadow South East.png'), (50, 90), 100)
shadow_nw = (pygame.image.load('Shadow North West.png'), (50, 90), 100)
shadow_sw = (pygame.image.load('Shadow South West.png'), (50, 90), 100)
shadow_ne = (pygame.image.load('Shadow North East.png'), (50, 90), 100)


class BlockType:
	PLAYER, BUG, ROCK, TREE, FILLER, BUG_DEAD, SPEECH, WATER = range(8)

def make_block(position, tile, block_type):
	if len(position) != 3: raise Exception()
	block = [position, tile, block_type]
	blocks.append(block)
	update_blocks()
	return block

block_player = None
def make_player(position):
	global block_player
	block_player = make_block(position, tile_player, BlockType.PLAYER)
	
	def center_camera_on_player():
		move_camera_to(sum3d(block_player[0], (0, -1, 0)))
	center_camera_on_player()
	
	def update_tile():
		if is_block_type_at(block_player[0], BlockType.WATER):
			block_player[1] = tile_player_in_water
		else:
			block_player[1] = tile_player
	update_tile()
	
	
	on_event(lambda a: a.type == AppEvent.BLOCK_MOVED and a.block == block_player, lambda a: (
		center_camera_on_player(), update_tile()
	))

	
	
def make_grass(position):
	make_block(position, tile_grass, BlockType.FILLER)
def make_stone(position):
	make_block(position, tile_gray, BlockType.FILLER)
def make_boulder(position):
	make_block(position, tile_rock, BlockType.ROCK)
def make_tree(position):
	make_block(position, tile_tree, BlockType.TREE)
def make_bush_0(position):
	make_block(position, tile_bush_0, BlockType.TREE)
def make_bush_1(position):
	make_block(position, tile_bush_1, BlockType.TREE)
def make_wood_floor(position):
	make_block(position, tile_wood, BlockType.FILLER)
def make_water(position):
	make_block(position, tile_water, BlockType.WATER)
def make_dirt(position):
	make_block(position, tile_dirt, BlockType.FILLER)


scale_cache = {} # { surface: ((x, y), result_surface) }
def scale_surface_to(surface, dest_size):
	if not (surface in scale_cache and scale_cache[surface][0] == dest_size):
		scale_cache[surface] = (dest_size, pygame.transform.smoothscale(surface, dest_size))
	return scale_cache[surface][1]

def draw_tile(tile, position):
	tile_surface = tile[0]
	tile_reg_width = tile[2]
	
	scale_world2screen = surface_screen.get_height() / (camera[1] * TILE_L)
	scale_image2tile = tile_surface.get_width() / tile_reg_width
	
	dest_w = scale_world2screen * scale_image2tile
	dest_h = dest_w * tile_surface.get_height() / tile_surface.get_width()
	surface_screen.blit(
		#pygame.transform.smoothscale(tile_surface, int2d((dest_w, dest_h))),
		scale_surface_to(tile_surface, int2d((dest_w, dest_h))),
		sum2d(
			### positioning before camera motion
			dif2d(
				scale2d(
					(
						position[0] * TILE_W,
						position[2] * TILE_L - position[1] * TILE_H
					),
					scale_world2screen
				),
				scale2d(tile[1], scale_world2screen / tile_reg_width)
			),
			
			sum2d(
				### camera position
				scale2d(
					(TILE_W * -camera[0][0], TILE_H * camera[0][1] - TILE_L * camera[0][2]), 
					scale_world2screen
				),
				(surface_screen.get_width() / 2, surface_screen.get_height() / 2)
			)
		)
	)

"""tile_to_fog_surface = {} # { tile: (surface, color)
def draw_tile_fog(tile, position):
	if tile in tile_to_fog_surface:
		surface = tile_to_fog_surface[tile][0]
	else:
		surface = tile[0].copy()
		tile_to_fog_surface[tile] = (surface, None)
		#surface.fill((255, 0, 0), special_flags=pygame.BLEND_RGBA_MULT)
	#surface = tile[0].copy()
	#pygame.draw.rect(surface, pygame.Color(0, 0, 0), surface.get_rect())
	
	if tile_to_fog_surface[tile][1] == None:
		surface.blit(tile[0], (0, 0))
		surface.fill((255, (position[2] - camera[1]) * 20 + 127, 0), special_flags=pygame.BLEND_RGBA_MULT)
	draw_tile((surface, tile[1], tile[2], tile[3]), position)
###"""

def draw_environment(event):
	def is_filler_at(position):
		for block in get_blocks_at(position):
			if block[1][3]:
				return True
		return False
	
	for block in blocks:
		tile = block[1]
		position = block[0]
		draw_tile(tile, position)
		#draw_tile_fog(tile, position)
		if tile[3]:
			### surface shadows
			if not is_filler_at(sum3d(position, (0, 1, 0))):
				if is_filler_at(sum3d(position, (1, 1, 0))):
					draw_tile(shadow_e, position)
				if is_filler_at(sum3d(position, (-1, 1, 0))):
					draw_tile(shadow_w, position)
				if is_filler_at(sum3d(position, (0, 1, 1))):
					draw_tile(shadow_s, position)
				if is_filler_at(sum3d(position, (0, 1, -1))):
					draw_tile(shadow_n, position)
				
				### corners
				if not is_filler_at(sum3d(position, (0, 1, 1))):
					if is_filler_at(sum3d(position, (1, 1, 1))) and not is_filler_at(sum3d(position, (1, 1, 0))):
						draw_tile(shadow_se, position)
					if is_filler_at(sum3d(position, (-1, 1, 1))) and not is_filler_at(sum3d(position, (-1, 1, 0))):
						draw_tile(shadow_sw, position)
				if is_filler_at(sum3d(position, (-1, 1, -1))) and not is_filler_at(sum3d(position, (0, 1, -1))) and not is_filler_at(sum3d(position, (-1, 1, 0))):
					draw_tile(shadow_nw, position)
				if is_filler_at(sum3d(position, (1, 1, -1))) and not is_filler_at(sum3d(position, (0, 1, -1))) and not is_filler_at(sum3d(position, (1, 1, 0))):
					draw_tile(shadow_ne, position)
			
			### front shadows
			if not is_filler_at(sum3d(position, (0, 0, 1))):
				if is_filler_at(sum3d(position, (-1, 0, 1))):
					draw_tile(shadow_side_w, position)
			
		#draw_tile_fog(tile, position)
		
	#pygame.draw.rect(surface_screen, color_HUD, pygame.Rect(300 - 2, 200 - 2, 4, 4)) # centered guide dot
on_event(lambda a: a.type == EVENT_DRAW, draw_environment)

on_event(lambda a: a.type == AppEvent.INPUT_DIRECTION and a.direction == Direction.NORTH, lambda a: move_player(block_player, (0, 0, -1)))
on_event(lambda a: a.type == AppEvent.INPUT_DIRECTION and a.direction == Direction.SOUTH, lambda a: move_player(block_player, (0, 0, 1)))
on_event(lambda a: a.type == AppEvent.INPUT_DIRECTION and a.direction == Direction.EAST, lambda a: move_player(block_player, (1, 0, 0)))
on_event(lambda a: a.type == AppEvent.INPUT_DIRECTION and a.direction == Direction.WEST, lambda a: move_player(block_player, (-1, 0, 0)))

#on_event(lambda a: a.type == pygame.KEYDOWN and a.key == pygame.K_EQUALS, lambda a: zoom_camera(-1))
#on_event(lambda a: a.type == pygame.KEYDOWN and a.key == pygame.K_MINUS, lambda a: zoom_camera(1))

def render_text(text, position, anchor, dest_surface, font, color_fill, color_outline):
	surface = font.render(text, True, color_outline)
	position = sum2d(position, negate2d(basic_product_2d(surface.get_size(), anchor)))
	#pygame.Rect().size
	
	dest_surface.blit(surface, sum2d(position, (2, 0)))
	dest_surface.blit(surface, sum2d(position, (-2, 0)))
	dest_surface.blit(surface, sum2d(position, (0, 2)))
	dest_surface.blit(surface, sum2d(position, (0, -2)))
	
	surface = font.render(text, True, color_fill)
	dest_surface.blit(surface, position)


fps_clock = pygame.time.Clock()
gui_font = pygame.font.SysFont('Verdana', 28)
def draw_fps(event):
	fps_clock.tick()
	render_text('FPS: ' + str(int(fps_clock.get_fps())), (0, 0), (0, 0), surface_screen, gui_font, color_HUD, color_HUD_outline)
on_event(lambda a: a.type == EVENT_DRAW, draw_fps)


def draw_instructions(event):
	render_text('Use the arrow keys or d-pad to move.', (surface_screen.get_width(), 0), (1, 0), surface_screen, gui_font, color_HUD, color_HUD_outline)
on_event(lambda a: a.type == EVENT_DRAW, draw_instructions)

#################################################################### unit tests

assert mag_scale_to_2d((1, 0), 2) == (2, 0)
assert mag_scale_to_2d((-2, 0), .5) == (-.5, 0)
assert mag_scale_to_2d((1, 1), 1) == (1 / math.sqrt(2), 1 / math.sqrt(2))


######################################################################### begin

import map_0
map_0.make(make_player, make_bug, make_grass, make_stone, make_boulder, make_tree, make_bush_0, make_bush_1, make_wood_floor, make_water, make_dirt)


event_loop()