-1

它一直说语法错误意外'n'期待:: ['或'。' 和语法错误意外关键字_确保预期输入结束。我的代码有什么问题?

require 'rubygems'
require 'rubygame'

class
      def initialize
             @screen = Rubygame::Screen.new [640, 480], 0, [Rubygame::HWSURFACE, Rubygame::DOUBLEBUF] 
             @screen.title = "Pong"

             @queue = Rubygame::EventQueue.new
             @clock =  Rubygame::Clock.new
             @clock.target_framerate = 60
      end

      def run!
          loop do
                      update
                      draw
                      @clock.tick
           end  
      end

      def update
      end

      def draw
      end
end

g = Game.new
g.run!
4

3 回答 3

2
class

should be:

class Game

That will get you started.

Stylistically, your code is formatted wrong for Ruby:

  • Use 2-space indenting
  • It's smart to use trailing () after a method name: It visually sets it apart when you're reading it, and there are occasions where Ruby will misunderstand and think a method is a variable until its seen a definite method vs. variable use of that name.
  • Use parenthesis to surround the parameters for methods like:

    @screen = Rubygame::Screen.new [640, 480], 0, [Rubygame::HWSURFACE, Rubygame::DOUBLEBUF] 
    

    You can encounter a world of debugging-hurt if you try to pass a block to a method call without surrounding parameters. Ruby will be confused and will throw errors; Simply getting in the habit of surrounding them will avoid the problem cleanly and without fuss.

于 2013-09-13T15:54:49.303 回答
2

您没有类名,只有关键字“类”。

于 2013-09-13T15:51:54.940 回答
0

所以,这是一个非常神秘的错误消息,因为您的代码中有一个基本的语法错误!

正如其他人所指出的,问题是缺少类名。也就是说,第 4 行,而不是这个:

class

应该是这样的:

class Game

但为什么?我们怎么知道它应该是“游戏”?

在 Ruby 中,您通常在“class”关键字之后包含一个名称。使用此名称,您可以根据此类定义创建对象。这是程序倒数第二行发生的情况:

g = Game.new

这一行说,“创建一个 'Game' 类的新实例并将其分配给变量 'g'。” 为了让这条线真正起作用,需要有一个名为“Game”的类。这是我们知道这个类的名称应该是什么的线索。

您显然已经克服了学习 Ruby 的最初障碍。坚持下去!随着您能够掌握更多语法,它开始变得更容易。

祝你好运!

于 2013-09-13T19:01:26.640 回答