Pygbag Black Screen - python

When ever I run my pygame script in the web build it shows a black screen, I have tried making a new project and it works fine, pls help
here is my code:
import asyncio
import pygame
import sys
import keyboard
pygame.init()
win = pygame.display.set_mode((500, 500,))
jellee = pygame.font.SysFont("assets/Jellee-Bold.otf", 24)
# init pygame here
def player(posX, posY):
global win
character = pygame.image.load("assets/pole.png")
win.blit(character, (posX, posY))
def pause(sizeX, sizeY):
global win
character_image = pygame.image.load("assets/Menu.png")
character = pygame.transform.scale(character_image, (sizeX, sizeY))
win.blit(character, (0, 0))
def button1(sizeX, sizeY, posX, posY):
global jellee
global win
text_image = jellee.render("Resume", False, pygame.Color(254, 164, 22))
text = pygame.transform.scale(text_image, (sizeX - 20, sizeY - 10))
button_image = pygame.image.load("assets/Button1.png")
button = pygame.transform.scale(button_image, (sizeX, sizeY))
win.blit(button, (posX, posY))
win.blit(text, (posX + 10, posY + 5))
def menu(events):
...
# draw
# check events
# change state
...
def play(events):
...
# draw
# check events
# change state
...
game_state = menu
async def main():
global game_state
openmenu = False
playerX = 250
playerY = 250
# or init pygame here
while True:
win.fill("red")
player(playerX, playerY)
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
if not openmenu:
if keyboard.is_pressed("ESCAPE"):
openmenu = True
if keyboard.is_pressed("a"):
playerX -= 10
if keyboard.is_pressed("d"):
playerX += 10
if openmenu:
pause(500, 500)
button1(250, 125, 125, 100)
testmouseX, testmouseY = pygame.mouse.get_pos()
if pygame.mouse.get_pressed() == (1, 0, 0) and testmouseX > 126 and testmouseY > 102 and testmouseX < 369 and testmouseY < 217:
print(testmouseX, testmouseY)
openmenu = False
game_state(pygame.event.get())
pygame.display.update()
await asyncio.sleep(0)
# Closing the game. not strictly required, neither on desktop
pygame.quit()
sys.exit()
asyncio.run( main() )
I tried replacing the while loop and pasting code into working project, nothing seems to work
I need a web build for a game jam I am in(not strictly required but nice to have) does anyone know how to fix this? or a alternative to pygbag?

Related

OOP Pygame player_x variable changing but no changes happen in display

Hi am pretty new to programming in general so this might be a pretty dumb problem. Am currently trying to learn more about OOP by making a game.
while the value of player_x is changing for some reasons its not moving as I expected.
main.py
import pygame, settings, obstacles, npc, player
from utils import *
pygame.init()
window = pygame.display.set_mode((settings.WIDTH, settings.HEIGHT))
FPS = pygame.time.Clock()
player = player.Player(window)
Loop
run = True
while run:
FPS.tick(settings.FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_w:
settings.PLAYER_X -= 5
print(settings.PLAYER_X)
pygame.display.update()
player.py
import pygame, settings
pygame.init()
class Player():
def __init__(self, window) -> None:
pygame.draw.rect(window, settings.OLIVE, (settings.PLAYER_X, settings.PLAYER_Y, settings.PLAYER_WIDTH, settings.PLAYER_HEIGHT)) # (x, y, width, height)
def player_control(self):
pass
settings.py
WIDTH = 1440
HEIGHT = 720
FPS = 60
PLAYER_X = 100
PLAYER_Y = 200
PLAYER_WIDTH = 50
PLAYER_HEIGHT = 50
OLIVE = (136, 196, 23)
To move your player, you need to:
Render your player in every while-loop
Render your player with the updated PLAYER_X
And to achieve it, you need a few modification in your code:
Create a function to render in your player.py and call it in the loop instead of render a player in __init__, which will only be called once.
Reference settings.PLAYER_X only once in the __init__ in player.py and update the variable of the player object when key are pressed.
At the end of every loop, render the player object.
player.py
import pygame, settings
pygame.init()
class Player():
def __init__(self, window) -> None:
self.window = window
self.color = settings.OLIVE
self.X = settings.PLAYER_X
self.Y = settings.PLAYER_Y
self.W = settings.PLAYER_WIDTH
self.H = settings.PLAYER_HEIGHT
self.render()
def render(self):
pygame.draw.rect(self.window, self.color, (self.X, self.Y, self.W, self.H))
def player_control(self):
pass
main.py
import pygame, settings, player
pygame.init()
window = pygame.display.set_mode((settings.WIDTH, settings.HEIGHT))
FPS = pygame.time.Clock()
player = player.Player(window)
run = True
while run:
FPS.tick(settings.FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_w:
player.X -= 5
print(player.X)
window.fill((0, 0, 0))
player.render()
pygame.display.update()

How to stop images from looping through a list

I am making a match-3 style game. I am a beginner with pygame and have managed to randomly generate a board so that each playthrough is different. My only issue at the moment is my tiles seem to be continuously cycling through the list I created for each image. I tried adding a for loop to delete each element as it is being generated but nothing I seem to change is working. Could anybody help? You can find the images I used in a google drive! I appreciate anything!
GoogleDrive
import pygame
from pygame.locals import *
import math
import time
import sys
import random
pygame.init()
# game variables
display_h = 900
display_w = 750
game_row = 12
game_column = 10
background_img = pygame.image.load('pink_background_resized.png')
clock = pygame.time.Clock()
running = True
# build screen and window name
screen = pygame.display.set_mode((display_w, display_h))
pygame.display.set_caption("Jelliez")
screen.fill((255,255,255))
class Tile():
# initialize tiles
def __init__(self, x, y, image, clicked):
self.image = image
self.rect = self.image.get_rect()
self.rect.topleft = (x,y)
self.clicked = clicked
def draw(self):
action = False
# get mouse position
pos = pygame.mouse.get_pos()
# check mouse over and clicked psotion
if self.rect.collidepoint(pos):
if (pygame.mouse.get_pressed()[0] == 1) and (self.clicked == False):
self.clicked = True
action = True
if pygame.mouse.get_pressed()[0] == 0:
self.clicked = False
screen.blit(self.image, (self.rect.x, self.rect.y))
return action
def generateBoard():
screen.blit(background_img, (0,0))
return [[image_list[random.randrange(0, len(image_list))] for i in range (game_column)] for x in range(game_row)]
def showBoard(board):
screen.blit(background_img, (0,0))
rowNum = 0
for row in board:
columnNum = 0
for shape in row:
screen.blit(shape, (70 * columnNum, 64 * rowNum ))
columnNum += 1
rowNum += 1
# add game images
blue_jelly_img = pygame.image.load('blue_jelly.png').convert_alpha()
gray_jelly_img = pygame.image.load('gray_jelly.png').convert_alpha()
green_jelly_img = pygame.image.load('green_jelly.png').convert_alpha()
pink_jelly_img = pygame.image.load('pink_jelly.png').convert_alpha()
red_jelly_img = pygame.image.load('red_jelly.png').convert_alpha()
yellow_jelly_img = pygame.image.load('yellow_jelly.png').convert_alpha()
# create tile istances
blue_jelly = Tile(100, 231, blue_jelly_img, False)
gray_jelly = Tile(100, 231, gray_jelly_img, False)
green_jelly = Tile(100, 231, green_jelly_img, False)
pink_jelly = Tile(100, 231, pink_jelly_img, False)
red_jelly = Tile(100, 231, red_jelly_img, False)
yellow_jelly = Tile(100, 231, yellow_jelly_img, False)
image_list = [blue_jelly_img, gray_jelly_img, green_jelly_img, pink_jelly_img, red_jelly_img, yellow_jelly_img]
for x in range(len(image_list) - 6):
del(image_list[0])
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
gameBoard = generateBoard()
showBoard(gameBoard)
pygame.display.update()
pygame.quit()
The problem is that the board is recreated every frame.
Generate the board once before the application loop. Clear the display and show the board in the application loop:
gameBoard = generateBoard()
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
screen.blit(background_img, (0,0))
showBoard(gameBoard)
pygame.display.update()
pygame.quit()

Creating rect Buttons with Pygame [duplicate]

This question already has answers here:
Pygame mouse clicking detection
(4 answers)
Closed 1 year ago.
I am trying to make buttons using rect in Pygame. I started with the red quit button and checked if a click was inside the boundingbox of the button.
import pygame
"""import nemesis.py;"""
pygame.init();
screen = pygame.display.set_mode((400,300));
pygame.display.set_caption("menu");
menuAtivo = True;
start_button = pygame.draw.rect(screen,(0,0,240),(150,90,100,50));
continue_button = pygame.draw.rect(screen,(0,244,0),(150,160,100,50));
quit_button = pygame.draw.rect(screen,(244,0,0),(150,230,100,50));
pygame.display.flip();
while menuAtivo:
for evento in pygame.event.get():
print(evento);
if evento.type == pygame.MOUSEBUTTONDOWN:
if pygame.mouse.get_pos() >= (150,230):
if pygame.mouse.get_pos() <= (250,280):
pygame.quit();
When using rects in pygame, it's best to use the in built collision detection.
here is an example code on how to do it hope it helps you solve your problem.
Before that though i'd like to mention you should render/draw your objects withing the while loop or the wont show up.
import pygame
import sys
def main():
pygame.init()
clock = pygame.time.Clock()
fps = 60
size = [200, 200]
bg = [255, 255, 255]
screen = pygame.display.set_mode(size)
button = pygame.Rect(100, 100, 50, 50) # creates a rect object
# The rect method is similar to a list but with a few added perks
# for example if you want the position of the button you can simpy type
# button.x or button.y or if you want size you can type button.width or
# height. you can also get the top, left, right and bottom of an object
# with button.right, left, top, and bottom
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
return False
if event.type == pygame.MOUSEBUTTONDOWN:
mouse_pos = event.pos # gets mouse position
# checks if mouse position is over the button
if button.collidepoint(mouse_pos):
# prints current location of mouse
print('button was pressed at {0}'.format(mouse_pos))
screen.fill(bg)
pygame.draw.rect(screen, [255, 0, 0], button) # draw button
pygame.display.update()
clock.tick(fps)
pygame.quit()
sys.exit
if __name__ == '__main__':
main()
Another good way to create buttons on pygame (in python) is by installing the package called pygame_widgets (pip3 install pygame_widgets) on Mac or Linux and (pip install pygame_widgets) on Windows. And also make sure you have pip installed otherwise, it is not going to work.
# Importing Modules
import pygame as pg
import pygame_widgets as pw
# creating screen
pg.init()
screen = pg.display.set_mode((800, 600))
running = True
button = pw.Button(
screen, 100, 100, 300, 150, text='Hello',
fontSize=50, margin=20,
inactiveColour=(255, 0, 0),
pressedColour=(0, 255, 0), radius=20,
onClick=lambda: print('Click')
)
while running:
events = pg.event.get()
for event in events:
if event.type == pg.QUIT:
running = False
button.listen(events)
button.draw()
pg.display.update()
Hope this helps you.
TKS GUYS,
Here is my answer :
import pygame
pygame.init();
screen = pygame.display.set_mode((400,300));
pygame.display.set_caption("menu");
menuAtivo = True;
start_button = pygame.draw.rect(screen,(0,0,240),(150,90,100,50));
continue_button = pygame.draw.rect(screen,(0,244,0),(150,160,100,50));
quit_button = pygame.draw.rect(screen,(244,0,0),(150,230,100,50));
pygame.display.flip();
def startGame():
screen.fill((0,0,0));
pygame.display.flip();
import nemesis.py;
while menuAtivo:
for evento in pygame.event.get():
print(evento);
if evento.type == pygame.MOUSEBUTTONDOWN:
if pygame.mouse.get_pos()[0] >= 150 and pygame.mouse.get_pos()[1] >= 230:
if pygame.mouse.get_pos()[0] <= 250 and pygame.mouse.get_pos()[1] <= 280:
pygame.quit();
if pygame.mouse.get_pos()[0] >= 150 and pygame.mouse.get_pos()[1] >= 90:
if pygame.mouse.get_pos()[0] <= 250 and pygame.mouse.get_pos()[1] <= 140:
startGame();
I think the main problem in your code is that you compare pygame.mouse.get_pos() directly with a Tuple, which is ambiguous. You should try testing x then y separately:
while menuAtivo:
for evento in pygame.event.get():
print(evento);
if evento.type == pygame.MOUSEBUTTONDOWN:
if pygame.mouse.get_pos()[0] >= 150 and pygame.mouse.get_pos()[1] >= 230:
if pygame.mouse.get_pos()[0] <= 250 and pygame.mouse.get_pos()[1] <= 280:
pygame.quit();
I have already provided an answer on the above. Here is my another answer without the module pygame_widgets:
import pygame
import sys
# initializing the constructor
pygame.init()
# screen resolution
res = (720,720)
# opens up a window
screen = pygame.display.set_mode(res)
# white color
color = (255,255,255)
# light shade of the button
color_light = (170,170,170)
# dark shade of the button
color_dark = (100,100,100)
# stores the width of the
# screen into a variable
width = screen.get_width()
# stores the height of the
# screen into a variable
height = screen.get_height()
# defining a font
smallfont = pygame.font.SysFont('Corbel',35)
# rendering a text written in
# this font
text = smallfont.render('quit' , True , color)
while True:
for ev in pygame.event.get():
if ev.type == pygame.QUIT:
pygame.quit()
#checks if a mouse is clicked
if ev.type == pygame.MOUSEBUTTONDOWN:
#if the mouse is clicked on the
# button the game is terminated
if width/2 <= mouse[0] <= width/2+140 and height/2 <= mouse[1] <= height/2+40:
pygame.quit()
# fills the screen with a color
screen.fill((60,25,60))
# stores the (x,y) coordinates into
# the variable as a tuple
mouse = pygame.mouse.get_pos()
# if mouse is hovered on a button it
# changes to lighter shade
if width/2 <= mouse[0] <= width/2+140 and height/2 <= mouse[1] <= height/2+40:
pygame.draw.rect(screen,color_light,[width/2,height/2,140,40])
else:
pygame.draw.rect(screen,color_dark,[width/2,height/2,140,40])
# superimposing the text onto our button
screen.blit(text , (width/2+50,height/2))
# updates the frames of the game
pygame.display.update()
Hope This Helps if pygame_widgets (pip install pygame_widgets) module could not be installed in your python version.
this is my solution
class button():
def __init__(self, color, x,y,width,height, text=''):
self.color = color
self.x = x
self.y = y
self.width = width
self.height = height
self.text = text
def draw(self,win,outline=None):
#Call this method to draw the button on the screen
if outline:
pygame.draw.rect(win, outline, (self.x-2,self.y-2,self.width+4,self.height+4),0)
pygame.draw.rect(win, self.color, (self.x,self.y,self.width,self.height),0)
if self.text != '':
font = pygame.font.SysFont('comicsans', 60)
text = font.render(self.text, 1, (0,0,0))
win.blit(text, (self.x + (self.width/2 - text.get_width()/2), self.y + (self.height/2 - text.get_height()/2)))
def isOver(self, pos):
#Pos is the mouse position or a tuple of (x,y) coordinates
if pos[0] > self.x and pos[0] < self.x + self.width:
if pos[1] > self.y and pos[1] < self.y + self.height:
return True
return False

Pygame keeps crashing when I open it

I've have this dodging aliens game and it's not working. I can get the front begin screen to open but then when I hit enter to start it crashes and freezes. I've tried running it from python.exe instead of just IDLE but in that case it just pops up then closes right down. A few errors popped up the first few times I tried to run it but now there are no errors indicating what might be wrong. It just stops responding. What am I doing wrong here?
import pygame, random, sys
from pygame.locals import *
def startGame():
if event.type == K_ENTER:
if event.key == K_ESCAPE:
sys.exit()
return
def playerCollision():
for a in aliens:
if playerRect.colliderect(b['rect']):
return True
return False
pygame.init()
screen = pygame.display.set_mode((750,750))
clock = pygame.time.Clock()
pygame.display.set_caption('Dodge the Aliens')
font = pygame.font.SysFont(None, 55)
playerImage = pygame.image.load('')
playerRect = playerImage.get_rect()
alienImage = pygame.image.load('')
drawText('Dodge the Aliens!', font, screen, (750 / 3), (750 / 3))
drawText('Press ENTER to start.', font, screen, (750 / 3) - 45, (750 / 3) + 65)
pygame.display.update()
topScore = 0
while True:
aliens = []
score = 0
playerRect.topleft = (750 /2, 750 - 50)
alienAdd = 0
while True:
score += 1
pressed = pygame.key.get_pressed()
if pressed[pygame.K_LEFT]: x -=3
if pressed[pygame.K_RIGHT]: x += 3
if pressed[pygame.K_ESCAPE]: sys.exit()
alienAdd += 1
if alienAdd == addedaliens:
aliendAdd = 0
alienSize = random.randint(10, 40)
newAlien = {'rect': pygame.Rect(random.randint(0, 750 - alienSize), 0 -alienSize, alienSize, alienSize), 'speed': random.randint(1, 8), 'surface':pygame.transform.scale(alienImage, (alienSize, alienSize)), }
aliens.append(newAlien)
for a in aliens[:]:
if a['rect'].top > 750:
aliens.remove(a)
screen.fill(0,0,0)
drawText('Score %s' % (score), font, screen, 10, 0)
screen.blit(playerImage, playerRect)
for a in aliens:
screen.blit(b['surface'], b['rect'])
pygame.display.update()
if playerCollision(playerRect, aliens):
if score > topScore:
topScore = score
break
clock.tick(60)
drawText('Game Over!', font, screen, (750 / 3), ( 750 / 3))
drawText('Press ENTER To Play Again.', font, screen, ( 750 / 3) - 80, (750 / 3) + 50)
pygame.display.update()
startGame()
Here's my new code after modifying it some
import pygame, random, sys
from pygame.locals import*
alienimg = pygame.image.load('C:\Python27\alien.png')
playerimg = pygame.image.load('C:\Python27\spaceship.png')
def playerCollision(): # a function for when the player hits an alien
for a in aliens:
if playerRect.colliderect(b['rect']):
return True
return False
def screenText(text, font, screen, x, y): #text display function
textobj = font.render(text, 1, (255, 255, 255))
textrect = textobj.get_rect()
textrect.topleft = (x,y)
screen.blit(textobj, textrect)
def main(): #this is the main function that starts the game
pygame.init()
screen = pygame.display.set_mode((750,750))
clock = pygame.time.Clock()
pygame.display.set_caption('Dodge the Aliens')
font = pygame.font.SysFont("monospace", 55)
pressed = pygame.key.get_pressed()
aliens = []
score = 0
alienAdd = 0
addedaliens = 0
while True: #our while loop that actually runs the game
for event in pygame.event.get(): #key controls
if event.type == KEYDOWN and event.key == pygame.K_ESCAPE:
sys.exit()
elif event.type == KEYDOWN and event.key == pygame.K_LEFT:
playerRect.x -= 3
elif event.type == KEYDOWN and event.key == pygame.K_RIGHT:
playerRect.x += 3
playerImage = pygame.image.load('C:\\Python27\\spaceship.png').convert() # the player images
playerRect = playerImage.get_rect()
playerRect.topleft = (750 /2, 750 - 50)
alienImage = pygame.image.load('C:\\Python27\\alien.png').convert() #alien images
alienAdd += 1
pygame.display.update()
if alienAdd == addedaliens: # randomly adding aliens of different sizes and speeds
aliendAdd = 0
alienSize = random.randint(10, 40)
newAlien = {'rect': pygame.Rect(random.randint(0, 750 - alienSize), 0 -alienSize, alienSize, alienSize), 'speed': random.randint(1, 8), 'surface':pygame.transform.scale(alienImage, (alienSize, alienSize)), }
aliens.append(newAlien)
for a in aliens[:]:
if a['rect'].top > 750:
aliens.remove(a) #removes the aliens when they get to the bottom of the screen
screen.blit(screen, (0,0))
screenText('Score %s' % (score), font, screen, 10, 0)
screen.blit(playerImage, playerRect)
for a in aliens:
screen.blit(b['surface'], b['rect'])
pygame.display.flip()
if playerCollision(playerRect, aliens):
if score > topScore:
topScore = score
break
clock.tick(60)
screenText('Game Over!', font, screen, (750 / 6), ( 750 / 6))
screenText('Press ENTER To Play Again.', font, screen, ( 750 / 6) - 80, (750 / 6) + 50)
pygame.display.update()
main()
I still see several issues with your code and I think you're trying to do too much at once for the very beginning. Try to keep it as simple as possible. Try creating a display and draw some image:
import pygame
pygame.init()
display = pygame.display.set_mode((750, 750))
img = pygame.image.load("""C:\\Game Dev\\alien.png""")
display.blit(img, (0, 0))
pygame.display.flip()
You'll have to adjust the img path of course. Running this you should either get an explicit Error (which you should then post in another thread) or see your img on the screen. BUT the program will not respond as there's no event handling and no main loop at all.
To avoid this, you could introduce a main loop like:
import sys
import pygame
pygame.init()
RESOLUTION = (750, 750)
FPS = 60
display = pygame.display.set_mode(RESOLUTION)
clock = pygame.time.Clock()
img = pygame.image.load("""C:\\Game Dev\\alien.png""")
while True: # <--- game loop
# check quit program
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# clear the screen
display.fill((0, 0, 0))
# draw the image
display.blit(img, (0, 0))
# update the screen
pygame.display.flip()
# tick the clock
clock.tick(FPS)
This should result in a program that displays the same img over and over, and it can be quit properly using the mouse. But still it's like a script, and if someone imported this, it would execute immediately, which is not what we want. So let's fix that as well and wrap it all up in a main function like this:
import sys
import pygame
#defining some constants
RESOLUTION = (750, 750)
FPS = 60
def main(): # <--- program starts here
# setting things up
pygame.init()
display = pygame.display.set_mode(RESOLUTION)
clock = pygame.time.Clock()
img = pygame.image.load("""C:\\Game Dev\\alien.png""")
while True: # <--- game loop
# check quit program
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# clear the screen
display.fill((0, 0, 0))
# draw the image
display.blit(img, (0, 0))
# update the screen
pygame.display.flip()
# tick the clock
clock.tick(FPS)
if __name__ == "__main__":
main()
The 'if name == "main":' ensures that the program does not execute when it's imported.
I hope this helps. And remember: Don't try too much all at once. Take small steps, one after another, and try to keep the control over your program. If needed, you can even put a print statement after every single line of code to exactly let you know what your program does and in what order.

Making image move straight with pygame

I have to move the rectangular object straight through the pygame window. I have tried some code with pygame. The code is
import pygame
from itertools import cycle
pygame.init()
screen = pygame.display.set_mode((300, 300))
s_r = screen.get_rect()
player = pygame.Rect((100, 100, 50, 50))
timer = pygame.time.Clock()
movement = "straight"
x = 0
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
raise
if movement == 'straight':
x += 50
screen.fill(pygame.color.Color('Black'))
pygame.draw.rect(screen, pygame.color.Color('Grey'), player)
pygame.display.flip()
timer.tick(25)
Here the image didnt moves. What I need is that the image must be moved in a straight way.
x is adding, but that does not affect player, which actually affects the drawing of the rectangle.
import pygame
from itertools import cycle
pygame.init()
screen = pygame.display.set_mode((300, 300))
s_r = screen.get_rect()
timer = pygame.time.Clock()
movement = "straight"
x = 0
player = pygame.Rect((x, 100, 50, 50))
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
raise
if movement == 'straight':
x += 10
player = pygame.Rect((x, 100, 50, 50))
if x >= 300:
x = 0
screen.fill(pygame.color.Color('Black'))
pygame.draw.rect(screen, pygame.color.Color('Grey'), player)
pygame.display.flip()
timer.tick(25)
You need to adjust the player rectangle each time you change x. From http://www.pygame.org/docs/ref/rect.html, you can see that the first two arguments are "left" and "top". So, if you want to the rectangle to move from left to right, you'll want something like this:
player = pygame.Rect((100 + x, 100, 50, 50))
pygame.draw.rect(screen, pygame.color.Color('Grey'), player)
import pygame
BLACK = pygame.color.Color('Black')
GREY = pygame.color.Color('Grey')
pygame.init()
screen = pygame.display.set_mode((300, 300))
screen_rect = screen.get_rect()
timer = pygame.time.Clock()
movement = "straight"
player = pygame.Rect(0, 100, 50, 50) # four aguments in place of tuple (,,,)
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if movement == 'straight':
player.x += 10
if player.x >= 300: # check only when `player.x` was changed
player.x = 0
screen.fill(BLACK)
pygame.draw.rect(screen, GREY, player)
pygame.display.flip()
timer.tick(25)
BTW:
don't use raise to exit program.
use readable variable - not s_r but screen_rect
you don't need x - you have player.x
you can create rectangle only once
remove repeated empty lines when you add code to question

Categories

Resources