跳到主要内容

基本语法

缩进语法

注意缩进使用tab而不是4个空格,在某些编辑器中可能会有影响

定义变量

var health=100
var waiting_orders := []

如果不定义变量类型,那么它和JS一样,作为弱类型,可以赋值任意类型

# 这在语法上是没问题的,可以通过指定变量类型禁止这种情况发生
var health=100
health="一百"
print(health)

使用类型提示指定类型

var variable_name: Type = value

var cell_size: Vector2 = Vector2(50, 50)
# 可以简写为
cell_size := Vector2(50, 50)
# 计算机会(使用type interface功能)自动设置类型
# 这里和golang语法基本一致

访问成员变量

与绝大多数语言一样,使用.

position.x=200

声明一个函数

func 函数名(参数名):

无参方法

格式:func functionName(): 例:

func draw()

有参方法

格式:func functionName(参数1,参数2): 示例:

func draw_corner(length):
move_forward(length)
turn_right(90)
move_forward(length)

判断语句

语法:if 条件 : 注意条件的括号()后面有个冒号:

if true:
print('条件成立')
if true :
print('条件成立')
else:
print('条件不成立')

循环

while

func move_to_bottom():
while cell.y < board_size.y - 1
cell += Vector2(0, 1)

for

func move_to_bottom():
for number in range(board_size.y - 1):
cell += Vector2(0, 1)

数组

数组在Godot中与JS一样,使用[]来定义,数组内部的元素不需要是同一个类型

var array = [Vector2(0,0),Vector2(1,1),5,-1]

循环与数组结合

通过item in robot_path判断是不是有这个元素

var robot_path = [Vector2(1, 0), Vector2(1, 1), Vector2(1, 2), Vector2(2, 2), Vector2(3, 2), Vector2(4, 2), Vector2(5, 2)]

func run():
for item in robot_path:
if item in robot_path:
robot.move_to(item)