3-D game Ray Casting
import math from ion import * from kandinsky import * import kandinsky as kd SCREEN_WIDTH = 320 SCREEN_HEIGHT = 240 VIDEO_HALF_HEIGHT = SCREEN_HEIGHT // 2 FOV = math.pi / 3 def rotate_point(x, y, angle): cos_a = math.cos(angle) sin_a = math.sin(angle) new_x = x * cos_a - y * sin_a new_y = x * sin_a + y * cos_a return new_x, new_y def project_point(x, y, z): scale = SCREEN_HEIGHT // (2 * z) screen_x = (x * scale) + (SCREEN_WIDTH // 2) screen_y = (y * scale) + VIDEO_HALF_HEIGHT return int(screen_x), int(screen_y) def draw_line(x1, y1, x2, y2, color): dx = x2 - x1 dy = y2 - y1 length = math.sqrt(dx * dx + dy * dy) angle = math.atan2(dy, dx) for i in range(int(length)): xi = x1 + math.cos(angle) * i yi = y1 + math.sin(angle) * i kd.fill_rect(int(xi), int(yi), 1, 1, color) def draw_cube(rotation_angle, forward, backward): vertices = [ (-1, -1, -1), (1, -1, -1), (1, 1, -1), (-1, 1, -1), (-1, -1, 1), (1, -1, 1), (1, 1, 1), (-1, 1, 1), ] edges = [ (0, 1), (1, 2), (2, 3), (3, 0), (4, 5), (5, 6), (6, 7), (7, 4), (0, 4), (1, 5), (2, 6), (3, 7), ] for edge in edges: x1, y1, z1 = vertices[edge[0]] x2, y2, z2 = vertices[edge[1]] x1, y1 = rotate_point(x1, y1, rotation_angle) x2, y2 = rotate_point(x2, y2, rotation_angle) x1, y1 = project_point(x1, y1, z1) x2, y2 = project_point(x2, y2, z2) draw_line(x1, y1, x2, y2, kd.color(0, 0, 0)) if forward: for i in range(len(vertices)): vertices[i] = (vertices[i][0], vertices[i][1], vertices[i][2] + 0.1) elif backward: for i in range(len(vertices)): vertices[i] = (vertices[i][0], vertices[i][1], vertices[i][2] - 0.1) def main(): rotation_angle = 0 forward = False backward = False while True: kd.fill_rect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, kd.color(255, 255, 255)) # Clear the screen with white draw_cube(rotation_angle, forward, backward) fill_rect(0,0,320,220,("white")) rotation_angle += 0.02 # Rotate the cube if keydown(KEY_LEFTPARENTHESIS): rotation_angle -= 0.02 # Rotate left elif keydown(KEY_RIGHTPARENTHESIS): rotation_angle += 0.02 # Rotate right forward = keydown(KEY_UP) backward = keydown(KEY_DOWN) if __name__ == "__main__": main()