This is my class program, for the instances I've created so far, it's worked fine.
from random import random
class team:
wins = 0
losses = 0
def __init__(self,name):
self.name = name
def win(self):
self.wins += 1
def lose(self):
self.losses += 1
def play(self,opponent):
if random()<0.5:
self.win()
opponent.lose()
print(self.name,"won",opponent.name,"lost")
else:
self.lose()
opponent.win()
print(opponent.name,"won",self.name,"lost")
def record(self):
return (self.wins,'-',self.losses)
def startgames(self, array_of_team_objects):
k = 1
outer = 0
space = True
while outer<len(array_of_team_objects):
inner = 0
while space == True:
inner = outer + k
if inner == len(Teams): space = False
array_of_team_objects[outer].play(array_of_team_objects[inner])
k +=1
#whileinner
outer+=1
#whileouter
print("Every team has now played every other team once")
team1 = team("Yankees") # creates a team object with given name
team2 = team("Mets") # each new team starts with 0 wins and 0 losses
team1.play(team2) #prints "Yankees won, Mets lost" or "Mets won, Yankees lost"
print(team1.record()) # should print "1-0" or "0-1" depending on above
print(team2.record()) # should print "0-1" or "1-0" depending on above
For the next part of this program, which I will use the 'startgames' method for, I want to make every element of the list 'Names' an object of the class. How can I do this?
Names =["Mets","Yankees","Dodgers","Cubs","Nationals","Rays","Marlins","Braves","Twins","Athletics","Orioles","Royals","Phillies","Pirates"]
Related
Your team has been assigned to develop a console or GUI turn-based battle game. The game allows player setup his/her team which made up of a numbers of units (default is 3). Each unit has a name, health point (HP), attack point (ATK), defence point (DEF), experience (EXP) and a rank. On top of that, a unit can be either a Warrior or Tanker which having different strength in different range for ATK and DEF point. The initial value for each attribute point are describe in the details requirement in Part A – Table 1.
The game will then setup another team belongs to AI which made up of same number of unit as the player’s team. The type of unit will be assigned randomly by chances. The name of each unit will be specify by the player while the name of each unit for AI team will be defined with prefix with “AI” follow by 2 random digits i.e. AI87.
A player can select a unit from his/her team and attack the other unit (the target) in the opponent / AI team. Unit which are severely damaged (i.e. HP equals to less than 0) will be defeated and removed from the team. The team (player / AI) which destroy all the opponent units first will be declared as winner of the game.
enter code here
class GameCharacter:
char_name = ""
char_type = ""
__hp = 0
__atk = 0
__def = 0
__rank = 0
def __init__(self, char_type, char_name):
self.char_type: str = char_type
self.char_name: str = char_name
if char_type == "Warrior":
self.setup_warrior()
elif char_type == "Tanker":
self.setup_tanker()
def setup_warrior(self):
self.__hp = 100
self.__atk = 20
self.__def = 6
self.__rank = 1
return [self]
def setup_tanker(self):
self.__hp = 100
self.__atk = 8
self.__def = 9
self.__rank = 1
return [self]
def get_attack(self):
return self.__atk
def get_health(self):
return self.__hp
def __str__(self):
text = "Character type:{},name:{}".format(self.char_type, self.char_name)
return text
enter code here
import game_setting
import random
rounds = 1
count = 0
gs = game_setting.GameCharacter.__init__(char_type, char_name)
player_team = []
ai_bot = []
def detail_ai():
print(ai_bot)
def detail_player():
print(player_team)
def details_all():
print(player_team)
print(ai_bot)
def main():
get_name = ""
j = random.randint(1, 2)
ch = ""
i: int
types = ""
for i in range(1, 4):
get_name = (input("Choose character name:"))
ch = (input("Choose character type [w/t]:")).lower()
if ch == 'w' and get_name != "":
types: str = "Warrior"
player_team.append(types)
player_team.append(get_name)
print("character", i, ":", types, "Name:", get_name)
elif ch == 't':
types: str = "Tanker"
player_team.append(self.types)
print("character", i, ":", types, "Name:", get_name)
else:
print("Wrong value ")
# =======================================Ai Bot name=================================================
for i in range(1, 4):
if ch == "w" and j != j:
ch: str = "Warrior"
ai_bot.append(ch)
elif ch == "t" and j != j:
types: str = "Tanker"
player_team.append(types)
else:
print("Wrong value ")
k = str(random.randint(10, 99))
if get_name != get_name:
get_name: str = "AI" + k
ai_bot.append(get_name)
else:
print("Done setting.")
print("character", i, " : ", types, "Name:", get_name)
show_name: str = ""
show_type: str = ""
main()
I have made this simple program all ut does so far is create tanks however i have come to a problem. I would like it to assign a number corrosponding to if its the first second third or fourth etc... could someone help me with this thanks in advance.
class Player:
def __init__(self, name, tank_name):
self.name = name
self.tank_name = tank_name
self.number = number
players = input('Please type player amount >>> ')
try:
players = int(players)
except ValueError:
print('Whoops... ' + players + ' is not a valid number. The auto amount is two players.')
players = int(2)
number = 0
def new_player():
name = input('What is your name >>> ')
tank_name = input('What is your tanks name >>> ')
number = str(number)
number = Player(name, tank_name)
for i in range(0, players):
number = int(number)
number = number + 1
new_player()
print()
print('Next player or end of player creation.')
print()
You can pass the number to new_player by changing it to this:
def new_player(number):
name = input('What is your name >>> ')
tank_name = input('What is your tanks name >>> ')
return Player(name, tank_name, number)
Note that I made it now return the created Player which you forgot to do.
We now give number to Player, so we need to change __init__ to this:
def __init__(self, name, tank_name, number):
self.name = name
self.tank_name = tank_name
self.number = number
Now you actually already have a variable called number that you increase by 1 each time (using number = number + 1), but you can instead use i directly like this. since the range will take care of increasing i by one each time for you:
for i in range(0, players):
player = new_player(i)
print()
print('Next player or end of player creation.')
print()
Note how I got rid of the int use, as i here is already an integer.
If you want to start the players at 1 instead of 0, you would change new_player(i) to new_player(i + 1).
I would recommend passing through a number variable to the class, and every time you are creating an instance of the Player class, you add one to the number. Also, it can be useful to store the instances of the class in list, and then you can access a specific player with the generator: [player for player in players if player.number == 1]
class Player:
def __init__(self, name, tank_name, number):
self.name = name
self.tank_name = tank_name
self.number = number
players = input('Please type player amount >>> ')
try:
players = int(players)
except ValueError:
print('Whoops... ' + players + ' is not a valid number. The auto amount is two players.')
players = int(2)
number = 0
players = []
def new_player():
name = input('What is your name >>> ')
tank_name = input('What is your tanks name >>> ')
number += 1
players.append(Player(name, tank_name, number))
for i in range(0, players):
new_player()
print()
print('Next player or end of player creation.')
print()
You can also just add a class level counter so every new player gets a unique number.
class Player:
playerctr = 0 # increment for each new player
def __init__(self, name, tank_name):
self.name = name
self.tank_name = tank_name
Player.playerctr += 1
self.number = Player.playerctr # set current counter to this player
I was sitting all week on this and I don't know how to get rid of these global points.
Here I define points.
def init():
global points, hidden_password, hidden_password2, country, used, start_time
points = 0
hidden_password = []
hidden_password2 = []
country = ""
used = []
start_time = datetime.now()
welcome()
choice()
Then it goes to choice() from choice to play_game() than to guessing_capital() and here I use points for the first time, and the program is working until var points reach 5.
def guessing_capital(password, used, user_name):
global points
while points < 5:
checking(password, user_name)
time.sleep(1)
print("\n Letters You failed guessing: ", ", ".join(used), end=".\n")
time.sleep(2)
print("\n *** You lost! Sorry, but the GAME is OVER! ***\n")
time.sleep(3)
init()
Then it goes to checking() and from checking it goes to the letter() and then to checking_password() where if the user didn't guess right letter it adds 1 to points and returns it.
def checking_password(number):
global points, hidden_password2, hidden_password
if hidden_password2 == hidden_password:
points += number
time.sleep(1)
print("\n Boo! You have +", number, "penalty points!")
time.sleep(1)
hidden_password2 = hidden_password
if points < 4:
manage_graphics(points)
elif points == 4:
manage_graphics(points)
print(" Hint: It's a capital of " + country + ".")
elif points >= 5:
manage_graphics(5)
return points
Here is a full code if someone wants: https://codeshare.io/aYBAzb
You can use a class to store attributes.
Class Game:
def __init__():
points = 0
self.hidden_password = []
self.hidden_password2 = []
self.country = ""
self.used = []
self.start_time = datetime.now()
self.welcome() # This should be in main function
self.choice() # This should be in main function
def choice(self, ...):
pass
def welcome(self, ...):
pass
def guessing_capital(self, ...):
pass
def checking_password(self, ...):
pass
So Im making a treasure hunt game in which the user is placed on a grid as 'P' and can move around to collect coins from chests ('X') which are shown on the grid. On the same gird, bandits('B') are also present which take away all previously collected coins.
Now, Ive gotten as far as allowing the player to move around the board but dont know how to add coins to the already created coins variable when the player lands on the treasure.
This is the relevant part of the code which randomly placed 5 Bandits and 10 treasure chests on the board:
def bandits(board):
added_bandits = 0
while added_bandits < 5:
x_bandit = r.randint(0,7)
y_bandit = r.randint(0,7)
if board[x_bandit][y_bandit] == 'O':
board[x_bandit][y_bandit] = 'B'
added_bandits = added_bandits + 1
def treasures(board):
added_treasure = 0
while added_treasure < 10:
x_treasure = r.randint(0,7)
y_treasure = r.randint(0,7)
if board[x_treasure][y_treasure] == 'O':
board[x_treasure][y_treasure] = 'X'
added_treasure = added_treasure + 1
I would create a class Player, where you store this information and that manage the adding/removing of the coins of the player.
class Player(object):
def __init__(self, name):
self.playername = name
self.total_coins = 0
def add_coins(self, number):
self.total_coins += number
def remove_coins(self, number):
self.total_coins -= number
def move(self, move_data):
#implement here the players's move semantic
def print_total_coins(self):
print("Total coins %d" % (self.total_coins))
That way you can get the total coins score like this:
player1 = Player("Player 1")
player1.print_total_coins()
I would further encapsulate the bandits and the treasures in classes too.
My code:
class Lobby(Definition):
Lcount = 0
def __init__(self):
if Lobby.Lcount == 0:
self.description = "test1"
elif Lobby.Lcount > 0:
self.description = "test2"
else:
print("\nHmmm something went wrong...\n")
self.contents = ["Briefcase"]
self.doors = {"n": "terminal", "w": "hallway"}
Lobby.Lcount += 1
I want it to be where after an instance of the room has been created (i.e. you have visited it before), it will display a different description than it the original one. However, it keeps printing the same description. So what precisely am I doing wrong here?
edit: Here is what is in my definition class:
class Definition:
def __init__(self):
self.description = ""
self.contents = []
self.doors = {}
def get_desc(self):
print("{}".format(self.description))
def get_direction(self):
direction = input("Enter a direction or search the room: ").lower()
search = True
if direction == "q":
return direction
elif direction in self.doors:
location = self.doors[direction]
return location
elif direction == "s":
while search:
action = input("\nYou search for some items... Press 1 to continue or 2 to quit.\n")
if action == "1":
if len(location.contents) == 0:
print("\nYou find nothing of value in the room.\n")
else:
find = random.randrange(1, 3)
if find == 1:
found = random.randrange(len(location.contents))
item = location.contents.pop(found)
print("\nYou found a {}\n".format(item))
self.items.append(item)
self.check_items()
else:
print("\nNothing found yet\n")
elif action == "2":
search = False
break
else:
print("\nLocation reminder: ")
location.get_description()
else:
return "\nNot a valid entry\n"
Something in Definition is preventing this from working appropriately.
class FooClass(object):
foo = 0
def __init__(self):
print("Foo {} before".format(self.__class__.foo))
self.__class__.foo += 1
print("Foo {} after".format(self.__class__.foo))
# Works appropriately
>>> x = Foo()
Foo 0 before
Foo 1 after
>>> x = Foo()
Foo 1 before
Foo 2 after
However I'd recommend a different way to track this if it's just a binary "seen" variable. Restricting your ability to create multiple Lobby objects may mess you up in the future. Strongly consider creating a dictionary that houses all your objects, with a visit method that runs the logic your __init__ is doing now, and sets a flag that makes a following visit do something different.
class SomeRoom(Room):
# where Room is some superclass like Definition is now
def __init__(self, *args):
super().__init__(args) # or however
self.__visited = False
#property
def visited(self):
return self.__visited
def visit(self):
if self.visited:
print("Welcome back")
else:
print("Welcome!")
self.__visited = True