I am creating a game in python with a scrolling background and I can't get my player to move. Just so you know, we are not allowed to use classes or sprites
def game():
running = True
backgrounX = 0
button = 0
movex = 0
movey = 0
player = image.load("images/player.gif")
def drawscene(screen,button,backx):
screen.fill((0, 0 , 0))
background = image.load("images/bc3.png") # Load image
bc = transform.scale(background, (1000, 700)) # Scale the image
screen.blit(bc, [backx, 0]) # To show image
screen.blit(bc, [backx + 1000, 0]) # For background to move
button_1 = Rect(0, 0, 100, 70)
draw.rect(screen, (0, 85, 255), button_1)
draw_text("Exit", font, (0, 0, 0), screen, 25, 25)
for e in event.get():
if e.type == MOUSEBUTTONDOWN:
if e.button == 1:
main_menu()
# Game loop
while running:
for e in event.get():
if e.type == QUIT:
quit()
sys.exit()
running = False
if e.type == KEYDOWN:
if e.key == K_LEFT or e.key == ord('a'):
movex = -1
if e.key == K_RIGHT or e.key == ord('d'):
movex = +1
if e.key == K_UP or e.key == ord('w'):
movey = -1
if e.type == KEYUP:
if e.key == K_LEFT or e.key == ord('a') or e.key == K_RIGHT or e.key == ord('d'):
movex = 0
if e.key == K_UP or e.key == ord('w'):
movey = 0
x += movex
y += movey
drawscene(screen, button, backgrounX)
screen.blit(player (movex, movey))
myClock.tick(60)
backgrounX -= 3 # background scroller speed
display.update()
this is what I have tried so far and an error shows up saying " local variable 'x' referenced before assignment" for line 40. Does anyone know any other way for making my player move?
The position of the player is (x, y) rather than (movex, movey). Furthermore there is a ',' missing in the argument list:
screen.blit(player (movex, movey))
screen.blit(player, (x, y))
Of course you have to define x and y somewhere before the application loop:
x = 0
y = 0
while running:
# [...]
x += movex
y += movey
# [...]
screen.blit(player, (x, y))
Related
I'm working on the basics of a game right now, but for some reason I cannot get my sprite to move. I know that it's registering when I'm pressing the key down, but the sprite for some reason just stays still.
import pygame
import sys
from pygame.locals import *
import time
pygame.init()
black = (0, 0, 0)
white = (255, 255, 255)
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption("RADICAL")
screen.fill(black)
imga = pygame.image.load('coina.png')
imgb = pygame.image.load('coinb.png')
sound = pygame.mixer.Sound('coin.mp3')
FPS = 80
imgx = 10
imgy = 10
pixMove = 10
steps = 0
x1 = 0
y1 = 0
keystate = pygame.key.get_pressed()
GameOver = False
while not GameOver:
screen.fill(white)
points = (steps)
font = pygame.font.SysFont(None, 30)
text = font.render('Score: '+str(points), True, black)
screen.blit(text, (0,0))
if steps % 2 == 0:
screen.blit(imga, (imgx, imgy))
else:
screen.blit(imgb, (imgx, imgy))
for event in pygame.event.get():
print event
if event.type == QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.KEYDOWN:
if keystate[pygame.K_UP]:
y1 -= pixMove
elif keystate[pygame.K_DOWN]:
y1 += pixMove
elif keystate[pygame.K_LEFT]:
x1 -= pixMove
elif keystate[pygame.K_RIGHT]:
x1 += pixMove
elif event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
x1 = 0
if event.key == pygame.K_UP or event.key == pygame.K_DOWN:
y1 = 0
steps +=1
if event.type == K_SPACE:
sound.play()
time.sleep(1)
sound.stop()
pygame.display.update()
fpsTime.tick(FPS)
Generally you blit() images on to the screen (pygame.display.set_mode()), for the changes to to reflect on the screen we call pygame.display.update(), In your case the game never comes the statement, which is out of while loop.
Im working on a simple game( a semi copy of the 'Dodger' game), and the game runs, yet displays nothing. I have a while loop running, so why is nothing showing up? Is it a problem with spacing, the images themselves, or am i just overlooking something?
import pygame,sys,random, os
from pygame.locals import *
pygame.init()
#This One Works!!!!!!!
WINDOWHEIGHT = 1136
WINDOWWIDTH = 640
FPS = 40
TEXTCOLOR = (255,255,255)
BACKGROUNDCOLOR = (0,0,0)
PLAYERMOVEMENT = 6
HARVEYMOVEMENT = 5
TJMOVEMENT = 7
LASERMOVEMENT = 10
ADDNEWBADDIERATE = 8
COLOR = 0
TJSIZE = 65
HARVEYSIZE = 65
#Check the sizes for these
def terminate():
if pygame.event() == QUIT:
pygame.quit()
def startGame():
while True:
for event in pygame.event.get():
if event.type == QUIT:
terminate()
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
terminate()
return
def playerHasHitBaddies(playerRect,TjVirus,HarVirus):
for b in TjVirus and HarVirus:
if playerRect.colliderect(b['rect']):
return True
return False
def drawText(text,font,surface, x, y):
textobj = font.render(text, 1, TEXTCOLOR)
textrect = textobj.get_rect()
textrect.topleft = (x, y)
surface.blit(textobj, textrect)
mainClock = pygame.time.Clock()
WindowSurface = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
pygame.mouse.set_visible(False)
pygame.display.set_caption('Virus')
#Player Images
# Check the name of the .png file
TjImage = pygame.image.load('Virus_TJ_edited-1.png')
TjRect = TjImage.get_rect()
#chanhe this part from the baddies variable in the 'baddies' area
playerImage = pygame.image.load('Tank_RED.png')
playerRect = playerImage.get_rect()
LaserImage = pygame.image.load('laser.png')
LaserRect = LaserImage.get_rect()
pygame.display.update()
startGame()
while True:
TjVirus = []#the red one / make a new one for the blue one
HarVirus = []#The BLue one / Need to create a new dictionary for this one
playerRect.topleft = (WINDOWWIDTH / 2, WINDOWHEIGHT - 50)
moveLeft = moveRight = moveUp = moveDown = laser = False
baddieAddCounter = 0
while True:
for event in pygame.event.get():
if event.type == QUIT:
terminate()
if event.type == KEYDOWN:
if event.key == ord('a'):
moveRight = False
moveLeft = True
if event.key == ord('d'):
moveLeft = False
moveRight = True
if event.key == ord('w'):
moveDown = False
moveUp = True
if event.key == ord('s'):
moveUp = False
moveDown = True
if event.key == K_SPACE:
lasers = True
if event.type == KEYUP:
if evnet.type == K_ESCAPE:
terminate()
if event.key == K_LEFT or event.key == ord('a'):
moveLeft = False
if event.key == K_RIGHT or event.key == ord('d'):
moveRight = False
if event.key == K_UP or event.key == ord('w'):
moveUp = False
if event.key == K_DOWN or event.key == ord('s'):
moveDown = False
if event.key == K_SPACE:
LaserImage.add(LaserRect)
if event.key == ord('j'):
COLOR = 2
if event.key == ord('k'):
if COLOR == 2:
COLOR = 1
playerImage = pygame.image.load('Tank_RED.png')
if COLOR == 1:
COLOR = 2
playerImage = pygame.image.load('Tank_BLUE.png')
if event.type == MOUSEMOTION:
playerRect.move_ip(event.pos[0] - playerRect.centerx, event.pos[1] - playerRect.centery)
if baddieAddCounter == ADDNEWBADDIERATE:
baddieAddCounter = 0
#Dict for TJ(RED) VIRUS
baddieSize = (TJSIZE)
NewTjVirus = {'rect':pygame.Rect(random.rantint(0,WINDOWWIDTH - TJSIZE),0 - TJSIZE,TJSIZE,TJSIZE),
'speed':(TJMOVEMENT),
'surface':pygame.transform.scale(TJImage,(TJSIZE,TJSIZE)),
}
TjVirus.append(NewTjVirus)
#Dict for Harvey(BLUE) virus
baddieSize = (HARVEYSIZE)
NewHarveyVirus = {'rect':pygame.Rect(random.randint(0,WINDOWWIDTH - HARVEYSIZE),0 - HARVEYSIZE,HARVEYSIZE,HARVEYSIZE),
'speed':(HARVEYMOVEMENT),
'surface':pygame.transform.scale(HARVEYSIZE,(HARVEYSIZE,HARVEYSIZE))
}
HarVirus.append(NewHarveyVirus)
#Player Movement
if moveLeft and playerRect.left >0:
playerRect.move_ip(-1*PLAYERMOVEMENT,0)
if moveRight and playerRect.right < WINDOWWIDTH:
playerRect.move_ip(PLAYERMOVEMENT,0)
if moveUp and playerRect.top >0:
playerRect.move_ip(0,-1*PLAYERMOVEMENT)
if moveDown and playerRect.bottom < WINDOWHEIGHT:
playerRect.move_ip(0,PLAYERMOVEMENT)
pygame,mouse.set_pos(playerRect.centerx,playerRect.centery)
#Need to change for each individual virus
for b in HarVirus and TjVirus:
b['rect'].move_ip(0,b['speed'])
for b in HarVirus and TjVirus:
if b['rect'].top > WINDOWHEIGHT:
baddies.remove(b)
windowSurface.fill(pygame.image.load('Background_Proto copy.png'))
for b in HarVirus and TjVirus:
windowSurface.blit(b['surface'],b['rect'])
pygame.display.update()
if playerHasHitBaddies(playerRect,HarVirus,TjVirus):
break
for b in TjVirus and HarVirus[:]:
if b['rect'].top < WINDOWHEIGHT:
HarVirus.remove(b)
TjVirus.remove(b)
mainClock.tick(FPS)
Usally I use pygame.display.flip() not pygame.display.update()
You call your startGame() in your script, which looks like this:
def startGame():
while True:
for event in pygame.event.get():
if event.type == QUIT:
terminate()
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
terminate()
return
The game is stuck in that while loop until you press a key.
That's your current problem, but there are other errors as well, like
def terminate():
if pygame.event() == QUIT:
pygame.quit()
pygame.event() is not callable. Maybe you wanted to pass an event as argument here?
And also
pygame,mouse.set_pos(playerRect.centerx,playerRect.centery)
, instead of .
I'm trying to blit an image as a background, and then have a sprite moving in all directions and rotate. So far, I have the following:
import pygame, sys
from pygame.locals import *
BGimageName = 'joker.jpg'
FGimageName = 'bmanicon.tga'
pygame.init()
DisWidth = 900
DisHeight = 600
x = -500
y = -300
spriteROT = 1.0
SPHpos = (DisWidth//2, DisHeight//2)
DISPLAYSURF = pygame.display.set_mode((DisWidth, DisHeight), 0, 32)
BGimage = pygame.image.load(BGimageName).convert()
FGimage = pygame.image.load(FGimageName).convert_alpha()
def main():
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == KEYDOWN:
if event.key == K_LEFT:
move_x = -1
elif event.key == K_RIGHT:
move_x = +1
elif event.key == K_UP:
move_y = -1
elif event.key == K_DOWN:
move_y = +1
elif event.key == K_r:
rotationDIR = + 1.0
elif event.key == K_w:
rotationDIR = - 1.0
elif event.type == KEYUP:
if event.key == K_LEFT:
move_x = 0
elif event.key == K_RIGHT:
move_x = 0
elif event.key == K_UP:
move_y = 0
elif event.key == K_DOWN:
move_y = 0
elif event.key == K_r:
rotationDIR = 0
elif event.key == K_w:
rotationDIR = 0
DISPLAYSURF.blit(BGimage, (x, y))
RotSPH = pygame.transform.rotate(FGimage, spriteROT)
w, h = RotSPH.get_size()
spriteDrawPos = (SPHpos[0] - w // 2, SPHpos[1] - h // 2)
DISPLAYSURF.blit(RotSPH, spriteDrawPos)
pygame.display.update()
main()
This is all pretty new to me. Most of it was provided by our professor, and we then had to figure out the rest and personalize it. Unfortunately I wasn't present the day of class where we discussed events, so I don't really understand them. I think that I currently have everything working because the background and the sprite both display, but the sprite doesn't move when I press any buttons. How can I get Python to recognize that I want the sprite to move?
I tried to put FGimage.move_x and such in the event keys, i.e.
if event.key == K_LEFT:
FGimage.move_x = -1
but that doesn't work, giving me the error
Attribute Error: 'pygame.Surface' object has no attribute 'move_x'
I think I'm close, but I'm still missing the last step.
The reason why you are not moving the sprite is because you are not changing any variables with the events.
Specifically the location variable spriteDrawPos is not changing because the line spriteDrawPos = (SPHpos[0] - w // 2, SPHpos[1] - h // 2) which modifies it is not changing because SPHpos is never going to change because spriteROT never changes.
To fix this modify the code to work with the variables you changed in the event.
spriteROT += rotationDIR
RotSPH = pygame.transform.rotate(FGimage, spriteROT)
w, h = RotSPH.get_size()
spriteDrawPos = (SPHpos[0] - w // 2 + move_x, SPHpos[1] - h // 2 + move_y)
DISPLAYSURF.blit(RotSPH, spriteDrawPos)
This will hopefully allow your sprite to move, but probably too fast.
this script spawns a alien that follows the player, i just want to know how to make the alien (nPc) and the player (mouse_c) a rect so i make the alien kill the player when the imagers overlap. any help would really help
thanks
import pygame, sys, random, time, math
from pygame.locals import *
pygame.init()
bifl = 'screeing.jpg'
milf = 'character.png'
alien = 'alien_1.png'
screen = pygame.display.set_mode((640, 480))
background = pygame.image.load(bifl).convert()
mouse_c = pygame.image.load(milf).convert_alpha()
nPc = pygame.image.load(alien).convert_alpha()
mouse_c = pygame.Rect((10, 10))
nPc = pygame.Rect((10, 10))
x, y = 0, 0
movex, movey = 0, 0
z, w = random.randint(10, 480), random.randint(10, 640)
movez, movew = 0, 0
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == KEYDOWN:
if event.key == K_w:
movey = -4
elif event.key == K_s:
movey = +4
elif event.key == K_a:
movex = -4
elif event.key == K_d:
movex = +4
if event.type == KEYUP:
if event.key == K_w:
movey = 0
elif event.key == K_s:
movey = 0
elif event.key == K_a:
movex = 0
elif event.key == K_d:
movex = 0
if w < x:
movew =+ 0.4
if w > x:
movew =- 0.4
if z < y:
movez =+ 0.4
if z > y:
movez =- 0.4
x += movex
y += movey
w += movew
z += movez
print('charecter pos: ' + str(x) + str(y))
print('alien pos: ' + str(w) + str(z))
chpos = x + y
alpos = w + z
print(alpos, chpos)
screen.blit(background, (0, 0))
screen.blit(mouse_c, (x, y))
screen.blit(nPc, (w, z))
pygame.display.update()
You could use Pygame Sprites
mouse_c = pygame.sprite.Sprite()
mouse_c.image = pygame.image.load(milf).convert_alpha()
mouse_c.rect = mouse_c.image.get_rect()
mouse_c.rect.move_ip(10,10)
nPc = pygame.sprite.Sprite()
nPc.image = pygame.image.load(milf).convert_alpha()
nPc.rect = nPc.image.get_rect()
nPc.rect.move_ip(10,10)
Then blit:
screen.blit(mouse_c.image, mouse_c.rect.topleft)
screen.blit(nPc.image, nPc.rect.topleft)
I had this script working before but now it doesnt work. Earlier, the image moved around the screen fine but now it wont even move, the image just stays in the corner not moving at all when i press up or down or left or right keys
import pygame, sys
from pygame.locals import *
pygame.init()
bifl = 'screeing.jpg'
milf = 'char_fowed_walk1.png'
screen = pygame.display.set_mode((640, 480))
background = pygame.image.load(bifl).convert()
mouse_c = pygame.image.load(milf).convert_alpha()
x, y = 0, 0
movex, movey = 0, 0
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == KEYDOWN:
if event.key == K_LEFT:
movex =- 0.3
elif event.key == K_RIGHT:
movex =+ 0.3
elif event.key == K_UP:
movey =- 0.3
elif event.key == K_DOWN:
movey =+ 0.3
if event.type == KEYDOWN:
if event.key == K_LEFT:
movex = 0
elif event.key == K_RIGHT:
movex = 0
elif event.key == K_UP:
movey = 0
elif event.key == K_DOWN:
movey = 0
x += movex
y += movey
screen.blit(background, (0, 0))
screen.blit(mouse_c, (x, y))
pygame.display.update()
I am using python 2.7
All you need to do is change the second KEYDOWN to KEYUP so that your movement speed doesn't get set to 0 whenever you press a key.
EDIT: Additionally you have some strange syntax in your code. =- and =+ are not Python operators. I think you meant += and -=. Also remember to use elif statements instead of if statements whenever possible. Not only does this optimize your code, it also makes it easier to understand and debug.
import pygame, sys
from pygame.locals import *
pygame.init()
bifl = 'screeing.jpg'
milf = 'char_fowed_walk1.png'
screen = pygame.display.set_mode((640, 480))
background = pygame.image.load(bifl).convert()
mouse_c = pygame.image.load(milf).convert_alpha()
x, y = 0, 0
movex, movey = 0, 0
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == KEYDOWN:
if event.key == K_LEFT:
movex -= 0.3
elif event.key == K_RIGHT:
movex += 0.3
elif event.key == K_UP:
movey -= 0.3
elif event.key == K_DOWN:
movey += 0.3
elif event.type == KEYUP:
if event.key == K_LEFT:
movex = 0
elif event.key == K_RIGHT:
movex = 0
elif event.key == K_UP:
movey = 0
elif event.key == K_DOWN:
movey = 0
x += movex
y += movey
screen.blit(background, (0, 0))
screen.blit(mouse_c, (x, y))
pygame.display.update()