make sprite crouch in current position python - python-3.x

Hi i'm making a fighting game to get some practice with pygame but I have run into a problem with crouching/ducking. When I press the down button it goes back to its original location then ducks. If you need more info to help i will provide.
import pygame
import random
display_height = 600
display_width = 1000
dis_screen = pygame.display.set_mode((display_width, display_height))
FPS = 30
clock = pygame.time.Clock()
img = pygame.image.load('foo.png')
crouchimg = pygame.image.load('crouchimg.png')
# Simple player object
class Player(object):
def __init__(self, x, y, image):
self.x = x
self.y = y
self.image = image
# Method to draw object
def draw(self):
dis_screen.blit(self.image, (self.x, self.y))
# Method to move object
def move(self, speedx, speedy):
self.x += speedx
self.y += speedy
class MainRun(object):
def __init__(self, displayw, displayh):
self.dw = displayw
self.dh = displayh
self.Main()
def Main(self):
# Put all variables up here
stopped = False
x_move = 0
y_move = 0
p1_y_loc = 200
p1_x_loc = 200
x = pygame.Rect().x
greg = Player(p1_x_loc, p1_y_loc, img)
# Main Loop
while not stopped:
print(x)
dis_screen.fill((255, 255, 255)) # Tuple for filling display... Current is white
# Event Tasking
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
y_move = 0
x_move = 5
elif event.key == pygame.K_LEFT:
y_move = 0
x_move = -5
elif event.key == pygame.K_UP:
y_move = -5
x_move = 0
elif event.key == pygame.K_DOWN:
p1_y_loc = 300
p1_x_loc = 0
greg = Player(p1_x_loc, p1_y_loc, crouchimg)
if event.type == pygame.KEYUP:
if event.key == pygame.K_DOWN:
p1_y_loc = 200
greg = Player(p1_x_loc, p1_y_loc, img)
if event.key == pygame.K_UP:
y_move = 0
if event.key == pygame.K_RIGHT or event.key == pygame.K_LEFT:
x_move = 0
greg.move(x_move, y_move)
greg.draw()
pygame.display.update()
clock.tick(FPS)
pygame.quit()
quit()
run = MainRun(display_width, display_height)
run.Main()

That's because when you're pressing the down key you're creating a new player at the x-position p1_x_loc (which you've set to 0) and y-position p1_y_loc (which you've set to 300). So when the player crouches it also moves it to (0, 300) no matter the position the player currently is.
A way to solve this would be to just change the player's image, and not create a completely new player. You can do it this way, player.image = crouchimg instead of greg = Player(p1_x_loc, p1_y_loc, crouchimg). And when the player gets up you just change the image again: player.image = img
And if you have to change the players' y-position when crouching you could do it the same way: player.y = 200 and player.y = 300.

Related

in my incomplete version of space invaders, the 1 bullet is not being fired.. but no error message is shown. can somebody review it suggest a solution [duplicate]

This question already has answers here:
How can i shoot a bullet with space bar?
(1 answer)
How do I stop more than 1 bullet firing at once?
(1 answer)
Closed 6 days ago.
import pygame
import random
# get the window
pygame.init
# window var declarataion and parameters
window = pygame.display.set_mode((800, 600))
background = pygame.image.load("space bg.png")
# characters
# spaceship
playerImg = pygame.image.load("spaceship-2.png")
playerX = 360
playerY = 535
playerX_change = 0
#enemy
enemyImg = pygame.image.load("space-invaders.png")
enemyX = random.randint(0, 536)
enemyY = random.randint(0, 120)
enemyX_change = 1
enemyY_change = 30
#bullet
bulletImg = pygame.image.load("space-invaders.png")
bulletX = playerX
bulletY = 535
bulletX_change = 0
bulletY_change = -100
bullet_state = "ready"
# character functions
#spaceship
def player(x, y):
window.blit(playerImg, (playerX, playerY))
def enemy(x, y):
window.blit(enemyImg, (enemyX, enemyY))
def fire_bullet(x, y):
global bullet_state
if bullet_state == "fire":
window.blit(bulletImg, (playerX + 16, playerY + 10))
# full loop
running = True
while running:
# to change the color of window
window.fill((255, 255, 255))
window.blit(background, (0, 0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# check if key pressed is right or left and executes events accordingly
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
playerX_change = -1
if event.key == pygame.K_RIGHT:
playerX_change = 1
if event.key == pygame.K_SPACE:
fire_bullet(playerX, bulletY)
bulletY -= bulletY_change
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
playerX_change = 0
# enemy movement
# loops the enemy movement
enemyX += enemyX_change
# to change the enemy direction when border of window hit
if enemyX <= 0:
enemyY += enemyY_change
enemyX_change = 1
elif enemyX >= 736:
enemyY += enemyY_change
enemyX_change = -1
# calling function
playerX += playerX_change
if playerX <= 0:
playerX = 0
elif playerX >= 736:
playerX = 736
player(playerX, playerY)
enemy(enemyX, enemyY)
pygame.display.update()
i tried to make the bullet move along the y axis of the spaceship by adding the code shown below into the keystroke code section:
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
playerX_change = -1
if event.key == pygame.K_RIGHT:
playerX_change = 1
if event.key == pygame.K_SPACE:
fire_bullet(playerX, bulletY)
bulletY -= bulletY_change
but no error message is shown, the bullet is not being shown, but everything else works perfectly.. like the invader moving along the x axis infinitely, and the spaceship can still be controlled by my arrow key.. only thing that doesn't work is the bullet not firing from the spaceship.. and I can't seem to make it work with this code.. if someone could tell me where I went wrong, it would be of tons of help, and I've been on this problem for days now.. so
it would save me a lot of time in the future. thanks

Space Invaders bug pygame

After finally beeing able to make multiple enemies in the game I confronted myself with the most annoying bug ever. I have multiple enemies, a space ship and I can even shoot bullets, but right after I added the enemies to the game and followed the exact same steps as show in this video, the background is gone for some reason, what made the speed of the player character, of the enemies and the bullet went like crazy. Plus, the sprites are duplicating themselves and wont go away, and the only think that I can think is "What the hell am I doing wrong??" because I feel like I can't even follow the steps and copy the code from a video (btw I'm not receiving any error messages). Anyways, here's the full game code.
import pygame
import random
import math
# Initiate pygame
pygame.init()
# Display the game window
screen = pygame.display.set_mode((800, 600))
# Title and Icon
pygame.display.set_caption('Space Invaders')
icon = pygame.image.load('icon.png')
pygame.display.set_icon(icon)
# Background
background = pygame.image.load('background.png')
# Player
playerSprite = pygame.image.load('player.png')
playerX = 370
playerY = 480
playerX_change = 0
# Enemies
enemySprite = []
enemyX = []
enemyY = []
enemyX_change = []
enemyY_change = []
num_of_enemies = 6
for i in range(num_of_enemies):
enemySprite.append(pygame.image.load('enemy.png'))
enemyX.append(random.randint(0, 736))
enemyY.append(random.randint(50, 150))
enemyX_change.append(4)
enemyY_change.append(40)
# Bullet
bulletSprite = pygame.image.load('bullet.png')
bulletX = 0
bulletY = 480
bulletY_change = 10
# When bullet_state = 'ready', you can't see the bullet on the screen
# When bullet_state = 'fire', the bullet is currently moving
bullet_state = 'ready'
score = 0
def player(x, y):
screen.blit(playerSprite, (x, y))
def enemy(x, y, i):
screen.blit(enemySprite[i], (x, y))
def fire_bullet(x, y):
global bullet_state
bullet_state = 'fire'
screen.blit(bulletSprite, (x + 16, y + 10))
def isCollision(enemyX, enemyY, bulletX, bulletY):
distance = math.sqrt((math.pow(enemyX - bulletX, 2)) + (math.pow(enemyY - bulletY, 2)))
if distance < 27:
return True
else:
return False
# Game Loop
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# If a key is pressed, check if it's the right or left arrow key
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
playerX_change = -5
if event.key == pygame.K_RIGHT:
playerX_change = 5
if event.key == pygame.K_SPACE:
if bullet_state == 'ready':
bulletX = playerX
fire_bullet(playerX, bulletY)
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
playerX_change = 0
# Player movement
playerX += playerX_change
# Prevents the player from going off the border
if playerX <= 0:
playerX = 0
elif playerX >= 736:
playerX = 736
# Enemies movement
for i in range(num_of_enemies):
enemyX[i] += enemyX_change[i]
if enemyX[i] <= 0:
enemyX_change[i] = 4
enemyY[i] += enemyX_change[i]
elif enemyX[i] >= 736:
enemyX_change[i] = -4
enemyY[i] += enemyY_change[i]
# Collision
collision = isCollision(enemyX[i], enemyY[i], bulletX, bulletY)
if collision:
bulletY = 480
bullet_state = 'ready'
score += 1
print(score)
enemyX[i] = random.randint(0, 736)
enemyY[i] = random.randint(50, 150)
enemy(enemyX[i], enemyY[i], i)
# Bullet movement
if bulletY <= 0:
bulletY = 480
bullet_state = 'ready'
if bullet_state == 'fire':
fire_bullet(bulletX, bulletY)
bulletY -= bulletY_change
player(playerX, playerY)
pygame.display.update()
the background is gone for some reason
Of course, because the background is never blit to screen.
the sprites are duplicating themselves and wont go away,
That's because you don't draw the background.
blit the background in the main application loop, before the objects of the scene are drawn:
while running:
# [...]
screen.blit(background, (0, 0))
# Enemies movement
for i in range(num_of_enemies):
# [...]
the speed of the player character, of the enemies and the bullet went like crazy.
Use pygame.time.Clock() to control the frames per second.
clock = pygame.time.Clock()
running = True
while running:
clock.tick(60)
# [...]
Another (less sophisticated) possibility, which is probably use in the tutorial is to use pygame.time.delay():
running = True
while running:
pygame.time.delay(10)
# [...]

I made a game where blocks fall and you have to dodge it but can't get the hitboxes right

The hitbox seems to be on the left side of the cube, so it feels like the game is ending without me even hitting anything. I want to make it that the hitbox is exactly on the red rectangle, so that it's obvious that the black rectangle had hit you.
the up and down controls are just for future movement option if needed.
here's the code
import pygame as pg,pygame
import random
import sys
pygame.init()
WIDTH = 1000
HEIGHT = 800
# Positions, sizes
SPEED = 10
MIDDLE = [500, 400]
score = 0
player_size = 90
player_pos = [WIDTH/2, HEIGHT-2*player_size]
playerX_move = 0
playerY_move = 0
enemy_size = 50
enemy_pos = [random.randint(0,WIDTH - enemy_size), 30]
enemy_list = [enemy_pos]
# Colors
WHITE = [255, 255, 255]
GREY = [25, 25, 25]
BLUE = [65,105,225]
BLACK = [0,0,0]
GREEN = [65,255,105]
RED = [255,0,0]
# -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
screen = pygame.display.set_mode((WIDTH,HEIGHT))
game_over = False
clock = pygame.time.Clock()
def drop_enemies(enemy_list):
delay = random.random()
if len(enemy_list) < 10 and delay < 0.1:
x_pos = random.randint(0,WIDTH-enemy_size)
y_pos = 30
enemy_list.append([x_pos, y_pos])
def draw_enemies(enemy_list):
for enemy_pos in enemy_list:
pygame.draw.rect(screen,BLACK, (enemy_pos[0], enemy_pos[1], enemy_size, enemy_size))
def update_enemy_positions(enemy_list, score):
for idx, enemy_pos in enumerate(enemy_list):
if enemy_pos[1] >= 0 and enemy_pos[1] < HEIGHT:
enemy_pos[1] += SPEED
else:
enemy_list.pop(idx)
score += 1
return score
def collision_check(enemy_list, player_pos):
for enemy_pos in enemy_list:
if detect_collision(enemy_pos, player_pos):
return True
return False
def detect_collision(player_pos, enemy_pos):
p_x = player_pos[0]
p_y = player_pos[1]
e_x = enemy_pos[0]
e_y = enemy_pos[1]
if (e_x >= p_x and e_x < (p_x + player_size)) or (p_x >= e_x and p_x < (e_x+enemy_size)):
if (e_y >= p_y and e_y < (p_y + player_size)) or (p_y >= e_y and p_y < (e_y+enemy_size)):
return True
return False
while not game_over:
player_pos[0] += playerX_move
player_pos[1] += playerY_move
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
playerX_move = -5
if event.key == pygame.K_RIGHT:
playerX_move = 5
# if event.key == pygame.K_UP:
# playerY_move = -5
# if event.key == pygame.K_DOWN:
# playerY_move = 5
if event.key == pygame.K_a:
playerX_move = -15
if event.key == pygame.K_d:
playerX_move = 15
# if event.key == pygame.K_w:
# playerY_move = -15
# if event.key == pygame.K_s:
# playerY_move = 15
if event.key == pg.K_SPACE:
print("SPACE")
if event.type == pygame.KEYUP:
if event.key == pygame.K_a or event.key == pygame.K_d or event.key == pygame.K_s or event.key == pygame.K_w:
playerX_move = 0
playerY_move = 0
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT or event.key == pygame.K_DOWN or event.key == pygame.K_UP:
playerX_move = 0
playerY_move = 0
screen.fill(BLACK)
drop_enemies(enemy_list)
score = update_enemy_positions(enemy_list,score)
if collision_check(enemy_list, player_pos):
game_over = True
draw_enemies(enemy_list)
pygame.draw.rect(screen, RED, (player_pos[0], player_pos[1], 90, 90))
clock.tick(30)
pygame.display.update()
I would recommend using a list of pygame.Rects instead of a List with the positions of your enemies. This would also allow you to use pygame.Rect.colliderect() instead of your detect_collision function.
I've also linked the Pygame Docs.

Powerbar decrease script, pygame

I'm trying to create a "powerbar."
In the following code I can press left & right key to increase the bar, and the prg terminates when the bar_start_width > 400 px.
I would like the "powerbar" to decrease while bar_start_width > 0. So, if you stop to press the buttons, the bar will slowly decrease until bar_start_width > 0.
With my code it is slowly decreasing bar_start_width, but not updating the display. The while loop also continues running.
Here is full code:
import time
import random
import pygame
import time
import pygame
pygame.init()
display_width = 800
display_height = 600
black = (0, 0, 0)
white = (255, 255, 255)
gameDisplay = pygame.display.set_mode((display_width, display_height))
clock = pygame.time.Clock()
def powerbar(thingx, thingy, thingw, thingh, color):
pygame.draw.rect(gameDisplay, color, [thingx, thingy, thingw, thingh])
def game_quit():
pygame.quit()
quit()
def game_loop():
decrease_speed = -1
bar_start_width = 0
bar_x = 100
bar_y = 100
bar_height = 50
bar_color = black
x_change = 0
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
gameDisplay.fill(white) # the background color before img
# Should change so you can ONLY press right after left (or opposite)
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x_change = 5
if event.key == pygame.K_RIGHT:
x_change = 5
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
x_change = 0
bar_start_width += x_change
# Draw powerbar
powerbar(bar_x, bar_y, bar_start_width, bar_height, bar_color)
if bar_start_width > 10:
while True:
bar_start_width += decrease_speed
time.sleep(0.5)
print(bar_start_width) #See output in terminal
if bar_start_width == 0:
break
if bar_start_width > 400:
game_quit()
pygame.display.update()
clock.tick(60)
game_loop()
pygame.quit()
quit()
I have tried also to think in terms of a for loop to solve my problems but after long time of trying out different things this is the best I can come up with.
Can anyone help, or link me to a similar discussion?
Thanks!
I'm not sure why you have a nested while loop in the main while loop. If I understand you correctly, you want to decrease the width every frame if (not while) the width is greater than 0. Just remove the while loop and the time.sleep call and decrease the width if bar_start_width > 0:.
import pygame
pygame.init()
black = (0, 0, 0)
white = (255, 255, 255)
gameDisplay = pygame.display.set_mode((800, 600))
clock = pygame.time.Clock()
def game_loop():
decrease_speed = -1
bar_start_width = 0
bar_x = 100
bar_y = 100
bar_height = 50
x_change = 0
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
return
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x_change = 5
elif event.key == pygame.K_RIGHT:
x_change = 5
elif event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
x_change = 0
bar_start_width += x_change
if bar_start_width > 0:
bar_start_width += decrease_speed
if bar_start_width <= 0: # Set it to the minimum width of 1.
bar_start_width = 1
if bar_start_width > 400:
print('> 400')
gameDisplay.fill(white)
# Draw powerbar
pygame.draw.rect(gameDisplay, black, (bar_x, bar_y, bar_start_width, bar_height))
pygame.display.update()
clock.tick(60)
game_loop()
pygame.quit()
I've rearranged a few things, because the game logic and the event loop were mixed. You should generally try to separate the event handling, game logic and the rendering.

TypeError, having issues defining certain things

Ok So, I'm making a simple game in python and pygame, where you're a spaceship and have to dodge meteors. But after adding in the meteor and writing the code to get it to spawn randomly and move down the screen. I had issues using the code tags as well, I'd do Ctrl + K and post my code inside the space provided and it gave me the code error. Sorry about that, here's my links (not the best way to do it I know, I couldn't get the code tags to work.)
My Error:
Traceback (most recent call last):
File "C:\Users\fredd_000\Desktop\Pygame_Script.py", line 127, in <module>
game_loop()
File "C:\Users\fredd_000\Desktop\Pygame_Script.py", line 98, in game_loop
things(thing_startx, thing_starty, thing_width, thing_height, black)
File "C:\Users\fredd_000\Desktop\Pygame_Script.py", line 28, in things
pygame.draw.circle(gameDisplay, color,[thingx, thingy, thingw, thingh])
TypeError: function takes at least 4 arguments (3 given)
My code where the error occurs:
def things(thingx, thingy, thingw, thingh, color):
pygame.draw.circle(gameDisplay, color,[thingx, thingy, thingw, thingh])
Full code:
import pygame
import time
import random
pygame.init()
display_width = 1200
display_height = 800
gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption('A Game By Freddie')
black = (0,0,0)
white = (255,255,255)
blue = (25,0,255)
red = (255,0,0)
car_width = 195
car_height = 1
clock = pygame.time.Clock()
gameExit = False
shipImg = pygame.image.load('ship.png')
def things(thingx, thingy, thingw, thingh, color):
pygame.draw.circle(gameDisplay, color,[thingx, thingy, thingw, thingh])
def ship(x,y):
gameDisplay.blit(shipImg, (x,y))
def text_objects(text, font):
textSurface = font.render(text, True, red)
return textSurface, textSurface.get_rect()
def message_display(text):
largeText = pygame.font.Font('freesansbold.ttf',120)
TextSurf, TextRect = text_objects(text, largeText)
TextRect.center = ((display_width/2),(display_height/2))
gameDisplay.blit(TextSurf, TextRect)
pygame.display.update()
time.sleep(2)
game_loop()
def crash():
message_display('You Died')
def game_loop():
x = (display_width * 0.375)
y = (display_height * 0.65)
x_change = 0
y_change = 0
thing_startx = random.randrange(0, display_width)
thing_starty = -600
thing_speed = 7
thing_width = 100
thing_height = 100
gameExit = False
while not gameExit:
gameDisplay.fill(blue)
shipImg = pygame.image.load('ship.png')
ship(x,y)
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x_change = -5
elif event.key == pygame.K_RIGHT:
x_change = 5
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
x_change = 0
x += x_change
things(thing_startx, thing_starty, thing_width, thing_height, black)
thing_starty += thing_speed
if x > display_width - car_width or x < 0:
crash()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
y_change = -5
elif event.key == pygame.K_DOWN:
y_change = 5
if event.type == pygame.KEYUP:
if event.key == pygame.K_UP or event.key == pygame.K_DOWN:
y_change = 0
y += y_change
if y > display_height - car_height or y < 0:
crash()
pygame.display.update()
clock.tick(60)
game_loop()
pygame.quit()
quit()
The problem with your code is that your using pygame.draw.circle() wrong. The syntax for using the function is: pygame.draw.circle(screen, color, (x, y), diameter). As you can probably tell, the way you did it was pygame.draw.circle(screen, color, [x, y, w, h]). This is incorrect, a circle does not have a width and height. Change your code to: pygame.draw.circle(gameDisplay, color, (thingx, thingy), thingw). thingw will be the diameter of your circle.
You should also change your function paramters to def things(thingx, thingy, thingw, color).
If your still new to Pygame or confused on how to draw shapes to the screen, i highly suggest reading the Pygame documentation on drawing, as Idos linked to in the comments.

Resources