codeacademy实验室编写python脚本时出错

时间:2013-12-29 09:44:35

标签: python

这是我第一次尝试用python编写游戏。我正试图通过codeacademy实验室运行它,但它说:

File "<stdin>", line 7
    __init__(self, name, size_v, size_h): 
^ SyntaxError: invalid syntax Unknown error.

不要害怕伤害我的感情我是一个非常新手的编码员,我知道我可能犯了很多错误。

我想我也在寻找关于如何在不同设置中编码和实验的解释或替代方案(我认为它被称为IDE)

from datetime import datetime

log = open("log.txt", "a")


class Ocean(object):
    __init__(self, name, size_v, size_h):
        self.name = name
        self.size_v = size_v
        self.size_h = size_h

class Ship(object):
    __init__(self, size):
        self.health = size
        self.size = size

class BattleShip(Ship)
    __init__(self):
        self.health = 4
        self.size = 4

class AirCarrier(Ship)
    __init__(self):
        self.health = 6
        self.size = 6

class MedicShip(Ship)
    __init__(self, size):
        self.health = 2
        self.size = 2

class ArmouredShip(Ship)
    __init__(self, size):
        self.health = 3
        self.size = 2

def create_user_profile(username):
    user_profile = open(username + "prof", "r+")

def create_default_ocean(name):
    ocean = Ocean(name, 20, 20)
    return ocean.populate(2,1,1,1)

def mainload():
    gametime = datetime.now()
    gamestate = "mainmenu"

    username = str(raw_input("What is your name? "))
    create_user_profile(username)

    gametype = str(raw_input("What do you want to play?     (QUICKPLAY) (CUSTOM)"))
    log.write("[] " + gametime + " [] " + gamestate + " [] " + username + " [] " +gametype")

quick = "quick quickplay qp q"
custom = "custom cust c"

mainload()
if gametype.lower() in quick:
    ocean = create_default_ocean(newocean)
elif gametype.lower() in custom:
    #get height/width of ocean
    #get amount of ships/size

2 个答案:

答案 0 :(得分:4)

您的脚本中有4种错误:

  1. 在每个函数之前忘记了def标识符:

    class Ocean(object):
        def __init__(self, name, size_v, size_h):
      # ^^^
            self.name = name
            self.size_v = size_v
            self.size_h = size_h
    

    请参阅documentation examples以获取类的语法:)

  2. 在课程定义后忘记了一些分号

    class MedicShip(Ship):
                       # ^ this one
    
  3. 最后一个函数(mainload)中也有语法错误,最后有一个引号。正确的行是:

    log.write("[] " + gametime + " [] " + gamestate + " [] " + username + " [] " +gametype)
    
  4. 最后,如果要执行代码,则需要在文件末尾的elif块中添加一些内容(注释除外)。否则,解释器将引发语法错误(EOF错误)。如果您不想暂时放置任何代码,请输入pass statement

    elif gametype.lower() in custom:
        pass     # <- do nothing but create a correct block for the elif
        #get height/width of ocean
        #get amount of ships/size
    
  5. 我建议你阅读一些初学Python教程来学习语法;)

答案 1 :(得分:0)

您应该通过在定义类后忘记放置':'的某些地方编写def __init__()来定义函数__init__(self, size)

  • 如果您是python的初学者,可以获得教程here(官方python文档)

  • 要练习一些基本的编程内容,请转到www.codingbat.com