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()
Related
class GameState():
def init(self):
self.state = 'main_game'
def main_game(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
if event.type == pygame.MOUSEBUTTONDOWN: # this is where the error comes from
mouse_state = 1
pygame.mouse.set_pos(mouse_x,mouse_y + 1)
else:
mouse_state = 0
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT or event.key == pygame.K_a:
snake.yV = 0
snake.xV = -1
if event.key == pygame.K_RIGHT or event.key == pygame.K_d:
snake.yV = 0
snake.xV = 1
if event.key == pygame.K_UP or event.key == pygame.K_w:
snake.xV = 0
snake.yV = -1
if event.key == pygame.K_DOWN or event.key == pygame.K_s:
snake.xV = 0
snake.yV = 1
mouse_x = pygame.mouse.get_pos()[0]
mouse_y = pygame.mouse.get_pos()[1]
pygame.display.set_caption("Snake, FPS: " + str(clock.get_fps()))
screen.fill(GREY)
snake.update()
food.update()
utility.update()
bombs.update()
food.draw()
snake.draw()
utility.draw()
bombs.draw()
pygame.display.flip()
button = Button()
snake = Snake()
food = Food()
utility = Utility()
bombs = Bombs()
game_state = GameState()
while not done:
game_state.main_game()
clock.tick(50)
pygame.quit()
This is just the snippit of code i can send the rest if needed the thing i did previously i had it under a game loop but this time im making a class and object so i can make multiple levels in the game
The if event.type == pygame.MOUSEBUTTONDOWN: and if event.type == pygame.KEYDOWN: are both outside of the for loop that defines the "event" variable.
def main_game(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
if event.type == pygame.MOUSEBUTTONDOWN: # this is where the error comes from
mouse_state = 1
pygame.mouse.set_pos(mouse_x,mouse_y + 1)
else:
mouse_state = 0
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT or event.key == pygame.K_a:
snake.yV = 0
snake.xV = -1
if event.key == pygame.K_RIGHT or event.key == pygame.K_d:
snake.yV = 0
snake.xV = 1
if event.key == pygame.K_UP or event.key == pygame.K_w:
snake.xV = 0
snake.yV = -1
if event.key == pygame.K_DOWN or event.key == pygame.K_s:
snake.xV = 0
snake.yV = 1
mouse_x = pygame.mouse.get_pos()[0]
mouse_y = pygame.mouse.get_pos()[1]
pygame.display.set_caption("Snake, FPS: " + str(clock.get_fps()))
screen.fill(GREY)
snake.update()
food.update()
utility.update()
bombs.update()
food.draw()
snake.draw()
utility.draw()
bombs.draw()
pygame.display.flip()
button = Button()
snake = Snake()
food = Food()
utility = Utility()
bombs = Bombs()
game_state = GameState()
Your code have indentation problems. Which makes event.MOUSEBUTTONDOWN and other events outside the loop. You code should have looks like this.
I created this program and when I run it the player is not moving. I checked and everything is right. Just in case you need it I am using python 3.8.6. Can you please help me? Here is my code.
# Game Loop
running = True
while running:
screen.fill((128, 20, 128))
for event in pygame.event.get():
player(playerX, playerY)
pygame.display.update()
# Movment
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_a:
player_x_change -= 10
if event.key == pygame.K_d:
player_x_change += 10
if event.key == pygame.K_w:
player_y_change -= 10
if event.key == pygame.K_s:
player_y_change += 10
if event.type == pygame.KEYUP:
if event.key == pygame.K_a:
player_x_change = 0
if event.key == pygame.K_d:
player_x_change = 0
playerX += player_x_change
playerY += player_y_change
# Close the game
if event.type == pygame.QUIT:
running = False
It's probably just an indentation error (perhaps pasting to the question), but none of your events are being handled because of the if event.type clauses are not inside the for event loop.
Simply fixing this indentation alleviates this.
The next problem is that you calculate the player_x_change and player_y_change, but never apply the amounts to playerX and playerY.
Since these changes only happen when pygame.KEYDOWN is received, it's easy to simply add this inside the event handler:
# Movment
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_a:
player_x_change -= 10
elif event.key == pygame.K_d:
player_x_change += 10
elif event.key == pygame.K_w:
player_y_change -= 10
elif event.key == pygame.K_s:
player_y_change += 10
# Move the player
playerX += player_x_change
playerY += player_y_change
Note the use of if .. elif. If the event is one particular type, it cannot possibly be another type too (at the same time). This means it's not necessary to keep re-checking the type. Using elif ("else if") helps with these checks, by stopping the check once a match is found. It is more efficient.
Final code:
import pygame
# Window size
WINDOW_WIDTH = 400
WINDOW_HEIGHT = 400
WINDOW_SURFACE = pygame.HWSURFACE|pygame.DOUBLEBUF
BACKGROUND = (128, 20, 128)
### initialisation
pygame.init()
pygame.mixer.init()
pygame.display.set_caption("Not Moving")
# Game Loop
clock = pygame.time.Clock()
running = True
while running:
for event in pygame.event.get():
# Close the game
if event.type == pygame.QUIT:
running = False
# Movment
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_a:
player_x_change -= 10
elif event.key == pygame.K_d:
player_x_change += 10
elif event.key == pygame.K_w:
player_y_change -= 10
elif event.key == pygame.K_s:
player_y_change += 10
# Move the player
playerX += player_x_change
playerY += player_y_change
# DON'T REALLY NEED THIS
#elif event.type == pygame.KEYUP:
# if event.key == pygame.K_a:
# player_x_change = 0
# elif event.key == pygame.K_d:
# player_x_change = 0
# Re-draw the screen
screen.fill( BACKGROUND )
player(playerX, playerY)
pygame.display.update()
clock.tick(60) # limit the re-fresh rate to save electricity
pygame.quit()
I also added a frame-rate limiter with a pygame.time.Clock() object, just to save some CPU.
I was able to fix the problem now, if anyone wants the code here it is. :) It turns out I put the "close program" code too early and it doesn't work until the close button is pressed. So my player did move, but only for a second.
# Game Loop
running = True
while running:
if event.type == pygame.QUIT:
running = False
# if keystroke is pressed check whether its right or left
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
playerX_change = -5
if event.key == pygame.K_RIGHT:
playerX_change = 5
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
playerX_change = 0
playerX += playerX_change
if playerX <= 0:
playerX = 0
elif playerX >= 736:
playerX = 736
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))
So, I'm making my first game in pygame, and have done OK up to this point. I just can't move the image. Can I please get some help?
mc_x = 20
mc_y = 20
spider_x = 690
spider_y = 500
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
mc_x -= 5
elif event.key == pygame.K_RIGHT:
mc_x += 5
elif event.key == pygame.K_UP:
mc_y += 5
elif event.key == pygame.K_DOWN:
mc_y -= 5
screen.blit(background,(0,0))#fixed
screen.blit(spider_small,(spider_x,spider_y))#FIXED
screen.blit(mc,(mc_x,mc_y))
pygame.display.update()
Based on your code:
screen.blit(mc,(mc_x,mc_y))
pygame.display.update()
should be inside the loop so that it would update/refresh your game for every keystroke.
You forgot to update the screen. Set the update function inside the main game loop. This is going to work fine!
Here's my sample code
import pygame
pygame.init()
WHITE = (255, 255, 255)
RED = (255, 0, 0)
canvas = pygame.display.set_mode((800, 600))
pygame.display.set_caption('Example')
gameExit = False
lead_x, lead_y = 300, 300
while not gameExit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
lead_x -= 10
elif event.key == pygame.K_RIGHT:
lead_x += 10
elif event.key == pygame.K_DOWN:
lead_y += 10
elif event.key == pygame.K_UP:
lead_y -= 10
canvas.fill(WHITE)
pygame.draw.rect(canvas, RED, [lead_x, lead_y, 30, 30])
pygame.display.update()
pygame.quit()
quit()
I've been working on a school project, and I need some assistance with player movement. The problem is I have to manually tap the arrow / WASD keys for the player to move one spot at a time. The player won't move if I hold in the keys. How do I fix this issue?
Note - I'm using an outdated Python - Python 2.7.3
Code:
# Begin 'The Maze'
# Import modules
import os, sys, time, pygame
from pygame.locals import *
from pygame.time import *
# Initialise Pygame + Clock
pygame.init()
mainClock = pygame.time.Clock()
# Window Setup
WINDOWHEIGHT = 480
WINDOWWIDTH = 600
windowSurface = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT), 0, 32)
pygame.display.set_caption('The Maze')
# Player Variables
player = pygame.Rect(50, 50, 50, 50)
# Colour Setup
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
BLUE = (0, 0, 255)
GREEN = (0, 255, 0)
# Movement Variables
moveLEFT = False
moveRIGHT = False
moveUP = False
moveDOWN = False
MOVESPEED = 7
x,y = 0,0
charx,chary = 0,0
movex,movey = 0,0
# Game Loop & Events + Updates
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
# Change the keyboard variables
if event.type == KEYDOWN:
if event.key == K_LEFT or event.key == ord('a'):
moveLEFT = True
movex = -0.5
if event.key == K_RIGHT or event.key == ord('d'):
moveRIGHT = True
movex = -0.5
if event.key == K_UP or event.key == ord('w'):
moveUP = True
movey = 0.5
if event.key == K_DOWN or event.key == ord('s'):
moveDOWN = True
movey = -0.5
if event.type == KEYUP:
if event.key == K_ESCAPE:
pygame.quit()
sys.exit()
if event.key == K_LEFT or event.key == ord('a'):
moveLEFT = False
movex = 0
if event.key == K_RIGHT or event.key == ord('d'):
moveRIGHT = False
movex = 0
if event.key == K_UP or event.key == ord ('w'):
moveUP = False
movey = 0
if event.key == K_DOWN or event.key == ord('s'):
moveDOWN = False
movey = 0
# Background Setup
windowSurface.fill(WHITE)
# Player Setup + Updating Screen
if moveDOWN and player.bottom < WINDOWHEIGHT:
player.top += MOVESPEED
if moveUP and player.top > 0:
player.top-= MOVESPEED
if moveLEFT and player.left > 0:
player.left -= MOVESPEED
if moveRIGHT and player.right < WINDOWWIDTH:
player.right += MOVESPEED
pygame.draw.rect(windowSurface, GREEN, player)
pygame.display.update()
mainClock.tick(40)
Thanks!
A simple dedent of the block of code after # Background Setup did the job.
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
# Change the keyboard variables
if event.type == KEYDOWN:
if event.key == K_LEFT or event.key == ord('a'):
moveLEFT = True
elif event.key == K_RIGHT or event.key == ord('d'):
moveRIGHT = True
elif event.key == K_UP or event.key == ord('w'):
moveUP = True
elif event.key == K_DOWN or event.key == ord('s'):
moveDOWN = True
elif event.type == KEYUP:
if event.key == K_ESCAPE:
pygame.quit()
sys.exit()
elif event.key == K_LEFT or event.key == ord('a'):
moveLEFT = False
elif event.key == K_RIGHT or event.key == ord('d'):
moveRIGHT = False
elif event.key == K_UP or event.key == ord ('w'):
moveUP = False
elif event.key == K_DOWN or event.key == ord('s'):
moveDOWN = False
# <-- Dedent
# Background Setup
windowSurface.fill(WHITE)
# Player Setup + Updating Screen
if moveDOWN and player.bottom < WINDOWHEIGHT:
player.top += MOVESPEED
if moveUP and player.top > 0:
player.top-= MOVESPEED
if moveLEFT and player.left > 0:
player.left -= MOVESPEED
if moveRIGHT and player.right < WINDOWWIDTH:
player.right += MOVESPEED
pygame.draw.rect(windowSurface, GREEN, player)
pygame.display.update()
mainClock.tick(40)