❏ 站外平台:

OpenGL 与 Go 教程(三)实现游戏

作者: Kylewbanks 译者: LCTT 周家未

| 2017-10-18 09:43   收藏: 2    

该教程的完整源代码可以从 GitHub 上找到。

欢迎回到《OpenGL 与 Go 教程》!如果你还没有看过 第一节第二节,那就要回过头去看一看。

到目前为止,你应该懂得如何创建网格系统以及创建代表方格中每一个单元的格子阵列。现在可以开始把网格当作游戏面板实现康威生命游戏Conway's Game of Life

开始吧!

实现康威生命游戏

康威生命游戏的其中一个要点是所有细胞cell必须同时基于当前细胞在面板中的状态确定下一个细胞的状态。也就是说如果细胞 (X=3,Y=4) 在计算过程中状态发生了改变,那么邻近的细胞 (X=4,Y=4) 必须基于 (X=3,Y=4) 的状态决定自己的状态变化,而不是基于自己现在的状态。简单的讲,这意味着我们必须遍历细胞,确定下一个细胞的状态,而在绘制之前不改变他们的当前状态,然后在下一次循环中我们将新状态应用到游戏里,依此循环往复。

为了完成这个功能,我们需要在 cell 结构体中添加两个布尔型变量:

  1. type cell struct {
  2. drawable uint32
  3. alive bool
  4. aliveNext bool
  5. x int
  6. y int
  7. }

这里我们添加了 alivealiveNext,前一个是细胞当前的专题,后一个是经过计算后下一回合的状态。

现在添加两个函数,我们会用它们来确定 cell 的状态:

  1. // checkState 函数决定下一次游戏循环时的 cell 状态
  2. func (c *cell) checkState(cells [][]*cell) {
  3. c.alive = c.aliveNext
  4. c.aliveNext = c.alive
  5. liveCount := c.liveNeighbors(cells)
  6. if c.alive {
  7. // 1. 当任何一个存活的 cell 的附近少于 2 个存活的 cell 时,该 cell 将会消亡,就像人口过少所导致的结果一样
  8. if liveCount < 2 {
  9. c.aliveNext = false
  10. }
  11. // 2. 当任何一个存活的 cell 的附近有 2 至 3 个存活的 cell 时,该 cell 在下一代中仍然存活。
  12. if liveCount == 2 || liveCount == 3 {
  13. c.aliveNext = true
  14. }
  15. // 3. 当任何一个存活的 cell 的附近多于 3 个存活的 cell 时,该 cell 将会消亡,就像人口过多所导致的结果一样
  16. if liveCount > 3 {
  17. c.aliveNext = false
  18. }
  19. } else {
  20. // 4. 任何一个消亡的 cell 附近刚好有 3 个存活的 cell,该 cell 会变为存活的状态,就像重生一样。
  21. if liveCount == 3 {
  22. c.aliveNext = true
  23. }
  24. }
  25. }
  26. // liveNeighbors 函数返回当前 cell 附近存活的 cell 数
  27. func (c *cell) liveNeighbors(cells [][]*cell) int {
  28. var liveCount int
  29. add := func(x, y int) {
  30. // If we're at an edge, check the other side of the board.
  31. if x == len(cells) {
  32. x = 0
  33. } else if x == -1 {
  34. x = len(cells) - 1
  35. }
  36. if y == len(cells[x]) {
  37. y = 0
  38. } else if y == -1 {
  39. y = len(cells[x]) - 1
  40. }
  41. if cells[x][y].alive {
  42. liveCount++
  43. }
  44. }
  45. add(c.x-1, c.y) // To the left
  46. add(c.x+1, c.y) // To the right
  47. add(c.x, c.y+1) // up
  48. add(c.x, c.y-1) // down
  49. add(c.x-1, c.y+1) // top-left
  50. add(c.x+1, c.y+1) // top-right
  51. add(c.x-1, c.y-1) // bottom-left
  52. add(c.x+1, c.y-1) // bottom-right
  53. return liveCount
  54. }

checkState 中我们设置当前状态(alive) 等于我们最近迭代结果(aliveNext)。接下来我们计数邻居数量,并根据游戏的规则来决定 aliveNext 状态。该规则是比较清晰的,而且我们在上面的代码当中也有说明,所以这里不再赘述。

更加值得注意的是 liveNeighbors 函数里,我们返回的是当前处于存活(alive)状态的细胞的邻居个数。我们定义了一个叫做 add 的内嵌函数,它会对 XY 坐标做一些重复性的验证。它所做的事情是检查我们传递的数字是否超出了范围——比如说,如果细胞 (X=0,Y=5) 想要验证它左边的细胞,它就得验证面板另一边的细胞 (X=9,Y=5),Y 轴与之类似。

add 内嵌函数后面,我们给当前细胞附近的八个细胞分别调用 add 函数,示意如下:

  1. [
  2. [-, -, -],
  3. [N, N, N],
  4. [N, C, N],
  5. [N, N, N],
  6. [-, -, -]
  7. ]

在该示意中,每一个叫做 N 的细胞是 C 的邻居。

现在是我们的 main 函数,这里我们执行核心游戏循环,调用每个细胞的 checkState 函数进行绘制:

  1. func main() {
  2. ...
  3. for !window.ShouldClose() {
  4. for x := range cells {
  5. for _, c := range cells[x] {
  6. c.checkState(cells)
  7. }
  8. }
  9. draw(cells, window, program)
  10. }
  11. }

现在我们的游戏逻辑全都设置好了,我们需要修改细胞绘制函数来跳过绘制不存活的细胞:

  1. func (c *cell) draw() {
  2. if !c.alive {
  3. return
  4. }
  5. gl.BindVertexArray(c.drawable)
  6. gl.DrawArrays(gl.TRIANGLES, 0, int32(len(square)/3))
  7. }

如果我们现在运行这个游戏,你将看到一个纯黑的屏幕,而不是我们辛苦工作后应该看到生命模拟。为什么呢?其实这正是模拟在工作。因为我们没有活着的细胞,所以就一个都不会绘制出来。

现在完善这个函数。回到 makeCells 函数,我们用 0.01.0 之间的一个随机数来设置游戏的初始状态。我们会定义一个大小为 0.15 的常量阈值,也就是说每个细胞都有 15% 的几率处于存活状态。

  1. import (
  2. "math/rand"
  3. "time"
  4. ...
  5. )
  6. const (
  7. ...
  8. threshold = 0.15
  9. )
  10. func makeCells() [][]*cell {
  11. rand.Seed(time.Now().UnixNano())
  12. cells := make([][]*cell, rows, rows)
  13. for x := 0; x < rows; x++ {
  14. for y := 0; y < columns; y++ {
  15. c := newCell(x, y)
  16. c.alive = rand.Float64() < threshold
  17. c.aliveNext = c.alive
  18. cells[x] = append(cells[x], c)
  19. }
  20. }
  21. return cells
  22. }

我们首先增加两个引入:随机(math/rand)和时间(time),并定义我们的常量阈值。然后在 makeCells 中我们使用当前时间作为随机种子,给每个游戏一个独特的起始状态。你也可也指定一个特定的种子值,来始终得到一个相同的游戏,这在你想重放某个有趣的模拟时很有用。

接下来在循环中,在用 newCell 函数创造一个新的细胞时,我们根据随机浮点数的大小设置它的存活状态,随机数在 0.01.0 之间,如果比阈值(0.15)小,就是存活状态。再次强调,这意味着每个细胞在开始时都有 15% 的几率是存活的。你可以修改数值大小,增加或者减少当前游戏中存活的细胞。我们还把 aliveNext 设成 alive 状态,否则在第一次迭代之后我们会发现一大片细胞消亡了,这是因为 aliveNext 将永远是 false

现在继续运行它,你很有可能看到细胞们一闪而过,但你却无法理解这是为什么。原因可能在于你的电脑太快了,在你能够看清楚之前就运行了(甚至完成了)模拟过程。

让我们降低游戏速度,在主循环中引入一个帧率(FPS)限制:

  1. const (
  2. ...
  3. fps = 2
  4. )
  5. func main() {
  6. ...
  7. for !window.ShouldClose() {
  8. t := time.Now()
  9. for x := range cells {
  10. for _, c := range cells[x] {
  11. c.checkState(cells)
  12. }
  13. }
  14. if err := draw(prog, window, cells); err != nil {
  15. panic(err)
  16. }
  17. time.Sleep(time.Second/time.Duration(fps) - time.Since(t))
  18. }
  19. }

现在你能给看出一些图案了,尽管它变换的很慢。把 FPS 加到 10,把方格的尺寸加到 100x100,你就能看到更真实的模拟:

  1. const (
  2. ...
  3. rows = 100
  4. columns = 100
  5. fps = 10
  6. ...
  7. )

 “Conway's Game of Life” - 示例游戏

“Conway's Game of Life” - 示例游戏

试着修改常量,看看它们是怎么影响模拟过程的 —— 这是你用 Go 语言写的第一个 OpenGL 程序,很酷吧?

进阶内容?

这是《OpenGL 与 Go 教程》的最后一节,但是这不意味着到此而止。这里有些新的挑战,能够增进你对 OpenGL (以及 Go)的理解。

  1. 给每个细胞一种不同的颜色。
  2. 让用户能够通过命令行参数指定格子尺寸、帧率、种子和阈值。在 GitHub 上的 github.com/KyleBanks/conways-gol 里你可以看到一个已经实现的程序。
  3. 把格子的形状变成其它更有意思的,比如六边形。
  4. 用颜色表示细胞的状态 —— 比如,在第一帧把存活状态的格子设成绿色,如果它们存活了超过三帧的时间,就变成黄色。
  5. 如果模拟过程结束了,就自动关闭窗口,也就是说所有细胞都消亡了,或者是最后两帧里没有格子的状态有改变。
  6. 将着色器源代码放到单独的文件中,而不是把它们用字符串的形式放在 Go 的源代码中。

总结

希望这篇教程对想要入门 OpenGL (或者是 Go)的人有所帮助!这很有趣,因此我也希望理解学习它也很有趣。

正如我所说的,OpenGL 可能是非常恐怖的,但只要你开始着手了就不会太差。你只用制定一个个可达成的小目标,然后享受每一次成功,因为尽管 OpenGL 不会总像它看上去的那么难,但也肯定有些难懂的东西。我发现,当遇到一个难于理解用 go-gl 生成的代码的 OpenGL 问题时,你总是可以参考一下在网上更流行的当作教程的 C 语言代码,这很有用。通常 C 语言和 Go 语言的唯一区别是在 Go 中,gl 函数的前缀是 gl. 而不是 gl,常量的前缀是 gl 而不是 GL_。这可以极大地增加了你的绘制知识!

该教程的完整源代码可从 GitHub 上获得。

回顾

这是 main.go 文件最终的内容:

  1. package main
  2. import (
  3. "fmt"
  4. "log"
  5. "math/rand"
  6. "runtime"
  7. "strings"
  8. "time"
  9. "github.com/go-gl/gl/v4.1-core/gl" // OR: github.com/go-gl/gl/v2.1/gl
  10. "github.com/go-gl/glfw/v3.2/glfw"
  11. )
  12. const (
  13. width = 500
  14. height = 500
  15. vertexShaderSource = `
  16. #version 410
  17. in vec3 vp;
  18. void main() {
  19. gl_Position = vec4(vp, 1.0);
  20. }
  21. ` + "\x00"
  22. fragmentShaderSource = `
  23. #version 410
  24. out vec4 frag_colour;
  25. void main() {
  26. frag_colour = vec4(1, 1, 1, 1.0);
  27. }
  28. ` + "\x00"
  29. rows = 100
  30. columns = 100
  31. threshold = 0.15
  32. fps = 10
  33. )
  34. var (
  35. square = []float32{
  36. -0.5, 0.5, 0,
  37. -0.5, -0.5, 0,
  38. 0.5, -0.5, 0,
  39. -0.5, 0.5, 0,
  40. 0.5, 0.5, 0,
  41. 0.5, -0.5, 0,
  42. }
  43. )
  44. type cell struct {
  45. drawable uint32
  46. alive bool
  47. aliveNext bool
  48. x int
  49. y int
  50. }
  51. func main() {
  52. runtime.LockOSThread()
  53. window := initGlfw()
  54. defer glfw.Terminate()
  55. program := initOpenGL()
  56. cells := makeCells()
  57. for !window.ShouldClose() {
  58. t := time.Now()
  59. for x := range cells {
  60. for _, c := range cells[x] {
  61. c.checkState(cells)
  62. }
  63. }
  64. draw(cells, window, program)
  65. time.Sleep(time.Second/time.Duration(fps) - time.Since(t))
  66. }
  67. }
  68. func draw(cells [][]*cell, window *glfw.Window, program uint32) {
  69. gl.Clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT)
  70. gl.UseProgram(program)
  71. for x := range cells {
  72. for _, c := range cells[x] {
  73. c.draw()
  74. }
  75. }
  76. glfw.PollEvents()
  77. window.SwapBuffers()
  78. }
  79. func makeCells() [][]*cell {
  80. rand.Seed(time.Now().UnixNano())
  81. cells := make([][]*cell, rows, rows)
  82. for x := 0; x < rows; x++ {
  83. for y := 0; y < columns; y++ {
  84. c := newCell(x, y)
  85. c.alive = rand.Float64() < threshold
  86. c.aliveNext = c.alive
  87. cells[x] = append(cells[x], c)
  88. }
  89. }
  90. return cells
  91. }
  92. func newCell(x, y int) *cell {
  93. points := make([]float32, len(square), len(square))
  94. copy(points, square)
  95. for i := 0; i < len(points); i++ {
  96. var position float32
  97. var size float32
  98. switch i % 3 {
  99. case 0:
  100. size = 1.0 / float32(columns)
  101. position = float32(x) * size
  102. case 1:
  103. size = 1.0 / float32(rows)
  104. position = float32(y) * size
  105. default:
  106. continue
  107. }
  108. if points[i] < 0 {
  109. points[i] = (position * 2) - 1
  110. } else {
  111. points[i] = ((position + size) * 2) - 1
  112. }
  113. }
  114. return &cell{
  115. drawable: makeVao(points),
  116. x: x,
  117. y: y,
  118. }
  119. }
  120. func (c *cell) draw() {
  121. if !c.alive {
  122. return
  123. }
  124. gl.BindVertexArray(c.drawable)
  125. gl.DrawArrays(gl.TRIANGLES, 0, int32(len(square)/3))
  126. }
  127. // checkState 函数决定下一次游戏循环时的 cell 状态
  128. func (c *cell) checkState(cells [][]*cell) {
  129. c.alive = c.aliveNext
  130. c.aliveNext = c.alive
  131. liveCount := c.liveNeighbors(cells)
  132. if c.alive {
  133. // 1. 当任何一个存活的 cell 的附近少于 2 个存活的 cell 时,该 cell 将会消亡,就像人口过少所导致的结果一样
  134. if liveCount < 2 {
  135. c.aliveNext = false
  136. }
  137. // 2. 当任何一个存活的 cell 的附近有 2 至 3 个存活的 cell 时,该 cell 在下一代中仍然存活。
  138. if liveCount == 2 || liveCount == 3 {
  139. c.aliveNext = true
  140. }
  141. // 3. 当任何一个存活的 cell 的附近多于 3 个存活的 cell 时,该 cell 将会消亡,就像人口过多所导致的结果一样
  142. if liveCount > 3 {
  143. c.aliveNext = false
  144. }
  145. } else {
  146. // 4. 任何一个消亡的 cell 附近刚好有 3 个存活的 cell,该 cell 会变为存活的状态,就像重生一样。
  147. if liveCount == 3 {
  148. c.aliveNext = true
  149. }
  150. }
  151. }
  152. // liveNeighbors 函数返回当前 cell 附近存活的 cell 数
  153. func (c *cell) liveNeighbors(cells [][]*cell) int {
  154. var liveCount int
  155. add := func(x, y int) {
  156. // If we're at an edge, check the other side of the board.
  157. if x == len(cells) {
  158. x = 0
  159. } else if x == -1 {
  160. x = len(cells) - 1
  161. }
  162. if y == len(cells[x]) {
  163. y = 0
  164. } else if y == -1 {
  165. y = len(cells[x]) - 1
  166. }
  167. if cells[x][y].alive {
  168. liveCount++
  169. }
  170. }
  171. add(c.x-1, c.y) // To the left
  172. add(c.x+1, c.y) // To the right
  173. add(c.x, c.y+1) // up
  174. add(c.x, c.y-1) // down
  175. add(c.x-1, c.y+1) // top-left
  176. add(c.x+1, c.y+1) // top-right
  177. add(c.x-1, c.y-1) // bottom-left
  178. add(c.x+1, c.y-1) // bottom-right
  179. return liveCount
  180. }
  181. // initGlfw 初始化 glfw,返回一个可用的 Window
  182. func initGlfw() *glfw.Window {
  183. if err := glfw.Init(); err != nil {
  184. panic(err)
  185. }
  186. glfw.WindowHint(glfw.Resizable, glfw.False)
  187. glfw.WindowHint(glfw.ContextVersionMajor, 4)
  188. glfw.WindowHint(glfw.ContextVersionMinor, 1)
  189. glfw.WindowHint(glfw.OpenGLProfile, glfw.OpenGLCoreProfile)
  190. glfw.WindowHint(glfw.OpenGLForwardCompatible, glfw.True)
  191. window, err := glfw.CreateWindow(width, height, "Conway's Game of Life", nil, nil)
  192. if err != nil {
  193. panic(err)
  194. }
  195. window.MakeContextCurrent()
  196. return window
  197. }
  198. // initOpenGL 初始化 OpenGL 并返回一个已经编译好的着色器程序
  199. func initOpenGL() uint32 {
  200. if err := gl.Init(); err != nil {
  201. panic(err)
  202. }
  203. version := gl.GoStr(gl.GetString(gl.VERSION))
  204. log.Println("OpenGL version", version)
  205. vertexShader, err := compileShader(vertexShaderSource, gl.VERTEX_SHADER)
  206. if err != nil {
  207. panic(err)
  208. }
  209. fragmentShader, err := compileShader(fragmentShaderSource, gl.FRAGMENT_SHADER)
  210. if err != nil {
  211. panic(err)
  212. }
  213. prog := gl.CreateProgram()
  214. gl.AttachShader(prog, vertexShader)
  215. gl.AttachShader(prog, fragmentShader)
  216. gl.LinkProgram(prog)
  217. return prog
  218. }
  219. // makeVao 初始化并从提供的点里面返回一个顶点数组
  220. func makeVao(points []float32) uint32 {
  221. var vbo uint32
  222. gl.GenBuffers(1, &vbo)
  223. gl.BindBuffer(gl.ARRAY_BUFFER, vbo)
  224. gl.BufferData(gl.ARRAY_BUFFER, 4*len(points), gl.Ptr(points), gl.STATIC_DRAW)
  225. var vao uint32
  226. gl.GenVertexArrays(1, &vao)
  227. gl.BindVertexArray(vao)
  228. gl.EnableVertexAttribArray(0)
  229. gl.BindBuffer(gl.ARRAY_BUFFER, vbo)
  230. gl.VertexAttribPointer(0, 3, gl.FLOAT, false, 0, nil)
  231. return vao
  232. }
  233. func compileShader(source string, shaderType uint32) (uint32, error) {
  234. shader := gl.CreateShader(shaderType)
  235. csources, free := gl.Strs(source)
  236. gl.ShaderSource(shader, 1, csources, nil)
  237. free()
  238. gl.CompileShader(shader)
  239. var status int32
  240. gl.GetShaderiv(shader, gl.COMPILE_STATUS, &status)
  241. if status == gl.FALSE {
  242. var logLength int32
  243. gl.GetShaderiv(shader, gl.INFO_LOG_LENGTH, &logLength)
  244. log := strings.Repeat("\x00", int(logLength+1))
  245. gl.GetShaderInfoLog(shader, logLength, nil, gl.Str(log))
  246. return 0, fmt.Errorf("failed to compile %v: %v", source, log)
  247. }
  248. return shader, nil
  249. }

请在 Twitter @kylewbanks 告诉我这篇文章对你是否有帮助,或者在 Twitter 下方关注我以便及时获取最新文章!


via: https://kylewbanks.com/blog/tutorial-opengl-with-golang-part-3-implementing-the-game

作者:kylewbanks 译者:GitFuture 校对:wxy

本文由 LCTT 原创编译,Linux中国 荣誉推出



最新评论

从 2025.1.15 起,不再提供评论功能
LCTT 译者
周家未 🌟🌟🌟🌟
共计翻译: 27.0 篇 | 共计贡献: 864
贡献时间:2016-06-10 -> 2018-10-21
访问我的 LCTT 主页 | 在 GitHub 上关注我


返回顶部

分享到微信

打开微信,点击顶部的“╋”,
使用“扫一扫”将网页分享至微信。