Some pretext that's maybe useful idk. I use mixer and am trying to do a random music choice but the random.choice always take the last one (song 5). This is my code
if Mamp=='1':
vad=input("[1] Bakground music")
#Mixer shit
mixer.init()
pygame.mixer.get_init
if vad=='1':
commands=[mixer.music.load("song1.mp3"), mixer.music.load("song2.mp3"),mixer.music.load("song3.mp3"),mixer.music.load("song4.mp3"),mixer.music.load("song5.mp3")]
current_command=random.choice(commands)
current_command
mixer.music.play(0)
I looked at many answers for the same problem but all wer're just fixing thier (the uploader's) code and uploaded it so I couldn't use it for my code. And since i'm trying to learn python it would be great if you could also explain what went wrong?
commands=[mixer.music.load("song1.mp3"), ...]
current_command=random.choice(commands)
current_command
You're doing this part all wrong.
It seems like you want to make a list of commands to be executed later, but that's not what you're actually doing. The load() commands are actually executed when the commands list is created.
And because song5.mp3 is the last one, it gives the appearance of being "picked" every time.
Try it this way instead:
songs = ["song1.mp3", "song2.mp3", "song3.mp3", "song4.mp3", "song5.mp3"]
song = random.choice(songs)
mixer.music.load(song)
Related
I started learning Python 2 weeks ago, and now I am trying to code a text adventure game. However, I've run into a problem. So far, I haven't found any solution on Google which can help me.
I decided to store basically all relevant variables in dictionaries - feel free to tell me wether that's even a clever idea or rather stupid of me, I actually do not know this, I just thought it might be a solution that works.
Here's my problem: last thing I decided to insert into the program is a save_game() function. So I defined:
def save_game(data):
import shelve
savegame = shelve.open('./save/savegame')
savegame['data'] = data
savegame.close()
And of course, if I then call
save_game(save_game_data)
with save_game_data being the dictionary where I've put all the other dictionaries so I can handle saving with a single function call (I thought that might be better?), it actually works.
But of course a save_game() only makes sense if you can also reload the data into the program.
So I defined:
def load_game(data):
import shelve, time
savegame = shelve.open('./save/savegame')
data = savegame['data']
data = dict(data) # This was inserted because I hoped it would solve my problem, but it doesn't
savegame.close()
But the result of
load_game(save_game_data)
Unfortunately is no updated dictionary save_game_data with all the keys and values, and I just can't get my head around how to get all the stored data back into values in the dictionaries. Maybe I'm on a totally wrong way all together, maybe I just don't know enough about Python yet to even know where I'm erring.
The save_game() and load_game() functions are in a different file from the main file, and are correctly imported if that is relevant.
It looks like you're trying to pass save_game_data to load_game() as if to mean "load data and put it into save_game_data" but this isn't what load_game() is doing. By doing this:
def load_game(data):
import shelve, time
savegame = shelve.open('./save/savegame')
data = (savegame['data'])
You're replacing what data refers to, so save_game_data doesn't get changed.
Instead, you can drop the argument to load_game() and add:
return data
at the end of the function, and call it like this:
save_game_data = load_game()
I have a problem I can't figure out. I am doing a discord bot in python.
I have a ghost_list.py (separate file) which has usual_suspects =[500 numbers here separated by,]
from ghost_list import usual_suspects
#bot.command()
async def isidonlist(ctx, arg):
if arg in usual_suspects:
nameget = opener.open(f"{api_url}{theme}/{arg}?selections=&key=
{api_key}").read()
namegetdata = json.loads(nameget)
ghost_name = (namegetdata['name'])
await ctx.send(f"{ghost_name} is on the list of usual suspects.")
else:
await ctx.send(f"{arg} is NOT on the list of usual suspects.")
Now the problem is I always get the else result. Which makes me wonder what is wrong with this code. I input the numbers that I know are on the list yet it always shows NOT on the list.
When I use this list in other command which uses
for i in range(len(usual_suspects)):
it works fine.
Is there a different way I should be approaching this or is it just some mistake I am unaware of?
Thank You!
Since it is difficult to determine based on the information provided, here is a possible case. arg may be being passed in as a string. Make sure you convert it into an int first, if there are ints in your usual suspects list as you said. Revise your code like the following: int(arg)
I am using clingo version 4 and wish to be able to ground relations via python script (please don't ask why, it's not a crime, since you can at least ground 1-ary relations). I am hoping this is possible, and need some help.
#script (python)
import gringo;
def main(prg):
prg.ground([('base', [])]);
# ... compute somethings ...
prg.ground([('myrel', [[10,20],[30,40],[70,40]])]);
prg.solve();
#end.
#program myrel(x,y).
r(x,y).
#show r/2.
this doesn't work. Does anyone know how to do this? I tried [(10,20),(30,40),(70,40)] instead, but that also did not work.
It is possible, but one has to input each entry one by one (which for my application is actually good). Instead of
prg.ground([('myrel', [[10,20],[30,40],[70,40]])]);
one has to write
prg.ground([('myrel', [10,20])]);
prg.ground([('myrel', [30,40])]);
prg.ground([('myrel', [70,40])]);
and then it is accepted and yields the right output.
I'm coding a text game in python 3.4 and when I though about making a save game came the question:
How can I jump to the place that the player stopped?
I'm making a simple game, me and my friends, so I just wanna jump to a certain part of the code, and I can't do that without having to make around 15 copies of the code, so can I jump to a line?
You can do that using something like python-goto but this is a very bad idea.
In python, you don't have really any reason to do a goto.
A way better way would be to save the structure containing your data with something like pickle and loading it back when the user want to restart the game.
For instance:
import pickle
game_data = {'something': [1, 2, 3 ]}
pickle.dump(game_data, open('file.bin', 'wb')
Then, you can load the data back:
import pickle
game_data = pickle.load(open('file.bin', 'rb'))
There is no goto built into Python. There are ways to effectively 'halt' in a method by using yield and creating a generator, which is effectively how Python coroutines work (see the asyncio module) however this isn't really appropriate for your needs.
For saving game state, saving and serialising the state you need to resume the gameplay in a more general way is a much better idea. You could use pickle For this serialisation.
You need to consider the game-state as something that you can assign a value (or values) to. If this is a very simple text game, then the player will have a location, and that location will presumably be something you can "jump" to via use of a reference.
Let's say your code follows this pseudo-code pattern:
start
player_location = 0
print_start_game_text()
begin loop:
display_text_for_location[player_location]
display_options_for_location[player_location]
player_location = parse_player_response(response_options_for_location[player_location])
if isGameEndCondition(player_location):
break;
print_end_game_text()
end
This pattern would reference some data files that, for each location provided some collection such as 1, "you are in a room, doors are [E]ast and [W]est. You can [S]ave your game, or [L]oad a previously saved one", { "E" : 3, "W" : 2, "S" : "savegame", "L" : "loadgame" }
Then using a function to display some options, collecting the users response and parsing that data, returning a single value; the next location. You then have a new key to reference the next element in the data-file.
IF your game is as simple as this, then your save file need only contain a single reference, the player's location! Simple.
If you have objects that the player can manipulate, then you'll need to figure out a way to keep track of those, their locations, or state-values - it all depends on what your game does, and how it's played.
You should be thinking along these program vs data lines though, as it will make the game much easier to design, and later, extend, since all you'd have to do to create a new adventure, or level, is provide a new datafile.
I have an extremely long program for a Canasta game that I am writing, in it there is a variable that ends the turn of the player if it equals a certain value. However, the turn repeats itself.
I have read many different articles and posts on forums like this one, but none of these seem to work. I even have a debug system to print the value of the variable before the if statement, and the variable is the right value, but the if statement doesn't see the same value.
I can't give the entire code, as it is extremely long, but I can give the sections that use this variable. I am using Python 2.7.2 and cannot make files separate from the main file to import.
The first line of the program is:
endTurn=1
The following function is called when conditions to win the game are met, but I have not been able to test that this works because of the bug.
def winGame(player):
global endTurn
gameWinner=player
gameWinner["score"]+=100
endTurn=0
The following function is called when a move is made. The variable decide is a raw_input() variable.
def move(player,decide):
global endTurn
theMove=decide.lower()
#if player says to end turn
if theMove=="end":
#until player discards something
discarded=0
while not discarded:
displayHand(player)
#ask player for discard
discard=int(raw_input(" Enter the list number of the card you wish to discard:"))-1
#if discard ID is in player's hand length
if not discard<0 and not discard>len(player["hand"])-1:
#add card to discard pile and remove from hand
discardPile.append(player["hand"][discard])
del(player["hand"][discard])
discarded=1
debug("Before changing, endTurn is %s"%str(endTurn))
endTurn = 0
debug("After changing, endTurn is %s"%str(endTurn))
if theMove=="new book":
newBook(player)
if theMove=="add to book":
addBook(player)
Here is where the turn should be ended. turn(thePlayer) repeats the function. The debug statement shows the correct value, 0, but the if still reads a 1. The function this is in also has the global endTurn at the top.
debug("If ending turn, endTurn of %s should be 0."%str(endTurn))
if endTurn==1:
turn(thePlayer)
Any help is greatly appreciated!
EDIT: The code is available at http://labs.codecademy.com/CV9z#:workspace. I ask that anyone viewing the code does not modify it, so that other people can see the true code.
I fixed the bug. I removed the endTurn variable and instead made the function that ends the turn just do the turn of the next player. It also simplified my code a bit.
I am wondering though, is using this method of running a function inside of itself over and over and over again (without leaving) rather messy or maybe slowing down my program?
EDIT: I now realize that this answer does not exactly help with anyone else who is stuck with global variables...
The previous answer I posted was just wrong, as it was based on a misinterpretation of the namespace docs as I had read them (Thanks to TheifMaster for pointing out my error), so this is a SEVERELY EDITED ANSWER:
The problem is in the while loop that I was able to read when the link to the entire code was posted after the erroneous answer I gave earlier.
while gameWinner==0:
endTurn=1
turn(player1)
if not gameWinner==0:
endTurn=1
turn(player2)
The game can never get to player two in this loop until gameWinner!=0.
I added the entire code to my sandbox and changed it to:
while gameWinner==0:
endTurn=1
turn(player1)
if gameWinner==0: #if player1 did not win yet
endTurn=1
turn(player2)
However, the game is still buggy... No one can win! gameWinner is not changed globally by the winGame() function until you add it to the global statement as I have shown here.
def winGame(player):
global endTurn, gameWinner
gameWinner=player
gameWinner["score"]+=100
debug("gameWinner == " + str(gameWinner))
endTurn=0