GITHUB排行榜C位出道-手把手教你玩转V语言版的俄罗斯方块

    最近 V 语言-一个GO语言最吸晴的项目,在千呼万唤之后,终于迎来开源,并正式发布了首个可用版本,其一经推出,便强势登顶 GitHub的榜首,引来各方热议。目前V已经可以实现自我编译迭代,笔者大致了解了一下V语言,主要有如下一些特性。

    1.快速编译:  V每CPU核心每秒编译约120万行代码。  V也可以调用C,编译速度下降到≈100k行/秒/CPU。安全
    2.安全策略:没有空;没有全局变量(意味着变量都是在函数体中声明) 没有未定义的行为 
    3.性能:和C一样快,操作C没有任何成本,不支持运行时反射,编译器只有400K,整个语言及其标准库都小于400kb。V目前是用V写的,你可以在0。4秒内完成。(到今年年底,这个数字将降至≈0.15秒。)

    4.强大的图形能力:支持在GDI+/Cocoa绘图之上的跨平台绘图库,以及一个基于OpenGL的图形库,以支持加载复杂的三维对象与纹理

   由于曾经做过一段时间的DIRECTX的开发,V语言对于图形能力的特性宣传最吸引笔者的注意。所以我到其官网及Github上学习了一下相关内容,按照编译运行了一下俄罗斯 方块的例程,接下来向大家做一下分享。

   安装V语言

    如果只是HELLO WORLD程序是非常简单的,只需要按照https://vlang.io官网的标准步骤来执行即可。而如果使用其图形处理能力笔者目前只在UBANTU平台测试成功。下面均是以UBANTU为例来说明

   首先将整个项目克隆下来,再make即可

 git clone https://github.com/vlang/v
 cd v
 make

    如果报curl command not found,则执行以下命令安装curl

sudo apt install curl

    接下来在建立软链接

sudo ln -s /home/machao/v/v /usr/local/bin/v

  然后运行v就能进到v语言的命令行了。而如果要运行俄罗斯方块还需要以下这些库的支持,

 sudo apt install libglfw3 libglfw3-dev libfreetype6-dev libcurl3-dev

        运行俄罗斯方块
    

      接下来cd tetris,进入到俄罗斯方块的目录,先使用gedit tetris.v,来看一下v语言的代码样例,其主要部分如下:

    

fn main() {
	glfw.init()//实始化类
	mut game := &Game{gg: 0} // TODO
	game.parse_tetros()
	game.init_game()
	mut window := glfw.create_window(glfw.WinCfg {
		width: WinWidth
		height: WinHeight
		title: 'V Tetris'
		ptr: game // glfw user pointer
	})
	window.make_context_current()
	window.onkeydown(key_down)//注册事件
	gg.init()
	game.gg = gg.new_context(gg.Cfg {
		width: WinWidth
		height: WinHeight
		use_ortho: true // This is needed for 2D drawing
	})
	go game.run() // Run the game loop in a new thread
	gl.clear() // For some reason this is necessary to avoid an intial flickering
	gl.clear_color(255, 255, 255, 255)
	for {
		gl.clear()
		gl.clear_color(255, 255, 255, 255)
		game.draw_scene()
		window.swap_buffers()
		glfw.wait_events()
		if window.should_close() {
			window.destroy()
			glfw.terminate()
			exit(0)
		}
	}
}

fn (g mut Game) move_right(dx int) {
	// Reached left/right edge or another tetro?
	for i := 0; i < TetroSize; i++ {
		tetro := g.tetro[i]
		y := tetro.y + g.pos_y
		x := tetro.x + g.pos_x + dx
		row := g.field[y]
		if row[x] != 0 {
			// Do not move
			return
		}
	}
	g.pos_x += dx
}

fn (g mut Game) delete_completed_lines() {
	for y := FieldHeight; y >= 1; y-- {
		g.delete_completed_line(y)
	}
}

fn (g mut Game) delete_completed_line(y int) {
	for x := 1; x <= FieldWidth; x++ {
		f := g.field[y]
		if f[x] == 0 {
			return
		}
	}
	// Move everything down by 1 position
	for yy := y - 1; yy >= 1; yy-- {
		for x := 1; x <= FieldWidth; x++ {
			mut a := g.field[yy + 1]
			mut b := g.field[yy]
			a[x] = b[x]
		}
	}
}

// Place a new tetro on top
fn (g mut Game) generate_tetro() {
	g.pos_y = 0
	g.pos_x = FieldWidth / 2 - TetroSize / 2
	g.tetro_idx = rand.next(BTetros.len)
	g.rotation_idx = 0
	g.get_tetro()
}

// Get the right tetro from cache
fn (g mut Game) get_tetro() {
	idx := g.tetro_idx * TetroSize * TetroSize + g.rotation_idx * TetroSize
	g.tetro = g.tetros_cache.slice(idx, idx + TetroSize)
}

fn (g mut Game) drop_tetro() {
	for i := 0; i < TetroSize; i++ {
		tetro := g.tetro[i]
		x := tetro.x + g.pos_x
		y := tetro.y + g.pos_y
		// Remember the color of each block
		// TODO: g.field[y][x] = g.tetro_idx + 1
		mut row := g.field[y]
		row[x] = g.tetro_idx + 1
	}
}

fn (g &Game) draw_tetro() {
	for i := 0; i < TetroSize; i++ {
		tetro := g.tetro[i]
		g.draw_block(g.pos_y + tetro.y, g.pos_x + tetro.x, g.tetro_idx + 1)
	}
}

fn (g &Game) draw_block(i, j, color_idx int) {
	g.gg.draw_rect((j - 1) * BlockSize, (i - 1) * BlockSize,
		BlockSize - 1, BlockSize - 1, Colors[color_idx])
}

fn (g &Game) draw_field() {
	for i := 1; i < FieldHeight + 1; i++ {
		for j := 1; j < FieldWidth + 1; j++ {
			f := g.field[i]
			if f[j] > 0 {
				g.draw_block(i, j, f[j])
			}
		}
	}
}

fn (g &Game) draw_scene() {
	g.draw_tetro()
	g.draw_field()
}

fn parse_binary_tetro(t int) []Block {
	res := [Block{} ; 4]
	mut cnt := 0
	horizontal := t == 9// special case for the horizontal line
	for i := 0; i <= 3; i++ {
		// Get ith digit of t
		p := int(math.pow(10, 3 - i))
		mut digit := int(t / p)
		t %= p
		// Convert the digit to binary
		for j := 3; j >= 0; j-- {
			bin := digit % 2
			digit /= 2
			if bin == 1 || (horizontal && i == TetroSize - 1) {
				// TODO: res[cnt].x = j
				// res[cnt].y = i
				mut point := &res[cnt]
				point.x = j
				point.y = i
				cnt++
			}
		}
	}
	return res
}

// TODO: this exposes the unsafe C interface, clean up
fn key_down(wnd voidptr, key, code, action, mods int) {
	if action != 2 && action != 1 {
		return
	}
	// Fetch the game object stored in the user pointer
	mut game := &Game(glfw.get_window_user_pointer(wnd))
	switch key {
	case glfw.KEY_ESCAPE:
		glfw.set_should_close(wnd, true)
	case glfw.KeyUp:
		// Rotate the tetro
		game.rotation_idx++
		if game.rotation_idx == TetroSize {
			game.rotation_idx = 0
		}
		game.get_tetro()
		if game.pos_x < 0 {
			game.pos_x = 1
		}
	case glfw.KeyLeft:
		game.move_right(-1)
	case glfw.KeyRight:
		game.move_right(1)
	case glfw.KeyDown:
		game.move_tetro() // drop faster when the player presses <down>
	}
}

   我们看到这个程序是在这行代码window.onkeydown(key_down)来进行事件注册的,其渲染是在draw_scene函数进行渲染的。

使用v run tetris.v命令就能看到以下的效果了。左边是debug窗口,右边是程序效果。

 

     后面笔者还会继续关注V语言的发展,为大家带来第一手的教程分享。