I'm new to the python language and pygame, what I'm trying to do is create a function which will convert the data from a 2D black and white image into areas where the player can or cannot move. In other words: I want to take a maze that I've drawn in a graphics program and use pygame to interpolate black and white images so that a player class object may move wherever the surface contains bytes of (255, 255, 255) and cannot move where the surface contains bytes of (0, 0, 0) First I need to be able to get the data. What I have so far is.
def GetMaze(M):
Get = M.get_view('2')
Sep = Get.raw
In this function M represents a black and white bitmap of a maze ('Maze.bmp'). I know what I have so far will grab the bytes in an unstructured block of bytes. What I need this function to do is iterate the bytes into lists of floors where the bytes equal (255, 255, 255) and walls where they equal (0, 0, 0) but I can't figure out how to get it to that point.
Using code found here http://www.petercollingridge.co.uk/book/export/html/550:
import sys, pygame
from pygame.locals import *
screen = pygame.display.set_mode((200,200))
imgsurf = pygame.Surface((200,200))
def init():
global mazearray
mazeimg = pygame.image.load("maze.bmp")
mazearray = pygame.surfarray.array3d(mazeimg)
def update():
global mazearray
screen.fill((0,0,0))
imgsurf.fill((255,255,255))
for x in range(200):
for y in range(200):
if mazearray[x][y][0] == 0 and mazearray[x][y][1] == 0 and mazearray[x][y][2] == 0:
pygame.draw.rect(imgsurf, (0,0,0), (x,y,2,2))
screen.blit(imgsurf, (0,0))
pygame.display.flip()
if __name__=="__main__":
init()
update()
while True:
events = pygame.event.get()
for event in events:
if event.type == pygame.QUIT:
sys.exit()
keys=pygame.key.get_pressed()
if keys[K_q]:
sys.exit()
Obviously you will need to change the sizes for your maze. Also, I hand drew the maze in GIMP, so the lines were wonky, hence the maze it drew was wonky.
Related
I'm making this space invaders type game with pygame and I have this issue where, enemies keep spawning while the time is stopped. I need a fix that removes those enemies from the window ( I use .blit to display my surfaces) right after the time is started again.
E.G:
def draw_on_window(enemy):
window.blit(enemy)
def main():
# Command that clears the window of "Enemy surfaces" somehow?? :
# window.remove(enemy) ??
run = True
while run:
draw_on_window(blue_enemy)
#game
In pygame you don't remove something from a surface like the window. window.blit(image) draws an image to the window surface.
To clear everything you have to fill the window black.
In pygame you do the following things your main loop normally:
fill the screen black window.fill((0, 0, 0))
draw everything again
handle all events (eg. QUIT, MOUSEBUTTONDOWN...)
let the clock tick at a specified frame rate
enemy_coords = [(5, 9), (3, 4)] # just an example
clock = pygame.time.Clock()
max_fps = 60
while run:
window.fill((0, 0, 0)) # fill the window with black
for coord in enemy_coords:
window.blit(enemy_image, coord)
do_events...
pygame.display.update()
clock.tick(max_fps)
All you need to do is manage the enemies in a list and remove the enemies from the list (see How to remove items from a list while iterating?). Draw only the enemies that are in the list.
e.g.: represent the enemies by pygame.Rect objects and remove them when they are out of the window:
def draw_on_window(enemies):
for enemy_rect in enemies:
window.blit(enemy_image, enemy_rect)
def main():
enemies = []
enemies.append(pygame.Rect(x1, y1, w, h))
enemies.append(pygame.Rect(x2, y2, w, h))
run = True
while run:
# [...]
for enemy in enemies[:]:
if not enemies.colliderect(window.get_rect())
enemies.remove(enemy)
# [...]
draw_on_window(enemies)
pygame.dispaly.update()
You can remove all items from a list with the clear() method:
enemies.clear()
This is my first real code project. I am trying to create a Crash gambling project for a math project at School.
My current problem is that when I flip my arc it draws 2 separate arcs. I don't know why it does this but if anyone can help it would be much appreciated.
Here is my code:
import pygame
from math import sin, cos, radians
grid = pygame.image.load('grid3.jpg')
wn = pygame.display.set_mode((600, 600))
wn2 = pygame.display.set_mode((600, 600))
clock = pygame.time.Clock()
r = 600
a = 0
b = 0
def x_y(r, i, a, b):
return (int(r * cos(radians(i)) + a), int(r * sin(radians(i)) + b))
for i in range(0, 90, 1):
clock.tick(30)
pygame.draw.line(wn, (255, 255, 255), x_y(r, i, a, b), x_y(r, i+1, a, b), 10)
wn2.blit(wn, (0,0))
wn.blit(grid,(0,0))
wn2.blit(pygame.transform.rotate(wn2, -90), (0, 0))
wn = pygame.transform.flip(wn2, True, False)
pygame.display.update()
When you draw onto a display Surface, it won't remove the other existing elements. Take this code as an example:
import pygame
from pygame.locals import *
screen = pygame.display.set_mode((320, 240))
pygame.draw.rect(screen, (0, 255, 0), Rect(50, 20, 100, 100))
pygame.draw.rect(screen, (255, 0, 0), Rect(120, 100, 100, 100))
pygame.display.flip() # same as pygame.display.update() (with no arguments)
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
exit()
When executing this, you will see 2 squares appear, the second one being drawn not preventing the first one from still appearing, even though you updated the screen.
As a display surface is also a transparent surface, blitting a display Surface onto another will not erase its content.
To do that, you can call the Surface.fill function.
A few optional (but some I recommend) improvements to your code:
Implement a game loop to your game/simulation to namely get the user events and preventing your game from constantly crashing after a while
Use pygame.display.flip() instead of pygame.display.update() (the latter is useful when you want to only update part of the screen)
You are creating 2 screen surfaces, but that's not possible. wn and wn2 are referring to the same surface. Use pygame.Surface for creating other surfaces.
Try to leave the main display surface as it is, and work with other surfaces rather than changing the entire screen by transforming it, as this can be confusing when debugging.
I hope that helped!
I'm building a pong game trying to get better at programming but Im having trouble moving the ball. When the move_right method is called the ellipse stretches to the right instead of moving to the right. I've tried putting the ball variable in the init method but that just makes it not move at all even though the variables should be changing on account of the move_right method. I have also tried setting the x and y positions as parameters in the Ball class,but that just stretches it also.
I don't understand why when I run the following code the ball I'm trying to move stretches to the right instead of moves to the right. Can someone explain why this is happening? I have tried everything I can think of but i can't get it to do what I want.
import pygame,sys
import random
class Ball:
def __init__(self):
self.size = 30
self.color = light_grey
self.x_pos = width/2 -15
self.y_pos = height/2 -15
self.speed = 1
#self.ball = pygame.Rect(self.x_pos, self.y_pos,self.size,self.size)
def draw_ball(self):
ball = pygame.Rect(self.x_pos, self.y_pos,self.size,self.size)
pygame.draw.ellipse(screen,self.color,ball)
def move_right(self):
self.x_pos += self.speed
class Player:
def __init__(self,x_pos,y_pos,width,height):
self.x_pos = x_pos
self.y_pos = y_pos
self.width = width
self.height = height
self.color = light_grey
def draw_player(self):
player = pygame.Rect(self.x_pos,self.y_pos,self.width,self.height)
pygame.draw.rect(screen,self.color,player)
class Main:
def __init__(self):
self.ball=Ball()
self.player=Player(width-20,height/2 -70,10,140)
self.opponent= Player(10,height/2-70,10,140)
def draw_elements(self):
self.ball.draw_ball()
self.player.draw_player()
self.opponent.draw_player()
def move_ball(self):
self.ball.move_right()
pygame.init()
size = 30
clock = pygame.time.Clock()
pygame.display.set_caption("Pong")
width = 1000
height = 600
screen = pygame.display.set_mode((width,height))
bg_color = pygame.Color('grey12')
light_grey = (200,200,200)
main = Main()
#ball = pygame.Rect(main.ball.x_pos, main.ball.y_pos,main.ball.size,main.ball.size)
#player = pygame.Rect(width-20,height/2 -70,10,140)
#opponent = pygame.Rect(10,height/2-70,10,140)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
#ball = pygame.Rect(main.ball.x_pos, main.ball.y_pos,main.ball.size,main.ball.size)
#pygame.draw.rect(screen,light_grey,player)
#pygame.draw.rect(screen,light_grey,opponent)
#pygame.draw.ellipse(screen,light_grey,ball)
main.draw_elements()
main.move_ball()
main.ball.x_pos += main.ball.speed
pygame.display.flip()
clock.tick(60)
You have to clear the display in every frame with pygame.Surface.fill:
while True:
# [...]
screen.fill(0) # <---
main.draw_elements()
main.move_ball()
main.ball.x_pos += main.ball.speed
pygame.display.flip()
# [...]
Everything that is drawn is drawn on the target surface. The entire scene is redraw in each frame. Therefore the display needs to be cleared at the begin of every frame in the application loop. The typical PyGame application loop has to:
handle the events by either pygame.event.pump() or pygame.event.get().
update the game states and positions of objects dependent on the input events and time (respectively frames)
clear the entire display or draw the background
draw the entire scene (blit all the objects)
update the display by either pygame.display.update() or pygame.display.flip()
I need to store a Circle in a variable but after I've done that it has turned into a rect
circle_1 = pygame.draw.circle(screen, (0, 0, 0), (300, 300), 30)
Print(circle_1)
the print returns
<rect(270, 270, 60, 60)>
but I can't work with that.
My circle is predefined but it won't show it on the canvas, here is an example of the problem
> import pygame, sys
>
>
> pygame.init() screen = pygame.display.set_mode((600, 600))
> predefined_circle = pygame.draw.circle(screen,(0, 0, 0),(300, 300), 30)
>
> def update():
> screen.fill((200, 0, 0))
> while 1:
> for event in pygame.event.get():
> if event.type == pygame.QUIT: sys.exit()
> # It shows my circle if I dirctly tip pygame.draw.circle(screen,(0, 0, 0),(300, 300), 30) into it
> predefined_circle
> pygame.display.update()
>
> update()
So that you can better relate to what I'm trying to achieve here is the code of what I'm doing but it is not necessary to read as I've already tried to explain it as best as I can above.
Please note the comments should explain everything that the block of code below it is doing.
# Creating the canvas which can paint any wanted Object from another class
class Canvas:
# Initialising the screen and setting all needed variables
def __init__(self, painting):
pygame.init()
self.screen_size = (600, 600)
self.background = (25, 255, 255)
self.screen = pygame.display.set_mode(self.screen_size)
self.paint = painting
# Let the user set the name of the canvas
def set_screen_name(self):
return self.screen
# Draw the everything you want to
def update(self):
# Paint the canvas
self.screen.fill(self.background)
# Make the game be quittable
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT: sys.exit()
# Draw the defined Circle and then update the Canvas
# it only draws a circle if directly tip pygame.draw.circle(surface, color, position, radius)
self.paint
pygame.display.update()
# Draw any circle you like
class Cir:
# Get all the required Information's to Draw a circle
def __init__(self, canvas, what_color, position, radius, line=0):
self.can = canvas
self.color = what_color
self.pos = position
self.r = radius
self.line = line
self.cir = None
# Create the circle with the acquired Information's
def create(self):
self.cir = pygame.draw.circle(self.can, self.color, self.pos, self.r, self.line)
return self.cir
# So far there is no Surface for the Cir class
# And there is no Object that cloud be painted for the Canvas class
# I initialise a canvas instance without anything that needs to be painted
get_surface = Canvas(None)
# Now I can access set_screen_name from the Canvas class and give the surface a name
# Which the Cir class can now use as a surface
screen = get_surface.set_screen_name()
c1 = pygame.draw.circle(screen, (0,0,0), (300, 300), 30)
print(c1)
# I'm initialising a circle
init_circle = Cir(screen, (0, 255, 0), (300, 300), 30)
# Create the initialised circle
circle_1 = init_circle.create()
# Give the Canvas class the created circle
paint = Canvas(circle_1)
# Draw the circle
paint.update()
My circle turns to a rect.
Actually, no, it doesn't. As per the documentation for those drawing functions, the intent of the calls is to draw something immediately, not to give you an object you can draw later:
Draw several simple shapes to a Surface.
From analysis of your question, it sounds like you believe that you are storing the act of drawing the circle so that it can be done later. That is not the case. Instead, what you are doing is actually drawing the circle and saving the result of that drawing action - evaluating the result later on will not actually draw, or redraw, the circle.
So, if the draw function is not returning something for later drawing, what is it returning? That can also be found in the above-mentioned documentation:
The functions return a rectangle representing the bounding area of changed pixels.
In other words, it's telling you the smallest rectangle that was changed by the drawing action - this will be a square with sides the same length as the diameter and centered around the same point.
Obviously, the authors of PyGame thought this information may be handy for some purpose, just not the purpose of redrawing the circle :-)
One way to do what you're trying to achieve would be to simply have a function to draw the "predefined" circle and call that instead of trying to evaluate the rectangle returned from a previous call.
I am working on this project to move a sprite, but I can't seem to figure out how to move a sprite to the right as well as move it downwards. Any thoughts?
Here is my program:
import pygame
import time
import sys
pygame.init()
# Set up window
screen = pygame.display.set_mode((320, 240))
# Load an image
rocket = pygame.image.load("rocket.png")
rocketrect = rocket.get_rect()
x_coord = 0
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT: sys.exit()
screen.fill((0,0,0))
screen.blit(rocket, rocketrect)
pygame.display.flip()
x_coord += 1
rocketrect.centerx = x_coord
In your method of mving the sprite, you change the coordinatses (x) and then assign it to the centerx of the images rectangle. If you want to keep this kind of method (changing and assigning), and also move the image down, you will need to give a y value. For example
# Define y variable
y_coord = 0
# Your code
…
y_coords += 1
rocketrect.centery = y_coord
This works similarly to how you moved your x_coords, but in total, the program is a bit basic and is not how programmers (or at least me) usually code. Another person might used a tuple for the location, along with making a rocket class. There are also some other ways to move the sprite, such as the .move() or .move_ip() that I would suggest. But it's up to you.