当前位置:   article > 正文

python-pyglet游戏之Minecraft_pyglet 游戏 源代码

pyglet 游戏 源代码

今天,我要为大家带来的是真实的Minecraft!这次大家可以不用失望了,真的是了!

---------------------------------------------------开始写代码了!---------------------------------------------------------

首先我要提醒大家的是先pip一下:

打开cmd,输入以下代码:

pip install pyglet

因程序太长了,所以我不会细分讲解。

一、提前准备和变量定义

先导入模块

定义好任务的变量,如重力,跳跃距离等。

  1. from __future__ import division
  2. import sys
  3. import math
  4. import random
  5. import time
  6. from collections import deque
  7. from pyglet import image
  8. from pyglet.gl import *
  9. from pyglet.graphics import TextureGroup
  10. from pyglet.window import key, mouse
  11. TICKS_PER_SEC = 60
  12. SECTOR_SIZE = 16
  13. GAMETYPES = False # 是否开启冰雪世界
  14. SEED = random.randint(10, 1000000)#656795(种子"akioi") # 世界种子
  15. GTIME = 0 # 当前世界时间
  16. GDAY = 0.0005
  17. GNIGHT = 0.0015
  18. PLAYER_HEIGHT = 2 # 玩家高度
  19. WALKING_SPEED = PLAYER_HEIGHT + 2# 走路速度
  20. RUNNING_SPEED = PLAYER_HEIGHT * 2 # 跑步速度
  21. FLYING_SPEED = 15 # 飞行速度
  22. # 35.0
  23. GRAVITY = 35.0 # 重力
  24. MAX_JUMP_HEIGHT = PLAYER_HEIGHT - 0.75 # 最大跳跃速度
  25. JUMP_SPEED = math.sqrt(2 * GRAVITY * MAX_JUMP_HEIGHT)
  26. TERMINAL_VELOCITY = 35 # 终端速度
  27. WORLDLEN = 128 # 世界长度
  28. TEXTURE_PATH = 'texture2_1.png' # 纹理文件

最后我会奉上图片的

二、主要函数、地图生成和人物设定

为了让大家看得清楚,我这里就不讲解了,直接让大家看代码:

  1. def cube_vertices(x, y, z, n):
  2. # 返回立方体的顶点,大小为2n。
  3. return [
  4. x-n,y+n,z-n, x-n,y+n,z+n, x+n,y+n,z+n, x+n,y+n,z-n, # top
  5. x-n,y-n,z-n, x+n,y-n,z-n, x+n,y-n,z+n, x-n,y-n,z+n, # bottom
  6. x-n,y-n,z-n, x-n,y-n,z+n, x-n,y+n,z+n, x-n,y+n,z-n, # left
  7. x+n,y-n,z+n, x+n,y-n,z-n, x+n,y+n,z-n, x+n,y+n,z+n, # right
  8. x-n,y-n,z+n, x+n,y-n,z+n, x+n,y+n,z+n, x-n,y+n,z+n, # front
  9. x+n,y-n,z-n, x-n,y-n,z-n, x-n,y+n,z-n, x+n,y+n,z-n, # back
  10. ]
  11. def tex_coord(x, y, n=8):
  12. # 返回纹理的边界顶点。
  13. m = 1.0 / n
  14. dx = x * m
  15. dy = y * m
  16. return dx, dy, dx + m, dy, dx + m, dy + m, dx, dy + m
  17. def tex_coords(top, bottom, side):
  18. # 返回顶部、底部和侧面的纹理列表。
  19. top = tex_coord(*top)
  20. bottom = tex_coord(*bottom)
  21. side = tex_coord(*side)
  22. result = []
  23. result.extend(top)
  24. result.extend(bottom)
  25. result.extend(side * 4)
  26. return result
  27. if GAMETYPES:
  28. GRASS = tex_coords((4, 0), (0, 1), (1, 3))
  29. else:
  30. GRASS = tex_coords((1, 0), (0, 1), (0, 0))
  31. SAND = tex_coords((1, 1), (1, 1), (1, 1))
  32. DIRT = tex_coords((0, 1), (0, 1), (0, 1))
  33. STONE = tex_coords((2, 0), (2, 0), (2, 0))
  34. ENDSTONE = tex_coords((2, 1), (2, 1), (2, 1))
  35. if GAMETYPES:
  36. WATER = tex_coords((3, 1), (3, 1), (3, 1))
  37. else:
  38. WATER = tex_coords((0, 4), (0, 4), (0, 4))
  39. WOOD = tex_coords((0, 2), (0, 2), (3, 0))
  40. LEAF = tex_coords((0, 3), (0, 3), (0, 3))
  41. BRICK = tex_coords((1, 2), (1, 2), (1, 2))
  42. PUMKEY = tex_coords((2, 2), (3, 3), (2, 3))
  43. MELON = tex_coords((2, 4), (2, 4), (1, 4))
  44. CLOUD = tex_coords((3, 2), (3, 2), (3, 2))
  45. TNT = tex_coords((4, 2), (4, 3), (4, 1))
  46. # 立方体的6个面
  47. FACES = [
  48. ( 0, 1, 0),
  49. ( 0,-1, 0),
  50. (-1, 0, 0),
  51. ( 1, 0, 0),
  52. ( 0, 0, 1),
  53. ( 0, 0,-1),
  54. ]
  55. random.seed(SEED)
  56. def normalize(position):
  57. # 将三维坐标'position'的x、y、z取近似值
  58. x, y, z = position
  59. x, y, z = (round(x), round(y), round(z))
  60. return (x, y, z)
  61. def sectorize(position):
  62. x, y, z = normalize(position)
  63. x, y, z = x // SECTOR_SIZE, y // SECTOR_SIZE, z // SECTOR_SIZE
  64. return (x, 0, z)
  65. persistence = random.uniform(0.01,0.15)
  66. Number_Of_Octaves = random.randint(3,5)
  67. def Noise(x, y):
  68. n = x + y * 57
  69. n = (n * 8192) ^ n
  70. return ( 1.0 - ( (n * (n * n * 15731 + 789221) + 1376312589) & 0x7fffffff) / 1073741824.0)
  71. def SmoothedNoise(x, y):
  72. corners = ( Noise(x-1, y-1)+Noise(x+1, y-1)+Noise(x-1, y+1)+Noise(x+1, y+1) ) / 16
  73. sides = ( Noise(x-1, y) +Noise(x+1, y) +Noise(x, y-1) +Noise(x, y+1) ) / 8
  74. center = Noise(x, y) / 4
  75. return corners + sides + center
  76. def Cosine_Interpolate(a, b, x):
  77. ft = x * 3.1415927
  78. f = (1 - math.cos(ft)) * 0.5
  79. return a*(1-f) + b*f
  80. def Linear_Interpolate(a, b, x):
  81. return a*(1-x) + b*x
  82. def InterpolatedNoise(x, y):
  83. integer_X = int(x)
  84. fractional_X = x - integer_X
  85. integer_Y = int(y)
  86. fractional_Y = y - integer_Y
  87. v1 = SmoothedNoise(integer_X, integer_Y)
  88. v2 = SmoothedNoise(integer_X + 1, integer_Y)
  89. v3 = SmoothedNoise(integer_X, integer_Y + 1)
  90. v4 = SmoothedNoise(integer_X + 1, integer_Y + 1)
  91. i1 = Cosine_Interpolate(v1, v2, fractional_X)
  92. i2 = Cosine_Interpolate(v3, v4, fractional_X)
  93. return Cosine_Interpolate(i1, i2, fractional_Y)
  94. def PerlinNoise(x, y):
  95. noise = 0
  96. p = persistence
  97. n = Number_Of_Octaves
  98. for i in range(n):
  99. frequency = pow(2,i)
  100. amplitude = pow(p,i)
  101. noise = noise + InterpolatedNoise(x * frequency, y * frequency) * amplitude
  102. return noise
  103. class Model(object):
  104. def __init__(self):
  105. self.batch = pyglet.graphics.Batch()
  106. self.group = TextureGroup(image.load(TEXTURE_PATH).get_texture()) # 纹理列表
  107. self.world = {} # 地图
  108. self.shown = {} # 显示的方块
  109. self._shown = {} # 显示的纹理
  110. self.sectors = {}
  111. self.queue = deque()
  112. self.dfy = self._initialize()
  113. def tree(self, y, x, z):
  114. # 生成树
  115. th = random.randint(4, 6)
  116. ts = random.randint(th // 2, 4)
  117. for i in range(y, y + th):
  118. self.add_block((x, i, z), WOOD, immediate=False)
  119. for dy in range(y + th, y + th + 2):
  120. for dx in range(x - ts, x + ts + 1):
  121. for dz in range(z - ts, z + ts + 1):
  122. self.add_block((dx, dy, dz), LEAF, immediate=False)
  123. for dy in range(y + th + 2, y + th + ts + 2):
  124. ts -= 1
  125. for dx in range(x - ts, x + ts + 1):
  126. for dz in range(z - ts, z + ts + 1):
  127. self.add_block((dx, dy, dz), LEAF, immediate=False)
  128. def _initialize(self):
  129. # 初始化世界
  130. hl = WORLDLEN // 2
  131. mn = 0
  132. quality = 4
  133. gmap = [[0 for x in range(0, WORLDLEN)]for z in range(0, WORLDLEN)]
  134. for x in range(0, WORLDLEN):
  135. for z in range(0, WORLDLEN):
  136. gmap[x - hl][z - hl] += round(PerlinNoise(x / quality, z / quality) * quality)
  137. mn = min(mn, gmap[x - hl][z - hl])
  138. for x in range(-hl, hl):
  139. for z in range(-hl, hl):
  140. gmap[x][z] += abs(mn)
  141. if gmap[x][z] < 2:
  142. self.add_block((x, -1, z), random.choice([SAND, STONE]))
  143. self.add_block((x, 0, z), WATER)
  144. self.add_block((x, 1, z), WATER)
  145. else:
  146. for y in range(-1, gmap[x][z]):
  147. self.add_block((x, y, z), STONE)
  148. self.add_block((x, gmap[x][z], z), GRASS)
  149. self.add_block((x, -2, z), ENDSTONE)
  150. for x in range(-hl, hl, 4):
  151. for z in range(-hl, hl, 4):
  152. if x == 0 and z == 0:
  153. continue
  154. if random.randint(0, 3) == 1 and gmap[x][z] > 1:
  155. self.tree(gmap[x][z] + 1, x, z)
  156. for i in range(x, x + 4):
  157. for j in range(z, z + 4):
  158. self._show_block((i, 30, j), CLOUD)
  159. elif random.randint(0, 4) == 2 and gmap[x][z] > 2:
  160. self.add_block((x, gmap[x][z] + 1, z), random.choice([PUMKEY, MELON]))
  161. return gmap[0][0] + abs(mn) + 2
  162. def hit_test(self, position, vector, max_distance=8):
  163. m = 8
  164. x, y, z = position
  165. dx, dy, dz = vector
  166. previous = None
  167. for _ in range(max_distance * m):
  168. key = normalize((x, y, z))
  169. if key != previous and key in self.world:
  170. return key, previous
  171. previous = key
  172. x, y, z = x + dx / m, y + dy / m, z + dz / m
  173. return None, None
  174. def exposed(self, position):
  175. x, y, z = position
  176. for dx, dy, dz in FACES:
  177. if (x + dx, y + dy, z + dz) not in self.world:
  178. return True
  179. return False
  180. def add_block(self, position, texture, immediate=True):
  181. if position in self.world:
  182. self.remove_block(position, immediate)
  183. self.world[position] = texture
  184. self.sectors.setdefault(sectorize(position), []).append(position)
  185. if immediate:
  186. if self.exposed(position):
  187. self.show_block(position)
  188. self.check_neighbors(position)
  189. def remove_block(self, position, immediate=True):
  190. del self.world[position]
  191. self.sectors[sectorize(position)].remove(position)
  192. if immediate:
  193. if position in self.shown:
  194. self.hide_block(position)
  195. self.check_neighbors(position)
  196. def check_neighbors(self, position):
  197. x, y, z = position
  198. for dx, dy, dz in FACES:
  199. key = (x + dx, y + dy, z + dz)
  200. if key not in self.world:
  201. continue
  202. if self.exposed(key):
  203. if key not in self.shown:
  204. self.show_block(key)
  205. else:
  206. if key in self.shown:
  207. self.hide_block(key)
  208. def show_block(self, position, immediate=True):
  209. texture = self.world[position]
  210. self.shown[position] = texture
  211. if immediate:
  212. self._show_block(position, texture)
  213. else:
  214. self._enqueue(self._show_block, position, texture)
  215. def _show_block(self, position, texture):
  216. x, y, z = position
  217. vertex_data = cube_vertices(x, y, z, 0.5)
  218. texture_data = list(texture)
  219. self._shown[position] = self.batch.add(24, GL_QUADS, self.group,
  220. ('v3f/static', vertex_data),
  221. ('t2f/static', texture_data))
  222. def hide_block(self, position, immediate=True):
  223. self.shown.pop(position)
  224. if immediate:
  225. self._hide_block(position)
  226. else:
  227. self._enqueue(self._hide_block, position)
  228. def _hide_block(self, position):
  229. self._shown.pop(position).delete()
  230. def show_sector(self, sector):
  231. for position in self.sectors.get(sector, []):
  232. if position not in self.shown and self.exposed(position):
  233. self.show_block(position, False)
  234. def hide_sector(self, sector):
  235. for position in self.sectors.get(sector, []):
  236. if position in self.shown:
  237. self.hide_block(position, False)
  238. def change_sectors(self, before, after):
  239. before_set = set()
  240. after_set = set()
  241. pad = 4
  242. for dx in range(-pad, pad + 1):
  243. for dy in [0]:
  244. for dz in range(-pad, pad + 1):
  245. if dx ** 2 + dy ** 2 + dz ** 2 > (pad + 1) ** 2:
  246. continue
  247. if before:
  248. x, y, z = before
  249. before_set.add((x + dx, y + dy, z + dz))
  250. if after:
  251. x, y, z = after
  252. after_set.add((x + dx, y + dy, z + dz))
  253. show = after_set - before_set
  254. hide = before_set - after_set
  255. for sector in show:
  256. self.show_sector(sector)
  257. for sector in hide:
  258. self.hide_sector(sector)
  259. def _enqueue(self, func, *args):
  260. self.queue.append((func, args))
  261. def _dequeue(self):
  262. func, args = self.queue.popleft()
  263. func(*args)
  264. def process_queue(self):
  265. start = time.perf_counter()
  266. while self.queue and time.perf_counter() - start < 1.0 / TICKS_PER_SEC:
  267. self._dequeue()
  268. def process_entire_queue(self):
  269. while self.queue:
  270. self._dequeue()
  271. class Window(pyglet.window.Window):
  272. def __init__(self, *args, **kwargs):
  273. super(Window, self).__init__(*args, **kwargs)
  274. self.exclusive = False
  275. self.flying = False # 是否在飞行
  276. self.walking = True # 是否在走路
  277. self.jumping = False # 是否在跳
  278. self.model = Model()
  279. self.strafe = [0, 0]
  280. self.position = (0, self.model.dfy, 0)
  281. self.rotation = (0, 0)
  282. self.sector = None
  283. self.reticle = None
  284. self.dy = 0
  285. self.inventory = [GRASS, DIRT, STONE, SAND, WOOD, BRICK, PUMKEY, MELON, TNT]
  286. self.block = self.inventory[0]
  287. self.num_keys = [
  288. key._1, key._2, key._3, key._4, key._5,
  289. key._6, key._7, key._8, key._9, key._0]
  290. self.label = pyglet.text.Label('', font_name='Arial', font_size=18,
  291. x=10, y=self.height - 10, anchor_x='left', anchor_y='top',
  292. color=(0, 0, 0, 255))
  293. pyglet.clock.schedule_interval(self.update, 1.0 / TICKS_PER_SEC)
  294. def set_exclusive_mouse(self, exclusive):
  295. super(Window, self).set_exclusive_mouse(exclusive)
  296. self.exclusive = exclusive
  297. def get_sight_vector(self):
  298. x, y = self.rotation
  299. m = math.cos(math.radians(y))
  300. dy = math.sin(math.radians(y))
  301. dx = math.cos(math.radians(x - 90)) * m
  302. dz = math.sin(math.radians(x - 90)) * m
  303. return (dx, dy, dz)
  304. def get_motion_vector(self):
  305. if any(self.strafe):
  306. x, y = self.rotation
  307. strafe = math.degrees(math.atan2(*self.strafe))
  308. y_angle = math.radians(y)
  309. x_angle = math.radians(x + strafe)
  310. if self.flying:
  311. m = math.cos(y_angle)
  312. dy = math.sin(y_angle)
  313. if self.strafe[1]:
  314. dy = 0.0
  315. m = 1
  316. if self.strafe[0] > 0:
  317. dy *= -1
  318. dx = math.cos(x_angle) * m
  319. dz = math.sin(x_angle) * m
  320. else:
  321. dy = 0.0
  322. dx = math.cos(x_angle)
  323. dz = math.sin(x_angle)
  324. else:
  325. dy = 0.0
  326. dx = 0.0
  327. dz = 0.0
  328. return (dx, dy, dz)
  329. def update(self, dt):
  330. # 刷新
  331. global GTIME
  332. global GNIGHT
  333. global GDAY
  334. glClearColor(0.5 - GTIME * 0.01, 0.69 - GTIME * 0.01, 1.0 - GTIME * 0.01, 1)
  335. setup_fog()
  336. GTIME += GDAY if GTIME < 23 else GNIGHT
  337. if GTIME > 50:
  338. GTIME = 50
  339. GNIGHT = -GNIGHT
  340. GDAY = -GDAY
  341. elif GTIME < 0:
  342. GTIME = 0
  343. GNIGHT = -GNIGHT
  344. GDAY = -GDAY
  345. self.model.process_queue()
  346. sector = sectorize(self.position)
  347. if sector != self.sector:
  348. self.model.change_sectors(self.sector, sector)
  349. if self.sector is None:
  350. self.model.process_entire_queue()
  351. self.sector = sector
  352. m = 8
  353. dt = min(dt, 0.2)
  354. if self.jumping:
  355. if self.dy == 0:
  356. self.dy = JUMP_SPEED
  357. for _ in range(m):
  358. self._update(dt / m)
  359. def _update(self, dt):
  360. speed = FLYING_SPEED if self.flying else WALKING_SPEED if self.walking else RUNNING_SPEED
  361. d = dt * speed
  362. dx, dy, dz = self.get_motion_vector()
  363. dx, dy, dz = dx * d, dy * d, dz * d
  364. if not self.flying:
  365. self.dy -= dt * GRAVITY
  366. self.dy = max(self.dy, -TERMINAL_VELOCITY)
  367. dy += self.dy * dt
  368. x, y, z = self.position
  369. x, y, z = self.collide((x + dx, y + dy, z + dz), PLAYER_HEIGHT)
  370. self.position = (x, y, z)
  371. def collide(self, position, height):
  372. pad = 0.25
  373. p = list(position)
  374. np = normalize(position)
  375. for face in FACES:
  376. for i in range(3):
  377. if not face[i]:
  378. continue
  379. d = (p[i] - np[i]) * face[i]
  380. if d < pad:
  381. continue
  382. for dy in range(height):
  383. op = list(np)
  384. op[1] -= dy
  385. op[i] += face[i]
  386. if tuple(op) not in self.model.world:
  387. continue
  388. p[i] -= (d - pad) * face[i]
  389. if face == (0, -1, 0) or face == (0, 1, 0):
  390. self.dy = 0
  391. break
  392. return tuple(p)
  393. def TNTboom(self, x, y, z):
  394. # TNT爆炸
  395. self.model.remove_block((x, y, z))
  396. bf = 4
  397. s = 0
  398. for dy in range(y - bf, y):
  399. for i in range(x - s, x + s):
  400. for j in range(z - s, z + s):
  401. if (i, dy, j) in self.model.world:
  402. if j == z-s or j == z+s-1 or i == x-s or i == x+s-1:
  403. if random.randint(0, 1):
  404. if self.model.world[(i, dy, j)] == TNT:
  405. self.TNTboom(i, dy, j)
  406. continue
  407. if self.model.world[(i, dy, j)] != ENDSTONE:
  408. self.model.remove_block((i, dy, j))
  409. else:
  410. if self.model.world[(i, dy, j)] == TNT:
  411. self.TNTboom(i, dy, j)
  412. continue
  413. if self.model.world[(i, dy, j)] != ENDSTONE:
  414. self.model.remove_block((i, dy, j))
  415. s += 1
  416. s = bf
  417. for i in range(x - s, x + s):
  418. for j in range(z - s, z + s):
  419. if (i, y, j) in self.model.world:
  420. if j == z-s or j == z+s-1 or i == x-s or i == x+s-1:
  421. if random.randint(0, 1):
  422. if self.model.world[(i, y, j)] == TNT:
  423. self.TNTboom(i, y, j)
  424. continue
  425. self.model.remove_block((i, y, j))
  426. else:
  427. if self.model.world[(i, y, j)] == TNT:
  428. self.TNTboom(i, y, j)
  429. continue
  430. self.model.remove_block((i, y, j))
  431. for dy in range(y + 1, y + s + 1):
  432. for i in range(x - s, x + s):
  433. for j in range(z - s, z + s):
  434. if (i, dy, j) in self.model.world:
  435. if j == z-s or j == z+s-1 or i == x-s or i == x+s-1:
  436. if random.randint(0, 1):
  437. if self.model.world[(i, dy, j)] == TNT:
  438. self.TNTboom(i, dy, j)
  439. continue
  440. if self.model.world[(i, dy, j)] != ENDSTONE:
  441. self.model.remove_block((i, dy, j))
  442. else:
  443. if self.model.world[(i, dy, j)] == TNT:
  444. self.TNTboom(i, dy, j)
  445. continue
  446. if self.model.world[(i, dy, j)] != ENDSTONE:
  447. self.model.remove_block((i, dy, j))
  448. s -= 1
  449. def on_mouse_press(self, x, y, button, modifiers):
  450. if self.exclusive:
  451. vector = self.get_sight_vector()
  452. block, previous = self.model.hit_test(self.position, vector)
  453. if (button == mouse.RIGHT) or \
  454. ((button == mouse.LEFT) and (modifiers & key.MOD_CTRL)):
  455. if previous:
  456. # 鼠标右击
  457. x, y, z = self.position
  458. flag = True
  459. for i in range(0, PLAYER_HEIGHT):
  460. if previous == normalize((x, y - i, z)):
  461. flag = False
  462. break
  463. if flag:
  464. self.model.add_block(previous, self.block)
  465. elif button == pyglet.window.mouse.LEFT and block:
  466. # 鼠标左击
  467. texture = self.model.world[block]
  468. if texture == TNT:
  469. self.TNTboom(block[0], block[1], block[2])
  470. elif texture != ENDSTONE:
  471. self.model.remove_block(block)
  472. else:
  473. self.set_exclusive_mouse(True)
  474. def on_mouse_motion(self, x, y, dx, dy):
  475. if self.exclusive:
  476. m = 0.15
  477. x, y = self.rotation
  478. x, y = x + dx * m, y + dy * m
  479. y = max(-90, min(90, y))
  480. self.rotation = (x, y)
  481. def on_key_press(self, symbol, modifiers):
  482. # 键盘按键
  483. if symbol == key.W:
  484. self.strafe[0] -= 1
  485. elif symbol == key.S:
  486. self.strafe[0] += 1
  487. elif symbol == key.A:
  488. self.strafe[1] -= 1
  489. elif symbol == key.D:
  490. self.strafe[1] += 1
  491. elif symbol == key.SPACE:
  492. self.jumping = True
  493. elif symbol == key.R:
  494. self.walking = not self.walking
  495. elif symbol == key.ESCAPE:
  496. self.set_exclusive_mouse(False)
  497. elif symbol == key.E:
  498. self.set_exclusive_mouse(False)
  499. elif symbol == key.TAB:
  500. self.flying = not self.flying
  501. elif symbol in self.num_keys:
  502. index = (symbol - self.num_keys[0]) % len(self.inventory)
  503. self.block = self.inventory[index]
  504. def on_key_release(self, symbol, modifiers):
  505. # 键盘松键
  506. if symbol == key.W:
  507. self.strafe[0] += 1
  508. elif symbol == key.S:
  509. self.strafe[0] -= 1
  510. elif symbol == key.A:
  511. self.strafe[1] += 1
  512. elif symbol == key.D:
  513. self.strafe[1] -= 1
  514. elif symbol == key.SPACE:
  515. self.jumping = False
  516. def on_resize(self, width, height):
  517. # label
  518. self.label.y = height - 10
  519. # reticle
  520. if self.reticle:
  521. self.reticle.delete()
  522. x, y = self.width // 2, self.height // 2
  523. n = 10
  524. self.reticle = pyglet.graphics.vertex_list(4,
  525. ('v2i', (x - n, y, x + n, y, x, y - n, x, y + n))
  526. )
  527. def set_2d(self):
  528. # 3d模式
  529. width, height = self.get_size()
  530. glDisable(GL_DEPTH_TEST)
  531. viewport = self.get_viewport_size()
  532. glViewport(0, 0, max(1, viewport[0]), max(1, viewport[1]))
  533. glMatrixMode(GL_PROJECTION)
  534. glLoadIdentity()
  535. glOrtho(0, max(1, width), 0, max(1, height), -1, 1)
  536. glMatrixMode(GL_MODELVIEW)
  537. glLoadIdentity()
  538. def set_3d(self):
  539. # 3d模式
  540. width, height = self.get_size()
  541. glEnable(GL_DEPTH_TEST)
  542. viewport = self.get_viewport_size()
  543. glViewport(0, 0, max(1, viewport[0]), max(1, viewport[1]))
  544. glMatrixMode(GL_PROJECTION)
  545. glLoadIdentity()
  546. gluPerspective(65.0, width / float(height), 0.1, 60.0)
  547. glMatrixMode(GL_MODELVIEW)
  548. glLoadIdentity()
  549. x, y = self.rotation
  550. glRotatef(x, 0, 1, 0)
  551. glRotatef(-y, math.cos(math.radians(x)), 0, math.sin(math.radians(x)))
  552. x, y, z = self.position
  553. glTranslatef(-x, -y, -z)
  554. def on_draw(self):
  555. # 绘制
  556. self.clear()
  557. self.set_3d()
  558. glColor3d(1, 1, 1)
  559. self.model.batch.draw()
  560. self.draw_focused_block()
  561. self.set_2d()
  562. self.draw_label()
  563. self.draw_reticle()
  564. def draw_focused_block(self):
  565. vector = self.get_sight_vector()
  566. block = self.model.hit_test(self.position, vector)[0]
  567. if block:
  568. x, y, z = block
  569. vertex_data = cube_vertices(x, y, z, 0.51)
  570. glColor3d(0, 0, 0)
  571. glPolygonMode(GL_FRONT_AND_BACK, GL_LINE)
  572. pyglet.graphics.draw(24, GL_QUADS, ('v3f/static', vertex_data))
  573. glPolygonMode(GL_FRONT_AND_BACK, GL_FILL)
  574. def draw_label(self):
  575. x, y, z = self.position
  576. self.label.text = '%02d (%.2f, %.2f, %.2f) %d / %d' % (
  577. pyglet.clock.get_fps(), x, y, z,
  578. len(self.model._shown), len(self.model.world))
  579. self.label.draw()
  580. def draw_reticle(self):
  581. glColor3d(0, 0, 0)
  582. self.reticle.draw(GL_LINES)
  583. def setup_fog():
  584. # 初始化迷雾和光照
  585. glEnable(GL_FOG)
  586. glFogfv(GL_FOG_COLOR, (GLfloat * 4)(0.5 - GTIME * 0.01, 0.69 - GTIME * 0.01, 1.0 - GTIME * 0.01, 1))
  587. glHint(GL_FOG_HINT, GL_DONT_CARE)
  588. glFogi(GL_FOG_MODE, GL_LINEAR)
  589. glFogf(GL_FOG_START, 30.0)
  590. glFogf(GL_FOG_END, 60.0)
  591. glLightfv(GL_LIGHT0, GL_POSITION, (GLfloat * 4)(0.0, 0.0, 0.0, 0.0))
  592. setup_light()
  593. def setup_light():
  594. # 初始化光照
  595. gamelight = 5.0 - GTIME / 10
  596. glLightfv(GL_LIGHT0, GL_AMBIENT, (GLfloat * 4)(gamelight, gamelight, gamelight, 1.0))
  597. glLightfv(GL_LIGHT0, GL_DIFFUSE, (GLfloat * 4)(gamelight, gamelight, gamelight, 1.0))
  598. glLightfv(GL_LIGHT0, GL_SPECULAR, (GLfloat * 4)(1.0, 1.0, 1.0, 1.0))
  599. glEnable(GL_LIGHTING)
  600. glEnable(GL_LIGHT0)
  601. def setup():
  602. # 初始化
  603. glClearColor(0.5 - GTIME * 0.01, 0.69 - GTIME * 0.01, 1.0 - GTIME * 0.01, 1)
  604. glEnable(GL_CULL_FACE)
  605. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)
  606. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)
  607. setup_fog()
  608. def main():
  609. window = Window(width=800, height=600, caption='Minecraft 2.1', resizable=True)
  610. window.set_exclusive_mouse(True)
  611. setup()
  612. pyglet.app.run()

是不是很长呢?

三、主程序运行(其实它是最简单的!)

奉上代码!

  1. if __name__ == '__main__':
  2. print("Welcome play python Minecraft 2.1")
  3. print("Snow Word is open:", GAMETYPES)
  4. print("World Seed:", SEED)
  5. main()

最后程序简单不简单?

四、效果图

一、一般世界

二、冰雪世界

 是不是很酷?

五、图片资源

注意:命名为texture2_1哦!

 六、知识总结

python非常厉害,非常实用!大家可以来试一试哦!

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/468422
推荐阅读
相关标签
  

闽ICP备14008679号