Related
I am working on an assignment, the goal is this...
create a program for a school tournament where participants can enter a tournament, then points are alocated to the team based on where they place in the event. there will be events such as (dodgeball, football, math, english) but i will work on these at a later date
at the moment i am trying to construct some code that will asign a point to a team, which is working. and then print the leaderboard(list of teams) this does not work
the leaderboard() function is not working and i do not know why not, please help me
class Team:
def __init__(self, num, name, size, score):
self.num = num
self.name = name
self.size = size
self.score = score
def add_victory(self):
self.score += 1
def __repr__(self):
return f'Team Number: {self.num} |-| Team Name: {self.name} |-| Member Count: {self.size} |-| Team Score: {self.score}'
def NewTournament():
teams = []
TeamCounter=int(input('How many Teams will be in the tournament? '))
print('')
for i in range(TeamCounter):
NameOfTeam=input(f'Please Enter Team {i+1} Name: ')
MemberCount=int(input('How Many Members in Team? '))
print('')
teams.append( Team( i+1, NameOfTeam, MemberCount, 0) )
def Score(teams):
winner = input('Which Team Won the Event? ')
for team in teams:
if team.name == winner:
team.add_victory()
break
print('Updated Leaderboard')
def Leaderboard():
for t in teams: #does not work, does nothing
print(t)
def Menu():
MenuLoop=1
while MenuLoop==1:
print('1.Create Tournament')
print('2.Update Existing Tournament')
print('3.View Leaderboard')
print('4.Exit')
MenuOption=input('')
if MenuOption=='1':
print('Creating Tournament')
NewTournament()#runs the new tournament function
MenuLoop-=1
Menu()
elif MenuOption=='2':
print('Updating Tournament')
MenuLoop-=1
EventName=input('Which Event Was Completed? ')
winner=input('Which Team Won the Event? ')
print('Event Winner:', winner, '||', 'Event:',EventName)
print('Is this correct? Y/N')
Check=input('')
if Check=='y':
print('Updating Leaderboard')
Score(teams)
Menu()
elif MenuOption=='3':
MenuLoop-=1
Leaderboard()
elif MenuOption=='4':
print('Exiting Program...')
else:
print('Error, please choose an option from the list below.')#keeps looping if user is not choosing a correct number from list
#start of program
teams = []
print('░██╗░░░░░░░██╗███████╗██╗░░░░░░█████╗░░█████╗░███╗░░░███╗███████╗')
print('░██║░░██╗░░██║██╔════╝██║░░░░░██╔══██╗██╔══██╗████╗░████║██╔════╝')
print('░╚██╗████╗██╔╝█████╗░░██║░░░░░██║░░╚═╝██║░░██║██╔████╔██║█████╗░░')
print('░░████╔═████║░██╔══╝░░██║░░░░░██║░░██╗██║░░██║██║╚██╔╝██║██╔══╝░░')
print('░░╚██╔╝░╚██╔╝░███████╗███████╗╚█████╔╝╚█████╔╝██║░╚═╝░██║███████╗')
print('░░░╚═╝░░░╚═╝░░╚══════╝╚══════╝░╚════╝░░╚════╝░╚═╝░░░░░╚═╝╚══════╝')#welcome user
print('')
Username=input('Enter Username: ')
Password=input('Enter Password: ')
if Username =='Admin' and Password == 'Admin':#very basic login system for security of school
print('Logging in...')
print('User Verified')
Menu()
else:
print('User Does Not Exist.')#stops pupils gaining unauthorised access
please understand i am still very new to python so the layout may be a mess or complicated or may not even make any sense to you, i am trying to make sense of it for you
Your issue comes from how you are storing your teams. At the bottom you initialize global teams list as teams = []. Then later in NewTournament you create a new teams list which clashes with the global one:
def NewTournament():
teams = []
TeamCounter=int(input('How many Teams will be in the tournament? '))
print('')
for i in range(TeamCounter):
NameOfTeam=input(f'Please Enter Team {i+1} Name: ')
MemberCount=int(input('How Many Members in Team? '))
print('')
teams.append( Team( i+1, NameOfTeam, MemberCount, 0) )
Because of this when you append the new Team to teams the change does not change the global teams which you use when listing the leader board. The simplest solution is to just remove the local teams variable:
def NewTournament():
TeamCounter=int(input('How many Teams will be in the tournament? '))
print('')
for i in range(TeamCounter):
NameOfTeam=input(f'Please Enter Team {i+1} Name: ')
MemberCount=int(input('How Many Members in Team? '))
print('')
teams.append( Team( i+1, NameOfTeam, MemberCount, 0) )/
A better fix would be to create a new Tournament class which can store the state of the tournament (the list of teams) more clearly, and remove your need to have top level methods which rely on global variables which is rarely a great idea.
I'm practice classes and inheritance in a program idea that I came up with myself. Basically Im making an arcade game menu simulator that can play two modes, single player and multiplayer. Every time I enter a choice, either 1 or 2, the menu displays a couple times and then it proceeds to accept the input, I only want the menu to be displayed once. Heres my code:
# Suppose you are at an arcade and you and your friend want to play a multiplayer game that requires UI.
# Make the game ask for the users name and age to see if they can play, make the program so that it can add a friend.
# If any of the players are under the age of 18, they are not allowed to play, otherwise proceed.
# **EXTRA CREDIT** --> Add a functionality which adds the players to a list until the list reaches 4 players, then stop adding to the list.
# arcade_game.py
import sys
# give the user a greeting
import self as self
lst = []
class menu:
def __init__(self, ready):
self.ready = ready
#display menu
#classmethod
def display_menu(self):
print("Pick from one of the choices below, type in the corressponding number")
print("1. single player \n"
"2. Multiplayer")
choice = int(input("Enter your choice here: "))
return choice
# ready or not function to see if the user is ready to play
def ready_or_not(self):
# see if user types 1 or 2 with try & except
try:
# ask user if they are ready
self.ready = int(input("Are you ready to play? Type 1 for yes, 2 for no"))
self.display_menu()
except ValueError:
print("You did not type 1 or 2, please try again!")
# add players class
class player(menu):
# add a default player to __init__(), **(since there has to be at least one player)**
def __init__(self, ready, player1):
super().__init__(ready)
self.player1 = player1
# single player method
def set_name(self):
self.player1 = input("Enter your name for single player mode")
print("Lets play! ", self.player1)
# multiplayer method
def set_names(self):
try:
self.player1 = input("Enter your name to begin")
lst.append(self.player1)
# add another player to continue
while len(lst) <= 4:
add = input("Add player here: ")
lst.append(add)
if len(lst) == 4:
print("Player limit reached!")
break;
except ValueError:
print("You didnt enter valid input, please try again")
# get the names of the players only if 1 is picked from display_menu() above, including player1
def check_choice(self):
if self.display_menu() == 1:
self.set_name()
elif self.display_menu() == 2:
self.set_names()
else:
print("Exiting....")
print("Goodbye!")
sys.exit(0)
m = menu("yes")
m.ready_or_not()
p = player("yes", "test")
p.check_choice()
ready_or_not calls self.display_menu():
def ready_or_not(self):
# see if user types 1 or 2 with try & except
try:
# ask user if they are ready
self.ready = int(input("Are you ready to play? Type 1 for yes, 2 for no"))
self.display_menu()
except ValueError:
print("You did not type 1 or 2, please try again!")
check_choice also calls self.display_menu() at least once, and twice if you type anything other than 1 the first time:
def check_choice(self):
if self.display_menu() == 1:
self.set_name()
elif self.display_menu() == 2:
self.set_names()
else:
print("Exiting....")
print("Goodbye!")
sys.exit(0)
Your top-level code calls ready_or_not() on one menu instance:
m = menu("yes")
m.ready_or_not()
… and check_choice() on another:
p = player("yes", "test")
p.check_choice()
So, your program displays the menu twice, and then a third time if you type anything but 1.
If you don't want the menu displayed two or three times, don't call the method two or three times.
If you want to display the menu only once and remember the choice, instead of displaying it two or three times, you need to use that self.ready attribute that you create in ready_or_not, instead of calling the method again.
However, that still isn't going to work as-is, because your class design is weird. You've made two separate instances, m and p, each of which has its own independent attributes. I'm not sure why player inherits from menu in the first place (or why display_menu is a #classmethod, or why it calls its parameter self rather than cls if it is one, and various other things), but, given that a player is a menu in your design, you probably just want a single player instance, like this:
p = player("yes", "test")
p.ready_or_not()
p.check_choice()
And then, you can change check_choice like this:
def check_choice(self):
if self.choice == 1:
self.set_name()
elif self.choice == 2:
self.set_names()
else:
print("Exiting....")
print("Goodbye!")
sys.exit(0)
Took me a while to figure out, but it seems like when you are done with display_menu() your calling ready_or_not() so you need to remove display_menu() from ready or not like this
# ready or not function to see if the user is ready to play
def ready_or_not(self):
# see if user types 1 or 2 with try & except
try:
# ask user if they are ready
self.ready = int(input("Are you ready to play? Type 1 for yes, 2 for no"))
# self.display_menu()
except ValueError:
print("You did not type 1 or 2, please try again!")
EDIT
looks like im late to the party
So my issue is that currently I have code for my yahtzee (I will not post all of the code, but the important stuff is looking like this (and it works):
from terminaltables import AsciiTable
class Player:
def __init__(self,name):
self.name=name
self.ones=0
self.twos=0
self.threes=0
self.fours=0
self.fives=0
self.sixs=0
self.abovesum=0
self.bonus=0
self.onepair=0
self.twopair=0
self.threepair=0
self.fourpair=0
self.smalladder=0
self.bigladder=0
self.house=0
self.chance=0
self.yatzy=0
self.totalsum=0
def welcome():
global spelarlista
spelarlista=[]
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
spelarlista.append(Player(player))
table_data = [["Name"] + spelarlista,
['Ones'] + [player.ones for player in spelarlista],
['Twos'] + [player.twos for player in spelarlista],
['Threes'] + [player.threes for player in spelarlista],
['Fours'] + [player.fours for player in spelarlista],
['Fives'] + [player.fives for player in spelarlista],
['Sixs'] + [player.sixs for player in spelarlista]]
table = AsciiTable(table_data)
table.inner_row_border = True
print(table.table)
spelarlista[0].add()
welcome()
The issue right now is that I want to add a dictionary instead of all those self.ones, self.twos etc. If you take a look at my welcome method, you can see that I have [player.ones for player in spelarlista]and I need this to assign the players points, how can I fix so this work for a dictionary instead? The dictionary is neccesary for my next method, add, if you were curious!
Thanks in advance!
dict_names = ['ones', 'twos', ..., 'totalsum']
self.dict = {name:0 for name in dict_names}
and to access you'd use player.dict['fours'] instead if player.fours
I'm tasked with creating a program that simulates a scantron being turned on from an off state, once turned on it compares two arrays and displays a student's grade based on the comparison of the two arrays. I'm also tasked with creating classes.
I can get the machine to turn on but the grading part is where I'm having trouble. My program tells me that 'correct is not defined' in 'grade = Answers (correct, student, theGrade)'. I don't think I returned or didn't pass the variable correctly. Below is the code. Can anyone PLEASE help??
#this program creates a scantron grading system
#the machine will be turned on, scan the correct answers,
#then will grade the student's answers, and display results
#start class initializing machine off and then switching on
class quizGrader:
#initialize state of machine off
def __init__(self):
self.power = 'Off'
#create module to ask if the user would like to turn on the machine
def switch(self):
#ask user if they'd like to turn on the machine
powerOn = input('Would you like to turn the machine on? (enter Y for yes)')
#create if statement for system to be turned on or off
if powerOn == 'y' or powerOn == 'Y':
self.power = 'On'
else:
self.power = 'Off'
def get_power(self):
return self.power
#create class for correct answers, student answers, and
#for the student's scantron to be graded
class Answers:
#initialize the grades
def __init__(self, correct, student, theGrade):
#declare what each self. will be equal to
self.__correctAnswers = correct
self.__studentAnswers = student
self.__studentGrade = theGrade
#create set method for correctAnswers
def set_correctAnswers(self, correct):
self.__correctAnswers = correct
correct = ['A','B','C','D','E','E','D','C','B','A', \
'A','B','C','D','E','E','D','C','B','A']
print('Correct answers have been recorded...')
return correct
#create set method for studentAnswers
def set_studentAnswers(self, student):
self.__studentAnswers = student
student = ['B','B','C','D','A','E','D','C','B','A', \
'A','B','C','D','E','E','D','C','B','A']
return student
#create set method for student's scantron to be graded
def set_studentGrade(self, theGrade):
self.__studentGrade = theGrade
right = 0
index = 1
#create a for loop and if statement for the right answers
#to be counted and then calculate the % of the grade
for index in range(0,20):
if self.__correctAnswers [index] == self.__studentAnswers [index]:
right += 1
percent = float(right/20)
percent = theGrade
return theGrade
#return all the methods previously created
def get_correctAnswers(self, correct):
return self.__correctAnswers
def get_studentAnswers(self, student):
return self.__studentAnswers
def get_studentGrade(self, theGrade):
return self.__studentGrade
#start main module
def main():
#create an object from the quizGrader class
machine = quizGrader()
#display that the machine is off
print('The machine is powered:', machine.get_power())
#ask the user if they'd like to turn the machine on
machine.switch()
#display the user's choice to turn on or leave machine powered off
print('The machine is now/still powered:',machine.get_power())
#create an object from the Answers class
grade = Answers(correct, student, theGrade)
#display that the correct answers have been recorded and display the answers
print('Correct answers have been recorded:',grade.get_correctAnswers())
print()
print()
#display that the student's answers have been recorded and display the answers
print('Student answers have been recorded:', grade.get_studentAnswers())
print()
#grade the student's answers
grade.studentGrade()
#display the amount of answers student answered correctly
#and the percentage of their grade based on correct answers
print('The student grade is',right,'out of 20 or',percent,'%.')
#close main function
main()
You have not defined what correct or student or even theGrade are
grade = Answers(correct, student, theGrade)
You need to instantiate the classes you've created, but you need to actually have those variables available in the main() function.
For example:
def main():
#create an object from the quizGrader class
machine = quizGrader()
correct = ['A','B','C','D','E','E','D','C','B','A', \
'A','B','C','D','E','E','D','C','B','A']
student = ['B','B','C','D','A','E','D','C','B','A', \
'A','B','C','D','E','E','D','C','B','A']
will get you a little farther...
Just because you declare them in the classes above doesn't mean they're available.
The variable correct is not defined in your main function.
For example, you could simply add the line correct = 'C' before the line grade = Answers(correct, student, theGrade) to show that the correct answer is C.
The finished product would look something like this:
...
correct = 'C'
grade=Answers(correct, student, theGrade)
...
Through some educational materials I've been tasked to use the below structure (the classes) for a text adventure game and am required to add a simple combat system for battle between a hero and an enemy.
Currently I am able to have an enemy created in each room and move between the start room(corridor) to the bathroom and back, but at this point I'm stuck. I can't determine where I should be creating my 'hero' or how I'd communicate the changes I'd need to make to the health attributes etc.
If I could structure the code in another way, I would be able to complete the game, but as it is there is a gap in my understanding of how to enable various sections of code communicate with each other.
Thanks,
Dave
# text based adventure game
import random
import time
from sys import exit
class Game(object):
def __init__(self, room_map):
self.room_map = room_map
def play(self):
current_room = self.room_map.opening_room()
while True:
next_room_name = current_room.enter()
current_room = self.room_map.next_room(next_room_name)
class Character(object):
def __init__(self, name, health, attack):
self.name = name
self.health = health
self.attack = attack
class Hero(Character):
def __init__(self, name):
super(Hero, self).__init__(name, 10, 2)
def __str__(self):
rep = "You, " + self.name + ", have " + str(self.health) + " health and " + \
str(self.attack) + " attack."
return rep
class Enemy(Character):
ENEMIES = ["Troll", "Witch", "Ogre", "Jeremy Corbyn"]
def __init__(self):
super(Enemy, self).__init__(random.choice(self.ENEMIES),
random.randint(4, 6), random.randint(2, 4))
def __str__(self):
rep = "The " + self.name + " has " + str(self.health) + \
" health, and " + str(self.attack) + " attack."
return rep
class Room(object):
def __init__(self):
self.commands = ["yes", "no"]
self.rooms = ["\'corridor\'", "\'bathroom\'", "\'bedroom\'"]
self.enemy = Enemy()
def command_list(self):
print("Commands: ", ", ".join(self.commands))
def enter_room_question(self):
print("Which room would you like to enter?")
print("Rooms:", ", ".join(self.rooms))
def leave_room_question(self):
print("Do you want to leave this room?")
print("Commands:", ", ".join(self.commands))
class Bathroom(Room):
def enter(self):
print("You enter the bathroom. But, wait! There is an", \
self.enemy.name, "!")
print(self.enemy)
print("You are in the bathroom. Need to take a dump? ")
self.command_list()
response = input("> ")
while response not in self.commands:
print("Sorry I didn't recognise that answer")
print("You are in the bathroom. Need to take a dump?")
self.command_list()
response = input("> ")
if response == "yes":
print("Not while I'm here!")
return "death"
elif response == "no":
print("Good.")
self.leave_room_question()
response = input("> ")
if response == "yes":
return "corridor"
else:
return "death"
class Bedroom(Room):
def enter(self):
pass
class Landing(Room):
def enter(self):
pass
class Corridor(Room):
def enter(self):
print("You are standing in the corridor. There are two rooms available to enter.")
self.enter_room_question()
response = input("> ")
if response == "corridor":
print("You're already here silly.")
else:
return response
class Death(Room):
QUIPS = ["Off to the man in sky. You are dead",
"You died, no-one cried.",
"Lolz. You're dead!"]
def enter(self):
time.sleep(1)
print(random.choice(Death.QUIPS))
exit()
class Map(object):
ROOMS = {"corridor": Corridor(),
"bathroom": Bathroom(),
"death": Death(),
"landing": Landing(),
"bedroom": Bedroom()}
def __init__(self, start_room):
self.start_room = start_room
self.hero = hero
def next_room(self, room_name):
return Map.ROOMS.get(room_name)
def opening_room(self):
return self.next_room(self.start_room)
a_hero = Hero("Dave")
a_map = Map("corridor")
a_game = Game(a_map, a_hero)
a_game.play()
If I were you, I would set out a game schema. You could find out asking yourself questions like this:
What are the really important entities?
In your case, as you have done, I would consider Character, Enemy, Room and Map, inheriting when it would be appropiate, like Character-> Hero and Enemy, and several types of room from Room as Bathroom, Corridor, ...
If I were you a consider using a data structure to represent the Map. For example, if you are considering do a text game adventure, you could think in different rooms as different states in your game. If you are in the bathroom, you could be attacked by an enemy and if you are in the bedroom, you can retrieve your hitpoints (life) so these places can be thought as different states.
As an example, you would an array for group all your different rooms (states)
rooms = ["bedroom", "bathroom", "corridor", "kitchen", "living_room"]
and other rooms that you can think about.
(there is probably a better example, more efficient and so on, so this example is to help you about not giving up when you gets stuck about an problem.
According to this example, if you use an array, you can assign a value to each room (equal to each position in the array)
Moreover, you will need to know the hero's position, so you could assign a random value to it using rand(). You can read links below for more information:
random docs python
stackoverflow answer
At last, you also would find useful to compare the hero's position, which would have a random assigned value previously with every position of your array or rooms
In this cases, you could use a if... elif.. elif... to compare those values and do something according to the room where your hero would be.
I hope this answer will be useful for you.
Let me know if you have any doubt about my answer.
Cheers