Загрузка данных
import pygame
from pygame.locals import *
from OpenGL.GL import *
from OpenGL.GLU import *
import math
import random
import sys
# --- МАТЕМАТИЧЕСКИЕ ОПЕРАЦИИ (ЧИСТЫЙ PYTHON) ---
def vec_len(v):
return math.sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2])
def vec_norm(v):
l = vec_len(v)
if l < 1e-6:
return [0.0, 0.0, 0.0]
return [v[0] / l, v[1] / l, v[2] / l]
def vec_dist(v1, v2):
return math.sqrt((v1[0] - v2[0])**2 + (v1[1] - v2[1])**2 + (v1[2] - v2[2])**2)
# --- ГРАФИЧЕСКИЕ ПРИМИТИВЫ (OPENGL 3D) ---
def draw_box(size, color, offset=(0, 0, 0)):
sx, sy, sz = size[0] / 2.0, size[1] / 2.0, size[2] / 2.0
ox, oy, oz = offset[0], offset[1], offset[2]
glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, [*color, 1.0])
glBegin(GL_QUADS)
# Спереди
glNormal3f(0.0, 0.0, 1.0)
glVertex3f(ox - sx, oy - sy, oz + sz)
glVertex3f(ox + sx, oy - sy, oz + sz)
glVertex3f(ox + sx, oy + sy, oz + sz)
glVertex3f(ox - sx, oy + sy, oz + sz)
# Сзади
glNormal3f(0.0, 0.0, -1.0)
glVertex3f(ox - sx, oy - sy, oz - sz)
glVertex3f(ox - sx, oy + sy, oz - sz)
glVertex3f(ox + sx, oy + sy, oz - sz)
glVertex3f(ox + sx, oy - sy, oz - sz)
# Сверху
glNormal3f(0.0, 1.0, 0.0)
glVertex3f(ox - sx, oy + sy, oz - sz)
glVertex3f(ox - sx, oy + sy, oz + sz)
glVertex3f(ox + sx, oy + sy, oz + sz)
glVertex3f(ox + sx, oy + sy, oz - sz)
# Снизу
glNormal3f(0.0, -1.0, 0.0)
glVertex3f(ox - sx, oy - sy, oz - sz)
glVertex3f(ox + sx, oy - sy, oz - sz)
glVertex3f(ox + sx, oy - sy, oz + sz)
glVertex3f(ox - sx, oy - sy, oz + sz)
# Справа
glNormal3f(1.0, 0.0, 0.0)
glVertex3f(ox + sx, oy - sy, oz - sz)
glVertex3f(ox + sx, oy + sy, oz - sz)
glVertex3f(ox + sx, oy + sy, oz + sz)
glVertex3f(ox + sx, oy - sy, oz + sz)
# Слева
glNormal3f(-1.0, 0.0, 0.0)
glVertex3f(ox - sx, oy - sy, oz - sz)
glVertex3f(ox - sx, oy - sy, oz + sz)
glVertex3f(ox - sx, oy + sy, oz + sz)
glVertex3f(ox - sx, oy + sy, oz - sz)
glEnd()
def draw_cylinder(radius, length, segments=12, color=(0.2, 0.2, 0.2)):
glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, [*color, 1.0])
glBegin(GL_QUAD_STRIP)
for i in range(segments + 1):
angle = 2.0 * math.pi * i / segments
x = radius * math.cos(angle)
y = radius * math.sin(angle)
glNormal3f(math.cos(angle), math.sin(angle), 0.0)
glVertex3f(x, y, 0.0)
glVertex3f(x, y, length)
glEnd()
# --- СИСТЕМА ЧАСТИЦ (БЕЗ NUMPY) ---
class ParticleSystem:
def __init__(self):
self.particles = []
def emit(self, pos, count=16, color=(1.0, 0.5, 0.1), speed=8.0, size=0.25):
for _ in range(count):
rx = random.uniform(-1, 1)
ry = random.uniform(0.5, 2.0)
rz = random.uniform(-1, 1)
norm = vec_norm([rx, ry, rz])
sp = random.uniform(speed * 0.4, speed)
p = {
'x': pos[0], 'y': pos[1], 'z': pos[2],
'vx': norm[0] * sp, 'vy': norm[1] * sp, 'vz': norm[2] * sp,
'life': 1.0,
'decay': random.uniform(1.2, 2.5),
'color': color,
'size': size
}
self.particles.append(p)
def update(self, dt):
survivors = []
for p in self.particles:
p['x'] += p['vx'] * dt
p['y'] += p['vy'] * dt
p['z'] += p['vz'] * dt
p['vy'] -= 9.8 * dt * 0.5
p['life'] -= p['decay'] * dt
if p['life'] > 0.0:
survivors.append(p)
self.particles = survivors
def draw(self):
glDisable(GL_LIGHTING)
for p in self.particles:
c = p['color']
s = p['size'] * p['life']
glPushMatrix()
glTranslatef(p['x'], p['y'], p['z'])
draw_box((s, s, s), c)
glPopMatrix()
glEnable(GL_LIGHTING)
# --- СНАРЯД ---
class Shell:
def __init__(self, pos, direction, is_player=True):
self.pos = list(pos)
self.dir = vec_norm(direction)
self.speed = 65.0
self.is_player = is_player
self.active = True
self.life = 2.5
def update(self, dt):
self.pos[0] += self.dir[0] * self.speed * dt
self.pos[1] += self.dir[1] * self.speed * dt
self.pos[2] += self.dir[2] * self.speed * dt
self.life -= dt
if self.life <= 0:
self.active = False
def draw(self):
glPushMatrix()
glTranslatef(self.pos[0], self.pos[1], self.pos[2])
col = (1.0, 0.9, 0.2) if self.is_player else (1.0, 0.2, 0.2)
draw_box((0.25, 0.25, 0.6), col)
glPopMatrix()
# --- СУЩНОСТЬ ТАНКА ---
class Tank:
def __init__(self, x, z, base_color, is_player=False):
self.pos = [float(x), 0.0, float(z)]
self.rotation_y = 0.0
self.turret_angle = 0.0
self.recoil = 0.0
self.color = base_color
self.is_player = is_player
self.max_hp = 5 if is_player else 3
self.hp = self.max_hp
self.speed = 13.0 if is_player else 7.0
self.turn_speed = 90.0
self.shoot_cd = 0.0
self.alive = True
def get_forward_vector(self):
rad = math.radians(self.rotation_y)
return [math.sin(rad), 0.0, math.cos(rad)]
def get_turret_forward(self):
rad = math.radians(self.rotation_y + self.turret_angle)
return [math.sin(rad), 0.0, math.cos(rad)]
def update(self, dt):
if self.shoot_cd > 0:
self.shoot_cd -= dt
if self.recoil > 0:
self.recoil = max(0.0, self.recoil - dt * 3.5)
def draw(self):
if not self.alive:
return
glPushMatrix()
glTranslatef(self.pos[0], self.pos[1], self.pos[2])
glRotatef(self.rotation_y, 0, 1, 0)
# Гусеницы и катки
track_col = (0.15, 0.15, 0.15)
draw_box((0.75, 0.65, 4.6), track_col, offset=(-1.35, 0.32, 0.0))
draw_box((0.75, 0.65, 4.6), track_col, offset=(1.35, 0.32, 0.0))
wheel_col = (0.28, 0.28, 0.3)
for side in (-1.35, 1.35):
for z_off in (-1.6, -0.8, 0.0, 0.8, 1.6):
draw_box((0.78, 0.45, 0.45), wheel_col, offset=(side, 0.25, z_off))
# Корпус
draw_box((2.3, 0.65, 4.2), self.color, offset=(0.0, 0.55, 0.0))
draw_box((2.0, 0.3, 3.8), [c * 0.85 for c in self.color], offset=(0.0, 0.85, -0.1))
# Башня
glPushMatrix()
glTranslatef(0.0, 1.15, 0.0)
glRotatef(self.turret_angle, 0, 1, 0)
draw_box((1.8, 0.65, 2.3), self.color, offset=(0.0, 0.0, -0.2))
draw_box((0.8, 0.4, 0.6), (0.1, 0.1, 0.1), offset=(0.0, 0.0, 0.95))
draw_box((0.5, 0.25, 0.5), (0.2, 0.2, 0.2), offset=(0.45, 0.42, -0.4))
# Ствол с откатом
glPushMatrix()
glTranslatef(0.0, 0.0, 1.2 - self.recoil)
draw_cylinder(0.12, 2.8, segments=12, color=(0.15, 0.15, 0.15))
draw_box((0.35, 0.35, 0.5), (0.1, 0.1, 0.1), offset=(0.0, 0.0, 2.8))
glPopMatrix()
glPopMatrix()
glPopMatrix()
self.draw_hp_bar()
def draw_hp_bar(self):
glDisable(GL_LIGHTING)
glPushMatrix()
glTranslatef(self.pos[0], self.pos[1] + 2.8, self.pos[2])
# Фиксируем на камеру
mat = glGetFloatv(GL_MODELVIEW_MATRIX)
for i in range(3):
for j in range(3):
mat[i][j] = 1.0 if i == j else 0.0
glLoadMatrixf(mat)
draw_box((1.6, 0.16, 0.02), (0.1, 0.1, 0.1))
pct = max(0.0, self.hp / self.max_hp)
fill_col = (0.2, 0.9, 0.2) if pct > 0.5 else ((0.9, 0.6, 0.1) if pct > 0.25 else (0.9, 0.1, 0.1))
draw_box((1.56 * pct, 0.12, 0.04), fill_col, offset=(-0.78 * (1.0 - pct), 0.0, 0.01))
glPopMatrix()
glEnable(GL_LIGHTING)
# --- ЗДАНИЯ ---
class Building:
def __init__(self, x, z, sx, sy, sz):
self.pos = [float(x), sy / 2.0, float(z)]
self.size = (sx, sy, sz)
self.hp = 3
self.alive = True
self.color = (0.45, 0.42, 0.4)
def draw(self):
if not self.alive:
return
draw_box(self.size, self.color, offset=self.pos)
# --- ДВИЖОК ИГРЫ ---
class TankWarGame:
def __init__(self):
pygame.init()
self.res = (1280, 720)
pygame.display.set_mode(self.res, DOUBLEBUF | OPENGL)
pygame.display.set_caption("3D Panzer Force")
pygame.mouse.set_visible(False)
pygame.event.set_grab(True)
self.clock = pygame.time.Clock()
self.particles = ParticleSystem()
self.map_size = 140.0
self.score = 0
self.game_over = False
self.init_gl()
self.init_world()
def init_gl(self):
glEnable(GL_DEPTH_TEST)
glEnable(GL_LIGHTING)
glEnable(GL_LIGHT0)
glEnable(GL_COLOR_MATERIAL)
glColorMaterial(GL_FRONT, GL_AMBIENT_AND_DIFFUSE)
glLightfv(GL_LIGHT0, GL_POSITION, [40.0, 60.0, 40.0, 1.0])
glLightfv(GL_LIGHT0, GL_DIFFUSE, [0.95, 0.92, 0.88, 1.0])
glLightfv(GL_LIGHT0, GL_AMBIENT, [0.4, 0.4, 0.42, 1.0])
glClearColor(0.53, 0.75, 0.92, 1.0)
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
gluPerspective(60, (self.res[0] / self.res[1]), 0.5, 350.0)
glMatrixMode(GL_MODELVIEW)
def init_world(self):
self.player = Tank(0, -30, (0.2, 0.55, 0.25), is_player=True)
self.enemies = []
self.bullets = []
self.buildings = []
random.seed(1337)
for _ in range(30):
bx = random.uniform(-self.map_size / 2 + 15, self.map_size / 2 - 15)
bz = random.uniform(-self.map_size / 2 + 15, self.map_size / 2 - 15)
if abs(bx) > 12 or abs(bz) > 12:
self.buildings.append(Building(bx, bz, random.choice([5, 8]), random.choice([4, 6]), random.choice([5, 8])))
for ex, ez in [(-35, 25), (0, 40), (35, 25), (-40, -10), (40, -10)]:
self.enemies.append(Tank(ex, ez, (0.7, 0.25, 0.2)))
self.cam_yaw = 0.0
self.cam_pitch = 20.0
self.cam_dist = 16.0
def handle_input(self, dt):
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
pygame.quit()
sys.exit()
if event.key == K_r and self.game_over:
self.init_world()
self.score = 0
self.game_over = False
return
if event.type == MOUSEMOTION:
dx, dy = event.rel
self.cam_yaw -= dx * 0.2
self.cam_pitch = max(8.0, min(50.0, self.cam_pitch + dy * 0.15))
if event.type == MOUSEBUTTONDOWN and event.button == 1:
if self.player.alive and self.player.shoot_cd <= 0:
self.fire_tank(self.player)
if not self.player.alive:
return
keys = pygame.key.get_pressed()
if keys[K_a]:
self.player.rotation_y += self.player.turn_speed * dt
if keys[K_d]:
self.player.rotation_y -= self.player.turn_speed * dt
move_dir = 0.0
if keys[K_w]:
move_dir += 1.0
if keys[K_s]:
move_dir -= 0.6
if move_dir != 0:
fwd = self.player.get_forward_vector()
new_x = self.player.pos[0] + fwd[0] * (move_dir * self.player.speed * dt)
new_z = self.player.pos[2] + fwd[2] * (move_dir * self.player.speed * dt)
limit = self.map_size / 2.0 - 4.0
if abs(new_x) < limit and abs(new_z) < limit:
blocked = False
for b in self.buildings:
if b.alive and vec_dist([new_x, 0, new_z], b.pos) < 4.5:
blocked = True
break
if not blocked:
self.player.pos[0] = new_x
self.player.pos[2] = new_z
target_turret = (self.cam_yaw - self.player.rotation_y) % 360
if target_turret > 180:
target_turret -= 360
self.player.turret_angle = target_turret
def fire_tank(self, tank):
tank.shoot_cd = 0.65 if tank.is_player else 2.6
tank.recoil = 0.4
fwd = tank.get_turret_forward()
spawn_pos = [
tank.pos[0] + fwd[0] * 3.8,
tank.pos[1] + 1.15,
tank.pos[2] + fwd[2] * 3.8
]
self.bullets.append(Shell(spawn_pos, fwd, is_player=tank.is_player))
self.particles.emit(spawn_pos, count=14, color=(1.0, 0.7, 0.2), speed=6.0, size=0.22)
def update_ai(self, dt):
for e in self.enemies:
if not e.alive:
continue
dist_to_p = vec_dist(e.pos, self.player.pos)
to_p = [self.player.pos[0] - e.pos[0], 0, self.player.pos[2] - e.pos[2]]
target_yaw = math.degrees(math.atan2(to_p[0], to_p[2]))
rel_yaw = (target_yaw - e.rotation_y) % 360
if rel_yaw > 180:
rel_yaw -= 360
e.turret_angle = rel_yaw
sign = 1.0 if rel_yaw > 0 else (-1.0 if rel_yaw < 0 else 0.0)
e.rotation_y += sign * e.turn_speed * 0.4 * dt
if dist_to_p > 18.0:
fwd = e.get_forward_vector()
e.pos[0] += fwd[0] * e.speed * dt
e.pos[2] += fwd[2] * e.speed * dt
if dist_to_p < 55.0 and e.shoot_cd <= 0 and self.player.alive:
self.fire_tank(e)
e.update(dt)
def update_physics(self, dt):
self.player.update(dt)
self.update_ai(dt)
self.particles.update(dt)
surviving_bullets = []
for b in self.bullets:
b.update(dt)
if not b.active:
continue
hit = False
# Укрытия
for bld in self.buildings:
if bld.alive and vec_dist(b.pos, bld.pos) < 4.0:
bld.hp -= 1
if bld.hp <= 0:
bld.alive = False
self.particles.emit(bld.pos, count=35, color=(0.4, 0.4, 0.4), speed=10.0, size=0.5)
self.particles.emit(b.pos, count=10, color=(0.6, 0.5, 0.3), speed=5.0)
hit = True
break
if hit:
continue
# Танки
if b.is_player:
for e in self.enemies:
if e.alive and vec_dist(b.pos, [e.pos[0], e.pos[1] + 0.8, e.pos[2]]) < 2.3:
e.hp -= 1
self.particles.emit(b.pos, count=25, color=(1.0, 0.3, 0.1), speed=12.0)
if e.hp <= 0:
e.alive = False
self.score += 100
self.particles.emit([e.pos[0], e.pos[1] + 1.0, e.pos[2]], count=60, color=(0.9, 0.4, 0.1), speed=15.0, size=0.6)
hit = True
break
else:
if self.player.alive and vec_dist(b.pos, [self.player.pos[0], self.player.pos[1] + 0.8, self.player.pos[2]]) < 2.3:
self.player.hp -= 1
self.particles.emit(b.pos, count=30, color=(1.0, 0.2, 0.1), speed=14.0)
if self.player.hp <= 0:
self.player.alive = False
self.game_over = True
self.particles.emit([self.player.pos[0], self.player.pos[1] + 1.0, self.player.pos[2]], count=80, color=(0.9, 0.3, 0.1), speed=16.0, size=0.8)
hit = True
if not hit:
surviving_bullets.append(b)
self.bullets = surviving_bullets
if all(not e.alive for e in self.enemies):
self.game_over = True
def render_ground(self):
glDisable(GL_LIGHTING)
step = 10
half = int(self.map_size / 2)
glBegin(GL_QUADS)
for x in range(-half, half, step):
for z in range(-half, half, step):
if (x // step + z // step) % 2 == 0:
glColor3f(0.32, 0.45, 0.28)
else:
glColor3f(0.36, 0.49, 0.31)
glVertex3f(x, 0.0, z)
glVertex3f(x + step, 0.0, z)
glVertex3f(x + step, 0.0, z + step)
glVertex3f(x, 0.0, z + step)
glEnd()
glEnable(GL_LIGHTING)
def draw_hud(self):
glMatrixMode(GL_PROJECTION)
glPushMatrix()
glLoadIdentity()
gluOrtho2D(0, self.res[0], 0, self.res[1])
glMatrixMode(GL_MODELVIEW)
glPushMatrix()
glLoadIdentity()
glDisable(GL_LIGHTING)
glDisable(GL_DEPTH_TEST)
font = pygame.font.SysFont("impact", 26)
alive_enemies = sum(1 for e in self.enemies if e.alive)
stats_surf = font.render(f"SCORE: {self.score} | ENEMIES LEFT: {alive_enemies}", True, (255, 230, 80))
stats_data = pygame.image.tostring(stats_surf, "RGBA", True)
glRasterPos2i(30, self.res[1] - 45)
glDrawPixels(stats_surf.get_width(), stats_surf.get_height(), GL_RGBA, GL_UNSIGNED_BYTE, stats_data)
# Прицельный маркер
cx, cy = self.res[0] // 2, self.res[1] // 2
glColor3f(1.0, 1.0, 1.0)
glBegin(GL_LINES)
glVertex2f(cx - 12, cy); glVertex2f(cx + 12, cy)
glVertex2f(cx, cy - 12); glVertex2f(cx, cy + 12)
glEnd()
if self.game_over:
msg = "MISSION ACCOMPLISHED!" if self.player.alive else "VEHICLE DESTROYED!"
col = (50, 255, 50) if self.player.alive else (255, 50, 50)
end_font = pygame.font.SysFont("impact", 48)
end_surf = end_font.render(msg, True, col)
end_data = pygame.image.tostring(end_surf, "RGBA", True)
glRasterPos2i(self.res[0] // 2 - end_surf.get_width() // 2, self.res[1] // 2 + 20)
glDrawPixels(end_surf.get_width(), end_surf.get_height(), GL_RGBA, GL_UNSIGNED_BYTE, end_data)
sub_font = pygame.font.SysFont("consolas", 20, bold=True)
sub_surf = sub_font.render("Press R to restart or ESC to quit", True, (255, 255, 255))
sub_data = pygame.image.tostring(sub_surf, "RGBA", True)
glRasterPos2i(self.res[0] // 2 - sub_surf.get_width() // 2, self.res[1] // 2 - 30)
glDrawPixels(sub_surf.get_width(), sub_surf.get_height(), GL_RGBA, GL_UNSIGNED_BYTE, sub_data)
glEnable(GL_DEPTH_TEST)
glEnable(GL_LIGHTING)
glPopMatrix()
glMatrixMode(GL_PROJECTION)
glPopMatrix()
glMatrixMode(GL_MODELVIEW)
def run(self):
while True:
dt = self.clock.tick(60) / 1000.0
self.handle_input(dt)
if not self.game_over:
self.update_physics(dt)
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
glLoadIdentity()
rad_yaw = math.radians(self.cam_yaw)
rad_pitch = math.radians(self.cam_pitch)
# Камера точно позади танка
cam_x = self.player.pos[0] - self.cam_dist * math.sin(rad_yaw) * math.cos(rad_pitch)
cam_y = self.player.pos[1] + self.cam_dist * math.sin(rad_pitch) + 2.0
cam_z = self.player.pos[2] - self.cam_dist * math.cos(rad_yaw) * math.cos(rad_pitch)
target_y = self.player.pos[1] + 1.2
gluLookAt(cam_x, cam_y, cam_z, self.player.pos[0], target_y, self.player.pos[2], 0, 1, 0)
self.render_ground()
for bld in self.buildings:
bld.draw()
self.player.draw()
for e in self.enemies:
e.draw()
for b in self.bullets:
b.draw()
self.particles.draw()
self.draw_hud()
pygame.display.flip()
if __name__ == "__main__":
game = TankWarGame()
game.run()