Trying to build a simple game using turtle graphics and Python.
I created enemies and put them in the while loop so that whenever they touch the boundaries on either sides they move down by 40 units. I put the value of y co-ordinate in a variable u. But when I run the code it says:
nameError: 'u' not defined
Help!!
#!/usr/bin/python
import turtle
import os
#screen
wn = turtle.Screen()
wn.bgcolor("black")
wn.title("spaceinvaders")
#boarder
border_pen = turtle.Turtle()
border_pen.speed(0)
border_pen.color("white")
border_pen.penup()
border_pen.setposition(-300,-300)
border_pen.pendown()
border_pen.pensize(3)
for side in range(4):
border_pen.fd(600)
border_pen.lt(90)
border_pen.hideturtle()
#player
player = turtle.Turtle()
player.color("blue")
player.shape("triangle")
player.penup()
player.speed(0)
player.setposition(0,-250)
player.setheading(90)
playerspeed = 15
#enemy
enemy = turtle.Turtle()
enemy.color("red")
enemy.shape("circle")
enemy.penup()
enemy.speed(0)
enemy.setposition(-200,250)
enemyspeed = 2
#move
def move_left():
x = player.xcor()
x -= playerspeed
if x < -280:
x = - 280
player.setx(x)
def move_right():
x = player.xcor()
x += playerspeed
if x > 280:
x = +280
player.setx(x)
#key bindings
turtle.listen()
turtle.onkey(move_left,"Left")
turtle.onkey(move_right,"Right")
#mainloop
while True:
#enemy moves
x = enemy.xcor()
x += enemyspeed
enemy.setx(x)
if enemy.xcor() < -280:
u = enemy.ycor()
u -= 40
enemyspeed *= -1
enemy.sety(u)
if enemy.xcor() > 280:
u = enemy.ycor()
u -= 40
enemyspeed *= -1
enemy.sety(u)
delay = raw_input("press enter to finish")
Even with the incorrect loop indentation that #downshift noted, you shouldn't have gotten the error you quoted as u is set immediately before being used.
The main problem I see with your code design is your use of while True: which should not occur in an event driven program. Rather, the enemy's motion should be handled via a timer event and program control turned over to mainloop() so that other events can fire correctly. I've reworked your program along those lines below and made some style and optimizaion tweaks:
import turtle
# player motion event handlers
def move_left():
turtle.onkey(None, 'Left') # avoid overlapping events
player.setx(max(-280, player.xcor() - playerspeed))
turtle.onkey(move_left, 'Left')
def move_right():
turtle.onkey(None, 'Right')
player.setx(min(280, player.xcor() + playerspeed))
turtle.onkey(move_right, 'Right')
# enemy motion timer event handler
def move_enemy():
global enemyspeed
# enemy moves
enemy.forward(enemyspeed)
x = enemy.xcor()
if x < -280 or x > 280:
enemy.sety(enemy.ycor() - 40)
enemyspeed *= -1
wn.ontimer(move_enemy, 10)
# screen
wn = turtle.Screen()
wn.bgcolor('black')
wn.title('spaceinvaders')
# border
STAMP_SIZE = 20
border_pen = turtle.Turtle('square', visible=False)
border_pen.shapesize(600 / STAMP_SIZE, 600 / STAMP_SIZE, 3)
border_pen.pencolor('white')
border_pen.stamp()
# player
player = turtle.Turtle('triangle', visible=False)
player.color('blue')
player.speed('fastest')
player.penup()
player.setheading(90)
player.setposition(0, -250)
player.showturtle()
playerspeed = 15
# enemy
enemy = turtle.Turtle('circle', visible=False)
enemy.color('red')
enemy.speed('fastest')
enemy.penup()
enemy.setposition(-200, 250)
enemy.showturtle()
enemyspeed = 2
# key bindings
turtle.onkey(move_left, 'Left')
turtle.onkey(move_right, 'Right')
turtle.listen()
wn.ontimer(move_enemy, 100)
turtle.mainloop() # for Python 3 use wn.mainloop()
This should hopefully smooth your path to adding more functionality to your game.
Related
I am currently trying to make a game animation based off the game plant versus zombies. When the zombie moves across the screen and contacts the plant, the plant sprite gets saved in a list called plants_eaten_list. The zombie also stops moving to the left. After a 1 second delay (when the plants_eaten_event is triggered), the plant loses 10 health points. When the plant's health reaches 0, the plant sprite dies through the plant.kill() command.
The code for setting up the timer (pygame.time.set_timer(plants_eaten_event, 1000) needs to be inside the main while loop in order to constantly check for a plant within the plants_eaten_list. However, my problem is that for every refresh of the while loop, the timer for the plants_eaten_event gets reset back to 1 second, so the plants_eaten_event never occurs.
Is there any way I can structure the logic of this program to alleviate this issue?
I do not own copyright to any of these images, and the images are intended only for private use.
The zombie image is downloaded from http://plantsvszombies.wikia.com/wiki/Zombie/Gallery?file=Regular_Zombie.png
The plant image is downloaded from http://plantsvszombies.wikia.com/wiki/File:Peashooter.png
Here is my code:
import pygame
import random
BLACK = (0,0,0)
WHITE = (255,255,255)
RED = (255,0,0)
BLUE = (0,0,255)
GREEN = (0,255,0)
pygame.init()
borders_sound = pygame.mixer.Sound("bump.wav")
class Zombie(pygame.sprite.Sprite):
def __init__(self, x, y):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load("Regular_Zombie.png").convert()
self.image.set_colorkey(WHITE)
# Make our top-left corner the passed-in location.
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
# -- Attributes
# Set speed vector
self.change_x = -1
self.change_y = 0
def changespeed(self, x, y):
""" Change the speed of the player"""
self.change_x += x
self.change_y += y
def move(self):
""" Find a new position for the player"""
#self.change_x = -1
self.rect.x += self.change_x
#print(self.rect.x)
#times = 0
if self.rect.x < 0:
self.rect.x = 0
def eatplant(self,plant):
pygame.time.set_timer(plants_eaten_event,6000)
self.change_x = 0
plant.health = plant.health - 10
class Plant(pygame.sprite.Sprite):
def __init__(self, x, y):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load("Peashooter.png").convert()
self.image.set_colorkey(BLUE)
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
self.alive = True
self.health = 60
screen_width = 700
screen_height = 400
screen = pygame.display.set_mode([screen_width, screen_height])
all_sprites_list = pygame.sprite.Group()
plants_list = pygame.sprite.Group()
zombies_list = pygame.sprite.Group()
zombie1 = Zombie(690, 15)
plant1 = Plant(300,15)
all_sprites_list.add(zombie1)
all_sprites_list.add(plant1)
plants_list.add(plant1)
zombies_list.add(zombie1)
done = False
clock = pygame.time.Clock()
plants_eaten_event = pygame.USEREVENT + 1
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
# If plant.health = 0 at the end of the timer, the plant is eaten.
# If plant.health != 0 at the end of the timer, the entire event
# must happen again in the while loop until the health = 0
elif event.type == plants_eaten_event:
print("Zombie 1 ate plant 1")
zombie1.eatplant(plant)
# Set timer equal to 0 until another plant gets eaten or zombie continues eating current plant
pygame.time.set_timer(plants_eaten_event, 0)
if plant.health == 0:
plant.alive = False
plant.kill()
zombie1.change_x = -1
zombie1.move()
elif event.type == zombie_eaten_plant_event:
zombie1.change_x = -1
zombie1.move()
print("Zombie 1 is eating plant")
pygame.time.set_timer(zombie_eaten_plant_event, 0)
screen.fill(WHITE)
zombie1.move()
if times == 0 and zombie1.rect.x <= 0:
times = times + 1
borders_sound.play()
all_sprites_list.draw(screen)
all_sprites_list.update()
# I set the do kill command in spritecollide command to False because I
# needed to delay the plants that were eaten before they were removed. They
# will be removed after six seconds(symbolize zombies eating plants). Aftera
# a period of time, then I will create a loop that will loop through all plants
# in the plants_eaten_list and use .kill() . I will need to create a separate
# collision function that will stall the zombies until the plants are killed.
plants_eaten_list = pygame.sprite.spritecollide(zombie1,plants_list,False)
# I changed the delay to 6 seconds, and plant 1 still died instantly. The zombie
# stayed frozen in place for 6 seconds before teh 2nd plant was instantly destroyed
for plant in plants_eaten_list:
# If I remove this, plant1 is not killed, even though
# there is the same code within the plants_eaten_event function.
if plant1.health == 0:
plant1.kill()
# The while loop loops so fast that the timer doesnot have a chance to
# finish its countdown before it restarts again. Will I need some kind of a threading
# module to prevent the timers from restarting until they end?
pygame.time.set_timer(plants_eaten_event, 1000)
for plant_eaten in plants_eaten_list:
borders_sound.play()
clock.tick(60)
pygame.display.flip()
pygame.quit()
my problem is that for every refresh of the while loop, the timer for the plants_eaten_event gets reset back to 1 second, so the plants_eaten_event never occurs.
That happens because the rect of the zombie still collides with the rect of the plant in the next frame, spritecollide returns the list with the colliding plant and the for plant in plants_eaten_list: loop where you call set_timer gets executed again each frame.
The first thing you need to do is to set the zombie.rect.left position to plant.rect.right after the first collision, so that the sprites don't collide anymore in the next frame:
for plant in plants_eaten_list:
zombie1.change_x = 0 # Stop the zombie.
# Move the rect so that it doesn't touch the plant's rect anymore.
zombie1.rect.left = plant.rect.right
if plant1.health <= 0:
plant1.kill()
pygame.time.set_timer(plants_eaten_event, 1000)
borders_sound.play()
However, once you start adding more zombies, the code will break because you use the zombie1 and the plant variable (which depends on the for plant in plants_eaten_list: loop) in the event loop, so it will work only for this zombie and the last collided plant. Unfortunately, it's not possible to send more information than the event type with pygame.time.set_timer, otherwise you could attach the specific zombie and plant to the event in order to handle them in the event loop.
An alternative solution would be to give each zombie an own timer attribute (just a number) which you can update in their update methods.
So when the zombie touches a plant, I start the timer by setting it to 1 (second) and then decrement it by the delta time (the time needed for the last frame) each frame. I also stop the zombie self.change_x = 0, move the rect back self.rect.left = plant.rect.right and store a reference to the plant because we need it to reduce its health when the timer is finished.
Once the timer is <= 0 the zombie starts to move again, takes a bite of the plant, the sprites touch again and the timer is started anew.
import pygame
WHITE = (255,255,255)
BLUE = (0,0,255)
GREEN = (0,255,0)
class Zombie(pygame.sprite.Sprite):
def __init__(self, x, y):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((30, 50))
self.image.fill(BLUE)
self.rect = self.image.get_rect(topleft=(x, y))
self.change_x = -1
self.timer = 0 # Timer for the attacks.
self.plant = None # Currently attacked target.
def update(self, dt):
"""Update the zombie."""
if self.timer != 0:
self.timer -= dt
if self.timer <= 0: # Move if the timer is inactive.
self.change_x = -1
# Check if a plant is touching and eat it.
if self.plant is not None:
self.plant.health -= 10
print('Health', self.plant.health)
if self.plant.health <= 0:
print('Eaten')
self.plant.kill()
self.plant = None
self.timer = 0
self.rect.x += self.change_x
if self.rect.x < 0:
self.rect.x = 0
def eatplant(self, plants):
print('Play sound')
self.change_x = 0 # Stop the zombie.
self.timer = 1 # Start the timer.
for plant in plants:
self.plant = plant # Store a reference to the plant.
# Move the zombie back, so that the sprites
# don't collide anymore.
self.rect.left = plant.rect.right
class Plant(pygame.sprite.Sprite):
def __init__(self, x, y):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((30, 50))
self.image.fill(GREEN)
self.rect = self.image.get_rect(topleft=(x, y))
self.health = 30
pygame.init()
screen = pygame.display.set_mode([700, 400])
# No need to assign the sprites to variables.
plants = pygame.sprite.Group(Plant(500, 15), Plant(350, 115))
zombies = pygame.sprite.Group(Zombie(690, 15), Zombie(690, 115))
all_sprites = pygame.sprite.Group(plants, zombies)
clock = pygame.time.Clock()
dt = 0
done = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
# Pass the delta time to the update methods of the sprites.
all_sprites.update(dt)
# groupcollide returns a dictionary of the collided zombies and plants.
plants_eaten = pygame.sprite.groupcollide(zombies, plants, False, False)
for zombie, collided_plants in plants_eaten.items():
zombie.eatplant(collided_plants)
screen.fill(WHITE)
all_sprites.draw(screen)
dt = clock.tick(60) / 1000 # Time in seconds since last tick.
pygame.display.flip()
pygame.quit()
Under #Trees i had written a for loop. The first loop works fine, x = 0.
The second loop, however, although x = 300, the shape doesn't move from its original spot.
What this is supposed to do is change the x coordinates of my shape after the 2nd "for loop" is finished creating the leaves on my tree.
import pygame
from pygame.locals import *
pygame.init()
window = pygame.display.set_mode([640,600])
# color reference
white = (255,245,238)
blue = (65,105,225)
green = (154,205,50)
grey = (105,105,105)
lightblue = (176,196,222)
brown = (93, 64, 55)
darkgreen = (0, 121, 107)
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
# Sky
window.fill((135,206,250))
# Pond
pygame.draw.rect (window, (blue), Rect((0,510),(640,100)))
# House base
pygame.draw.rect (window, (white), Rect((100,310),(200,190)))
# Grass
pygame.draw.rect (window, (green), Rect((0,500),(440,100)))
# Windowsill
pygame.draw.rect (window, (grey), Rect((200,420),(80,10)))
# Window/Door
pygame.draw.rect (window, (lightblue), Rect((206,360),(70,60)))
pygame.draw.rect (window, (lightblue), Rect((115,410),(70,90)))
# Doorknob
pygame.draw.circle(window, (grey), (125, 459), 5, 0)
# Roof
pygame.draw.polygon (window, (grey), ((100,310),(203,260),(299,310)))
# Trees
for trees in range(3):
y = 0
x = 0
pygame.draw.rect (window, (brown), Rect((40 + x,470),(20,30)))
for leaves in range(3):
pygame.draw.polygon (window, (darkgreen), ((10 + x,470 - y),(50 + x,410 - y),(90 + x,470 - y)))
y = y + 40
if leaves == 2:
x = x + 300
pygame.display.flip()
My goal is to have a tree on both sides of the house, using a for loop.
A little help would be tremendously appreciated.
This seemed to work
# Trees
y = 0
x = 0
for trees in range(2):
pygame.draw.rect (window, (brown), Rect((40 + x,470),(20,30)))
for leaves in range(3):
pygame.draw.polygon (window, (darkgreen), ((10 + x,470 - y),(50 + x,410 - y),(90 + x,470 - y)))
y = y + 40
if leaves == 2:
x = x + 300
y = y - 120
The for loop kept changing the x and y values back to zero, so i set the range of the leaves back to 3 and moved the x and y accumulator variables above the loop.
You actually don't need the y and x variables above the for loops, since you can pass an optional "step" argument to range. So for example list(range(0, 81, 40)) gives you [0, 40, 80].
for x in range(0, 301, 300):
pygame.draw.rect (window, (brown), Rect((40 + x,470),(20,30)))
for y in range(0, 81, 40):
pygame.draw.polygon(
window, darkgreen,
((10+x, 470-y), (50+x, 410-y), (90+x, 470-y)))
I'm writing a menu for a simple game, so I thought to use a while loop to let the user choose his wanted option by clicking on it. While my program works properly until this loop, it does not continue when reaching the line of the following loop:
pygame.mouse.set_visible(True) # This is the last line processed.
while True: # This line ist not processed.
(curx,cury)= pygame.mouse.get_pos()
screen.blit(cursor,(curx-17,cury-21))
pygame.display.flip()
# rating values of the cursor position and pressed mouse button below:
(b1,b2,b3) = pygame.mouse.get_pressed() #getting states of mouse buttons
if (b1 == True or b2 == True or b3 == True): # "if one mouse button is pressed"
(cx,cy) = pygame.mouse.get_pos()
if (px <= curx <= px+spx and py <= cury <= py+spy):
return (screen,0)
elif (ox <= curx <= ox+sox and oy <= cury <= oy+soy):
return (screen,1)
elif (cx <= curx <= cx+scx and cy <= cury <= cy+scy):
return (screen,2)
else:
return (screen,3)
time.sleep(0.05)
I have already checked such things like wrong indentation.
BTW my interpreter (python.exe, Python 2.7.11) always does not respond after reaching this line of the
while True:
Because the question was asked in a deleted answer:
I had a print("") between every above shown line to find the problematic line.
As I wrote 4 lines above: The interpreter (and with it the debugger and bug report) has crashed without any further response.
The whole code of this function is:
# MAIN MENU
def smenu (screen,res,menuimg,cursor):
#preset:
x,y = res
click = False
print("preset") # TEST PART
# Fontimports, needed because of non-standard font in use
menu = pygame.image.load("menu.png")
playGame = pygame.image.load("play.png")
options = pygame.image.load("options.png")
crdts = pygame.image.load("credits.png")
print("Fontimport") # TEST PART
#SIZETRANSFORMATIONS
# setting of sizes
smx,smy = int((y/7)*2.889),int(y/7)
spx,spy = int((y/11)*6.5),int(y/11)
sox,soy = int((y/11)*5.056),int(y/11)
scx,scy = int((y/11)*5.056),int(y/11)
print("setting of sizes") # TEST PART
# setting real size of text 'n' stuff
menu = pygame.transform.scale(menu,(smx,smy))
playGame = pygame.transform.scale(playGame,(spx,spy))
options = pygame.transform.scale(options, (sox,soy))
crdts = pygame.transform.scale(crdts, (scx,scy))
cursor = pygame.transform.scale(cursor,(41,33))
print("actual size transformation") # TEST PART
#DISPLAY OF MENU
# fixing positions
mx, my = int((x/2)-((y/7)/2)*2.889),10 # position: 1. centered (x) 2. moved to the left for half of the text's length 3. positioned to the top(y), 10 pixels from edge
px, py = int((x/2)-((y/11)/2)*6.5),int(y/7+10+y/10) # position: x like above, y: upper edge -"menu"'s height, -10, - height/10
ox, oy = int((x/2)-((y/11)/2)*5.056),int(y/7+10+2*y/10+y/11)
cx, cy = int((x/2)-((y/11)/2)*5.056),int(y/7+10+3*y/10+2*y/11)
print("fixing positions") # TEST PART
# set to display
#screen.fill(0,0,0)
screen.blit(menuimg,(0,0))
screen.blit(menu,(mx,my))
screen.blit(playGame,(px,py))
screen.blit(options,(ox,oy))
screen.blit(crdts,(cx,cy))
pygame.display.flip()
print("set to display") # TEST PART
# request for input (choice of menu options)
pygame.mouse.set_visible(True)
print("mouse visible") # TEST PART last processed line
while (True):
print("While-loop") # TEST PART
curx,cury = pygame.mouse.get_pos()
screen.blit(cursor,(curx-17,cury-21))
pygame.display.flip()
# decision value below
(b1,b2,b3) = pygame.mouse.get_pressed() # getting mouse button's state
if (b1 == True or b2 == True or b3 == True): # condition true if a buton is pressed
(cx,cy) = pygame.mouse.get_pos()
if (px <= curx <= px+spx and py <= cury <= py+spy):
return (screen,0)
elif (ox <= curx <= ox+sox and oy <= cury <= oy+soy):
return (screen,1)
elif (cx <= curx <= cx+scx and cy <= cury <= cy+scy):
return (screen,2)
else:
return (screen,3)
time.sleep(0.05)
print("directly skipped")
Would comment but can't because of low rep.
The problem might be, that you're returning a value to a while loop outside a function.
Although it's a bit weird that your interpreter/IDE isn't giving you the correct Error message for it.
I think that the problem is in the following line of your code:
if (b1 == True or b2 == True or b3 == True):
This condition never becomes true so you are stuck into the while loop without your function returning anything.
Thanks for looking at my question and helping me out. I have a user controlled sprite that should cause the screen to shift around the sprite's position, kinda like an old Gameboy Pokemon game, yet that does not happen. Instead my sprite is stuck inside a box of coordinates that I used to help define parameters for background shift. This is the code I believe is causing this:
# Shift world left (-x)
if player.rect.right >= 510:
diff = player.rect.right - 510
player.rect.right = 510
current_level.shift_world_x(-diff)
# Shift world right (+x)
if player.rect.left <= 130:
diff = 130 - player.rect.left
player.rect.left = 130
current_level.shift_world_x(diff)
# Shift world up (-y)
if player.rect.top <= 100:
diff = 100 - player.rect.top
player.rect.top = 100
current_level.shift_world_y(diff)
# Shift world down (y)
if player.rect.bottom >= 380:
diff = player.rect.bottom - 380
player.rect.bottom = 380
current_level.shift_world_y(-diff)
If I put a # next to player.rect.right = 510, or any of the other three varients, my sprite can move freely, yet the screen will not shift.
Zip file with all assets is here:
https://www.dropbox.com/s/3g2w0mv1fuupetl/DoneGeon.zip?dl=0
The entirety of my code is as follows:
import pygame
"""---Global Constants---"""
# Colors
BLACK = (0, 0, 0)
# Screen Variables
screen_x = 720
screen_y = 480
# Background variables
back_x = 0
back_y = -243
back_x_change = 0
back_y_change = 0
class Player(pygame.sprite.Sprite):
"""---User Controled Character---"""
# Methods
def __init__(self):
"""---Contructor Function---"""
# Call parent's constructor
pygame.sprite.Sprite.__init__(self)
# Load player image
self.image = pygame.image.load("player.png").convert()
# Set referance to image "hit box"
self.rect = self.image.get_rect()
# Set speed of player
self.change_x = 0
self.change_y = 0
def update(self):
"""---Move the Player---"""
# Move left/right
self.rect.x += self.change_x
# Move up/down
self.rect.y += self.change_y
# User controlled movements
def go_left(self):
self.change_x = -3
def go_right(self):
self.change_x = 3
def go_up(self):
self.change_y = -3
def go_down(self):
self.change_y = 3
def stop_x(self):
self.change_x = 0
def stop_y(self):
self.change_y = 0
class Barrier(pygame.sprite.Sprite):
"""---Barriers that prevent player from passing---"""
def __init__(self,width,height):
""" Barrier constructor """
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface([width,height])
self.image.fill(BLACK)
self.rect = self.image.get_rect()
class Level():
"""---All levels will spawn from this generic class---"""
def __init__(self,player):
""" Needed for when sprites collide with player """
self.barrier_list = pygame.sprite.Group()
self.enemy_list = pygame.sprite.Group()
self.player = player
# Distance world has been shifted left/right
self.world_shift_x = 0
# Background image
background_base = None
background_layera = None
# Distance world has been shifted up/down
self.world_shift_y = 0
def update(self):
""" Update everything on level """
self.barrier_list.update()
self.enemy_list.update()
def draw(self,screen):
""" Draw everything on level """
# Draw barriers
self.barrier_list.draw(screen)
# Draw the base layer
screen.blit(self.background_base,(back_x,back_y))
# Draw all sprites
self.enemy_list.draw(screen)
# Draw Layer A
screen.blit(self.background_layera,(back_x,back_y))
def shift_world_x(self,shift_x):
""" When character moves left/right, everything must follow """
# Track shift amount
self.world_shift_x += shift_x
# Go through all list and shift
for barrier in self.barrier_list:
barrier.rect.x += shift_x
for enemy in self.enemy_list:
enemy.rect.x += shift_x
def shift_world_y(self,shift_y):
""" When character moves up/down, everything must follow """
# Track shift amount
self.world_shift_y += shift_y
# Go through all list and shift
for barrier in self.barrier_list:
barrier.rect.y += shift_y
for enemy in self.enemy_list:
enemy.rect.y += shift_y
class Level_1(Level):
"""---Forest 1---"""
def __init__(self,player):
""" Create the level """
# Call parent constructor
Level.__init__(self,player)
self.level_limit_x = -1912
self.level_limit_y = 1080
# Make background
self.background_base = pygame.image.load("base1.png").convert()
self.background_layera = pygame.image.load("layera1.png").convert()
self.background_layera.set_colorkey(BLACK)
# List with w, h, x = 32, y = 32 of barriers
# Remove comment to activate-> level = []
# Go through the list above and add barriers
# Remove comment to activate-> for barriers in level:
def main():
"""---Main Program---"""
pygame.init()
# Set screen size and caption
size = (screen_x,screen_y)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("DoneGeon")
# Create Player
player = Player()
# Create all levels
level_list= []
level_list.append(Level_1(player))
# Set current level
current_level_no = 0
current_level = level_list[current_level_no]
# Add all sprites
active_sprite_list = pygame.sprite.Group()
# Add player
player.level = current_level
player.rect.x = 360
player.rect.y = 240
active_sprite_list.add(player)
# Loop until closed
done = False
# Screen update rate
clock = pygame.time.Clock()
# -------- Main Program Loop -----------
while not done:
"""---Main event loop---"""
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
"""---User Controls---"""
# Key Pressed
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
player.go_left()
if event.key == pygame.K_RIGHT:
player.go_right()
if event.key == pygame.K_UP:
player.go_up()
if event.key == pygame.K_DOWN:
player.go_down()
# Key Released
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
player.stop_x()
if event.key == pygame.K_UP or event.key == pygame.K_DOWN:
player.stop_y()
"""---Game Logic---"""
# Update Player
active_sprite_list.update()
# Update items in level
current_level.update()
# Shift world left (-x)
if player.rect.right >= 510:
diff = player.rect.right - 510
player.rect.right = 510
current_level.shift_world_x(-diff)
# Shift world right (+x)
if player.rect.left <= 130:
diff = 130 - player.rect.left
player.rect.left = 130
current_level.shift_world_x(diff)
# Shift world up (-y)
if player.rect.top <= 100:
diff = 100 - player.rect.top
player.rect.top = 100
current_level.shift_world_y(diff)
# Shift world down (y)
if player.rect.bottom >= 380:
diff = player.rect.bottom - 380
player.rect.bottom = 380
current_level.shift_world_y(-diff)
"""---Draw below here---"""
current_level.draw(screen)
active_sprite_list.draw(screen)
pygame.display.flip()
clock.tick(60)
pygame.quit()
if __name__ == "__main__":
main()
Thank you for any advice!
I think you'll find this easier to track down if you log the changes in player x and world x. Often with games small changes aren't visible so logging is the only way to monitor what's happening in the game loop.
I haven't tested this but my bet is that you've got a negative in the wrong place. This:
def shift_world_x(self,shift_x):
""" When character moves left/right, everything must follow """
suggests that if the player right edge moves past the world right edge the world right edge should extend to match the player but this code does the reverse:
if player.rect.right >= 510:
diff = player.rect.right - 510
player.rect.right = 510
current_level.shift_world_x(-diff)
If the player.right moves to 513 diff will be 3 so shift_world_x will be called with -3, moving the world box left to 507. Player right will then be set to 510 so the player right will still be outside the box the next loop. This suggests that the world image will drift to the left with the player sprite stuck at the right edge but it sounds like it's trapped against the right edge (I'm focussing on one edge because the logic is the same for all).
If you log player.rect.right and world.rect.right in the if shown above you should see the values as they change and get a better feel for what the game logic is doing.
I am new to Python and Pygame. I want to have a screen in pygame with multiple copies of the same images moving around independently. I have tried to write it as a class and then call instances of it inside the while loop, but it doesn't work. Could someone show how can i basically do such a thing using a class?
I've tried to keep everything simple
Example:
import pygame
pygame.init()
WHITE = (255,255,255)
BLUE = (0,0,255)
window_size = (400,400)
screen = pygame.display.set_mode(window_size)
clock = pygame.time.Clock()
class Image():
def __init__(self,x,y,xd,yd):
self.image = pygame.Surface((40,40))
self.image.fill(BLUE)
self.x = x
self.y = y
self.x_delta = xd
self.y_delta = yd
def update(self):
if 0 <= self.x + self.x_delta <= 360:
self.x += self.x_delta
else:
self.x_delta *= -1
if 0 <= self.y + self.y_delta <= 360:
self.y += self.y_delta
else:
self.y_delta *= -1
screen.blit(self.image,(self.x,self.y))
list_of_images = []
list_of_images.append(Image(40,80,2,0))
list_of_images.append(Image(160,240,0,-2))
done = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
screen.fill(WHITE)
for image in list_of_images:
image.update()
pygame.display.update()
clock.tick(30)
pygame.quit()
Each image can be called individually from the list and moved by simply changing Image.x/y to whatever you want