I'm trying to make a game were there is this little robot that shoots. The problem is that it shoots only when it's not moving, when I move left or right or when I jump it doesn't shoot. Is there something that I can do for let my barspace key works when I'm pressing the other keys? I tried to put another if key statement in a key statement that already exist but it doesn't work, like this I mean:
elif keys[py.K_LEFT] and man.x >= 0:
man.x -= man.vel
man.right = False
man.left = True
man.standing = False
man.idlecount = 0
man.direction = -1
if keys [py.K_SPACE] and shootloop == 0:
if man.left:
facing = -1
elif man.right:
facing = 1
if len(bullets) < 5:
man.standing = True
man.shooting = True
bullets.append(bulletss(round(man.x + man.lenght//2), round(man.y + man.lenght//2), facing))
shootloop = 1
I left my github here so you can run the program. Thank you for the help and sorry for my code that is a mess.
https://github.com/20nicolas/Game.git
The if keys [py.K_SPACE] and shootloop == 0: statement should not be inside of the elif keys[py.K_LEFT] and man.x >= 0: clause, otherwise you can only shoot when you press the left arrow key.
Also, in your repo it's actually,
if keys[py.K_RIGHT] and man.x <= 700:
# ...
elif keys[py.K_LEFT] and man.x >= 0:
# ...
elif keys [py.K_SPACE] and shootloop == 0:
which means that it will only be executed when neither K_LEFT nor K_RIGHT are pressed, because these statements are in the same if...elif sequence.
This version works for me:
elif keys[py.K_LEFT] and man.x >= 0:
man.x -= man.vel
man.right = False
man.left = True
man.standing = False
man.idlecount = 0
man.direction = -1
else:
man.standing = True
if keys [py.K_SPACE] and shootloop == 0:
if man.left:
facing = -1
elif man.right:
facing = 1
if len(bullets) < 5:
man.standing = True
man.shooting = True
bullets.append(bulletss(round(man.x + man.lenght//2), round(man.y + man.lenght//2), 1))
shootloop = 1
else:
man.shooting = False
Related
Recently started trying to learn pygame with the goal of making a simple platformer. So far, I've created a player that can move left and right and is affected by gravity. I haven't yet implemented object collision. Right now I'm trying to make a simple jump script. My current script for vertical movement is the following:
if man.y + man.height < ground:
man.yvel += man.velInc
elif man.y + man.height >= ground:
if man.isJump == True:
man.isJump == False
man.yvel = 0
if keys[pygame.K_SPACE] and man.isJump == False:
man.yvel = -20
man.isJump = True
man.y += man.yvel
This is run in a loop along with other stuff such as horizontal movement. ground is a variable that determines the y-coordinate of the ground, and is currently set to 350. The height of the window is 450. man.velInc is set to 1 and man.height is set to 32 I can provide any other info if necessary.
My problem is that when I run the program, I can only jump once, and then never again. I can still move left and right normally. I put in a script to print out man.x, man.y, and man.isJump. Before the jump, man.isJump is "False", and after, True. It never goes back to False. man.y also reads as 328. The jump itself however seems to work perfectly. I would appreciate any help to fix the issue, and maybe some advice on how to avoid things like this in the future.
You are confusing the == (Boolean equality) with = (set variable)
if man.y + man.height < ground:
man.yvel += man.velInc
elif man.y + man.height >= ground:
if man.isJump == True:
man.isJump = False # replace == with =
man.yvel = 0
if keys[pygame.K_SPACE] and man.isJump == False:
man.yvel = -20
man.isJump = True
man.y += man.yvel
Im making my own Hangman Python program, im still a newbie to python programming, so i dont quite understand what im doing wrong. I have specified that the lives are limited to 6, but when inputing a wrong input, the lives can go down to -2 as the console says..
import random
words = ["stone"]
word = words[random.randint(0, (len(words)) - 1)]
wordToLetters = list(word)
gaps = ["_"] * len(word)
lives = 6
gameOver = False
while not gameOver:
for num, x in enumerate(wordToLetters):
print(lives)
print(gaps)
eingabe = input("Buchstaben eingeben: ")
if lives < 0:
gameOver = True
print("spiel verloren...\n")
if gaps == wordToLetters:
print("Spiel gewonnen!\n")
print("Das Wort war: " + word)
gameOver = True
if eingabe in wordToLetters:
if eingabe in gaps:
lives -= 1
print("Buchstabe schon geraten!")
else:
gaps[num] = eingabe
print("Buchstabe vorhanden!\n")
else:
lives -= 1
print("Buchstabe nicht vorhanden! :(\n")
you must use elif to not test the other conditions when one of them is true:
import random
words = ["stone"]
word = words[random.randint(0, (len(words)) - 1)]
wordToLetters = list(word)
gaps = ["_"] * len(word)
lives = 6
gameOver = False
while not gameOver:
for num, x in enumerate(wordToLetters):
print(lives)
print(gaps)
eingabe = input("Buchstaben eingeben: ")
if lives < 0:
gameOver = True
print("spiel verloren...\n")
elif gaps == wordToLetters:
print("Spiel gewonnen!\n")
print("Das Wort war: " + word)
gameOver = True
elif eingabe in wordToLetters:
if eingabe in gaps:
lives -= 1
print("Buchstabe schon geraten!")
else:
gaps[num] = eingabe
print("Buchstabe vorhanden!\n")
else:
lives -= 1
print("Buchstabe nicht vorhanden! :(\n")
here if the first "if" is true then we will not check the others.
I made this simulation as a discordpy cog, but the bot goes offline and the console is open and don't do anything if I write or quit it...
At an amount of 15000 the bot crashes, what can I do, why it crashs?
There are discord emojies, which are selected randomly and there are different chances with the numbers etc. I hope somebody can help me here!
#bot.command()
async def simulate(self, ctx, amount):
wnitro = 0
wkey = 0
wgold = 0
wred = 0
wblue = 0
wgreen = 0
wgrey = 0
for zaehler in range(1, int(amount)):
drehungen = randint(5, 20)
gone = randint(1, 1000)
gtwo = randint(1, 1000)
gthree = randint(1, 1000)
gfour = randint(1, 1000)
gfive = randint(1, 1000)
gsix = randint(1, 1000)
gseven = randint(1, 1000)
geight = randint(1, 1000)
gnine = randint(1, 1000)
randomitem = [gone, gtwo, gthree, gfour, gfive, gsix, gseven, geight, gnine]
slots = []
for item in range(len(randomitem)):
if randomitem[item] >= 950:
slots.append("<a:classic:802844186026049546>")
elif randomitem[item] >= 850:
slots.append("<a:geld:770235576539676682>")
elif randomitem[item] >= 800:
slots.append("<a:goldendia:802976550995755019>")
elif randomitem[item] >= 650:
slots.append("<a:darkbluedia:802976435500875836>")
elif randomitem[item] >= 500:
slots.append("<a:reddia:802873281841463296>")
elif randomitem[item] >= 300:
slots.append("<a:greendia:802875898353156138>")
else:
slots.append("<a:greydia:802977070627553311>")
cdrehung = 1
nitroextra = randint(1, 100)
keyextra = randint(1, 10)
coinsextra = randint(1, 5)
coins2extra = randint(1, 2)
i = 0
while i < drehungen:
if cdrehung == 0:
gewinn = slots[4]
elif cdrehung == 1:
gewinn = slots[5]
elif cdrehung == 2:
gewinn = slots[6]
elif cdrehung == 3:
gewinn = slots[7]
elif cdrehung == 4:
gewinn = slots[8]
elif cdrehung == 5:
gewinn = slots[0]
elif cdrehung == 6:
gewinn = slots[1]
elif cdrehung == 7:
gewinn = slots[2]
elif cdrehung == 8:
gewinn = slots[3]
cdrehung -= 9
cdrehung += 1
i += 1
if i == drehungen:
if gewinn == "<a:classic:802844186026049546>":
if nitroextra == 1:
wnitro += 1
else:
drehungen += 1
elif gewinn == "<a:geld:770235576539676682>":
if keyextra == 1:
wkey += 1
else:
drehungen += 1
elif gewinn == "<a:goldendia:802976550995755019>":
if coinsextra == 1:
wgold += 1
else:
drehungen += 1
elif gewinn == "<a:darkbluedia:802976435500875836>":
if coins2extra == 1:
wblue += 1
else:
drehungen += 1
elif gewinn == "<a:reddia:802873281841463296>":
wred += 1
elif gewinn == "<a:greendia:802875898353156138>":
wgreen += 1
elif gewinn == "<a:greydia:802977070627553311>":
wgrey += 1
await ctx.send(f"There are the results out of `{str(amount)}x` spins: {str(wnitro)}x Nitro, {str(wkey)} Key, {str(wgold)} <a:goldendia:802976550995755019>, {str(wblue)} <a:darkbluedia:802976435500875836>, {str(wred)} <a:reddia:802873281841463296>, {str(wgreen)}<a:greendia:802875898353156138>, {str(wgrey)}<a:greydia:802977070627553311>")
thanks to everyone who helps c:
Update: I take it back, theoretically your slots could all be the same thing, or a combination of things that cause drehungen to always implement. You really need to reconsider the logic on your loop.
Update: actually that is false, you do update cdrehung which updates gewinn... this is pretty convoluted, but it does seems like it should have to end at some point. That being said this loop is a bit complicated, I would consider some debug messages for all these different variables to figure out what is going on.
Just looking at it, inside your while loop the state of gewinn doesn't change, or any of the other items (wnitro wkey wgold wblue)... sooo if that is the case it could mean that drehungen is always being incremented... which means i == drehungen is always true... which means an infinite loop.
I'm new to python and cant figure out whats the issue, tried multiple solutions, but that didn't work.
posting from the main function
def main(genomes, config):
nets = []
ge = []
birds = []
base = Base(680)
pipes = [Pipe(600)]
win = pygame.display.set_mode((WIN_WIDTH, WIN_HEIGHT))
clock = pygame.time.Clock()
score = 0
run = True
while run:
clock.tick(30)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
pygame.quit()
quit()
for x, bird in enumerate(birds):
bird.move()
ge[x].fitness += 0.1
if output[0] > 0.5:
bird.jump()
add_pipe = False
rem = []
It works the same in the loop below
for pipe in pipes:
for x,bird in enumerate(birds):
if pipe.collide(bird):
ge[x].fitness -= 1
birds.pop(x)
nets.pop(x)
ge.pop(x)
if not pipe.passed and pipe.x < bird.x:
pipe.passed = True
add_pipe = True
if pipe.x + pipe.PIPE_TOP.get_width() < 0:
rem.append(pipe)
pipe.move()
if add_pipe:
score += 1
for g in ge:
g.fitness += 5
pipes.append(Pipe(600))
for r in rem:
pipes.remove(r)
Here i'm getting that 'int object has no attribute bird' it works in other parts of the code
for x.bird in enumerate(birds):
if bird.y + bird.img.get_height() >= 680 or bird. y < 0:
birds.pop(x)
nets.pop(x)
ge.pop(x)
base.move()
draw_window(win, birds, pipes, base, score)
You have used a dot instead of a comma:
for x, bird in enumerate(birds):
Enumerate functions typical format:
for index, value in enumerate(values):
Long time user, first time asker. Just started using pygame and need some help as right now, my game isn't working as there seems to be a problem with the program choosing a gradient for the ball, and the ball now seems to go in a straight line across the x axis. The code is below, thanks in advance for any help
from pygame import *
import time
import random
init()
width = 1000
height = 1000
screen = display.set_mode((width,height))
display.set_caption('Graphics')
ball1 = Rect(10,10,40,40)
ball1dx = 2
ball1dy = 3
ball2 = Rect(500,500,40,40)
gradient = [-0.25,-0.5,-0.75,-1]
ran = 0
endProgram = False
a = 0
d = 0
w = 0
s = 0
while not endProgram:
for e in event.get():
if e.type == KEYUP:
if (e.key == K_a):
a = True
d = False
w = False
s = False
if (e.key == K_d):
d = True
a = False
w = False
s = False
if (e.key == K_w):
w = True
a = False
d = False
s = False
if (e.key == K_s):
s = True
a = False
d = False
w = False
if a:
ball2.x -= 1
if d:
ball2.x += 1
if w:
ball2.y -= 1
if s:
ball2.y += 1
ball1.move_ip(ball1dx,ball1dy)
if ball1.y < 0 or ball1.y > height - 40:
ran = random.random()
ball1dy *= random.choice(gradient)
if ball1.x < 0 or ball1.x > width - 40:
ran = random.random()
ball1dx *= random.choice(gradient)
screen.fill((0,0,200))
draw.ellipse(screen, (0,255,0), ball1)
draw.ellipse(screen, (255,0,0),ball2)
display.update()
I don't know what you were expecting but if you keep multiplying a number by a fraction between 1 and 0 you will start to approach 0 and essentially get 0. If you add a print statement after you pick the gradient you will see that your number is quickly heading towards zero.
-1.5
-0.5
0.5
-0.375
0.28125
-0.2109375
0.158203125
-0.0791015625
0.059326171875
-0.0296630859375
0.0222473144531
-0.0111236572266
.
.
.
-1.28840161923e-281
6.44200809614e-282
-3.22100404807e-282
3.22100404807e-282
I'm assuming you are just trying to get the ball to bounce around screen which you can do by just multiplying by -1. If you want variable speed while bouncing you will have to set up a range for min and max speed and only multiply by your gradient if it doesn't exceed those boundaries. You could do it like this
ball1.move_ip(ball1dx,ball1dy)
if ball1.y < 0 or ball1.y > height - 40:
choice = random.choice(gradient)
if abs(ball1dy*choice) < 5 and abs(ball1dy*choice) > 0.25:
ball1dy *= choice
else:
ball1dy*=-1
if ball1.x < 0 or ball1.x > width - 40:
choice = random.choice(gradient)
if abs(ball1dx*choice) < 5 and abs(ball1dx*choice) > 0.25:
ball1dx *= choice
else:
ball1dx*=-1
As a side note you can condense your if statements by changing them all to False right before the ifs and then only switching one to True like so
for e in event.get():
if e.type == KEYUP:
w = False
a = False
s = False
d = False
if (e.key == K_a):
a = True
if (e.key == K_d):
d = True
if (e.key == K_w):
w = True
if (e.key == K_s):
s = True