I have my code for a game here. I have commented out the displayScore(score) call in the main function to allow the program to run. When that call is uncommented the program window closes immediately after opening.
The objective of the function displayScore is to display the game score in the top left corner. Which also needs to be displayed in the right corner for the opposing player's score.
Here is the code for the game with displayScore commented out in the main function so you can run the game and everything will work. Uncomment it to see where the problem is:
ball = ballmovement(ball, ballDirX, ballDirY)
ballDirX, ballDirY = collisionwithedges(ball, ballDirX, ballDirY)
score = checkscore(paddle1, ball, score, ballDirX)
ballDirX = ballDirX * collisionwithpaddles(ball, paddle1, paddle2, ballDirX)
pygame.display.update() #updates the display to clear surface per the frame rate
FRAMECLOCK.tick(FRAMERATE) #Sets the Frames of program to defined rate
if __name__=='__main__':
main()
Just replace the line
displayScore(score)
By:
displayScore(str(score))
You are trying to use a number instead of a string to the argument of render ;) Score is an int and BASICFONT.render((score), True, WHITE)
asks for score to be a string or an array of bytes :)
I found the solution only by reading the console output which was a good indication ^^
Traceback (most recent call last):
File "test.py", line 130, in <module>
main()
File "test.py", line 118, in main
displayScore(score)
File "test.py", line 71, in displayScore
resultSurf = BASICFONT.render((score), True, WHITE)
TypeError: text must be a unicode or bytes
Related
i have this code in one file that is meant to pass the score_list variable to the run_game_over() in a seperate file Game_Over_Screen
from Game_Over_Screen import game_over
leaderboard = True
from Game_Over_Screen import game_over
leaderboard = True
while leaderboard:
print(score_list)
game_over.run_game_over(score_list)
leaderboard = False
running = False
this is the run_game_over() function
class game_over(Buttons, ellipse_button):
def run_game_over(self, score_list):
self.go_animation()
pygame.display.flip()
global game_over
game_over = True
while game_over:
Buttons.mouse_position(quit_icon)
Buttons.mouseclick(quit_icon)
Buttons.mouse_position(play_again_icon)
Buttons.mouseclick(play_again_icon)
for event in pygame.event.get():
pass
however when i run it i get the error:
Traceback (most recent call last):
File "C:\Users\matty\Documents\Programming Project\uno-1130\uno\src\Start.py", line 35, in <module>
game_over.run_game_over(score_list)
TypeError: run_game_over() missing 1 required positional argument: 'score_list'
Im not sure why this isnt working as i thought id set it up for the score_list variable to be an input correctly but clearly that is not the case
import turtle
def replaygame():
replay_label = turtle.Turtle()
replay_label.speed(0)
replay_label.color("White")
replay_label.penup()
replay_label.setposition(-290,280)
againornot = replay_label.textinput("Do you want to play again Y/N ?",False, align = "right", font = ("Arial" , 20, "normal"))
if againornot == Y:
True
else:
False
replaygame()
I'm not sure what the problem is. I imported turtle and I went through it twice. Here's the error I'm getting:
Traceback (most recent call last):
File "/Users/nn/Documents/sfgh.py", line 189, in <module>
replaygame()
File "/Users/nn/Documents/sfgh.py", line 158, in replaygame
againornot = replay_label.textinput("Do you want to play again Y/N ?",False, align = "right", font = ("Arial" , 20, "normal"))
AttributeError: 'Turtle' object has no attribute 'textinput'
When you have a minute, please post your error. In the meantime, I presume the error stems from here:
Try editing this line to put quotes around the Y. againornot == ’Y’
(Apologies for poor the formatting, I’m using my phone.)
Try it like this :
import turtle
def replaygame():
replay_label = turtle
replay_label.speed(0)
replay_label.color("White")
replay_label.penup()
replay_label.setposition(-290,280)
againornot = replay_label.textinput('Play Again', "Do you want to play again Y/N ?")
if againornot == Y:
True
else:
False
replaygame()
I have a problem with pyspotify. I'm trying to search for an artist name, get a list of their top tracks and then play one of them. This is my code segment:
search_string = "artist:"+artist_to_find
result = session.search(search_string)
result.load()
print result.track_total
browser = result.artists[0].browse()
browser.load()
print browser.tophit_tracks
for track in browser.tophit_tracks:
print track.name, track
toptracks = browser.tophit_tracks
print "error check"
if toptracks!=-1:
print "------------------"
tracktoplay=choice(toptracks)
rand = randint(0,10)
print "random track number = %s" %rand
tracktoplay = browser.tophit_tracks[rand]
print tracktoplay.link
print tracktoplay.name
print "------------------"
session.player.load(tracktoplay)
session.player.play()
I frequently call this code without the previous track finishing. Perodically (every few tracks) I get the following error:
random track number = 7
spotify:track:6vQN2a9QSgWcm74KEZYfDL
Take A Chance On Me
------------------
Traceback (most recent call last):
File "../jj.py", line 146, in <module>
app.run()
File "../jj.py", line 116, in run
conversation.handleForever()
File "/home/mh/Projects/jjo/client/conversation.py", line 44, in handleForever
listen(self)
File "/home/mh/Projects/jjo/client/new_play.py", line 110, in listen
play(self,response)
File "/home/mh/Projects/jjo/client/new_play.py", line 194, in play
session.player.load(tracktoplay)
File "/usr/local/lib/python2.7/dist-packages/spotify/player.py", line 45, in load
self._session._sp_session, track._sp_track))
File "/usr/local/lib/python2.7/dist-packages/spotify/error.py", line 30, in maybe_raise
raise LibError(error_type)
spotify.error.LibError: The track cannot be played
Can anyone advise on what I'm doing wrong?
Thanks
I don't have experiece on pyspotify, but I was looking at it out of curiosity.
If I was you I would check the PlayerState is LOADED before I call play()
Hope it helps.
Im currently in an intro coding class and for my final project, i am trying to learn the pyglet module to create a game with a picture in the background, and have a character on the left that a user can make jump, and then have jumps come from the right at a set speed that the user will jump over. i need to use classes for the assignment, and im really having a hard time using creating a sprite class. heres my current code:
import pyglet
window = pyglet.window.Window(700,700)
image = pyglet.image.load('IMG_3315.jpg')#use 10x10 in. image
#image_2 = pyglet.image.load('IMG_3559.jpg')
main_batch = pyglet.graphics.Batch()
score_label = pyglet.text.Label(text="Score: 0", x=570, y=650, batch=main_batch)
the_jump = pyglet.image.load("jumpsi.png")
#horse = pyglet.sprite.Sprite(image_2, x = 50, y = 50)
# background_sound = pyglet.media.load(
# 'Documents/Leave The Night On.mp3',
# streaming=False)
class Jump(pyglet.sprite.Sprite):
def __init__(self, img, x=0, y=0, blend_src=770, blend_dest=771, batch=None, group=None, usage='dynamic', subpixel=False):
self.img = the_jump
self.x = 50
self.y = 50
def draw(self):
self.draw()
# verticle = Jump('verticle')
#window.event
def on_draw():
window.clear()
image.blit(0, 0)
main_batch.draw()
window = Jump()
#horse.draw()
#background_sound.play()
if __name__ == "__main__":
sprite = Jump()
pyglet.app.run()
i know its probably wrong but everything else i have tried (using preexisting games as examples) hasn't worked either.
my current error message is:
Traceback (most recent call last):
File "jumper.py", line 39, in <module>
sprite = Jump()
TypeError: __init__() takes at least 2 arguments (1 given)
im just really stuck and have been trying to figure this out for hours and not made any leeway. any help you can offer would be greatly appreciated. Thanks so much!
UPDATE: i recently changed the code, noticing the problem that Gustav pointed out, and change the end call to
if __name__ == "__main__":
sprite = Jump(the_jump)
pyglet.app.run()
but now i get the error
Traceback (most recent call last):
File "jumper.py", line 39, in <module>
sprite = Jump(the_jump)
File "jumper.py", line 21, in __init__
self.x = 50
File "/Library/Python/2.7/site-packages/pyglet/sprite.py", line 459, in _set_x
self._update_position()
File "/Library/Python/2.7/site-packages/pyglet/sprite.py", line 393, in _update_position
img = self._texture
AttributeError: 'Jump' object has no attribute '_texture'
The error message is telling you exactly which line the error is in and exactly what is wrong. You are initializing the Jump class without passing in an argument for the required parameter img.
You can fix this by either changing the initialization method or your call to Jump().
Here's an example for how to read Python's traceback.
Hello I have recently been programming a game and I have come across and IndexError saying 'IndexError: list index out of range' and was wondering if anyone knew why?
class MenuScene(MenuClass):
def __init__(self, surface, engine):
MenuClass.__init__(self, surface)
self.MoonSurvival = engine
self.currentScene = 0
self.scenes = ['CARTER?! CARTER?! ARE YOU THERE?!\nYeah I am here',
'Look there have been sights of hostile alien activity near moon base 4,\n I need you to go and check it out as this could be a problem.\n\nOk I will, where is my rifle?', \
'It is just outside your room tell,\nme when you are ready and I will send you there.,\nGood luck Carter.\n\nThe aim of the game is to survive the alien invasion as long as possible,\nThere are some special drops the aliens can drop.\nThese include, health, shield, superhealth and triple-bullets.' \
'\nBe careful Carter. The aliens do not stay small for long....\n', \
'CONTROLS:\nA and D = Left, Right\nSPACE = Jump\nLeft Mouse Button = Shoot']
def renderText(self):
# split texts at \n (newline)
texts = self.scenes[self.currentScene].split('\n')
for i in range(len(texts)):
textSurface = self.menufont.render(texts[i], 0, (255, 0, 0))
textRect = textSurface.get_rect()
textRect.centerx = SCREEN_WIDTH / 2
textRect.centery = SCREEN_HEIGHT / 2 + i * self.menufont.size(texts[i])[1]
self.surface.blit(textSurface, textRect)
The error appears in the render text area of the code. Here is the nextScene function for the scenes.
def nextScene(self):
if self.currentScene < 4:
# li
self.currentScene += 1
elif self.currentScene == 5:
self.MoonSurvival.resetGame()
self.MoonSurvival.setState(MENU_GAMEFINISH)
else:
self.MoonSurvival.setState(MENU_INGAME)
The Error:
Traceback (most recent call last):
File "F:\My Game\MoonSurvival.py", line 416, in <module>
Game().run()
File "F:\My Game\MoonSurvival.py", line 194, in run
self.menuScene.draw()
File "F:\My Game\menus.py", line 168, in draw
self.renderText()
File "F:\My Game\menus.py", line 202, in renderText
texts = self.scenes[self.currentScene].split('\n')
IndexError: list index out of range
[Finished in 5.8s]
'It is just outside your room tell,\nme when you are ready and I will send you there.,\nGood luck Carter.\n\nThe aim of the game is to survive the alien invasion as long as possible,\nThere are some special drops the aliens can drop.\nThese include, health, shield, superhealth and triple-bullets.' \
It's hard to see with such a long line, but this line does not have a comma on the end. When Python sees two string literals next to each other, it concatenates their contents and treats them as one string. Put in a comma and see if the problem goes away. I recommend putting a comma after the last element of the list too, so you don't forget the comma when you go to add more scenes later.