我是python的新手。我正在写一个宇宙飞船战斗模拟。当我不使用任何while循环时,我的代码工作得很好,但是当我这样做时,返回“=:'str'和'int'”错误的“不支持的操作数类型”。 我正在使用python 2.7.13。如果有人能帮我解决这个问题,我真的很感激。
下面是我的代码,虽然缩进被四个空格填充了
import numpy as np
import random
import time
#below are for classes need to be used in this code
class ship:
#constructor: setup name with given input,
#and also hull and shield strength and laser damage
#create a list with its name to store log of battle
#the missle is for subclass
def __init__(self, setname):
self.name = setname
self.shield = 1000
self.hull = 600
self.laser = 400
self.missle = 800
self.histtitle = "history of " + str(self.name)
self.history = [self.histtitle]
#for identifying ship type
def shiptype(self):
return "standard spaceship"
#determine if the ship is destroyed
#update in log and print out
def destroy(self, hullstr):
if self.hull <= 0:
self.history.append(self.name + "has been destroyed!")
return "the ship", self.name, "has been destroyed!"
else:
pass
#the function for applying damage taken of the ship when called
#with inputting the value of damage, and who attacks the ship
def damed(self, damage, attacker):
#flow control for determine which part of the ship
#is supposed to take damage, and how much damage it
#supposed to take, and update the new status of the ship
#there are three possible sceneries
if self.shield >= damage:
self.shield -= damage
elif (self.shield > 0) and (self.shield < damage):
self.penetrate = damage - self.shield
self.hull = self.hull - self.penetrate/2
self.shield = "none"
else:
self.hull = self.hull - damage
self.shield = "none"
#update the battle log
self.damreport = str(self.name) + " is shot by " \
+ str(attacker) + " | current status: hull strength "\
+ str(self.hull) + " | shield strength: " + str(self.shield) + " "
self.history.append(self.damreport)
self.history.append(".................")
#this function for dealing with what kind of weapon being used
#by the ship and the target of the ship to attack
def attc(self, wtype):
#obtaining the damage of the weapon, and
#type of the weapon with flow control
self.damage = wtype
self.weapon = 0
k = -1
if self.damage == self.laser:
self.weapon = "laser"
else:
self.weapon = "missle"
#start to aim others with random.choice from the list of battle ships
target = random.choice(shiplist)
#the while loop makes sure the ship won't attack itself
#ensures the ship won't attack the ships that are destroyed
#by repeating drawing names
while (target.name == self.name) or (target.hull <= 0):
target = random.choice(shiplist)
#apply damed function to the target ship
target.damed(self.damage,self.name)
#update the log
self.attchist = str(self.name) + " shoot " + \
target.name + " with " + self.weapon
self.history.append(self.attchist)
#this function is to start a round of attack
#useful for latter of subclasses
def roundstart(self):
self.attc(self.laser)
#print out the whole battle log at the end
def getwholehistory(self):
return self.history
#the shorten version(last 6 news) of battle log
#being printed out during battle
def gethistory(self):
self.parthist = []
self.parthist.append("status of " + self.name)
self.parthist.append(self.history[-6:])
return self.parthist
#subclass warship
class warship(ship):
#for identifying ship type
def shiptype(self):
return "warship"
#redefine roundstart(), so that can fire
#missle 30% of time by random.random()
def roundstart(self):
ship.roundstart(self)
if random.random() <= 0.3:
self.attc(self.missle)
#subclass speeder
class speeder(ship):
#for identifying ship type
def shiptype(self):
return "speeder"
#adding 50% probability for dodging attack by
#modifying ship.damed() with random.random()
def damed(self, damage, attacker):
if random.random() <= 0.5:
pass
else:
ship.damed(self, damage, attacker)
#below are useful function for this code
#this function determines in which order that the ships
#will attack in a round randomly, for fairness
def randraw():
slistcopy = shiplist
random.shuffle(slistcopy)
ranshiplist = slistcopy
return ranshiplist
#this function is for declaring winner
def declare(mylist):
#in battling, the input will be a list with exactly one entry
#so this can return the last survivor
winner = mylist[0]
print "the winner is ", winner.name, \
"! congrat to ", winner.name
return
#this is the function for start the battle
def battling():
#initialize the parameters, deadnum
#for counting ships that are destroyed
#setup batlist by randraw()
deadnum = 0
batlist = randraw()
#use while loop to fight round by round
#looping until only one remains
while deadnum < (len(batlist) - 1):
#find and delete any ships that are destroyed
#from the battle list batlist so that they won't
#move. count the ships that are destroyed
for k in range(len(batlist)):
if batlist[k].hull <= 0:
batlist[k].destroy()
batlist.remove(batlist[k])
deadnum += 1
#randomize the battle list again after delete
#the destroyed ships from the list
batlist = randraw()
#due to the limitation of this while loop
#need an extra if to ensure the last survivor
#won't attack destroyed ships
if deadnum < (len(batlist) - 1):
for k in range(len(batlist)):
#print out battle log as battle in process
batlist[k].roundstart()
batlist[k].gethistory()
#slow down for readability
time.sleep(2)
#when battle done, print out the whole history
for k in range(len(shiplist)):
shiplist[k].getwholehistory()
#declare winner
declare(batlist)
#test for 4 ships
shipa = ship("A")
shipb = ship("B")
shipc = warship("C")
shipd = speeder("D")
shiplist = [shipa,shipb,shipc,shipd]
#these commands work just fine
shipc.roundstart()
for k in range(len(shiplist)):
print shiplist[k].getwholehistory()
battling() #this line causes mistake
以下是我在终端中获得的内容:
['history of A', 'A is shot by C | current status: hull strength
600 | shield strength: 600 ', '.................']
['history of B', 'B is shot by C | current status: hull strength
600 | shield strength: 200 ', '.................']
['history of C', 'C shoot A with laser', 'C shoot B with missle']
['history of D']
Traceback (most recent call last):
File "on.py", line 193, in <module>
battling()
File "on.py", line 173, in battling
batlist[k].roundstart()
File "on.py", line 85, in roundstart
self.attc(self.laser)
File "on.py", line 76, in attc
target.damed(self.damage,self.name)
File "on.py", line 41, in damed
self.shield -= damage
TypeError: unsupported operand type(s) for -=: 'str' and 'int'
再一次,我非常感谢你的任何帮助。
答案 0 :(得分:0)
你的盾牌变量属于int类型。您的损坏变量是String类型。当你这样做
self.shield -= damage
您尝试
int = int - String
因为混乱的缩进,你的代码是不可能的(至少对我而言)。所以我未经测试的解决方案是
def attc(self, wtype):
#obtaining the damage of the weapon, and
#type of the weapon with flow control
self.weapon = 0
k = -1
if wtype == self.laser:
self.weapon = "laser"
self.damage = self.laser
else:
self.weapon = "missle"
self.damage = self.missle
另外,我不确定,但我认为 init 需要
self.damage = 0