My issue right now with yatzy is that I wanna print a board with columns containing names and how much points they have. Currently my code is looking like this:
from terminaltables import AsciiTable
class Player:
def __init__(self,name):
self.name=name
self.lista={"ones":0,"twos":0,"threes":0, "fours":0,"fives":0,"sixs":0,"abovesum":0,"bonus":0,"onepair":0,"twopair":0,"threepair":0,"fourpair":0,"smalladder":0,"bigladder":0,"house":0,"chance":0,"yatzy":0,"totalsum":0}
self.spelarlista=[]
def __repr__(self):
return self.name
def __str__(self):
return self.name
def welcome(self):
t=0
print("Welcome to the yahtzee game!")
players = int(input("How many players: "))
rounds=0
while not players==rounds:
player=input("What is your name?: ")
rounds=rounds+1
self.spelarlista.append(Player(player))
table_data = [
['Heading1', 'Heading2'],
['hans', 'joha'],
['jens', 'drev'],
['sonny', 'elias']]
table = AsciiTable(table_data)
print(table.table)
def main():
play=Player("joakim")
play.welcome()
main()
Notice that the asciitable code is pretty much copied, because I'm not sure how to solve the issue to get columns based on how many players I have. As you can see, it starts with asking how many players, let's say I go with 3, "James","Patrik" and "Andy", then I want 3 columns, is this possible to make? Second question, is Asciitable the right way to go? Is there an easier way, perhaps with something built-in already in python, I just tried this out because I got recommended. Thanks in advance.
Related
i want to create code which will be outputing the sum of the product prize. Example below.
Input:
bread,rice
Output:
6,5 $
Here is my code:
class product:
def __init__(self,name,color,prize)
self.name=name
self.color=color
self.prize=prize
def info(self)
input(name)
return (self.prize)
tomato=product()
tomato.name="tomato"
tomato.color="czerwony"
tomato.prize= 4,56
turnip=product()
turnip.name="turnip"
turnip.color="white"
turnip.prize= 5.65
print("write the name of one products from the list and I will tell you how much it costs [tomato,turnip] "
info()
There is only 2 products,i wanted to reduce code lines.
I think you are looking for something like this, please note, the code below does not have any error/validation checks in place:
class product:
def __init__(self,name=None,color=None,prize=None):
self.name=name
self.color=color
self.prize=prize
def info(self):
return (self.prize)
tomato=product()
tomato.name="tomato"
tomato.color="czerwony"
tomato.prize= 4.56
turnip=product()
turnip.name="turnip"
turnip.color="white"
turnip.prize= 5.65
user_input = raw_input("write the name of one products from the list and I will tell you how much it costs [tomato,turnip]:")
print(eval(user_input).info())
I want to input data in a class. I don't know the number of students I want to input. I can only write p1.name="John" p2.name="Jack" etc but if I want to input more students I have to write p3,p4,p5...
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person
p1.name="John"
p1.age=15
print(p1.name)
print(p1.age)
Is there a method to work like with arrays for example p[0].name="John"....... p[123].name="Jack" or something like that... Sorry for my bad english
You probably meant
p1 = Person('John', 15)
p2 = Person('Jack', 42)
If you needed an arbitrary number of objects, you can store them in a data structure like
people = [Person('John', 15), Person('Jack', 42)]
for person in people:
print(person.name)
You can read data into that array as well-
people = []
with open('people.txt') as f:
for line in f:
name, age = line.split()
people.append(Person(name, age))
But my advice would be to find a more introductory tutorial to follow, you're going to struggle :)
Sounds like you need a list.
A list is a data structure that you can use for zero or more elements, and you can access each element by iteration or by indexing the list.
You can do something like this:
persons = [
Person("John", 15),
Person("Adele", 16),
...
]
and then you can access each person by an index: persons[0] will give you Jonh, and persons[1] will give Adele.
if your objective is to store the students in an array-like structure, then you can definitely do this in Python. What you're currently doing is instantiating a new class object for each student. While this is totally valid, it may not be appropriate for the task you're trying to achieve.
Before mastering classes, I'd recommend familiarising yourself with python data structures like dictionaries, lists and tuples.
Just another idea. You could store all of the students in a dictionary that is contained within a class. Wrapping the dictionary in a class will let you add or fetch students very easily.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
class Classroom:
def __init__(self):
self.students = {}
def add_student(self, student):
self.students[student.name] = student
def get_student(self, name):
return self.students[name]
classroom = Classroom();
classroom.add_student(Person("John", 12))
classroom.add_student(Person("Sarah", 13))
print(classroom.get_student("Sarah").age)
#Output
#13
def main():
classroom = Classroom()
n = input("How many students would you like yo add? ")
for i in range(int(n)):
classroom.add_student(Person(input("Enter Name: "), int(input("Enter Age: "))))
I am working on am assignment for my programming class in which we have to take a blackjack program and add the option to bet.
This is the original program:
http://courses.ischool.berkeley.edu/i90/f11/resources/chapter09/blackjack.py
This works with no problems.
In the class BJ_Game I have added some code to collect bets
class BJ_Game(object):
def __init__(self, names):
self.players = []
for name in names:
player = BJ_Player(name)
self.players.append(player)
self.dealer = BJ_Dealer("Dealer")
self.deck = BJ_Deck()
self.deck.populate()
self.deck.shuffle()
# betting
def placing_bets (self, names):
self.total_bets=10
for name in names:
yes_no=input("The dealer bets 10.", name, "would you like to bet on this round? (y/n)")
if yes_no=="y":
player_bet=input(int("How much would you like to bet?:"))
else:
break
self.total_bets=player_bet+self.total_bets
return self.total_bets
(Sorry about the formatting, I'm new at this. In real life it's indented just like in the link)
The only other change I made was to add the bottom two lines to print the bets that the winner has won:
def win(self):
print(self.name, "wins.")
# awarding bets
print("You win $", self.total_bets)
When I run this, I get an error:
AttributeError: 'BJ_Game' object has no attribute '_BJ_Game__additional_cards'
I am not understanding how the changes I made caused this issue. Help is greatly appreciated.
Is this line:
def __additional_cards(self, player):
still in your program? If not, you have your answer. If yes, have a closer look at the code directly above this line.
I'm making a (rather) simple card game in Python, I have everything set up for the game, I just need a way to deal with multiple users, and display something (the cards in the hand) to the user that they're assigned to. I've seen some responses about Twisted, but that doesn't seem to solve my problem, at least how it was presented. I'm looking for something like -
print player1cards to player1
print player2cards to player2
but in whatever format is needed.
Well, the obvious answer here would be to have a class Player :
class Player:
playercards = []
Another way is to assign each player a name:
class Player:
name = ""
And then have a Gameserver class :
class Gameserver:
cards = {'Player1':['4Clubs', 'QClubs'], .....}
def getCards(name):
return cards[name]
Then you can do something like this:
gameserver = GameServer()
#Initialize and blablabla
........
x = Player("Player1")
x.showHand()
#the line above would basically do the following:
#print gameserver.getCards(x.name())
I have a homework assignment that's really baking my noodle. It involves an elevator simulation that takes user inputs for the number of floors and the number of people using the elevator. the people's starting floor and destination floors are random numbers within the floors.
I realize that my code is very sparse and that there's quite a few gaps, but I really don't know where to go from here.
I need help within the building class, such as how to make the run() and output() sections work. any other tips would be greatly appreciated and helpful. Note that i am not looking for someone to do the code for me, but to kind of hold my hand and tell me which way to go. Classes seem to be completely mystifying to me.
import random
floors=raw_input('Please enter the number of floors for the simulation:')
while floors.isalpha() or floors.isspace() or int(floors) <=0:
floors=raw_input('Please re enter a digit for number of floors:')
customers=raw_input('Please enter the number of customers in the building:')
while customers.isalpha() or customers.isspace() or int(customers) <0:
customers=raw_input('Please re enter a digit for number of customers:')
count = 1
class building:
def num_of_floors():
num_of_floors = floors
def customer_list():
customer_list = customers
def run(self):
def output(self):
print elevator.cur_floor
class elevator:
def num_of_floors():
building.num_of_floors
def register_list():
register_list = []
def cur_floor(building):
cur_floor = 1
def direction(self):
if elevator.cur_floor == 1:
direction = up
if elevator.cur_floor == floors:
direction = down
def move(self):
if elevator.direction == up:
cur_floor +=1
if elevator.direction == down:
cur_floor -=1
def register_customer(self, customer):
register_list.append(customer.ID)
def cancel_customer (self, customer):
register_list.remove(customer.ID)
class customer:
def cur_floor(customer):
cur_floor = random.randint(0,int(floors))
def dst_floor(customer):
dst_floor = random.randint(0,int(floors))
while dst_floor == cur_floor:
dst_floor = random.randint(0,int(floors))
def ID():
cust_id = count
count+=1
def cust_dict(cust_id,dst_floor):
cust_dict = {cust_id:dst_floor}
def in_elevator():
in_elevator = 0
if customer.ID in register_list:
in_elevator = 1
def finished():
if customer.ID not in register_list:
pass
You need to understand the self
parameter to all methods.
You need to understand __init__,
the constructor.
You need to understand self.varible
for your member variables.
You need to understand how to setup a
main function.
You need to understand how to
return a value from a function or
method.
You need to understand how to assign to global variables from within a function or method.
Maybe your building class should start like this.
class building:
def __init__(self, floors, customers):
self.num_of_floors = floors
self.customer_list = customers
self.elevator = elevator()
You should definately spend some time on Python Tutorial or Dive into Python.
The first parameter of every method is a reference to the object and is usually called self. You need it to reference instancemembers of an object.
Second, referencing global variables from inside a class is considered a bad idea. You can better pass them to a class via the constructor or parameters.