I have already asked a similar question concerning this problem but my colleague and I still weren't able to fix it. For more information on the problem, please see my first question.
We have defined different objects (sun and planets of our solar system) and the forces between them. Now we want to define a menu which gives us the possibility to choose an object: It will then be defined as the currentobject and the simulation user will be able to vary its mass using a slider. The answer that we got to our first question was that a currentobject must be defined before the function "def M(m)" is used, so we defined the sun as the currentobject.
Here are the fragments of our code concerning this part of the simulation:
sun = sphere( pos=vector(0,0,0), radius=6.96E+09, texture="https://i.imgur.com/DTm6i8r.jpg",
mass = 1.989e30, momentum=vector(0,0,0), make_trail=True, visible=True ) #example of a defined object
currentobject=sun
def M(m):
global col, sun, mercury, venus, earth, mars, jupiter, saturn, uranus, neptune, currentobject
currentobject.visible = True
obj = m.selected
if obj == "Sonne":
currentobject = sun
elif obj == "Merkur":
currentobject = mercury
elif obj == "Venus":
currentobject = venus
elif obj == "Erde":
currentobject = earth
elif obj == "Mars":
currentobject = mars
elif obj == "Jupiter":
currentobject = jupiter
elif obj == "Saturn":
currentobject = saturn
elif obj == "Uranus":
currentobject = uranus
elif obj == "Neptun":
currentobject = neptune
currentobject.visible=True
menu(choices=['Sonne', 'Merkur', 'Venus', 'Erde', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptun'], bind=M)
scene.append_to_caption('\n\n')
scene.append_to_caption("Change mass of chosen object: \n\n")
def setmass(b):
wt.text = '{:1.1f}'.format(b.value)
sl = slider(min=1, max=10, value=1, length=1000, bind=setmass)
wt = wtext(text='{:1.1f}'.format(sl.value))
scene.append_to_caption('\n\n')
while (True):
rate(100)
if running:
if currentobject = sun:
sun.mass = (1.989e30)*sl.value
elif currentobject = mercury:
mercury.mass = (3.285e23)*sl.value
elif currentobject = venus:
venus.mass = (4.869e24)*sl.value
elif currentobject = earth:
earth.mass = (5.974e24)*sl.value
elif currentobject = mars:
mars.mass = (6.4185e23)*sl.value
elif currentobject = jupiter:
jupiter.mass = (1.8987e27)*sl.value
elif currentobject = saturn:
saturn.mass = (5.683e26)*sl.value
elif currentobject = uranus:
uranus.mass = (8.683e25)*sl.value
elif currentobject = neptune:
neptune.mass = (1.0241e26)*sl.value
When the program is run, no error message appears. However, we found out that while the currentobject is changed in the function M, it is not changed afterwards. (When you insert "print (currentobject.mass) in "def M(m)", the chosen objects mass appears in the simulation but when you insert it after the function, the suns mass appears). This means that the calculation always uses the sun as its currentobject and not the object that is chosen with the menu.
The only 3D object you have created is "sun". When in M() you say currentobject = mercury, you have set currentobject to "undefined" because there is no 3D object named "mercury".
Related
first of all, I'm new to Python.
I want to increase "humanscore" or "computerscore" in win and lose conditions.
This increase occurs in the win and lose functions, that is, +1 is added to the variables, but it becomes 0 again when you switch to the other function.
import random
R = "ROCK"
P = "PAPER"
S = "SCİSSORS"
print("Welcome to 'Rock Paper Scissors' game!\n")
humanscore = 0
computerscore = 0
def end():
print("\n\n\n\n\n")
print("Computer's weapon =", computer)
print("Your weapon =", human, "\n\n\n")
def win(humanscore):
print("You win!")
humanscore += 1
return humanscore
def lose(computerscore):
print("You lose!")
computerscore += 1
return computerscore
def Score(humanscore, computerscore):
score = (f"Human Score = {humanscore}, Computer Score = {computerscore}")
print(score)
while True:
allweapon = (R, P, S)
computer = random.choice(allweapon)
print(f"1. {R}\n2. {P}\n3. {S}\n")
human = str.upper(input("Choose your weapon!\n"))
if human == R:
if computer == S and human == R:
end()
win(humanscore)
Score(humanscore, computerscore)
elif computer == P and human == R:
end()
lose(computerscore)
Score(humanscore, computerscore)
if human == S:
if computer == P and human == S:
end()
win(humanscore)
Score(humanscore, computerscore)
elif computer == R and human == S:
end()
lose(computerscore)
Score(humanscore, computerscore)
if human == P:
if computer == S and human == P:
end()
lose(computerscore)
Score(humanscore, computerscore)
elif computer == R and human == P:
end()
win(humanscore)
Score(humanscore, computerscore)
if human == computer:
end()
Score(humanscore, computerscore)
print("Tied!")
if human != R:
print("There is no such weapon!\n")
I want to increase the score system properly.
Here is the code
import random
class Animal(object):
__name = ""
__animal_type = ""
__mood = 0
def __init__(self, animal_type, animal_name):
self.__animal_type = animal_type
self.__name = animal_name
self.__mood = random.randint(1, 3)
def get_animal_type(self, animal):
return self.__animal_type
def get_name(self, animal):
return self.__name
def check_mood(self, animal):
animal_mood = ""
if self.__mood == 0:
animal_mood = "the mood was 0 and didn't change"
elif self.__mood == 1:
animal_mood = "happy"
elif self.__mood == 2:
animal_mood = "hungry"
elif self.__mood == 3:
animal_mood = "sleepy"
return animal_mood
animal_list = [Animal]
do_animal_creation = True
while do_animal_creation:
print("Welcome to animal gen")
new_animal_type = input("What type of animal? ")
new_animal_name = input("Name of animal? ")
new_animal = Animal(new_animal_type, new_animal_name)
animal_list.append(new_animal)
do_animal_creation = input("Add another animal? y/n: ")
if do_animal_creation != 'y':
do_animal_creation = False
print("\nThanks for using this program.")
else:
do_animal_creation = True
print("Animal list:")
for item in animal_list:
item_name = item.get_name(item)
item_type = item.get_animal_type(item)
item_mood = item.check_mood(item)
print(item_name + " the " + item_type + " is " + item_mood + ".")
Everytime I try to call the get_name or get_animal_type or check_mood methods it tells me I'm sending an incorrect amount of parameters. Then I try to play with the parameters, either send one more like it asks me to, or take away a parameter in the method definition within the class, and neither of those work. I feel like I am syntactically not calling the methods correctly, but I don't know what exactly I'm doing wrong.
The first element of your animal_list is the Animal class, not an instance. Hence, calling instance methods on it won't work as expected. Whatever you might have tried to make that work (like passing an instance as first argument) will then fail for the subsequent elements which are instances.
Change
animal_list = [Animal]
# this puts the Animal class in your list
# Note: In Python, lists are not type-parametrized like in other languages,
# which is probably what you assumed you were doing
to
animal_list = []
Moreover, your getters should not take parameters:
def get_animal_type(self):
return self.__animal_type
and call it:
item.get_animal_type()
I am currently creating a tic-tac-toe game for a course. It has been going great, however, I have hit a roadblock. I am having trouble with the part when I want to check if a player has won or not, it is a function (called "game_over"). When I run the game, and if the "if" statement is met, it says "game_on = False". However, once the player while loop begins, it reverts back to True. Thus the game never stops.
game_on = True
player_ready = False
game_finish = False
turn = "Player1"
# THE BOARD
line1 = ["|", "___" , "|", "___", "|","___","|"]
line2 = ["|", "___" , "|", "___", "|","___","|"]
line3 = ["|", "___" , "|", "___", "|","___","|"]
list1 = ''.join(line1)
list2 = ''.join(line2)
list3 = ''.join(line3)
print(list1)
print(list2)
print(list3)
# FUNCTIONS AND THE GAME
Player1_character = "x"
def game_over(player,character):
if line1[1] == (f"_{character}_") and line1[3] == (f"_{character}_") and line1[5] == (f"_{character}_"):
game_on = False
print(f"Game Over, {player} won!game_on = {game_on}")
return
def print_character(numbers,char):
if numbers == 1:
line1[1] = (f"_{char}_")
if numbers == 2:
line1[3] = (f"_{char}_")
if numbers == 3:
line1[5] = (f"_{char}_")
if numbers == 4:
line2[1] = (f"_{char}_")
if numbers == 5:
line2[3] = (f"_{char}_")
if numbers == 6:
line2[5] = (f"_{char}_")
if numbers == 7:
line3[1] = (f"_{char}_")
if numbers == 8:
line3[3] = (f"_{char}_")
if numbers == 9:
line3[5] = (f"_{char}_")
list1 = ''.join(line1)
list2 = ''.join(line2)
list3 = ''.join(line3)
print(list1)
print(list2)
print(list3)
section = 0
# Tutorial Goes Here
while game_on == True:
# Selecting Players
while player_ready == False:
Player1_character = ""
Player1_character = input("Player1 choose your character 'x' or 'o': ")
Player2_character = "|"
if Player1_character == "x":
Player2_character = "o"
elif Player1_character == "o":
Player2_character = "x"
print(f"Player1 = {Player1_character} ||| Player2 = {Player2_character}")
print("LETS BEGIN!!!\n")
player_ready = True
#Starting game:
while turn == "Player1":
section = int(input(f"Player1's Turn: \nSelect where you want to put your '{Player1_character}'(1-9){game_on}: "))
print_character(section, Player1_character)
if game_on == False:
break
turn = "Player2"
while turn == "Player2":
section = int(input(f"Player2's Turn: \nSelect where you want to put your '{Player2_character}'(1-9){game_on}: "))
print_character(section, Player2_character)
game_over("Player2",Player2_character)
if game_on == False:
break
turn = "Player1"
See the Python Programming FAQ on the rules for using global variables in functions.
In Python, variables that are only referenced inside a function are implicitly global. If a variable is assigned a value anywhere within the function’s body, it’s assumed to be a local unless explicitly declared as global.
Its showing"line 42, in
if input_ !='no':
NameError: name 'input_' is not defined" error when i input 'no'
The code is :
def rock_paper_scissors():
comp_score = your_score = 0
y,z="This is a rockpaper scissors game. ","Do you wish to play"
x= ["rock","paper","scissors"]
input_=input(y+z+"?")
if input_ == "no":
return
rock_paper_scissors()
if input_ !='no':
a=input("Do you wanna play again?")
How can i rectify it? (this is just a small part of the entire program but i think this should do...)
Variable input_ is initialised inside function rock_paper_scissors() which means outside of it (function scope) is undefined. So we need to put it inside function or make input_ global.
def rock_paper_scissors():
comp_score = your_score = 0
y, z = "This is a rock paper scissors game. ", "Do you wish to play"
x= ["rock", "paper", "scissors"]
input_=input(y + z + "?")
if input_ == "no":
return
else: # no need for: if input_ != "no"
a = input("Do you wanna play again?")
rock_paper_scissors()
Hope this helps.
Here is my take on it, still needs some work, it functional...
# Tested via Python 3.7.4 - 64bit, Windows 10
# Author: Dean Van Greunen
# License: I dont care, do what you want
####################################
# Some Defines
####################################
# imports
import random
# global vars
comp_score = 0
your_score = 0
input_ = ''
ai_input = ''
# strings
string_1 = 'This is a rockpaper scissors game.'
question_1 = 'Do you wish to play? '
question_2 = 'Enter your move: '
question_3 = 'Do you wanna play again? '
string_4 = 'Valid Moves: '
string_5 = 'Thank you for playing!'
string_6 = 'Scores: Player {0} V.S. AI {1}'
yes = 'yes'
no = 'no'
# vaild moves
moves = ["rock","paper","scissors"]
####################################
# Code Setup
####################################
def displayWinner(player_move_str, ai_move_str):
# Vars
winner = ''
tie = False
# Winner Logic
if player_move_str == ai_move_str:
tie = True
elif player_move_str == 'paper' and ai_move_str == 'rock':
winner = 'Player'
elif player_move_str == 'scissor' and ai_move_str == 'rock':
winner = 'AI'
elif player_move_str == 'rock' and ai_move_str == 'paper':
winner = 'AI'
elif player_move_str == 'scissor' and ai_move_str == 'paper':
winner = 'Player'
elif player_move_str == 'rock' and ai_move_str == 'scissor':
winner = 'Player'
elif player_move_str == 'paper' and ai_move_str == 'scissor':
winner = 'AI'
# display Logic
if tie:
print('It Was A Tie!')
else:
global your_score
global comp_score
if winner == 'AI':
comp_score = comp_score + 1
elif winner == 'Player':
your_score = your_score + 1
print(winner + ' Won!')
def start():
global your_score
global comp_score
print(string_1)
print(string_6.format(your_score, comp_score))
input_ = input(question_1)
if input_ == yes:
print(string_4)
[print(x) for x in moves]# make sure input is valid.
input_ = input(question_2)
ai_input = random.choice(moves) # let AI pick move
print('AI Picked: ' + ai_input)
displayWinner(input_, ai_input)
input_ = input(question_3) # Play Again?
if input_ == yes:
start() # Restart Game (Recursive Call)
else:
print(string_5) # Thank you Message
####################################
# Game/Script Entry Point/Function
####################################
start()
Thanks yall. Fixed my program. Now it goes like:
import time
import random
input_ =""
def rock_paper_scissors():
comp_score = your_score = 0
y,z="This is a rockpaper scissors game. ","Do you wish to play"
x= ["rock","paper","scissors"]
global input_
input_=input(y+z+"?")
if input_ == "no":
return
max_score=("Enter max score : ")
while True:
input_=input("Enter your choice among rock, paper and scissors ('stop' to
quit):")
if input_ not in x and input_!='stop'and input_ != 'enough':
print("Invalid answer. Are you blind? Pick one from the 3.")
continue
n = random.randint(0,2)
k=x[n]
if n<2:
if input_==x[n+1]:
your_score+=1
elif input_==k:
pass
else:
comp_score+=1
else:
if input_=="paper":
comp_score+=1
elif input_=="rock":
your_score+=1
elif input_=="scissors":
pass
else:
pass
if input_!="stop" and input_ != "enough":
print(3)
time.sleep(1.5)
print(2)
time.sleep(1.5)
print(1)
time.sleep(1.5)
print("Your choice : "+input_ +"\nComputers move : "+k)
elif input_=="stop" and input_=="enough":
input_=input("Play again?")
if (your_score == max_score or comp_score==max_score) or (input_=="stop"
or input_=="enough"):
print("Your score is : ",your_score)
print("AI's score is : ",comp_score)
break
rock_paper_scissors()
if input_ !='no':
a=input("Do you wanna play again?")
if a =="yes":
rock_paper_scissors()
print("k.bye! \n :(")
I have to create this basic game for a high school project. I'm new to the timer in python. My code is as follows:
import random
from threading import Timer
score = -1
directions = ["RIGHT", "LEFT", "UP", "DOWN"]
accdirection=random.choice(directions)
def timeOut():
out_of_time = "yes"
print("TESTING ")
while accdirection:
TimeLimit = 1
score = score + 1
accdirection=random.choice(directions)
print(accdirection)
out_of_time = "no"
t=Timer(TimeLimit,timeOut)
t.start()
fast = input()
if out_of_time == "yes":
accdirection = None
if accdirection in directions:
t.cancel()
if accdirection == "RIGHT":
if fast == "d":
accdirection = random.choice(directions)
else:
accdirection = None
print("Oops, you clicked the wrong key.")
elif accdirection == "LEFT":
if fast == "a":
accdirection = random.choice(directions)
else:
accdirection = None
print("Oops, you clicked the wrong key.")
elif accdirection == "UP":
if fast == "w":
accdirection = random.choice(directions)
else:
accdirection = None
print("Oops, you clicked the wrong key.")
elif accdirection == "DOWN":
if fast == "s":
accdirection = random.choice(directions)
else:
accdirection = None
print("Oops, you clicked the wrong key.")
else:
print("Oof, too slow!")
accdirection = None
print("Your score is:", score)
The function of the code is that python outputs a direction, and then the user has to input w, a, s or d. If they get the wrong key, the game is over and they have lost. This part works fine.
When the time runs out it prints out "TESTING" which I have done simply to test if it even goes to the timeOut function. However, it feels like the value of out_of_time seems to always stay the same: "no" in this case. Therefore, the value for accdirection isn't able to reset to None to break the loop. I'm sorry if most of the code is just useless to my question. Please tell me how to fix this.
You set out_of_time = "yes" in the timeOut function, but never return the updated value of out_of_time.
And out_of_time is initially set in the global namespace, so indicate that, and you should get your expected behavior:
def timeOut():
global out_of_time
out_of_time = "yes"
print("TESTING ")
return out_of_time