this is my first attempt at coding a game with python. I am at trying to run it through codeacademy labs but it says this:
File "<stdin>", line 7
__init__(self, name, size_v, size_h):
^ SyntaxError: invalid syntax Unknown error.
don't be afraid of hurting my feelings I am a very novice coder and I know I'm probably making quite a few mistakes.
I supposed I'm also looking for an explanation or alternative on how to code and experiment in a different setting (i think it's called an 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
There's 4 kind of errors in your script:
You forget the def identifier before each function:
class Ocean(object):
def __init__(self, name, size_v, size_h):
# ^^^
self.name = name
self.size_v = size_v
self.size_h = size_h
See documentation examples to get the syntax of classes :)
You forget some semicolons after class definition
class MedicShip(Ship):
# ^ this one
You also have a syntax error in the last function (mainload), there's a quote at the end. The correct line is:
log.write("[] " + gametime + " [] " + gamestate + " [] " + username + " [] " +gametype)
Finally, if you want to execute your code, you'll need to put something (other than comments) in the elif block at the end of your file. Otherwise, the interpreter will raise a syntax error (EOF error). Put a pass statement if you don't want to put any code for the moment:
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
I recommend you to read some beginner Python tutorial to learn the syntax ;)
You should define your function __init__() by writing def __init__(self, size)
also in some places you have forgotten to put ':' after defining class.
If you are a beginner in python u can get tutorial here(official python documentation)
To practice some basic programming stuff go to www.codingbat.com
Related
I develop bottom up, starting with small simple methods to go to the big full fledged implementation
class Pop(object):
def welcome(self, name, new_member = False):
response = ""
if new_member:
response = " NOT"
return str("hello there "+name+", you seem"+response+" to be a member\n")
def ageVerification(self, name, age, new_member = False):
the_welcome_string = self.welcome(name, new_member)
minimum = ""
excuse = ""
if age < 16:
minimum = " NOT"
excuse = ", sorry"
return str(the_welcome_string+str(age)+" is"+minimum+" the minimum required age to buy beer in Belgium"+excuse+"\n")
def theWholething(self, name, age, address, new_member = False):
if age < 16:
appology = str("you cannot order any beer\n")
else:
appology = str("your beer will be shipped to "+address+"\n")
return str(self.ageVerification(name, age, new_member)+appology)
# EOF
My question is if it is normal that when i reach theWholeThingMethod, I carry along all the parameters of the previously defined methods? Is this pythonic?
My population class has almost 20 "helper" methods called in theWholeThing, and it seems I am just fiddling with parameters to get them in the right order ...
theWholeThing(self,\
name,\
age,\
address,\
registered = True,\
first_date_entered,\
last_date_entered,\
purchased_amount,\
favorite_beer,\
promotional_code,\
and_so_on0,\
and_so_on1,\
and_so_on2,\
and_so_on3,\
and_so_on4,\
and_so_on5,\
and_so_on6,\
and_so_on7,\
and_so_on8,\
and_so_on9,\
and_so_on10):
My question is if it is normal that when i reach theWholeThingMethod, I carry along all the parameters of the previously defined methods? Is this pythonic?
Neither.
There is really no point in having a class if all the methods take all the arguments anyway. These might as well just be functions.
There are many ways this could be done, depending on whether the various parameters are mandatory, or what happens when one is not provided, but here is one possibility:
from dataclasses import dataclass
#dataclass
class Pop(object):
name: str
age: int
address: str
new_member : bool = False
def welcome(self):
response = ""
if self.new_member:
response = " NOT"
return str("hello there "+self.name+", you seem"+response+" to be a member\n")
def ageVerification(self):
the_welcome_string = self.welcome()
minimum = ""
excuse = ""
if self.age < 16:
minimum = " NOT"
excuse = ", sorry"
return str(the_welcome_string+str(self.age)+" is"+minimum+" the minimum required age to buy beer in Belgium"+excuse+"\n")
def theWholething(self):
if self.age < 16:
appology = str("you cannot order any beer\n")
else:
appology = str("your beer will be shipped to "+self.address+"\n")
return str(self.ageVerification()+appology)
# EOF
Note: #nneonneo had a great suggestion of using a dataclasses, so answer tweaked to incorporate that
I created a super simple Character and Buildable class for a miniature game I am developing and I have created a nested class where Character is for the outer class and Buildable is the inner class. I am trying to loop through resources from Character inside my upgradeBuildable function within Buildable.
class Character:
# Constructor -- Also why do comments use # and not // -_-
def __init__(self):
self.name = "Pickle"
self.health = 100
self.resources = ["Fire", "Coal"]
self.buildObj = self.Buildable() # Object for nested 2nd class
# Function to display character info
def characterInfo(self):
print("CharacterInfo --> " + "Name:", self.name, "| Health:", self.health, "| Resources:", self.resources)
def printRes(self):
print(self.resources)
# Function for collecting resources
def collectResource(self, newResource):
self.resources.append(newResource)
class Buildable:
def __init__(self):
self.buildings = ["Fire 1"]
self.upgradeStatus = 0
self.outer = Character()
def displayBuildable(self):
print("Buildables -->", self.buildings)
def createBuildable(self, newBuilding):
self.buildings.append(newBuilding)
def upgradeBuildable(self, replaceBuilding):
if self.upgradeStatus == 0:
# Update selected building
for i in range(len(self.buildings)):
if self.buildings[i] == replaceBuilding:
self.buildings[i] = "2x"
break
print(Character.resources)
self.upgradeStatus = self.upgradeStatus + 1
print(self.upgradeStatus)
When I try to access print the resource attribute from Character in upgradeBuildable I get a recursion error "RecursionError: maximum recursion depth exceeded" which is confusing to me.
All I am trying to do is try and print the resources the character has inside my inner Buildable class. Any help is much appreciated !!
My main is followed below:
from BW_Classes import Character
pick = Character()
pick.characterInfo()
# Object created for inner class -- Buildable()
build = pick.buildObj
build.displayBuildable()
print()
print("Building......")
build.createBuildable("Fire 2")
build.createBuildable("Coal Mine")
build.createBuildable("Coal Supreme")
build.createBuildable("Ocean")
build.displayBuildable()
print()
print("Upgrading....")
build.upgradeBuildable("Fire 2")
build.displayBuildable()
I believe what you are look for is Inheritance. Inheritance basically means that a class inherits the properties and methods of another class, which I am assuming you are looking for when you say nested classes.
The error is being thrown because when you initialize the character, the function initializes the buildable. When the buildable is initialized, it initializes the character. See the loop?
Your code will probably look something like this:
class Character(Buildable):
def __init__(self):
self.name = "Pickle"
self.health = 100
self.resources = ["Fire", "Coal"]
#initialize the buildable class
super().__init__()
# Function to display character info
def characterInfo(self):
print("CharacterInfo --> " + "Name:", self.name, "| Health:", self.health, "| Resources:", self.resources)
def printRes(self):
print(self.resources)
# Function for collecting resources
def collectResource(self, newResource):
self.resources.append(newResource)
class Buildable():
def __init__(self):
self.buildings = ["Fire 1"]
self.upgradeStatus = 0
def displayBuildable(self):
print("Buildables -->", self.buildings)
def createBuildable(self, newBuilding):
self.buildings.append(newBuilding)
def upgradeBuildable(self, replaceBuilding):
if self.upgradeStatus == 0:
# Update selected building
for i in range(len(self.buildings)):
if self.buildings[i] == replaceBuilding:
self.buildings[i] = "2x"
break
print(Character.resources)
self.upgradeStatus = self.upgradeStatus + 1
print(self.upgradeStatus)
I'm currently working on a text adventure in python (this language just because it's the one I know), and I'm finding that creating and loading savefiles removes some of the mecahnics I've made. I'll include the problematic code here, rather than all of elements that work fine. it's mainly to do with classes and how instances are 'pickled'.
Here are some of the classes I've created:
class Player:
def __init__(self, name):
self.sack = []
self.kit = []
self.equipped = []
self.log = []
self.done = []
class Weapon:
def __init__(self, name, price, minattack, maxattack):
self.name = name
self.price = price
self.minattack = minattack
self.maxattack = maxattack
class Food:
def __init__(self, name, price, healthadd):
self.name = name
self.price = price
self.healthadd = healthadd
class Quest:
def __init__(self, name, requirement, num, gold, npc, place, give_text, prog_text, comp_text, done_text):
self.name = name
self.requirement = requirement
self.num = num
self.score = 0
self.gold = gold
self.npc = npc
self.place = place
self.give_text = give_text
self.prog_text = prog_text
self.comp_text = comp_text
self.done_text = done_text
The instances in the Player class I've included here are just the ones that are appended by other mechanics with Weapons, Food and Quests. The code includes regions where Weapons, Food and Quests are populated (though working on a separate assets file might tidy things up a bit).
Here's how the save/load functions work currently:
def save(lastplace):
clear()
with open('savefile', 'wb') as f:
PlayerID.currentplace = lastplace.name
pickle.dump(PlayerID, f)
print("Game saved:\n")
print(PlayerID.name)
print("(Level %i)" % (PlayerID.level))
print(lastplace.name)
print('')
option = input(">>> ")
goto(lastplace)
def load():
clear()
if os.path.exists("savefile") == True:
with open('savefile', 'rb') as f:
global PlayerID
PlayerID = pickle.load(f)
savedplace = PlayerID.currentplace
savedplace = locations[savedplace]
goto(savedplace)
else:
print("You have no save file for this game.")
option = input('>>> ')
main()
It's worth noting that upon entry to the game, PlayerID (you) becomes a global variable. You might begin to see some of the issues here, or rather the overarching issue. Essentially, the pickling process serialises all of the possible class types stored in lists within the class of Player just get appended by their names, thus removing their class properties when loaded back into the game.
Is there a pythonic way to ensure that class instances are saved for a future load so that they can still behave as classes, particularly when stacked inside the class of Player? I appreciate this is more of an editorial rather than a question by its length, but any help would be hugely appreciated.
The question is noted in the title. It might be a question of details, as always, but still, any help would be appreciated.
# create a supervilan class
class supervilan:
size = ""
color = ""
powers = ""
weapons = ""
special_ability = ""
def customs(self):
print(self.name + " has a supercool and technologic advanced suit.")
def organic_gear(self, gear):
print(self.name + " use they´re" + gear + " with mastery and precision!")
I reduced the amount of methods to facilitate:
# objects
Dracula = supervilan()
Dracula.size = "2.12cm"
Dracula.color = "white"
Dracula.organic_gear("Astucy")
Chimical = supervilan()
Chimical.size = "2.30cm"
Chimical.color = "Caucasian"
Dracula.organic_gear()
Chimical.customs()
Positional arguments are values you put in the brackets of a function (eg: function(arg1,arg2)). The organic_gear function requires two positional arguments as specified when you defined the function (organic_gear(self, gear)). However in your code you call organic_gear without specifying what "self" or "gear" are, and that's why that error message appears. There may be other errors or style improvements to be corrected but I'll leave that to people better versed in classes in python.
First, you should go through the basics of OOPs concept to work with class and instances.
Since you wants to create different instances of your supervilan class with different attribute of (size, color, etc..), you must make them instance variable not class and set default values when you are initializing the instance of your class.
class supervilan:
def __init__(self, name='', size='', color='', powers='', weapons='', special_ability=''):
self.name = name
self.size = size
self.color = color
self.powers = powers
self.weapons = weapons
def customs(self):
print(self.name + " has a supercool and technologic advanced suit.")
def organic_gear(self, gear):
print(self.name + " use they´re" + gear + " with mastery and precision!")
Now you can create different instances of your class with different attribute values
Dracula = supervilan("Dracula", "2.12cm", "white")
Chimical = supervilan("Chimical", "2.30cm", "Caucasian)
I'm quite confused as to how I can pass variables which are set within a function to a method, which is within a class.
Here is the code in question:
class monster():
def __init__(self, health, name):
print(name + " has been born!")
self.name = name
self.health = health
self.stats(name, health)
def stats(self, name, health):
self.name = name
self.health = health
print(self.name + " - " + str(self.health) + " HP")
I create an instance of monster() with this line at the start of the program:
gameMonster = monster(20, name)
However, you can see that the function stats() is supposed to display the name and health of the monster, which is set earlier. The game is in a loop, so the stats() function would be called after each "turn". However, I need to pass the variables name and health to stats() to be able to display them, but can't seem to figure out how.
My question is:
How do I pass the variables, which are declared on initialisation of the method, to another method within the same class?
Any help appreciated.
You don't need to set them again, they already live on the instance:
class Monster(object):
def __init__(self, health, name):
print(name + " has been born!")
self.name = name
self.health = health
self.stats()
def stats(self):
print(self.name + " - " + str(self.health) + " HP")
And usage:
>>> monster = Monster(20, 'Boris')
Boris has been born!
Boris - 20 HP
>>> monster.stats()
Boris - 20 HP
>>> monster.health -= 5
>>> monster.stats()
Boris - 15 HP