My sprite wont move right pygame - python

earlier my sprite wouldn't move at all so i posted the code and i got it fixed for the most part but now my up/down arrows work fine but my right key doesn't work. (Also, when you press two keys, and then let go of one, the walk animation doesn't work, but I'm not desperate right now to get that fixed.) Also i would prefer not to use user made classes. thanks in advance.
Here is the code:
from pygame.locals import *
import pygame._view
pygame.init()
clock = pygame.time.Clock()
height = 500
width = 500
screen = pygame.display.set_mode((width, height), 0, 32)
pygame.display.set_caption('placeholder text')
photo = 'grassbackground.png'
background = pygame.image.load(photo).convert()
rectexist = False
photo1 = 1
user = pygame.sprite.Sprite()
change = False
up = False
down = False
left = False
right = False
speed = 5
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == KEYDOWN:
if event.key == K_UP:
up = True
change = True
if event.key == K_DOWN:
down = True
change = True
if event.key == K_LEFT:
left = True
change = True
if event.type == K_RIGHT:
right = True
change = True
if event.type == KEYUP:
if event.key == K_UP:
up = False
change = False
if event.key == K_DOWN:
down = False
change = False
if event.key == K_LEFT:
left = False
change = False
if event.key == K_RIGHT:
right = False
change = False
if down and user.rect.bottom < height:
user.rect.top += speed
if up and user.rect.top > 0:
user.rect.top -= speed
if left and user.rect.left > 0:
user.rect.left -= speed
if right and user.rect.right < width:
user.rect.right += speed
if change == True:
pygame.time.wait(110)
photo1 += 1
if change == False:
photo1 = 1
if photo1 == 1:
user.image = pygame.image.load("1.png").convert()
if rectexist == False:
user.rect = user.image.get_rect()
rectexist = True
screen.blit(user.image, user.rect)
if photo1 == 2:
user.image = pygame.image.load("2.png").convert()
screen.blit(user.image, user.rect)
if photo1 == 3:
user.image = pygame.image.load("3.png").convert()
screen.blit(user.image, user.rect)
if photo1 >= 4:
photo1 = 1
thesprites = pygame.sprite.RenderPlain((user))
thesprites.update()
screen.blit(background, (0, 0))
thesprites.draw(screen)
pygame.display.update()
clock.tick(60)

In your code it says:
if event.type == K_RIGHT:
it should be:
if event.key == K_RIGHT:
To keep animating you'd need to change the code a little more, add a:
key_pressed = []
in the beginning. Then for each key-press block do:
key_pressed.append(event.key)
and key-release do:
key_pressed = [k for k in key_pressed if k != event.key]
instead of the change=True and change=False respectively. Then after the two segments of checking what was pressed and released have add these lines:
if len(key_pressed) > 0:
change = True
else:
change = False
That should fix most of your issues...

Use pressed = pygame.key.get_pressed() to get a dictionary (a tuple, actually, but the way things are structured you can think of it as a dictionary) of all keys that are currently pressed. You'd use it like this:
pressed = pygame.key.get_pressed()
if pressed[K_LEFT]:
# move left
elif pressed[K_RIGHT]:
# move right
# etc

Related

"if cond1 or cond2" statement not running second condition in Python

I am making a game in Python that looks like this so far:
import pygame, sys, time, random, threading
from threading import Timer
from pygame.locals import *
pygame.init()
WINDOWHEIGHT = 720
WINDOWWIDTH = 1280
windowSurface = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT), 0, 32)
pygame.display.set_caption('Hitman Grandma')
plorp = 'true'
white = (255,255,255)
red = (255,0,0)
black = (0,0,0)
green = (0,255,0)
blue = (0,0,255)
cyan = (0,255,255)
windowSurface.fill(white)
pygame.display.update()
mainClock = pygame.time.Clock()
hgleft = False
hgright = False
hgup = False
speed = 4
hgair = True
hgjumpallowed = False
level = 0
def stop() :
hgbox.move_ip(0,0)
return
hgbox = pygame.Rect(0 ,13 ,36 ,72)
hitmangrandma = pygame.image.load('hgrd1copy.jpg')
hg = pygame.transform.scale(hitmangrandma, (36,72))
landbox1 = pygame.Rect(0,400,200,50)
li = pygame.image.load('hgland1.png')
land1 = pygame.transform.scale(li,(200,50))
landbox2 = pygame.Rect(230,400,200,50)
land2 = pygame.transform.scale(li,(200,50))
land = landbox1,landbox2
while True:
windowSurface.fill(white)
windowSurface.blit(land1,landbox1)
windowSurface.blit(land2,landbox2)
for event in pygame.event.get():
if event.type == KEYDOWN:
if event.key == K_LEFT or event.key == K_a:
hgright = False
hgleft = True
if event.key == K_RIGHT or event.key == K_d:
hgleft = False
hgright = True
if event.key == K_UP or event.key == K_w:
hgair = True
hgup = True
hgupkey = True
if event.type == KEYUP:
if event.key == K_ESCAPE or K_q and pygame.key.get_mods() & pygame.KMOD_CTRL:
pygame.quit()
sys.exit()
exit
if event.key == K_LEFT or K_a:
hgleft = False
if event.key == K_RIGHT or K_d:
hgright = False
if hgup and hgbox.top > 0 and hgupkey == True and hgair == True and hgjumpallowed == True:
hgbox.top -= 100
hgair = True
if hgleft and hgbox.left > 0:
hgbox.left -= speed
if hgright and hgbox.right < WINDOWWIDTH:
hgbox.right += speed
if not hgbox.colliderect(landbox1) or not hgbox.colliderect(landbox2) and hgair == True:
hgair = False
hgbox.top += speed
hgjumpallowed = False
if hgbox.colliderect(landbox1) or hgbox.colliderect(landbox2):
hgjumpallowed = True
stop()
windowSurface.blit(hg, hgbox)
pygame.display.update()
mainClock.tick(40)
However, when I run my script, hgbox doesn't detect collision with landbox2, and just keeps falling. I think this problem is due to it only running the first part of the if statement, and not checking the other parts. What should I do to make it detect other parts of the if statement?
With an mcve I meant something like this (a minimal but complete example that we can copy, paste and run):
import sys
import pygame
pygame.init()
screen = pygame.display.set_mode((640, 480))
def stop() :
hgbox.move_ip(0, 0)
hgbox = pygame.Rect(0 ,13 ,36 ,72)
landbox1 = pygame.Rect(0,400,200,50)
landbox2 = pygame.Rect(230,400,200,50)
hgair = True
hgjumpallowed = False
hgup = False
hgupkey = False
speed = 9
clock = pygame.time.Clock()
done = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_w:
hgup = True
hgbox.x += 50
hgbox.y -= 90
if hgup and hgbox.top > 0 and hgupkey == True and hgair == True and hgjumpallowed == True:
hgbox.top -= 100
hgair = True
if not hgbox.colliderect(landbox1) or not hgbox.colliderect(landbox2) and hgair == True:
hgair = False
hgbox.top += speed
hgjumpallowed = False
if hgbox.colliderect(landbox1) or hgbox.colliderect(landbox2):
hgjumpallowed = True
stop()
screen.fill(pygame.Color('gray12'))
pygame.draw.rect(screen, (120, 70, 70), landbox1)
pygame.draw.rect(screen, (120, 70, 70), landbox2)
pygame.draw.rect(screen, (50, 70, 170), hgbox)
pygame.display.flip()
clock.tick(30)
pygame.quit()
sys.exit()
The problem is caused by this line:
if not hgbox.colliderect(landbox1) or not hgbox.colliderect(landbox2) and hgair == True:
It's evaluated as
if (not hgbox.colliderect(landbox1)) or (not hgbox.colliderect(landbox2) and hgair == True):
The second part would be always False in the example above. The hgbox always falls unless the first part of the condition is False as well (not hgbox.colliderect(landbox1)), that means it can only stand on the left platform.
Try to change it to:
if not hgbox.colliderect(landbox1) and not hgbox.colliderect(landbox2):
# Move downwards.
Edit: Here's a complete example to show you how I would write the movement and jump code. Use x_speed and y_speed to move the player every frame (also accelerate the y_speed) and in the event loop just set the speeds to the desired values. If the player touches a platform set him to the .top of the platform rect and hgjumpallowed to True.
import pygame, sys
from pygame.locals import *
from pygame.color import THECOLORS
pygame.init()
windowSurface = pygame.display.set_mode((1280, 720), 0, 32)
pygame.display.update()
mainClock = pygame.time.Clock()
hitmangrandma = pygame.Surface((36, 72))
hitmangrandma.fill((250, 160, 50))
hgbox = hitmangrandma.get_rect(topleft=(10, 10))
y_speed = 0
x_speed = 0
hgjumpallowed = False
land_img = pygame.Surface((200, 50))
land_img.fill((50, 100, 250))
land = pygame.Rect(0,400,200,50), pygame.Rect(230,400,200,50)
done = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT: # Quit game by pressing on the "x" button.
done = True
if event.type == KEYDOWN:
if event.key in (K_LEFT, K_a):
# Just set the x_speed and then move
# the rect in the while loop each frame.
x_speed = -4
if event.key in (K_RIGHT, K_d):
x_speed = 4
if (event.key == K_UP or event.key == K_w) and hgjumpallowed:
y_speed = -17
hgjumpallowed = False
if event.type == KEYUP:
if event.key == K_ESCAPE or K_q and pygame.key.get_mods() & pygame.KMOD_CTRL:
done = True
if event.key in (K_LEFT, K_a):
x_speed = 0
if event.key in (K_RIGHT, K_d):
x_speed = 0
y_speed += 1 # Accelerate downwards.
# Move the player.
hgbox.x += x_speed
hgbox.y += y_speed
# Check if player is on ground and can jump.
hgjumpallowed = False
for box in land:
if hgbox.colliderect(box): # If player touches ground.
hgjumpallowed = True
hgbox.bottom = box.top
y_speed = 0
windowSurface.fill(THECOLORS['white'])
for box in land:
windowSurface.blit(land_img, box)
windowSurface.blit(hitmangrandma, hgbox)
pygame.display.update()
mainClock.tick(40)
pygame.quit()
sys.exit()
There also was a mistake in the event loop: event.key == K_RIGHT or K_d is always True, because it's evaluated as (event.key == K_RIGHT) or (K_d) and K_d is a truthy value.
To ensure that Python evaluates the logical operators in the right order, add ().
if (not hgbox.colliderect(landbox1) or not hgbox.colliderect(landbox2)) and hgair == True:
This evaluates to True when there is no collision with either landbox1 or with landbox2, and when hgair == True.

I want to hold down a button for constant movement, but KEYUP is reading true even if I don't lift the key

I want to be able to hold the key down and move my little black dot, and then release the key and have it stop. However even if I hold the key down my if statement for key up is being executed. Here is my code:
manmovemaster = 0
l = 1
f1 = 0
from random import randint
from math import sin, cos, tan, pi
import pygame
from pygame.locals import*
Fps = pygame.time.Clock()
#starting variables
sw = 1200
sh = 650
r = 250
g = 250
b = 250
framerate = 40
#beginning of a man
man1x = 650
man1y = 50
mancolor=(0,0,0)
manlocation = (man1x, man1y)
Diamaterofhead = (5)
man1ymovedown = 0
man1ymoveup = False
man1xmoveright = False
man1xmoveleft = False
#game logic
while l:
pygame.init()
screen = pygame.display.set_mode((sw,sh))
pygame.display.set_caption("WGD THE GAME")
background = pygame.Surface(screen.get_size())
background = background.convert()
background.fill((r,g,b))
man1 = pygame.draw.circle(background,mancolor,(man1x,man1y),Diamaterofhead)
if man1ymovedown== True:
man1y += 1
manmovemaster = 0
if man1ymoveup == True:
man1y -= 1
if man1xmoveright == True:
man1x +=1
if man1xmoveleft == True:
man1x -=1
#screen refresh
for event in pygame.event.get():
if event.type ==pygame.QUIT:
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
man1xmoveleft = True
if event.key == pygame.K_RIGHT:
man1xmoveright = True
if event.key == pygame.K_UP:
man1ymoveup = True
if event.key == pygame.K_DOWN:
man1ymovedown = True
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT:
man1xmoveleft = False
if event.key == pygame.K_RIGHT:
man1xmoveright = False
if event.key == pygame.K_UP:
man1ymoveup = False
if event.key == pygame.K_DOWN:
man1ymovedown = False
else:
screen.blit(background, (0,0))
pygame.display.flip()
pygame.time.get_ticks
Fps.tick(framerate)
Use this instead:
import pygame
import sys
pygame.init()
screen = pygame.display.set_mode((400,400))
pygame.display.set_caption("WGD THE GAME")
Fps = pygame.time.Clock()
man1x = 200
man1y = 200
while True:
screen.fill((0, 0, 0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
pygame.draw.circle(screen,(255, 255, 255),(man1x,man1y), 25)
pressed = pygame.key.get_pressed()
if pressed[pygame.K_LEFT]:
man1x -= 1
if pressed[pygame.K_RIGHT]:
man1x += 1
if pressed[pygame.K_UP]:
man1y -= 1
if pressed[pygame.K_DOWN]:
man1y += 1
pygame.display.flip()
Fps.tick(60)
using pygame.key.get_pressed() instead of pygame.event.get() returns the state of the keys at all times, not just when you press it. So you can hold a key down and it will, and when you release it, it will stop. This will also work for diagonal movement. because it checks the state of all keys, it will check up and left so both will be true (pressed) and the character will move diagonally.
https://www.pygame.org/docs/ref/key.html#pygame.key.get_pressed
and then you can take all the event checking and boolean movement flags out. Also, each time through the loop you are calling pygame.init(). This isn't necessary. you also don't need to set the mode each time through the game loop, as well as the caption, and background

Snake problems - Movement

I am having some issues with my code in python, I am making a version of snake, my issue concerns the movement of the snake itself. I have gotten the directions working fine, I just need to make it so that the snake continues moving in the direction it has been told to do so via the key press, I also need to make it so that it is the one block, currently it shows all previous blocks once it has been moved.
import pygame, sys, time, random
from pygame.locals import *
pygame.init()
size = width,height = 480, 480 #16x30,16x30
grey = (128,128,128)
screen = pygame.display.set_mode(size)
icon = pygame.image.load('snakeIcon.png')
newDir = 0
prevDir = 0
FPS = 8
xCoord = 10.0
yCoord = 10.0
#Main Program:
pygame.display.set_caption('Anthony\'s Snake')
pygame.display.set_icon(icon)
screen.fill(grey)
fpsTime = pygame.time.Clock()
gameB = pygame.image.load('gameB.png')
border = {}
createLvl()
snakeH = pygame.image.load('snakeH.png')
snake = {}
refreshScreen()
keyCheck = {'LEFT':bool(0), 'RIGHT':bool(0), 'UP':bool(0), 'DOWN':bool(0), 'ESC':bool(0)}
pygame.mixer.music.load('retroMusik.mp3')
pygame.mixer.music.set_volume(0.5)
pygame.mixer.music.play(-1)
while bool(1):
for i in range(1):
snake[str(len(snake))]=snakeH.get_rect()
x = xCoord
y = yCoord
for i in range(len(snake)):
snake[str(i)].x = x*16
snake[str(i)].y = y*16
for event in pygame.event.get():
if event.type==QUIT:
pygame.quit()
sys.exit()
if event.type == KEYDOWN:
if event.key == K_UP :
keyCheck['UP'] = bool(1)
if event.key == K_DOWN :
keyCheck['DOWN'] = bool(1)
if event.key == K_LEFT :
keyCheck['LEFT'] = bool(1)
if event.key == K_RIGHT :
keyCheck['RIGHT'] = bool(1)
if event.key == K_ESCAPE :
keyCheck['ESC'] = bool(1)
if event.type == KEYUP:
if event.key == K_UP :
keyCheck['UP'] = bool(0)
elif event.key == K_DOWN :
keyCheck['DOWN'] = bool(0)
elif event.key == K_LEFT :
keyCheck['LEFT'] = bool(0)
elif event.key == K_RIGHT :
keyCheck['RIGHT'] = bool(0)
elif event.key == K_ESCAPE :
keyCheck['ESC'] = bool(0)
if keyCheck['UP']:
if prevDir != 'DOWN':
newDir = 'UP'
print('Direction changed to UP')
if keyCheck['DOWN']:
if prevDir != 'UP':
newDir = 'DOWN'
print('Direction changed to DOWN')
if keyCheck['LEFT']:
if prevDir != 'RIGHT':
newDir = 'LEFT'
print('Direction changed to LEFT')
if keyCheck['RIGHT']:
if prevDir != 'LEFT':
newDir = 'RIGHT'
print('Direction changed to RIGHT')
prevDir = newDir
if keyCheck['UP'] == bool(1):
yCoord -= 1
if keyCheck['DOWN'] == bool(1):
yCoord += 1
if keyCheck['LEFT'] == bool(1):
xCoord -= 1
if keyCheck['RIGHT'] == bool(1):
xCoord += 1
refreshScreen()
fpsTime.tick(FPS)
Please be soft on me, I am still new to this. Thank you in advance.
I think your animation doesn't work right because you don't erase (cover with background) the screen before drawing. See this Pygame tutorial for slow and detailed explanation.
Don't use bool(1). Use True and False.
I'm not sure but I think the problem with the snake not moving is either A) you reset your control/movement variable or B) you don't check it every "round"/frame.
I'd really recommend finding some tutorial (or something) and read some Python code by other people, your code could use a lot of improvement (this isn't bad, the important thing is trying to improve).

I keep getting syntax error when using def on python

NOTE: This is a very basic game i am working on as a practice project i get a syntax error when defining explosions ( near the end of the code list... also i am very new to programming so yeah... if anyone could help that would be great i am stuck because i am new so your help is more than appreciated
import pygame, aya, random
from pygame.locals import *
from threading import Timer
#set up pygame
pygame.init()
mainClock = pygame.time.Clock()
#set up the window
WINDOW_WIDTH = 400
WINDOW_HEIGHT = 400
WindowSurface = pygame.display.set_mode ( (WINDOW_WIDTH,
WINDOW_HEIGHT),0)
pygame.display.set_caption("Get Home!!")
#set up color constants
BLACK = (0,0,0)
BLUE = (0, 0, 255)
#set winning text
textFont = pygame.font.sysFont ("impact", 60)
text = textFont.render ("Welcome Home!", True, (193, 0, 0))
#set up the player and breadcrumbs
mapCounter = 0
NEW_GHOST = 20
GHOST_SIZE = 64
playerImage = pygame.image.load("playerimage.jpg")
playerImageTwo = pygame.image.load("playerimage.jpg")
ghostImage = pygame.image.load("ghost image.jpg")
ghostImageTwo = pygame.image.load("ghost image2.jpg")
player = pygame.Rect (300, 100,40, 40)
ghost = []
for i in range(20):
ghost.append(pygame.Rect(random.randint(0, WINDOW_WIDTH - GHOST_SIZE),
random.randint(0, WINDOW_HEIGHT - GHOST_SIZE),
GHOST_SIZE, GHOST_SIZE))
#movement variables
moveLeft = False
moveRight = False
moveDown = False
MOVE_SPEED = 6
#run the game loop
startGame = True
while startgame == True:
#check for quit
for event in pygame.event.get () :
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == KEYDOWN:
#keyboard variables
if event.key ++ K_LEFT:
moveRight = False
moveLeft = True
if event.key ++ K_RIGHT:
moveRight = False
moveLeft = False
if event.key ++ K_UP:
moveUp = True
moveDown = False
if event.key ++ K_DOWN:
moveUp = False
moveDown = True
if event.type == KEYUP:
if event.key == K_ESCAPE:
pygame.quit()
ays.exit()
if event.key == K_LEFT:
moveLeft = False
if event.key == K_RIGHT:
moveRight = False
if event.key == K_UP:
moveUP = False
if event.key == K_DOWN:
moveDown = False
ghostCounter += 1
if ghostcounter >= NEW_GHOST:
#clear ghost array and add new ghost
ghostCounter = 0
ghost.append(pygame.Rect(random.randint(0, WINDOW_WIDTH - GHOST_SIZE),
random.randint(0, WINDOW_HEIGHT - GHOST_SIZE),
GHOST_SIZE, GHOST_SIZE))
#draw black background
windowSurface.fill(BLACK)
#move player
if moveDown and play.bottom < WINDOW_HEIGHT:
player.top += MOVE_SPEED
if moveUp and play.top > 0:
player.top -= MOVE_SPEED
if moveleft and play.left > 0:
player.left -= MOVE_SPEED
if moveRight and play.right < WINDOW_HEIGHT:
player.right += MOVE_SPEED
windowSurface.blit(playerImage, player)
for ghost in ghosts:
windowSurface.blit(ghostImage, ghost)
#check if player has intersected with ghost
for ghost in ghosts[:]:
if player.colliderect(ghost):
windowSurface.blit(ghostImageTwo,ghost
def explosion():
for ghost in ghosts:
if player.colliderect(ghost) and (moveLeft == False and
moveRight == False and moveUp == False and
moveDown == False):
ghosts.remove(ghost)
if player.colliderect(ghost) and (moveLeft == false and
moveRight == False and moveUp == False and moveDown == False):
t = Timer(3, explosion)
t.start()
if len(ghost == 0:
ghostCounter = 0
windowSurface.blit(text, (90, 104))
startgame = False
#draw the window
pygame.display.update()
mainClock.tick(40)
while startgame == False
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
As #BurhanKhalid pointed out, you are missing ) at the end of line 111 (windowSurface.blit(ghostImageTwo,ghost), which is causing the error you noticed.
Additionally, you have numerous syntax errors. You define variables in a different case than you use them (startGame being used as startgame, you forget to close several other )s (line 124, etc). The list goes on.
Python is a forgiving language, but not that forgiving. Find an editor and use it, learn how to debug your code, and stop being sloppy. You will be unable to write code that works otherwise.

Python-Pygame always crashing and Not Responding when running a module in IDLE

I'm quite new to Pygame or even Python, but i know that when something in the isn't right, it displays some text in the Python Shell telling you that there was some error. I've actually encountered many of them and this time, it finally runs and displays the window, but it does not respond. I know there might be some mistakes in my whole code so please feel free to correct me (and please, kindly explain since I'm still new to this stuff).
The code is below, but if it can help, if you'd ask for it, i'll see if i could post the file as well. Anyway, here's the codes:
#import Modules
import os, sys
import pygame
from pygame.locals import *
background_img="C:/Users/JM/Documents/Python/Pygame_Alpha/background_img.jpg"
cursor_img="C:/Users/JM/Documents/Python/Pygame_Alpha/pygameCursor.png"
def load_image(img_file, colorkey=None):
file_pathname = os.path.join("\Users\JM\Documents\Python\Pygame_Alpha",img_file)
try:
image = pygame.image.load(file_pathname).convert_alpha()
except pygame.error, message:
print "Can't load image:", file_pathname
raise SystemExit, message
image = image.convert()
if colorkey is not None:
if colorkey is -1:
colorkey = image.get_at((0,0))
image.set_colorkey(colorkey, RLEACCEL)
return image, image.get_rect()
#Main character's position and movements
char_x,char_y = 0,0
char_go_x,char_go_y = 0,0
#Main char class
class char(pygame.sprite.Sprite):
"""Main Character"""
def __init__(self):
pygame.sprite.Sprite.__init__(self)#call Sprite initializer
self.image, self.rect = load_image("char_img.png", -1)
self.jumping = 0
def update(self):
self.rect.midtop = char_x,char_y
if self.jumping == 1:
self.rect.move_ip(-35,-3)
def char_no_jump(self):
self.jumping = 0
pygame.init()
pygame.display.set_caption("pygame_Alpha")
screen = pygame.display.set_mode((800,480),0,32)
background = pygame.image.load(background_img).convert()
cursor = pygame.image.load(cursor_img).convert_alpha()
char = char()
clock = pygame.time.Clock()
millisec = clock.tick()
sec = millisec/1000.0
char_fall = sec*25
jump = sec*50
#blit the background
screen.blit(background,(0,0))
#Main Loop
while 1:
#Tell pygame not to exceed 60 FPS
clock.tick(60)
#Events
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
#Events triggered when a key/s is/are pressed
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
pygame.quit()
sys.exit()
elif event.key == K_UP or event.key == K_w:
char.jumping = 1
elif event.key == K_DOWN or event.key == K_s:
char_go_y += 1
elif event.key == K_LEFT or event.key == K_a:
char_go_x -= 0.5
elif event.key == K_RIGHT or event.key == K_d:
char_go_x += 0.75
if char_x > 800:
char_x = 0
#Events triggered when a key/s is/are released
if event.type == KEYUP:
if event.key == K_UP or event.key == K_w:
char_go_y += 1
elif event.key == K_DOWN or event.key == K_s:
char_go_y = 0
elif event.key == K_LEFT or event.key == K_a:
char_go_x = 0
if char_x < 0:
char_x = 0
elif event.key == K_RIGHT or event.key == K_d:
char_go_x = 0
if char_x > 700:
char_x = 0
char.update()
while char_y < 200:
char_go_y += char_fall
if char_y > 200:
char_y = 200
#Update values of position of Main Char
char_x += char_go_x
char_y += char_go_y
#Position Variables of Cursor Image, setting its values equal to cursor pos, and blit it to screen
cursor_x,cursor_y = pygame.mouse.get_pos()
cursor_x -= cursor.get_width()/2
cursor_y -= cursor.get_height()/2
screen.blit(cursor,(cursor_x,cursor_y))
pygame.display.update()
Hmm...
while char_y < 200:
char_go_y += char_fall
Unless you have some interesting aliasing I'm not seeing, if char_y < 200 (which it should be at start, it will always be since you're updating char_go_y.
If that's not the issue, would still suggest adding some prints to figure out if it's getting through the loop or not.
is there any error message in idle when you run it? whenever the screen freezes you have something wrong, but its hard to pinpoint what without knowing the error messages. maybe it is trouble opening the picture, you should try putting .convert() at the end of your picture file name, but that is just a guess.
Calling pygame.quit and sys.exit are probably causing issues. Normally you'd never need them in pygame.
Instead of:
#Main Loop
while 1:
#Tell pygame not to exceed 60 FPS
clock.tick(60)
#Events
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
Do this
#Main Loop
done = False
while not done:
clock.tick(60)
for event in pygame.event.get():
if event.type == QUIT:
done = True
if event.type == KEYDOWN:
if event.key == K_ESC:
done = True

Categories