Ruby for Sketchup 贪吃蛇演示源码(naive_snake)

sketchup是非常简单易用的三维建模软件,可以利用ruby 做二次开发,

api文档 http://www.rbc321.cn/api

今天在su中做了一款小游戏 贪吃蛇,说一下步骤

展示

主要思路:

我制作的的玩法是这样的



关于入口文件


# ----------------------------- #
#  email:[email protected]        #
#  uri: http://www.rbc321.cn    #
# ------------------------------#
# 入口文件
require ‘json‘
require_relative ‘help.rb‘  # 帮助文件
module NaiveSnake
    $game = nil  # 用于保存蛇类实例变量
    class Index
        @@dig = nil
        @@setDig = nil
        @@lydig = nil
        def initialize
            cmd = UI::Command.new("NaiveSnake") {
                # 主窗口
                @@dig = UI::WebDialog.new "NaiveSnake", false, "", 229, 172, 5, 90, false
                @@dig.set_file __dir__+‘/index.html‘
                # 设置窗口
                @@setDig = UI::WebDialog.new "NaiveSnake_set", false, "", 262, 315, 235, 90, false
                @@setDig.set_file __dir__+‘/set.html‘
                # 排行窗口
                @@lydig = UI::WebDialog.new "NaiveSnake_琅琊榜", false, "", 290, 320, 5, 260, false
                @@lydig.set_url ‘http://00a00.com/snake/‘

                @@dig.show if not @@dig.visible?
                @@dig.add_action_callback ‘start‘ do
                    # 检测是否有模型
                    if Sketchup.active_model.active_entities.length > 0
                        is = UI.messagebox("检测到有模型存在,是否清空?\r\n(注:清空才可进入游戏)",MB_YESNO)
                        if is == 6
                            Sketchup.active_model.active_entities.clear!
                            load __dir__+‘/Base.rb‘

                            require_relative ‘Camera.rb‘
                            require_relative ‘Map.rb‘
                            load __dir__+‘/Food.rb‘
                            load __dir__+‘/Snake.rb‘
                            load __dir__+‘/SnakeTool.rb‘      

                            Camera.new        # 初始化相机
                            Map.new.show      # 显示场景
                            Food.new.show     # 显示食物
                            $game = Snake.new # 蛇实例
                            $game.start       # 开始游戏

                            Sketchup.active_model.select_tool SnakeTool.new # 选择工具
                            @@dig.close if @@dig.visible? # 关闭窗口
                            @@setDig.close if @@dig.visible? # 关闭窗口
                            @@lydig.close if @@dig.visible? # 关闭窗口
                        else
                            next
                        end
                    end
                end
                # ready
                @@dig.add_action_callback ‘ready‘ do
                    # 生成随机名字
                    len = 8
                    chars = ("a".."z").to_a + ("A".."Z").to_a + ("0".."9").to_a
                    newpass = ""
                    1.upto(len) { |i| newpass << chars[rand(chars.size-1)] }
                    config ‘nickname‘, newpass
                end

                # 设置按钮
                @@dig.add_action_callback ‘set‘ do
                    @@setDig.show
                end

                # 琅琊榜
                @@dig.add_action_callback ‘langYa‘ do
                    @@lydig.show
                end

                # 确认按钮
                @@setDig.add_action_callback(‘ok‘){|dig, json|
                    hash = JSON.parse json
                    hash.each{|k, v| config k, v }
                    dig.close
                }
                # 默认按钮
                @@setDig.add_action_callback(‘rec‘){|dig, json|
                    json = configRec()
                    @@setDig.execute_script "fill(#{json})"
                }
                # 页面刷新
                @@setDig.add_action_callback(‘init‘){|dig, json|
                    json = configAll()
                    @@setDig.execute_script "data = #{json}"
                }

            }
            # 工具栏
            cmd.small_icon = cmd.large_icon = __dir__+"/assets/icon.png"
            cmd.menu_text = "NaiveSnake"

            toolbar = UI::Toolbar.new "NaiveSnake"
            toolbar = toolbar.add_item cmd
            toolbar.show

            # 菜单
            menu = UI.menu(‘Plugins‘).add_submenu(‘NaiveSnake(贪吃蛇)‘)
            menu.add_item
        end
    end
end
NaiveSnake::Index.new

初始化基类

# ----------------------------- #
#  email:[email protected]        #
#  uri: http://www.rbc321.cn    #
# ------------------------------#
# 基类
module NaiveSnake
    class Base
        @@model = Sketchup.active_model   # 模型
        @@view  = @@model.active_view     # 视
        @@ent   = @@model.active_entities # 实体
        @@mat   = @@model.materials       # 材质

        @@mapWidth     = config(‘mapWidth‘).to_i    # 地图宽
        @@mapHeight    = config(‘mapHeight‘).to_i   # 地图高
        @@snakeHeight  = config(‘snakeHeight‘).to_i # 蛇高度
        @@snakeWidth   = config(‘snakeWidth‘).to_i     # 蛇宽度
        @@snakeNums    = config(‘snakeNums‘).to_i      # 蛇身数
        @@level        = config(‘级别‘)             # 级别
        @@direction    = UP     # 初始方向
        @@currentSnake = []     # 当前蛇body
        @@snakeArr     = []     # 出生蛇body
        @@foot         = []     # 储存食物
        @@blackList    = []     # 食物黑名单
        @@time_id      = nil    # 定时器
        @@score        = 0      # 分数
    end
end

初始化相机

# ----------------------------- #
#  email:[email protected]        #
#  uri: http://www.rbc321.cn    #
# ------------------------------#
# 相机类
module NaiveSnake
	class Camera < Base
		def initialize
			start
		end
		def start
			eye = [0, 0,1300]; target = [0,0,0]; up = [0,1,0]
			start_camera = Sketchup::Camera.new eye, target, up
			@@view.camera = start_camera
		end
	end
end

 初始化场景

# ----------------------------- #
#  email:[email protected]        #
#  uri: http://www.rbc321.cn    #
# ------------------------------#
# 场景类
module NaiveSnake
    class Map < Base
        def show
            grassland # 草地
        end
        def grassland
            filename = __dir__+‘/assets/grassland.skm‘
            material = @@mat.load(filename)

            pt1 = Geom::Point3d.new [email protected]@mapWidth/2, [email protected]@mapHeight/2, 0
            pt2 = Geom::Point3d.new @@mapWidth/2, [email protected]@mapHeight/2, 0
            pt3 = Geom::Point3d.new @@mapWidth/2, @@mapHeight/2, 0
            pt4 = Geom::Point3d.new [email protected]@mapWidth/2, @@mapHeight/2, 0
            grp = @@ent.add_group
            grp.entities.add_face pt1, pt2, pt3, pt4
            grp.material = material
        end
    end
end

初始化蛇类

# ----------------------------- #
#  email:[email protected]        #
#  uri: http://www.rbc321.cn    #
# ------------------------------#
# 蛇类
module NaiveSnake
	class Snake < Base
		def initialize
			@@snakeArr = initSnake @@snakeNums
			@up = 38; @down = 40; @left = 37; @right = 39
			@direction = @@direction
			@x = rand([email protected]@[email protected]@mapWidth)/2/10*10
			@y = rand([email protected]@[email protected]@mapHeight)/2/10*10
		end
		def start
			createSnake # 绘制蛇
			speed = 0.5
			case @@level
				when ‘普通‘; speed = 0.4
				when ‘勇士‘; speed = 0.1
				when ‘地狱‘; speed = 0.03
				when ‘噩梦‘; speed = 0.006
			end
			time = 1
			@@time_id = UI.start_timer(speed, true) do
				move(@direction)
				time += 1
			end
		end
		def set(direction)
			@direction = direction
		end
		# 绘制蛇
		def createSnake
			@@currentSnake.clear # 清空蛇当前状态
			@@snakeArr.each do |box|
				xBaseValue = @@snakeWidth/2
				yBaseValue = @@snakeWidth/2
				point1 = Geom::Point3d.new(box[0]-xBaseValue, box[1]-yBaseValue, 0)
				point2 = Geom::Point3d.new(box[0]+xBaseValue, box[1]-yBaseValue, 0)
				point3 = Geom::Point3d.new(box[0]+xBaseValue, box[1]+yBaseValue, 0)
				point4 = Geom::Point3d.new(box[0]-xBaseValue, box[1]+yBaseValue, 0)
				boxGroup = @@ent.add_group
				face = boxGroup.entities.add_face point1, point2, point3, point4
				face.reverse!.pushpull @@snakeHeight
				@@currentSnake.push boxGroup # 重新设置蛇身体
			end
		end
		# 移动
		def move(direction)
			tmpArray = [] # 临时容器
			head = @@snakeArr.last # 蛇头
			# 判断蛇头是否碰到黑名单
			@@blackList.each{|list|
				if head == list # Game Over
					gameOver
					return
				end
			}
			#判断蛇头是否碰到边缘
			if head[0].abs >= @@mapWidth/2 || head[1].abs >= @@mapHeight/2
				gameOver
				return
			end
			# 判断蛇头是否碰到食物
			if head == @@foot
				# 加分
				@@score += 10
				# 将食物列入黑名单
				@@blackList.push @@foot
				# 蛇头随机移动
				@x = rand(-(@@mapWidth-50)[email protected]@mapWidth-50)/2/10*10
				@y = rand([email protected]@[email protected]@mapHeight)/2/10*10
				@@snakeArr.push [@[email protected]@snakeWidth/2, @[email protected]@snakeHeight/2]
				# 再次显示食物
				Food.new.show
			end
			# 移动数组前一位
			lastValue = @@snakeArr.last.clone;
			for i in [email protected]@snakeArr.size-1
				tmpArray[i] = @@snakeArr[i+1]
			end
			tmpArray.push(lastValue)
			case direction
				when @up;    tmpArray.last[1] += @@snakeWidth
				when @down;  tmpArray.last[1] -= @@snakeWidth
				when @right; tmpArray.last[0] += @@snakeWidth
				when @left;  tmpArray.last[0] -= @@snakeWidth
			end
			@@snakeArr = tmpArray # 重新设置蛇body

			deleteSnake # 删除
			createSnake # 再次绘制
		end

		def deleteSnake
			@@currentSnake.each do |ent|
				ent.entities.each{|ent| @@ent.erase_entities ent}
			end # 删除原来
		end
		def gameOver
			UI.stop_timer @@time_id
			UI.messagebox "游戏结束!\r\n得分:"[email protected]@score.to_s
			updateScore # 更新分数
		end
		def updateScore
			hash = {
				:nickname => config(‘nickname‘),
				:score    => @@score,
				:level    => config(‘级别‘),
				:tk       => ‘qwertyuioplkjhgfdsazxcvbnm‘,
			}
			request = Sketchup::Http::Request.new("http://00a00.com/snake/save.php", Sketchup::Http::POST)
			request.body= httpBuild(hash)
			request.start do |request, response|
				p ‘琅琊榜更新成功‘ if response
			end
		end
		def httpBuild(hash)
			str = ‘‘
			hash.each{|k, v|
				str+= k.to_s+‘=‘+v.to_s+‘&‘
			}
			str.chop!
		end
		def initSnake(n)
			array = []
			n.times{|i|
				array.push [@@snakeWidth/[email protected]@snakeWidth*i, @@snakeWidth/2]
				next if i == 0
			}
			array
		end
	end
end

初始化食物类

# ----------------------------- #
#  email:[email protected]        #
#  uri: http://www.rbc321.cn    #
# ------------------------------#
# 食物类
module NaiveSnake
    class Food < Base
        def initialize
            @x = rand([email protected]@[email protected]@mapWidth)/2/10*10
            @y = rand([email protected]@[email protected]@mapHeight)/2/10*10
        end
        def show
            filename = __dir__+‘/assets/food.skm‘
            material = @@mat.load(filename)

            point = []
            unless isFull?
                point[0] = [@x, @y, 0]
                point[1] = [@x+@@snakeWidth, @y, 0]
                point[2] = [@[email protected]@snakeWidth, @y+@@snakeWidth, 0]
                point[3] = [@x, @y+@@snakeWidth, 0]

                group = @@ent.add_group

                @@foot = [@[email protected]@snakeWidth/2, @[email protected]@snakeHeight/2]
                face = group.entities.add_face point
                face.material = material
                face.reverse!.pushpull @@snakeHeight
                @foot = face
            else
                @x = rand(-@@[email protected]@mapWidth)
                @y = rand(-@@[email protected]@mapHeight)
            end
        end
        def isFull?
            return @@snakeArr.include? [@x, @y]
        end
    end
end

下载地址:

http://www.rbc321.cn/home/plugin/plugindetail/id/247

时间: 2024-10-02 00:20:46

Ruby for Sketchup 贪吃蛇演示源码(naive_snake)的相关文章

【141030】VC++贪吃蛇游戏源码(Win32+API)

不错的贪吃蛇游戏,运用了Win32的API.完整源代码,在VS2005下编译通过.内附有编程要点,很好的学习范例. 游戏源码下载地址:点击下载

ZedGraph 柱状图、饼图、折线图演示源码

http://code1.okbase.net/codefile/ZedGraphControl.ContextMenu.cs_201211225626_97.htm // //This library is free software; you can redistribute it and/or //modify it under the terms of the GNU Lesser General Public //License as published by the Free Sof

C#通过Socket在网络间发送和接收图片的演示源码

将内容过程中常用的内容段备份一次,如下资料是关于C#通过Socket在网络间发送和接收图片的演示的内容,希望能对码农们有帮助. using System;using System.Collections.Generic;using System.Text;using System.Net.Sockets;using System.Net;using System.IO; namespace ConsoleApplication1{Class Program{static void Main (S

C语言基础:数组作为函数参数传递演示源码

将做工程过程中常用的内容片段记录起来,如下内容内容是关于C语言基础:数组作为函数参数传递演示的内容,应该能对小伙伴也有好处. #include <stdio.h> void show_array(int values[], int number_of_elements) { int i; printf("About to display %d valuesn", number_of_elements); for (i = 0; i < number_of_elemen

python插入排序演示源码

工作闲暇时间,把写内容过程较好的内容段做个备份,下面的内容内容是关于python插入排序演示的内容,应该能对各朋友也有用处. def insert_sort(t): for i in xrange(len(t)): key = t[i] j = i - 1 while j>-1 and t[j]>key:#如果当前值比上一位小,循环结束 t[j+1] = t[j] j -= 1 t[j+1] = key #确保待插入值被插入到合适的地方 return t t = [1,3,2,4]print

linux c getchar()实用演示源码

将写代码过程中重要的代码做个备份,如下代码内容是关于linux c getchar()实用演示的代码,应该对小伙伴有一些用. ```#include <stdio.h> int main(void) { int c; is line buffered; this means it will while ((c = getchar()) != 'n') printf("%c", c); return 0; } 注:可以利用getchar()函数让程序调试运行结束后等待编程者按

C#线程池操作演示源码

把开发过程中经常用到的一些代码段做个备份,下面代码内容是关于C#线程池操作演示的代码. static void Main(string[] args){ThreadPool.SetMaxThreads(1000, 1000);for (int i = 0; i < 10;i ){ThreadPool.QueueUserWorkItem(new WaitCallback(ShowMessage), string.Format("当前编号{0}",i));}Console.ReadL

超多经典 canvas 实例,动态离子背景、移动炫彩小球、贪吃蛇、坦克大战、是男人就下100层、心形文字等等等

超多经典 canvas 实例 普及:<canvas> 元素用于在网页上绘制图形.这是一个图形容器,您可以控制其每一像素,必须使用脚本来绘制图形. 注意:IE 8 以及更早的版本不支持 <canvas> 元素. 贴士:全部例子都分享在我的 GayHub - https://github.com/bxm0927/canvas-special 尤雨溪个人主页炫彩三角纽带效果,点击还可变换 GitHub源码 . Demo演示 知乎登录注册页动态离子背景效果 GitHub源码 . Demo演

用代码移动桌面图标(贪吃蛇)

效果图 前言 记得上高二的时候,闲来无事,上b站搜电脑病毒的视频看(不要问我为什么会搜这个),看到一个很有意思的"病毒",其实也不算病毒,它会控制桌面图标形成一个人形,并跳舞,跳完之后电脑就蓝屏了.之后下定决心也要整一个,埋头研究了两个星期吧,写了一个贪吃蛇,此贪吃蛇非彼贪吃蛇,它当然是控制的桌面图标来玩啦,还写了个网络版的,通过手机去控制. 贪吃蛇效果 本文章只介绍如何移动图标,不介绍贪吃蛇实现(源码太多),可以评价私信要源码 实现思路 说到这,真的很后悔以前没第一个学c语言,反而学