一起用Go做一个小游戏(上)

本文介绍了使用Go语言的ebitengine库开发2D游戏的基础,包括游戏窗口显示、输入处理、设置背景和显示图片。通过重构代码,展示了如何创建和移动飞船,为开发《外星人入侵》小游戏奠定了基础。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

引子

最近偶然看到一个Go语言库,口号喊出“一个超级简单(dead simple)的2D游戏引擎”,好奇点开了它的官网。

9ce69bdfa073525abcb4394230a68c4f.png

官网上已经有很多可以在线体验的小游戏了(利用WASM技术)。例如曾经风靡一时的2048:

c1e92c377bd25e7488d8b17b07ea0963.png

当然只要安装了Go,我们也键入下面的命令本地运行这个游戏:

$ go run -tags=example github.com/hajimehoshi/ebiten/v2/examples/2048@latest

还有童年《俄罗斯方块》:

2828436fa436cfbdce821fb3e82c6cc3.png

有14年左右让无数人疯狂的《Flappy Bird》(或许称为Flappy Gopher更贴切一点😀):

faa661a233f0ec5c85f83a373d79c716.png

这些瞬间让我产生了极大的兴趣。简单浏览一下文档,整体感觉下来,虽然与成熟的游戏引擎(如Cocos2dx,DirectX,Unity3d等)相比,ebiten功能还不算丰富。但是麻雀虽小,五脏俱全。ebiten的API设计比较简单,使用也很方便,即使对于新手也可以在1-2个小时内掌握,并开发出一款简单的游戏。更妙的是,Go语言让ebitengine实现了跨平台!

接下来的3篇文章,我会介绍ebitengine这个库。对于游戏引擎来说,只介绍它的API用法似乎有点纸上谈兵。恰好我想起之前看到一个《外星人入侵》的小游戏,刚好可以拿来练手。那请大家坐稳扶好,我们出发咯。

安装

ebitengine 要求Go版本 >= 1.15。使用go module下载这个包:

$ go get -u github.com/hajimehoshi/ebiten/v2

显示窗口

游戏开发第一步是将游戏窗口显示出来,并且能在窗口上显示一些文字。先看代码:

package main

import (
  "log"

  "github.com/hajimehoshi/ebiten/v2"
  "github.com/hajimehoshi/ebiten/v2/ebitenutil"
)

type Game struct{}

func (g *Game) Update() error {
  return nil
}

func (g *Game) Draw(screen *ebiten.Image) {
  ebitenutil.DebugPrint(screen, "Hello, World")
}

func (g *Game) Layout(outsideWidth, outsideHeight int) (screenWidth, screenHeight int) {
  return 320, 240
}

func main() {
  ebiten.SetWindowSize(640, 480)
  ebiten.SetWindowTitle("外星人入侵")
  if err := ebiten.RunGame(&Game{}); err != nil {
    log.Fatal(err)
  }
}

使用命令go run运行该程序:

$ go run main.go

我们会看到一个窗口,标题为外星人入侵,并且左上角显示了文字Hello,World

74f36c678844f7076725984bd43efa5f.png

现在我们来分析使用ebiten开发的游戏程序的结构。

首先,ebiten引擎运行时要求传入一个游戏对象,该对象的必须实现ebiten.Game这个接口:

// Game defines necessary functions for a game.
type Game interface {
  Update() error
  Draw(screen *Image)
  Layout(outsideWidth, outsideHeight int) (screenWidth, screenHeight int)
}

ebiten.Game接口定义了ebiten游戏需要的3个方法:Update,DrawLayout

  • Update:每个tick都会被调用。tick是引擎更新的一个时间单位,默认为1/60s。tick的倒数我们一般称为帧,即游戏的更新频率。默认ebiten游戏是60帧,即每秒更新60次。该方法主要用来更新游戏的逻辑状态,例如子弹位置更新。上面的例子中,游戏对象没有任何状态,故Update方法为空。注意到Update方法的返回值为error类型,当Update方法返回一个非空的error值时,游戏停止。在上面的例子中,我们一直返回nil,故只有关闭窗口时游戏才停止。

  • Draw:每帧(frame)调用。帧是渲染使用的一个时间单位,依赖显示器的刷新率。如果显示器的刷新率为60Hz,Draw将会每秒被调用60次。Draw接受一个类型为*ebiten.Image的screen对象。ebiten引擎每帧会渲染这个screen。在上

<think>好的,用户让我帮他编写一个贪食蛇小游戏。首先,我需要考虑他的需求是什么。他可能是一个刚开始学习编程的新手,想要通过实践来提升自己的技能,或者只是想有一个可以运行的小游戏来玩。 接下来,我得确定使用什么编程语言来实现。贪食蛇是一个经典的游戏,通常用Python来实现比较方便,因为Python有简单的语法和丰富的库,比如pygame,适合图形化界面的开发。但用户可能没有安装pygame,或者希望用更基础的库,比如turtle,这样不需要额外安装,适合初学者。 然后,我需要考虑代码的结构。贪食蛇的基本组成部分包括蛇的移动、食物的生成、碰撞检测以及得分系统。蛇的身体可以用列表来存储每个段落的坐标,通过键盘事件来控制方向的变化。食物应该在随机位置生成,但不要和蛇身重叠。碰撞检测包括检查蛇头是否碰到边界或自己的身体。 用户可能对代码的复杂度有要求,所以需要保持代码简洁,同时添加足够的注释,方便他理解每一部分的功能。此外,考虑到用户可能是在学习阶段,代码中的错误处理和边界情况也需要处理清楚,比如当蛇反向移动时应该不允许,避免直接死亡。 还有,用户可能希望游戏有可视化的界面,所以选择turtle库的话,可以方便地绘制图形,而不需要处理复杂的窗口管理。同时,设置适当的刷新速度和游戏结束的提示也是必要的。 最后,我需要测试代码,确保没有语法错误,并且游戏逻辑正确。比如蛇的移动是否流畅,食物生成是否正确,碰撞检测是否准确等。然后,将代码和简单的使用说明一起提供给用户,确保他能顺利运行和修改游戏。</think>以下是一个使用 Python 的 turtle 模块实现的简单贪食蛇小游戏代码: ```python import turtle import time import random # 游戏设置 delay = 0.1 score = 0 high_score = 0 # 创建游戏窗口 wn = turtle.Screen() wn.title("贪食蛇游戏") wn.bgcolor("black") wn.setup(width=600, height=600) wn.tracer(0) # 关闭自动刷新 # 创建蛇头 head = turtle.Turtle() head.speed(0) head.shape("square") head.color("white") head.penup() head.goto(0, 0) head.direction = "stop" # 食物 food = turtle.Turtle() food.speed(0) food.shape("circle") food.color("red") food.penup() food.goto(0, 100) # 记分牌 pen = turtle.Turtle() pen.speed(0) pen.color("white") pen.penup() pen.hideturtle() pen.goto(0, 260) pen.write("得分: 0 最高分: 0", align="center", font=("Arial", 24, "normal")) # 蛇身列表 segments = [] # 移动函数 def go_up(): if head.direction != "down": head.direction = "up" def go_down(): if head.direction != "up": head.direction = "down" def go_left(): if head.direction != "right": head.direction = "left" def go_right(): if head.direction != "left": head.direction = "right" def move(): if head.direction == "up": y = head.ycor() head.sety(y + 20) if head.direction == "down": y = head.ycor() head.sety(y - 20) if head.direction == "left": x = head.xcor() head.setx(x - 20) if head.direction == "right": x = head.xcor() head.setx(x + 20) # 键盘控制 wn.listen() wn.onkeypress(go_up, "w") wn.onkeypress(go_down, "s") wn.onkeypress(go_left, "a") wn.onkeypress(go_right, "d") # 主游戏循环 while True: wn.update() # 碰撞检测(边界) if head.xcor()>290 or head.xcor()<-290 or head.ycor()>290 or head.ycor()<-290: time.sleep(1) head.goto(0,0) head.direction = "stop" # 隐藏旧蛇身 for segment in segments: segment.goto(1000, 1000) segments.clear() score = 0 delay = 0.1 pen.clear() pen.write("得分: {} 最高分: {}".format(score, high_score), align="center", font=("Arial", 24, "normal")) # 吃到食物 if head.distance(food) < 20: x = random.randint(-290, 290) y = random.randint(-290, 290) food.goto(x, y) # 添加新蛇身 new_segment = turtle.Turtle() new_segment.speed(0) new_segment.shape("square") new_segment.color("grey") new_segment.penup() segments.append(new_segment) # 更新分数 score += 10 if score > high_score: high_score = score pen.clear() pen.write("得分: {} 最高分: {}".format(score, high_score), align="center", font=("Arial", 24, "normal")) delay -= 0.001 # 移动蛇身 for index in range(len(segments)-1, 0, -1): x = segments[index-1].xcor() y = segments[index-1].ycor() segments[index].goto(x, y) if len(segments) > 0: x = head.xcor() y = head.ycor() segments[0].goto(x, y) move() # 碰撞检测(自身) for segment in segments: if segment.distance(head) < 20: time.sleep(1) head.goto(0,0) head.direction = "stop" for segment in segments: segment.goto(1000, 1000) segments.clear() score = 0 delay = 0.1 pen.clear() pen.write("得分: {} 最高分: {}".format(score, high_score), align="center", font=("Arial", 24, "normal")) time.sleep(delay) wn.mainloop() ``` 使用方法: 1. 需要安装 Python 环境 2. 安装 turtle 模块(通常已内置) 3. 保存为 .py 文件运行 4. 使用 W/S/A/D 键控制方向 游戏功能: - 吃红色食物增长身体 - 分数系统(吃一个+10分) - 最高分记录 - 碰撞墙壁或自身会结束游戏 - 游戏速度会逐渐加快 注意:这个版本是基础实现,你可以在此基础上添加更多功能如: - 游戏暂停功能 - 不同难度等级 - 多种食物类型 - 音效支持 - 更复杂的关卡设计等
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值