Untitled conversation
- Userlua
- Assistant
- User
Сделай танки реалистичнее
- Assistant
Сделай танки реалистичнее
import pygame
from pygame.locals import *
from OpenGL.GL import *
from OpenGL.GLU import *
import numpy as np
import noise # For Perlin noise
import ctypes
import pygame.time # For timing control
# Initialize Pygame and set up OpenGL with anti-aliasing
pygame.init()
# Enable multisample anti-aliasing (4x MSAA)
pygame.display.gl_set_attribute(pygame.GL_MULTISAMPLEBUFFERS, 1)
pygame.display.gl_set_attribute(pygame.GL_MULTISAMPLESAMPLES, 4)
display = (800, 600)
pygame.display.set_mode(display, DOUBLEBUF | OPENGL)
glEnable(GL_DEPTH_TEST)
glEnable(GL_MULTISAMPLE) # Enable anti-aliasing
# Terrain parameters
terrain_size = 40 # 40x40 grid
physical_size = 19.0 # Physical dimensions from 0 to 19 units
grid_unit = physical_size / (terrain_size - 1) # ≈ 0.487 units per grid cell
# Generate terrain heightmap using Perlin noise
terrain = np.zeros((terrain_size, terrain_size))
scale = 19.0 # Noise frequency
octaves = 4
persistence = 0.5
lacunarity = 2.0
base = 0 # Seed
for x in range(terrain_size):
for z in range(terrain_size):
noise_val = noise.pnoise2(
x / scale,
z / scale,
octaves=octaves,
persistence=persistence,
lacunarity=lacunarity,
repeatx=terrain_size,
repeaty=terrain_size,
base=base
)
# Map noise from [-1, 1] to [-1, 1] height range
terrain[x][z] = noise_val
# Calculate height at any (x, z) position with bilinear interpolation
def get_terrain_height(x, z):
grid_x = x / grid_unit
grid_z = z / grid_unit
if grid_x < 0 or grid_x > terrain_size - 1 or grid_z < 0 or grid_z > terrain_size - 1:
return 0
i, j = int(grid_x), int(grid_z)
dx, dz = grid_x - i, grid_z - j
if i < terrain_size - 1 and j < terrain_size - 1:
h = (1 - dx) * (1 - dz) * terrain[i][j] + \
dx * (1 - dz) * terrain[i + 1][j] + \
(1 - dx) * dz * terrain[i][j + 1] + \
dx * dz * terrain[i + 1][j + 1]
elif i == terrain_size - 1 and j < terrain_size - 1:
h = (1 - dz) * terrain[i][j] + dz * terrain[i][j + 1]
elif j == terrain_size - 1 and i < terrain_size - 1:
h = (1 - dx) * terrain[i][j] + dx * terrain[i + 1][j]
else:
h = terrain[i][j]
return h
# Compute vertex normals for smooth lighting
def calculate_vertex_normals():
normals = np.zeros((terrain_size, terrain_size, 3))
for x in range(terrain_size):
for z in range(terrain_size):
# Partial derivatives for normal calculation
df_dx = (terrain[min(x + 1, terrain_size - 1)][z] - terrain[max(x - 1, 0)][z]) / (2 * grid_unit if 0 < x < terrain_size - 1 else grid_unit)
df_dz = (terrain[x][min(z + 1, terrain_size - 1)] - terrain[x][max(z - 1, 0)]) / (2 * grid_unit if 0 < z < terrain_size - 1 else grid_unit)
normal = np.array([-df_dx, 1, -df_dz])
norm = np.linalg.norm(normal)
normals[x][z] = normal / norm if norm != 0 else normal
return normals
vertex_normals = calculate_vertex_normals()
# Prepare vertex and index data for VBOs
vertices = []
indices = []
for x in range(terrain_size):
for z in range(terrain_size):
phys_x = x * grid_unit
phys_z = z * grid_unit
y = terrain[x][z]
n = vertex_normals[x][z]
vertices.extend([phys_x, y, phys_z, n[0], n[1], n[2]])
for x in range(terrain_size - 1):
for z in range(terrain_size - 1):
i = x * terrain_size + z
indices.extend([i, i + 1, i + terrain_size, i + 1, i + terrain_size + 1, i + terrain_size])
vertices = np.array(vertices, dtype=np.float32)
indices = np.array(indices, dtype=np.uint32)
# Set up VBOs
vbo = glGenBuffers(1)
glBindBuffer(GL_ARRAY_BUFFER, vbo)
glBufferData(GL_ARRAY_BUFFER, vertices.nbytes, vertices, GL_STATIC_DRAW)
ibo = glGenBuffers(1)
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo)
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.nbytes, indices, GL_STATIC_DRAW)
# Tank properties with separate turret angle
tank1 = {"x": 5.0, "z": 5.0, "angle": 0.0, "turret_angle": 0.0, "color": (1, 0, 0)} # Red
tank2 = {"x": 15.0, "z": 15.0, "angle": 0.0, "turret_angle": 0.0, "color": (0, 0, 1)} # Blue
# Draw terrain using VBOs
def draw_terrain():
glColor3f(0, 0.5, 0) # Set terrain color to green
glEnableClientState(GL_VERTEX_ARRAY)
glEnableClientState(GL_NORMAL_ARRAY)
glBindBuffer(GL_ARRAY_BUFFER, vbo)
glVertexPointer(3, GL_FLOAT, 24, None)
glNormalPointer(GL_FLOAT, 24, ctypes.c_void_p(12))
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo)
glDrawElements(GL_TRIANGLES, len(indices), GL_UNSIGNED_INT, None)
glDisableClientState(GL_VERTEX_ARRAY)
glDisableClientState(GL_NORMAL_ARRAY)
# Draw tank with elongated hull, turret, and barrel
def draw_tank(tank):
tank_y = get_terrain_height(tank["x"], tank["z"]) + 0.5
glPushMatrix()
glTranslatef(tank["x"], tank_y, tank["z"])
glRotatef(tank["angle"], 0, 1, 0) # Rotate hull
# Draw hull (elongated rectangle)
glColor3f(*tank["color"])
glBegin(GL_QUADS)
# Front
glNormal3f(0, 0, 1)
glVertex3f(-0.5, -0.5, 0.75); glVertex3f(0.5, -0.5, 0.75)
glVertex3f(0.5, 0.5, 0.75); glVertex3f(-0.5, 0.5, 0.75)
# Back
glNormal3f(0, 0, -1)
glVertex3f(-0.5, -0.5, -0.75); glVertex3f(0.5, -0.5, -0.75)
glVertex3f(0.5, 0.5, -0.75); glVertex3f(-0.5, 0.5, -0.75)
# Left
glNormal3f(-1, 0, 0)
glVertex3f(-0.5, -0.5, -0.75); glVertex3f(-0.5, -0.5, 0.75)
glVertex3f(-0.5, 0.5, 0.75); glVertex3f(-0.5, 0.5, -0.75)
# Right
glNormal3f(1, 0, 0)
glVertex3f(0.5, -0.5, -0.75); glVertex3f(0.5, -0.5, 0.75)
glVertex3f(0.5, 0.5, 0.75); glVertex3f(0.5, 0.5, -0.75)
# Top
glNormal3f(0, 1, 0)
glVertex3f(-0.5, 0.5, -0.75); glVertex3f(0.5, 0.5, -0.75)
glVertex3f(0.5, 0.5, 0.75); glVertex3f(-0.5, 0.5, 0.75)
# Bottom
glNormal3f(0, -1, 0)
glVertex3f(-0.5, -0.5, -0.75); glVertex3f(0.5, -0.5, -0.75)
glVertex3f(0.5, -0.5, 0.75); glVertex3f(-0.5, -0.5, 0.75)
glEnd()
# Draw turret (cylinder)
glPushMatrix()
glTranslatef(0, 0.5, 0) # Move to top of hull
glRotatef(tank["turret_angle"], 0, 1, 0) # Rotate turret
quadric = gluNewQuadric()
glColor3f(0.5, 0.5, 0.5) # Gray color for turret
glRotatef(90, 1, 0, 0) # Rotate cylinder to stand vertically
gluCylinder(quadric, 0.3, 0.3, 0.5, 20, 20) # Turret cylinder
glPopMatrix()
# Draw barrel (thin cylinder)
glPushMatrix()
glTranslatef(0, 0.75, 0) # Position barrel on top of turret
glRotatef(tank["turret_angle"], 0, 1, 0) # Rotate with turret
glColor3f(0.3, 0.3, 0.3) # Dark gray for barrel
glTranslatef(0, 0, 0.3) # Offset to front of turret
glRotatef(90, 0, 1, 0) # Rotate to point forward
gluCylinder(quadric, 0.1, 0.1, 1.0, 10, 10) # Barrel cylinder
glPopMatrix()
glPopMatrix()
# Set up lighting
def setup_lighting():
glEnable(GL_LIGHTING)
glEnable(GL_LIGHT0)
glLightfv(GL_LIGHT0, GL_POSITION, [0, 1, 0, 0]) # Directional light
glEnable(GL_COLOR_MATERIAL)
glColorMaterial(GL_FRONT, GL_DIFFUSE)
# Render a viewport for a tank
def render_viewport(tank, viewport_x, viewport_width):
glViewport(viewport_x, 0, viewport_width, 600)
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
gluPerspective(45, viewport_width / 600, 0.1, 50.0)
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
tank_y = get_terrain_height(tank["x"], tank["z"]) + 0.5
camera_offset = 5.0
camera_x = tank["x"] - camera_offset * np.sin(np.radians(tank["angle"]))
camera_z = tank["z"] - camera_offset * np.cos(np.radians(tank["angle"]))
camera_x = max(0, min(physical_size, camera_x))
camera_z = max(0, min(physical_size, camera_z))
camera_y = get_terrain_height(camera_x, camera_z) + 3
gluLookAt(camera_x, camera_y, camera_z, tank["x"], tank_y, tank["z"], 0, 1, 0)
draw_terrain()
draw_tank(tank1)
draw_tank(tank2)
# Initialize lighting
setup_lighting()
# Game loop
desired_speed = 6.0 # Units per second
angular_speed = 90.0 # Degrees per second for hull rotation
turret_angular_speed = 90.0 # Degrees per second for turret rotation
clock = pygame.time.Clock()
while True:
dt = clock.get_time() / 1000.0 # Time in seconds since last frame
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
keys = pygame.key.get_pressed()
# Tank 1 controls (hull: arrows, turret: Page Up/Down)
if keys[K_UP]:
tank1["x"] += desired_speed * np.sin(np.radians(tank1["angle"])) * dt
tank1["z"] += desired_speed * np.cos(np.radians(tank1["angle"])) * dt
if keys[K_DOWN]:
tank1["x"] -= desired_speed * np.sin(np.radians(tank1["angle"])) * dt
tank1["z"] -= desired_speed * np.cos(np.radians(tank1["angle"])) * dt
if keys[K_LEFT]:
tank1["angle"] += angular_speed * dt
tank1["angle"] %= 360
if keys[K_RIGHT]:
tank1["angle"] -= angular_speed * dt
tank1["angle"] %= 360
if keys[K_PAGEUP]:
tank1["turret_angle"] += turret_angular_speed * dt
tank1["turret_angle"] %= 360
if keys[K_PAGEDOWN]:
tank1["turret_angle"] -= turret_angular_speed * dt
tank1["turret_angle"] %= 360
# Tank 2 controls (hull: WASD, turret: I/K)
if keys[K_w]:
tank2["x"] += desired_speed * np.sin(np.radians(tank2["angle"])) * dt
tank2["z"] += desired_speed * np.cos(np.radians(tank2["angle"])) * dt
if keys[K_s]:
tank2["x"] -= desired_speed * np.sin(np.radians(tank2["angle"])) * dt
tank2["z"] -= desired_speed * np.cos(np.radians(tank2["angle"])) * dt
if keys[K_a]:
tank2["angle"] += angular_speed * dt
tank2["angle"] %= 360
if keys[K_d]:
tank2["angle"] -= angular_speed * dt
tank2["angle"] %= 360
if keys[K_i]:
tank2["turret_angle"] += turret_angular_speed * dt
tank2["turret_angle"] %= 360
if keys[K_k]:
tank2["turret_angle"] -= turret_angular_speed * dt
tank2["turret_angle"] %= 360
# Clamp positions
tank1["x"] = max(0, min(physical_size, tank1["x"]))
tank1["z"] = max(0, min(physical_size, tank1["z"]))
tank2["x"] = max(0, min(physical_size, tank2["x"]))
tank2["z"] = max(0, min(physical_size, tank2["z"]))
# Render
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
render_viewport(tank1, 0, 400) # Left: Tank 1
render_viewport(tank2, 400, 400) # Right: Tank 2
pygame.display.flip()
clock.tick(60) # Cap at 60 FPS
Преобразуй следующий код, чтобы он соответствовал уровню senior-разработчика: используй объектно-ориентированное программирование с инкапсуляцией, абстракцией и наследованием там, где это уместно, сделай архитектуру модульной, расширяемой и поддерживаемой, оптимизируй производительность и читаемость, улучшай именования переменных, функций и классов, устраняй дублирование кода, применяй подходящие паттерны проектирования для гибкости и масштабируемости, внедри обработку ошибок с информативными сообщениями и обеспечь логирование ключевых событий, добавь подробные комментарии и документацию к основным классам и методам, обеспечь финальный код простым для понимания, тестирования и поддержки.
import logging
import sys
import ctypes
from typing import Tuple, Optional
import numpy as np
import noise # Perlin noise
import pygame
from pygame.locals import *
from OpenGL.GL import *
from OpenGL.GLU import *
# ===========================
# Configure logging
# ===========================
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(name)s - %(message)s",
handlers=[logging.StreamHandler(sys.stdout)]
)
logger = logging.getLogger("TankTerrainSim")
# ===========================
# Constants and Configurations
# ===========================
WINDOW_WIDTH = 800
WINDOW_HEIGHT = 600
FPS = 60
# Terrain constants
TERRAIN_GRID_SIZE = 40
TERRAIN_PHYSICAL_SIZE = 19.0
GRID_CELL_SIZE = TERRAIN_PHYSICAL_SIZE / (TERRAIN_GRID_SIZE - 1)
# Perlin noise parameters for terrain generation
NOISE_SCALE = 19.0
NOISE_OCTAVES = 4
NOISE_PERSISTENCE = 0.5
NOISE_LACUNARITY = 2.0
NOISE_BASE_SEED = 0
# Tank movement parameters
TANK_MOVE_SPEED = 6.0 # Units per second
TANK_ANGULAR_SPEED = 90.0 # Degrees per second for hull rotation
TURRET_ANGULAR_SPEED = 90.0 # Degrees per second for turret rotation
# ===========================
# Exceptions
# ===========================
class TerrainError(Exception):
"""Custom exception for terrain-related errors."""
class TankError(Exception):
"""Custom exception for tank-related errors."""
class GraphicsError(Exception):
"""Custom exception for graphics-related errors."""
# ===========================
# Utility Functions
# ===========================
def clamp(value: float, min_val: float, max_val: float) -> float:
"""Clamp a float value within [min_val, max_val]."""
return max(min_val, min(value, max_val))
# ===========================
# Terrain Module
# ===========================
class Terrain:
"""
Represents a 3D terrain generated using Perlin noise.
Attributes:
grid_size (int): Number of points along one axis of the terrain grid.
physical_size (float): Physical size of terrain in units.
grid_cell_size (float): Distance between adjacent grid points.
height_map (np.ndarray): 2D array representing height values.
normals (np.ndarray): 3D array of vertex normals for smooth lighting.
"""
def __init__(self,
grid_size: int = TERRAIN_GRID_SIZE,
physical_size: float = TERRAIN_PHYSICAL_SIZE,
noise_scale: float = NOISE_SCALE,
noise_octaves: int = NOISE_OCTAVES,
noise_persistence: float = NOISE_PERSISTENCE,
noise_lacunarity: float = NOISE_LACUNARITY,
noise_seed: int = NOISE_BASE_SEED):
self.grid_size = grid_size
self.physical_size = physical_size
self.grid_cell_size = physical_size / (grid_size - 1)
logger.info(f"Initializing terrain grid {self.grid_size}x{self.grid_size} with physical size {self.physical_size}")
self.height_map = np.zeros((self.grid_size, self.grid_size), dtype=np.float32)
# Normals: shape (grid_size, grid_size, 3)
self.normals = np.zeros((self.grid_size, self.grid_size, 3), dtype=np.float32)
try:
self._generate_height_map(
noise_scale,
noise_octaves,
noise_persistence,
noise_lacunarity,
noise_seed
)
self._calculate_vertex_normals()
except Exception as ex:
logger.error(f"Error during terrain generation: {ex}")
raise TerrainError(f"Could not generate terrain: {ex}")
def _generate_height_map(self,
scale: float,
octaves: int,
persistence: float,
lacunarity: float,
base_seed: int):
"""
Generate height map using Perlin noise.
"""
logger.debug("Generating Perlin noise height map.")
for x_grid in range(self.grid_size):
for z_grid in range(self.grid_size):
# Normalize grid coordinates to noise scale
noise_val = noise.pnoise2(
x_grid / scale,
z_grid / scale,
octaves=octaves,
persistence=persistence,
lacunarity=lacunarity,
repeatx=self.grid_size,
repeaty=self.grid_size,
base=base_seed
)
# Noise output is in [-1,1]; directly use it as height
self.height_map[x_grid, z_grid] = noise_val
logger.info("Completed generating height map.")
def _calculate_vertex_normals(self):
"""
Calculate normals per vertex for smooth lighting using central differences.
"""
logger.debug("Calculating vertex normals for terrain.")
for x in range(self.grid_size):
for z in range(self.grid_size):
# Compute df/dx
x_plus = min(x + 1, self.grid_size - 1)
x_minus = max(x - 1, 0)
dx = (self.height_map[x_plus, z] - self.height_map[x_minus, z])
denom_dx = 2 * self.grid_cell_size if 0 < x < self.grid_size - 1 else self.grid_cell_size
df_dx = dx / denom_dx
# Compute df/dz
z_plus = min(z + 1, self.grid_size - 1)
z_minus = max(z - 1, 0)
dz = (self.height_map[x, z_plus] - self.height_map[x, z_minus])
denom_dz = 2 * self.grid_cell_size if 0 < z < self.grid_size - 1 else self.grid_cell_size
df_dz = dz / denom_dz
# Normal vector
normal_vec = np.array([-df_dx, 1.0, -df_dz], dtype=np.float32)
norm_length = np.linalg.norm(normal_vec)
if norm_length != 0:
normal_vec /= norm_length
self.normals[x, z] = normal_vec
logger.info("Vertex normals calculated successfully.")
def get_height(self, x_pos: float, z_pos: float) -> float:
"""
Get interpolated height at physical coordinates (x_pos, z_pos) using bilinear interpolation.
Args:
x_pos (float): X coordinate in physical units.
z_pos (float): Z coordinate in physical units.
Returns:
float: Interpolated height value at the given position.
"""
grid_x = x_pos / self.grid_cell_size
grid_z = z_pos / self.grid_cell_size
if not (0 <= grid_x <= self.grid_size - 1 and 0 <= grid_z <= self.grid_size - 1):
logger.warning(f"Position ({x_pos}, {z_pos}) is out of terrain bounds.")
return 0.0 # Outside terrain bounds
i, j = int(grid_x), int(grid_z)
dx, dz = grid_x - i, grid_z - j
# Handle edge cases for interpolation
if i < self.grid_size - 1 and j < self.grid_size - 1:
h00 = self.height_map[i, j]
h10 = self.height_map[i + 1, j]
h01 = self.height_map[i, j + 1]
h11 = self.height_map[i + 1, j + 1]
height = (1 - dx) * (1 - dz) * h00 + dx * (1 - dz) * h10 + (1 - dx) * dz * h01 + dx * dz * h11
return height
elif i == self.grid_size - 1 and j < self.grid_size - 1:
h0 = self.height_map[i, j]
h1 = self.height_map[i, j + 1]
height = (1 - dz) * h0 + dz * h1
return height
elif j == self.grid_size - 1 and i < self.grid_size - 1:
h0 = self.height_map[i, j]
h1 = self.height_map[i + 1, j]
height = (1 - dx) * h0 + dx * h1
return height
else:
return self.height_map[i, j]
def create_buffers(self) -> Tuple[int, int, int]:
"""
Create Vertex Buffer Object (VBO), Index Buffer Object (IBO), and count of indices.
Returns:
Tuple of (vbo_id, ibo_id, index_count).
"""
logger.debug("Creating buffers for terrain rendering.")
vertices = []
indices = []
for x in range(self.grid_size):
for z in range(self.grid_size):
phys_x = x * self.grid_cell_size
phys_z = z * self.grid_cell_size
y = self.height_map[x, z]
n = self.normals[x, z]
# Pack position and normal (x, y, z, nx, ny, nz)
vertices.extend([phys_x, y, phys_z, *n])
for x in range(self.grid_size - 1):
for z in range(self.grid_size - 1):
top_left = x * self.grid_size + z
top_right = top_left + 1
bottom_left = top_left + self.grid_size
bottom_right = bottom_left + 1
# Two triangles per quad
indices.extend([
top_left, top_right, bottom_left,
top_right, bottom_right, bottom_left
])
vertices_array = np.array(vertices, dtype=np.float32)
indices_array = np.array(indices, dtype=np.uint32)
# Create and bind VBO
vbo = glGenBuffers(1)
glBindBuffer(GL_ARRAY_BUFFER, vbo)
glBufferData(GL_ARRAY_BUFFER, vertices_array.nbytes, vertices_array, GL_STATIC_DRAW)
# Create and bind IBO
ibo = glGenBuffers(1)
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo)
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices_array.nbytes, indices_array, GL_STATIC_DRAW)
logger.info(f"Created terrain buffers: VBO={vbo}, IBO={ibo}, indices={len(indices_array)}")
return vbo, ibo, len(indices_array)
# ===========================
# Tank Module
# ===========================
class Tank:
"""
Represents a tank with a hull and turret that can move on the terrain.
Attributes:
x (float): X position in world coordinates.
z (float): Z position in world coordinates.
hull_angle (float): Yaw angle of tank hull in degrees.
turret_angle (float): Yaw angle of turret relative to hull in degrees.
color (Tuple[float, float, float]): RGB color values.
terrain (Terrain): Reference to terrain for height sampling.
"""
def __init__(self,
terrain: Terrain,
start_x: float,
start_z: float,
hull_angle_deg: float,
color: Tuple[float, float, float]):
self._terrain = terrain
self._position = np.array([start_x, 0.0, start_z], dtype=np.float32) # x, y, z
self._position[1] = self._terrain.get_height(start_x, start_z) + 0.5 # Height offset above terrain
self.hull_angle = hull_angle_deg
self.turret_angle = 0.0
self.color = color
logger.info(f"Created Tank at ({start_x:.2f}, {start_z:.2f}) with hull angle {hull_angle_deg}° and color {color}")
@property
def x(self) -> float:
return self._position[0]
@x.setter
def x(self, value: float):
self._position[0] = clamp(value, 0.0, self._terrain.physical_size)
self._update_height()
@property
def z(self) -> float:
return self._position[2]
@z.setter
def z(self, value: float):
self._position[2] = clamp(value, 0.0, self._terrain.physical_size)
self._update_height()
@property
def y(self) -> float:
return self._position[1]
def _update_height(self):
"""Recalculate the y-position based on terrain height at current x, z."""
terrain_height = self._terrain.get_height(self._position[0], self._position[2])
self._position[1] = terrain_height + 0.5 # Offset lift for tank body
def move_forward(self, distance: float):
"""Move tank forward in direction of hull_angle by distance."""
rad = np.radians(self.hull_angle)
new_x = self._position[0] + distance * np.sin(rad)
new_z = self._position[2] + distance * np.cos(rad)
logger.debug(f"Tank move forward by {distance:.3f} units.")
self.x = new_x
self.z = new_z
def move_backward(self, distance: float):
"""Move tank backward in direction opposite to hull_angle by distance."""
rad = np.radians(self.hull_angle)
new_x = self._position[0] - distance * np.sin(rad)
new_z = self._position[2] - distance * np.cos(rad)
logger.debug(f"Tank move backward by {distance:.3f} units.")
self.x = new_x
self.z = new_z
def rotate_hull(self, angle_delta: float):
"""Rotate the hull by angle_delta degrees."""
self.hull_angle = (self.hull_angle + angle_delta) % 360
logger.debug(f"Tank hull rotated to {self.hull_angle:.2f}°.")
def rotate_turret(self, angle_delta: float):
"""Rotate the turret by angle_delta degrees."""
self.turret_angle = (self.turret_angle + angle_delta) % 360
logger.debug(f"Tank turret rotated to {self.turret_angle:.2f}°.")
def draw(self):
"""
Render the tank as an elongated hull, turret, and barrel.
"""
glPushMatrix()
# Move to tank position
glTranslatef(self.x, self.y, self.z)
# Apply hull rotation
glRotatef(self.hull_angle, 0, 1, 0)
# Draw hull (elongated cuboid)
self._draw_hull()
# Draw turret and barrel
self._draw_turret_and_barrel()
glPopMatrix()
def _draw_hull(self):
"""Draw the tank hull as a colored rectangular cuboid."""
glColor3f(*self.color)
glBegin(GL_QUADS)
# Front face (normal +Z)
glNormal3f(0, 0, 1)
glVertex3f(-0.5, -0.5, 0.75)
glVertex3f(0.5, -0.5, 0.75)
glVertex3f(0.5, 0.5, 0.75)
glVertex3f(-0.5, 0.5, 0.75)
# Back face (normal -Z)
glNormal3f(0, 0, -1)
glVertex3f(-0.5, -0.5, -0.75)
glVertex3f(0.5, -0.5, -0.75)
glVertex3f(0.5, 0.5, -0.75)
glVertex3f(-0.5, 0.5, -0.75)
# Left face (normal -X)
glNormal3f(-1, 0, 0)
glVertex3f(-0.5, -0.5, -0.75)
glVertex3f(-0.5, -0.5, 0.75)
glVertex3f(-0.5, 0.5, 0.75)
glVertex3f(-0.5, 0.5, -0.75)
# Right face (normal +X)
glNormal3f(1, 0, 0)
glVertex3f(0.5, -0.5, -0.75)
glVertex3f(0.5, -0.5, 0.75)
glVertex3f(0.5, 0.5, 0.75)
glVertex3f(0.5, 0.5, -0.75)
# Top face (normal +Y)
glNormal3f(0, 1, 0)
glVertex3f(-0.5, 0.5, -0.75)
glVertex3f(0.5, 0.5, -0.75)
glVertex3f(0.5, 0.5, 0.75)
glVertex3f(-0.5, 0.5, 0.75)
# Bottom face (normal -Y)
glNormal3f(0, -1, 0)
glVertex3f(-0.5, -0.5, -0.75)
glVertex3f(0.5, -0.5, -0.75)
glVertex3f(0.5, -0.5, 0.75)
glVertex3f(-0.5, -0.5, 0.75)
glEnd()
def _draw_turret_and_barrel(self):
"""Draw the rotating turret and barrel on top of the hull."""
# Draw turret (gray cylinder)
glPushMatrix()
glTranslatef(0, 0.5, 0) # Position turret on top of hull
glRotatef(self.turret_angle, 0, 1, 0)
glColor3f(0.5, 0.5, 0.5)
quadric = gluNewQuadric()
glRotatef(90, 1, 0, 0) # Rotate cylinder upright
gluCylinder(quadric, 0.3, 0.3, 0.5, 20, 20)
gluDeleteQuadric(quadric)
glPopMatrix()
# Draw barrel (dark gray thin cylinder)
glPushMatrix()
glTranslatef(0, 0.75, 0) # Position barrel on top of turret
glRotatef(self.turret_angle, 0, 1, 0)
glColor3f(0.3, 0.3, 0.3)
glTranslatef(0, 0, 0.3) # Move to front of turret
glRotatef(90, 0, 1, 0) # Align barrel forward
quadric = gluNewQuadric()
gluCylinder(quadric, 0.1, 0.1, 1.0, 10, 10)
gluDeleteQuadric(quadric)
glPopMatrix()
# ===========================
# Renderer Module
# ===========================
class Renderer:
"""
Handles initialization and rendering of the OpenGL context,
terrain, tanks, and multiple viewports.
"""
def __init__(self,
terrain: Terrain,
tanks: Tuple[Tank, Tank],
window_size: Tuple[int, int] = (WINDOW_WIDTH, WINDOW_HEIGHT)):
self._terrain = terrain
self._tanks = tanks
self._window_width, self._window_height = window_size
# Initialize pygame and OpenGL context
self._init_pygame_context()
# Prepare OpenGL states and buffers
try:
self._terrain_vbo, self._terrain_ibo, self._num_indices = self._terrain.create_buffers()
except Exception as ex:
logger.error(f"Failed to create terrain buffers: {ex}")
raise GraphicsError(ex)
self._setup_opengl_states()
self._setup_lighting()
self._configure_opengl_projection()
logger.info("Renderer initialized successfully.")
def _init_pygame_context(self):
"""Initialize Pygame and setup OpenGL context with MSAA (multisample anti-aliasing)."""
pygame.init()
pygame.display.gl_set_attribute(pygame.GL_MULTISAMPLEBUFFERS, 1)
pygame.display.gl_set_attribute(pygame.GL_MULTISAMPLESAMPLES, 4)
pygame.display.set_mode(
(self._window_width, self._window_height),
DOUBLEBUF | OPENGL
)
glEnable(GL_DEPTH_TEST)
glEnable(GL_MULTISAMPLE) # Enable anti-aliasing
# Basic viewport setup
glViewport(0, 0, self._window_width, self._window_height)
glClearColor(0.2, 0.3, 0.4, 1.0) # Clear color (sky-like)
logger.info("Pygame and OpenGL context initialized with MSAA.")
def _setup_opengl_states(self):
"""Setup fixed function pipeline states required for rendering."""
glEnableClientState(GL_VERTEX_ARRAY)
glEnableClientState(GL_NORMAL_ARRAY)
glEnable(GL_COLOR_MATERIAL)
glColorMaterial(GL_FRONT, GL_DIFFUSE)
def _setup_lighting(self):
"""Configure OpenGL lighting parameters."""
glEnable(GL_LIGHTING)
glEnable(GL_LIGHT0)
# Directional light from above
light_position = [0.0, 1.0, 0.0, 0.0]
glLightfv(GL_LIGHT0, GL_POSITION, light_position)
glLightfv(GL_LIGHT0, GL_DIFFUSE, [0.8, 0.8, 0.8, 1.0])
glLightfv(GL_LIGHT0, GL_SPECULAR, [1.0, 1.0, 1.0, 1.0])
logger.info("Lighting setup completed.")
def _configure_opengl_projection(self):
"""Initial projection setup."""
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
gluPerspective(45, self._window_width / self._window_height, 0.1, 50.0)
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
def _bind_terrain_buffers(self):
"""Bind terrain VBO and IBO, and setup pointers for vertex attributes."""
glBindBuffer(GL_ARRAY_BUFFER, self._terrain_vbo)
glVertexPointer(3, GL_FLOAT, 6 * 4, ctypes.c_void_p(0))
glNormalPointer(GL_FLOAT, 6 * 4, ctypes.c_void_p(3 * 4))
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, self._terrain_ibo)
def draw_terrain(self):
"""Render the terrain using VBOs and IBOs."""
glColor3f(0.0, 0.5, 0.0) # Default terrain color (green-ish)
self._bind_terrain_buffers()
glDrawElements(GL_TRIANGLES, self._num_indices, GL_UNSIGNED_INT, None)
def _setup_camera(self, tank: Tank, viewport_x: int, viewport_width: int):
"""
Setup viewport and camera to follow the specified tank.
"""
glViewport(viewport_x, 0, viewport_width, self._window_height)
# Setup projection matrix per viewport
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
aspect_ratio = viewport_width / self._window_height if self._window_height != 0 else 1.0
gluPerspective(45, aspect_ratio, 0.1, 50.0)
# Setup camera position and orientation
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
# Camera offset from tank position behind the hull
offset_distance = 5.0
rad = np.radians(tank.hull_angle)
camera_x = tank.x - offset_distance * np.sin(rad)
camera_z = tank.z - offset_distance * np.cos(rad)
# Clamp camera within terrain bounds
camera_x = clamp(camera_x, 0.0, self._terrain.physical_size)
camera_z = clamp(camera_z, 0.0, self._terrain.physical_size)
camera_y = self._terrain.get_height(camera_x, camera_z) + 3.0 # Camera height
# Look at tank position with some height offset
tank_y = self._terrain.get_height(tank.x, tank.z) + 0.5
gluLookAt(
camera_x, camera_y, camera_z,
tank.x, tank_y, tank.z,
0, 1, 0
)
def render_frame(self):
"""
Perform rendering of the entire scene with two viewports (split-screen).
"""
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
half_width = self._window_width // 2
# Left viewport - tank 1
self._setup_camera(self._tanks[0], 0, half_width)
self.draw_terrain()
self._tanks[0].draw()
self._tanks[1].draw()
# Right viewport - tank 2
self._setup_camera(self._tanks[1], half_width, half_width)
self.draw_terrain()
self._tanks[0].draw()
self._tanks[1].draw()
pygame.display.flip()
logger.debug("Frame rendered.")
# ===========================
# Input Handler Module
# ===========================
class InputHandler:
"""
Abstracts input handling, processing events, and mapping keys
to tank controls.
"""
def __init__(self):
# Key mappings dictionary: tank index -> dict mapping action to pygame key
self._tank_key_map = [
{
"move_forward": K_UP,
"move_backward": K_DOWN,
"rotate_hull_left": K_LEFT,
"rotate_hull_right": K_RIGHT,
"rotate_turret_left": K_PAGEUP,
"rotate_turret_right": K_PAGEDOWN,
},
{
"move_forward": K_w,
"move_backward": K_s,
"rotate_hull_left": K_a,
"rotate_hull_right": K_d,
"rotate_turret_left": K_i,
"rotate_turret_right": K_k,
},
]
def process_inputs(self, tanks: Tuple[Tank, Tank], delta_time: float):
"""
Poll pygame events and update tank states accordingly.
Args:
tanks (Tuple[Tank, Tank]): Tanks to control.
delta_time (float): Time elapsed since last frame in seconds.
"""
keys = pygame.key.get_pressed()
for index, tank in enumerate(tanks):
controls = self._tank_key_map[index]
# Movement
if keys[controls["move_forward"]]:
tank.move_forward(TANK_MOVE_SPEED * delta_time)
if keys[controls["move_backward"]]:
tank.move_backward(TANK_MOVE_SPEED * delta_time)
# Hull rotation
if keys[controls["rotate_hull_left"]]:
tank.rotate_hull(TANK_ANGULAR_SPEED * delta_time)
if keys[controls["rotate_hull_right"]]:
tank.rotate_hull(-TANK_ANGULAR_SPEED * delta_time)
# Turret rotation
if keys[controls["rotate_turret_left"]]:
tank.rotate_turret(TURRET_ANGULAR_SPEED * delta_time)
if keys[controls["rotate_turret_right"]]:
tank.rotate_turret(-TURRET_ANGULAR_SPEED * delta_time)
# Clamp position to terrain bounds (already handled in setters)
# ===========================
# Application Core
# ===========================
class TankTerrainSimulation:
"""
Core application class managing terrain, tanks, input, and rendering loop.
"""
def __init__(self):
logger.info("Starting Tank Terrain Simulation application.")
try:
self.terrain = Terrain()
except TerrainError as e:
logger.critical(f"Failed to initialize terrain: {e}")
sys.exit(1)
self.tank1 = Tank(self.terrain, 5.0, 5.0, hull_angle_deg=0.0, color=(1.0, 0.0, 0.0))
self.tank2 = Tank(self.terrain, 15.0, 15.0, hull_angle_deg=0.0, color=(0.0, 0.0, 1.0))
self.tanks = (self.tank1, self.tank2)
try:
self.renderer = Renderer(self.terrain, self.tanks)
except GraphicsError as e:
logger.critical(f"Failed to initialize renderer: {e}")
sys.exit(1)
self.input_handler = InputHandler()
self.clock = pygame.time.Clock()
self.running = True
def run(self):
"""Run the main application loop."""
logger.info("Entering main loop.")
while self.running:
delta_time = self.clock.tick(FPS) / 1000.0
for event in pygame.event.get():
if event.type == QUIT:
logger.info("Received QUIT event. Exiting.")
self.running = False
elif event.type == KEYDOWN and event.key == K_ESCAPE:
logger.info("ESC pressed. Exiting.")
self.running = False
# Process inputs and update tank state
self.input_handler.process_inputs(self.tanks, delta_time)
# Render the current frame
self.renderer.render_frame()
self.cleanup()
def cleanup(self):
"""Cleanup resources and quit."""
pygame.quit()
logger.info("Simulation terminated cleanly.")
# ===========================
# Entry Point
# ===========================
if __name__ == "__main__":
try:
app = TankTerrainSimulation()
app.run()
except Exception as err:
logger.exception(f"An unhandled exception occurred: {err}")
pygame.quit()
sys.exit(1)
Terrain, Tank, Renderer, InputHandler, TankTerrainSimulation) to encapsulate respective state and behavior._ where appropriate, and methods encapsulate details such as terrain generation, normal calculation, rendering, and input processing.TerrainError, TankError, GraphicsError) signal domain-specific failures, with try-except blocks catching and logging errors with informative messages.logging library for flexible logging levels and output formatting, with meaningful messages throughout the lifecycle.gluDeleteQuadric).This refactoring produces a clean, maintainable codebase suitable for a senior developer environment, cleanly separating concerns and enabling further development and testing easily.
Чтобы танки выглядели реалистичнее, следует улучшить их визуальное представление — добавить более сложную геометрию, текстуры, детализацию кузова, гусениц, более аккуратное позиционирование башни и ствола, а также освещение и тени.
В рамках текущей архитектуры и выбора OpenGL фиксированной функции (legacy pipeline), можно улучшить танки следующим образом:
Дополню предыдущий код с новым классом Tank, заменив метод draw на более комплексный и подробно комментированный.
class Tank:
"""
Реалистичное представление танка с корпусом, башней, гусеницами и стволом.
Атрибуты:
x, z - позиция танка на местности
hull_angle - угол поворота корпуса
turret_angle - угол башни относительно корпуса
color - основной цвет танка
terrain - объект Terrain для определения высоты
"""
def __init__(self,
terrain: Terrain,
start_x: float,
start_z: float,
hull_angle_deg: float,
color: Tuple[float, float, float]):
self._terrain = terrain
self._position = np.array([start_x, 0.0, start_z], dtype=np.float32)
self._position[1] = self._terrain.get_height(start_x, start_z) + 0.5
self.hull_angle = hull_angle_deg
self.turret_angle = 0.0
self.color = color
logger.info(f"Created Tank at ({start_x:.2f}, {start_z:.2f}) with hull angle {hull_angle_deg}° and color {color}")
@property
def x(self) -> float:
return self._position[0]
@x.setter
def x(self, value: float):
self._position[0] = clamp(value, 0.0, self._terrain.physical_size)
self._update_height()
@property
def z(self) -> float:
return self._position[2]
@z.setter
def z(self, value: float):
self._position[2] = clamp(value, 0.0, self._terrain.physical_size)
self._update_height()
@property
def y(self) -> float:
return self._position[1]
def _update_height(self):
terrain_height = self._terrain.get_height(self._position[0], self._position[2])
self._position[1] = terrain_height + 0.5
def move_forward(self, distance: float):
rad = np.radians(self.hull_angle)
new_x = self._position[0] + distance * np.sin(rad)
new_z = self._position[2] + distance * np.cos(rad)
self.x = new_x
self.z = new_z
def move_backward(self, distance: float):
rad = np.radians(self.hull_angle)
new_x = self._position[0] - distance * np.sin(rad)
new_z = self._position[2] - distance * np.cos(rad)
self.x = new_x
self.z = new_z
def rotate_hull(self, angle_delta: float):
self.hull_angle = (self.hull_angle + angle_delta) % 360
def rotate_turret(self, angle_delta: float):
self.turret_angle = (self.turret_angle + angle_delta) % 360
def draw(self):
glPushMatrix()
glTranslatef(self.x, self.y, self.z)
glRotatef(self.hull_angle, 0, 1, 0)
self._draw_hull()
self._draw_tracks()
self._draw_turret_and_barrel()
glPopMatrix()
def _draw_hull(self):
"""
Рисуем корпус танка с материалом — кузов выполнен из нескольких кубоидов,
с цветом и блеском для реалистичности.
"""
# Материал корпуса — слегка металлизированный
mat_ambient = [0.2 * c for c in self.color] + [1.0]
mat_diffuse = [0.6 * c for c in self.color] + [1.0]
mat_specular = [0.8, 0.8, 0.8, 1.0]
mat_shininess = 50.0
glMaterialfv(GL_FRONT, GL_AMBIENT, mat_ambient)
glMaterialfv(GL_FRONT, GL_DIFFUSE, mat_diffuse)
glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular)
glMaterialf(GL_FRONT, GL_SHININESS, mat_shininess)
# Корпус: основной блок — большой кубоид
width, height, length = 1.2, 0.6, 2.0
self._draw_box(-width/2, 0, -length/2, width, height, length)
# Декоративный модуль спереди — "люк"
hatch_width, hatch_height, hatch_length = 0.6, 0.3, 0.4
hatch_x = 0
hatch_y = height
hatch_z = length / 2 - hatch_length / 2
self._draw_box(hatch_x - hatch_width / 2, hatch_y, hatch_z - hatch_length / 2,
hatch_width, hatch_height, hatch_length, color_mod=(0.7, 0.7, 0.7))
def _draw_tracks(self):
"""
Рисуем гусеницы по бокам корпуса — упрощенные кубы.
Цвет темно-серый с легкими бликами для имитации металла.
"""
track_width, track_height, track_length = 0.3, 0.4, 2.0
track_y = 0.1 # чуть ниже корпуса
# Материал гусениц (темно-серый, немного блестящий)
glMaterialfv(GL_FRONT, GL_AMBIENT, [0.1, 0.1, 0.1, 1])
glMaterialfv(GL_FRONT, GL_DIFFUSE, [0.3, 0.3, 0.3, 1])
glMaterialfv(GL_FRONT, GL_SPECULAR, [0.5, 0.5, 0.5, 1])
glMaterialf(GL_FRONT, GL_SHININESS, 25)
x_offset = 0.75 # боковое смещение (полусумма ширины корпуса + ширина гусеницы/2)
# Левая гусеница
self._draw_box(-x_offset - track_width/2, track_y, -track_length/2,
track_width, track_height, track_length)
# Правая гусеница
self._draw_box(x_offset - track_width/2, track_y, -track_length/2,
track_width, track_height, track_length)
def _draw_turret_and_barrel(self):
"""
Нарисовать вращающуюся башню с более реалистичной формой и
ствол с небольшим смещением для естественного расположения.
"""
glPushMatrix()
turret_base_height = 0.6
glTranslatef(0, turret_base_height, 0) # Высота установки башни
# Вращение башни относительно корпуса
glRotatef(self.turret_angle, 0, 1, 0)
# Материал башни — серый матовый металл
glMaterialfv(GL_FRONT, GL_AMBIENT, [0.3, 0.3, 0.3, 1])
glMaterialfv(GL_FRONT, GL_DIFFUSE, [0.6, 0.6, 0.6, 1])
glMaterialfv(GL_FRONT, GL_SPECULAR, [0.5, 0.5, 0.5, 1])
glMaterialf(GL_FRONT, GL_SHININESS, 30)
# Турель — цилиндр с усеченной верхушкой (конусовидная крышка)
turret_radius = 0.5
turret_height = 0.5
quad = gluNewQuadric()
gluQuadricNormals(quad, GLU_SMOOTH)
gluCylinder(quad, turret_radius, turret_radius * 0.9, turret_height, 30, 1)
# Верхняя крышка - конус
glTranslatef(0, 0, turret_height)
gluCylinder(quad, turret_radius * 0.9, 0.0, 0.3, 30, 1)
gluDeleteQuadric(quad)
# Ствол — тонкая длинная цилиндрическая труба, с небольшим наклоном вверх
glPopMatrix()
glPushMatrix()
barrel_base_height = turret_base_height + turret_height * 0.7
glTranslatef(0, barrel_base_height, 0)
glRotatef(self.turret_angle, 0, 1, 0)
# Немного наклоняем вверх ствол (~5 градусов)
glRotatef(-5, 1, 0, 0)
# Сдвигаем ствол вперед относительно центра башни
glTranslatef(0.0, 0.0, turret_radius * 1.1)
# Материал ствола — темный металл
glMaterialfv(GL_FRONT, GL_AMBIENT, [0.2, 0.2, 0.2, 1])
glMaterialfv(GL_FRONT, GL_DIFFUSE, [0.4, 0.4, 0.4, 1])
glMaterialfv(GL_FRONT, GL_SPECULAR, [0.6, 0.6, 0.6, 1])
glMaterialf(GL_FRONT, GL_SHININESS, 60)
quad = gluNewQuadric()
gluQuadricNormals(quad, GLU_SMOOTH)
barrel_radius = 0.1
barrel_length = 1.5
gluCylinder(quad, barrel_radius, barrel_radius, barrel_length, 20, 5)
# Конец ствола — немного расширенный носик (гоним конус)
glTranslatef(0, 0, barrel_length)
gluCylinder(quad, barrel_radius * 1.4, 0.0, 0.3, 20, 2)
gluDeleteQuadric(quad)
glPopMatrix()
def _draw_box(self, x: float, y: float, z: float, width: float, height: float, length: float, color_mod: Optional[Tuple[float, float, float]] = None):
"""
Вспомогательная функция для рисования окрашенного кубоида.
Args:
x, y, z — координаты нижнего левого переднего угла
width, height, length — размеры куба по осям XYZ
color_mod — если задан, модифицирует текущий цвет (умножает)
"""
# Если есть модификатор цвета — применим
if color_mod:
orig_color = glGetFloatv(GL_CURRENT_COLOR)
new_color = tuple(orig_color[i] * color_mod[i] for i in range(3)) + (orig_color[3],)
glColor4f(*new_color)
# Куб с нормалями для освещения
glBegin(GL_QUADS)
# Bottom face (y)
glNormal3f(0, -1, 0)
glVertex3f(x, y, z)
glVertex3f(x + width, y, z)
glVertex3f(x + width, y, z + length)
glVertex3f(x, y, z + length)
# Top face (y + height)
glNormal3f(0, 1, 0)
glVertex3f(x, y + height, z)
glVertex3f(x + width, y + height, z)
glVertex3f(x + width, y + height, z + length)
glVertex3f(x, y + height, z + length)
# Front face (z + length)
glNormal3f(0, 0, 1)
glVertex3f(x, y, z + length)
glVertex3f(x + width, y, z + length)
glVertex3f(x + width, y + height, z + length)
glVertex3f(x, y + height, z + length)
# Back face (z)
glNormal3f(0, 0, -1)
glVertex3f(x, y, z)
glVertex3f(x + width, y, z)
glVertex3f(x + width, y + height, z)
glVertex3f(x, y + height, z)
# Left face (x)
glNormal3f(-1, 0, 0)
glVertex3f(x, y, z)
glVertex3f(x, y, z + length)
glVertex3f(x, y + height, z + length)
glVertex3f(x, y + height, z)
# Right face (x + width)
glNormal3f(1, 0, 0)
glVertex3f(x + width, y, z)
glVertex3f(x + width, y, z + length)
glVertex3f(x + width, y + height, z + length)
glVertex3f(x + width, y + height, z)
glEnd()
if color_mod:
# Восстановим цвет (редко критично, но лучше так)
glColor4f(*orig_color)
Просто замените старый класс Tank данным классом в вашем проекте и убедитесь, что освещение и режимы OpenGL включены (что уже сделано в Renderer).
Если потребуется — могу помочь с добавлением текстур или переходом на PyOpenGL shader pipeline для освоения более современного OpenGL!
Not yet included in a published release.