This question already has answers here:
How to get keyboard input in pygame?
(11 answers)
Faster version of 'pygame.event.get()'. Why are events being missed and why are the events delayed?
(1 answer)
Closed 4 months ago.
Hello i need to programm a Game with pygame for school. I nearly finish the Game but when i want to Press the "C" button in the Gameover loop then nothing happends and the game will not restart.
unti i spam the "C" Button. I dont think that there is a problem with the detection of pressing the button because i made a print command thatalways prints something when i press the "C" Button and it always print something out.
I hope you can help me with the Problem :)
from turtle import pos
import pygame
import time
from pygame.locals import *
import random
pygame.init()
dis_width = 600
dis_height = 400
pos_x = 303
pos_y = 370
x_change = 0
y_change = 0
enemie_pos_x = random.randint(180, 420)
enemie_pos_y = 30
clock = pygame.time.Clock()
screen=pygame.display.set_mode((dis_width, dis_height))
font_style = pygame.font.SysFont("bahnschrift", 25)
time_font = pygame.font.SysFont("bahnschrift", 25)
running=True
obj = False
obj2 = False
enemie = False
game_over = False
crash = True
start = time.time() + 0.1
tolleranz = 40
speed = 5
timer = 5
score = 0
displayscore = 0
highscore = 0
ROT = (255, 0, 0)
BLACK = (0, 0, 0)
pygame.display.update()
def stopwatch(time):
value = time_font.render("Time: " + str(time), True, ROT)
screen.blit(value, [0, 0])
value2 = time_font.render("Score: " + str(score), True, ROT)
screen.blit(value2, [0, 30])
value6 = time_font.render("HighScore: " + str(highscore), True, ROT)
screen.blit(value6, [0, 60])
def enemies():
counter = 1
global enemie_pos_x, enemie_pos_y, speed, aTimeRound, timer, displayscore, highscore
enemie_pos_y += speed
if aTimeRound > timer:
speed += 5
timer += 5
if enemie_pos_y > 430:
enemie_pos_y = 0
enemie_pos_x = random.randint(180, 420)
global score
score += 1
if highscore <= score:
if highscore != score:
highscore += 1
displayscore = score
def gameoverF():
global score, start, speed, timer, game_over, displayscore, highscore
screen.fill(BLACK)
value3 = time_font.render("GAMEOVER", True, ROT)
screen.blit(value3, [230, 100])
value6 = time_font.render("Score:" + str(displayscore), True, ROT)
screen.blit(value6,[230, 150])
value4 = time_font.render("Highscore: " + str(highscore), True, ROT)
screen.blit(value4,[225, 200])
value5 = time_font.render("Press 'C' to play again OR Press 'Q' to Quit", True, ROT)
screen.blit(value5,[70,250])
score = 0
start = time.time()
speed = 5
timer = 5
pygame.display.update()
while running:
while game_over == True:
for event in pygame.event.get(): # Bei jeden GameLoop die Liste an Events abfragen
if event.type == pygame.QUIT:
running = False
pygame.quit()
quit()
if event.type == pygame.KEYDOWN: # Prüfen, ob der Eventtyp ein Tastendruck ist
if event.key == ord("c"): # Prüfen, ob die Cursor-Links-Taste gedrückt wurde...
game_over = False
speed = 5
timer = 5
score = 0
print("GEDRÜCKT!!!!!!!")
if event.key == ord("q"):
pygame.quit()
gameoverF()
#Messung der Zeit
aTime = time.time()-start
aTimeRound = round(time.time()-start,1)
#print(aTime)
#Malen der Steuer Kugel und der Linien
pos_x += x_change
screen.fill(BLACK)
pygame.draw.line(screen, ROT, (150,0),(150,400), 10)
pygame.draw.line(screen, ROT, (450,0),(450,400), 10)
pygame.draw.circle(screen, [255,255,255],(pos_x,pos_y), 25)
stopwatch(aTimeRound)
enemies()
pygame.draw.circle(screen, [255,255,255],(enemie_pos_x,enemie_pos_y), 25)
#print( enemie_pos_x - pos_x)
check_x = pos_x - enemie_pos_x
if check_x < 0:
check_x = check_x * -1
print(check_x)
if check_x < tolleranz and pos_y - enemie_pos_y < tolleranz:
game_over = True
clock.tick(30)
if pos_x <= 192:
pos_x = 192
if pos_x >= 410:
pos_x = 410
for event in pygame.event.get(): # Bei jeden GameLoop die Liste an Events abfragen
if event.type == pygame.QUIT:
running = False
pygame.quit()
quit()
if event.type == pygame.KEYDOWN: # Prüfen, ob der Eventtyp ein Tastendruck ist
if event.key == pygame.K_LEFT or event.key == ord("a"): # Prüfen, ob die Cursor-Links-Taste gedrückt wurde...
x_change = -10
y_change = 0 # Aktion bei Cursor-Links
if event.key == pygame.K_RIGHT or event.key == ord("d"):
x_change = 10
y_change = 0
pygame.display.update()
gameoverF()
Played your game got highscore of 22 oh I mean I read the code and and I debugged it
Well actually playing was the debugging haha. The problem is that after you press C game restarts as it should but the enemy which hit you is not removed and it instantly kills you again and moves tiny bit lower. By spamming C you move it out of screen and game continues
Simple fix to reset enemy pose when C is pressed
if event.key == ord("c"):
enemie_pos_y = 30 # Reset enemy pose
Keep up the good work!
Related
This question already has answers here:
Updating text in pygame
(1 answer)
Creating a self-updating score
(1 answer)
Closed 23 days ago.
I made a surface for the player health and drew it on the screen. Then I made an if statement checking to see if the player X position was == to the enemy X position and if it was the player health would continuously decrease. I know it was decreasing because I was having it print out the player health afterwards in the console and everything was good but the health on the screen would not change. What am I doing wrong?
I am a newbie at pygame and a beginner in python therefore my code is not written in the best way...
Sorry the code is very long but the # should show everything...
import pygame
from sys import exit
from time import sleep
pygame.init()
clock = pygame.time.Clock()
screen = pygame.display.set_mode((1200, 535))
background = pygame.image.load("background1.jpg")
background = pygame.transform.rotozoom(background, 0, 2)
# Player
player_surf = pygame.image.load("player_sprites/player_right.png").convert_alpha()
player_rect = player_surf.get_rect(bottomright = (575, 470))
player_surf = pygame.transform.rotozoom(player_surf, 0, 2.5).convert_alpha()
# Health...
health = 50
health_font = pygame.font.Font('Pixeltype.ttf', 50)
health_display = health_font.render(f"Health {health}", True, (0, 0, 0))
# Enemy #1
enemy1_surf = pygame.image.load("enemy1sprites/enemy1_right.png").convert_alpha()
enemy1_rect = enemy1_surf.get_rect(bottomleft = (1100, 462))
enemy1_surf = pygame.transform.rotozoom(enemy1_surf, 0, 2.5).convert_alpha()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
screen.blit(background, (0, 0))
screen.blit(player_surf, player_rect)
screen.blit(enemy1_surf, enemy1_rect)
screen.blit(health_display, (550, 75))
# Player Movement
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
player_surf = pygame.image.load("player_sprites/player_left.png")
player_surf = pygame.transform.rotozoom(player_surf, 0, 2.5)
player_rect.x -= 4
if event.key == pygame.K_RIGHT:
player_surf = pygame.image.load("player_sprites/player_right.png")
player_surf = pygame.transform.rotozoom(player_surf, 0, 2.5)
player_rect.x += 4
if player_rect.x >= 1075:
player_rect.x = 1075
elif player_rect.x <= 0:
player_rect.x = 0
wave_one = True
# Enemy 1 AI
if player_rect.x != enemy1_rect.x:
if player_rect.x > enemy1_rect.x:
enemy1_surf = pygame.image.load("enemy1sprites/enemy1_right.png")
enemy1_surf = pygame.transform.rotozoom(enemy1_surf, 0, 2.5)
enemy1_rect.x += 1
elif player_rect.x < enemy1_rect.x:
enemy1_surf = pygame.image.load("enemy1sprites/enemy1_left.png")
enemy1_surf = pygame.transform.rotozoom(enemy1_surf, 0, 2.5)
enemy1_rect.x -= 1
# Collision with enemy
if player_rect.x == enemy1_rect.x:
health -= 0.005
print(health)
pygame.display.update()
clock.tick(60)
I expected it to continuously update the health_display but It did not.
Have you tried updating / re-rendering the text on screen? From your code, it appears that the health is only printed when updated, not shown in the game.
I can't collide rect whit rectangles, should I give up or try using x and y positions?
I don't get any errors from it but it closes right after i run it.
can you please suggest me what to do.
import pygame,sys,time,random
pygame.init()
x = 425
y = 750
player_x = x/2-25
player_y = 600
player_speed = 0
timer = 0
score = 0
screen = pygame.display.set_mode((x,y))
clock = pygame.time.Clock()
enemy_x = random.randint(0,425)
enemy_y = -(random.randint(0,500))
enemy2_x = random.randint(0,425)
enemy2_y = -(random.randint(0,500))
police_x = random.randint(0,425)
police_y = random.randint(750,1400)
police2_x = random.randint(0,425)
police2_y = random.randint(750,1400)
enemy_speed = 16
police_speed = 3
font = pygame.font.SysFont("comicsansms",50)
player = pygame.image.load("macchina.png").convert_alpha()
pygame.display.set_caption("NapoliSimulator (schiva le buche e non farti prendere dalla pula)")
def player_a():
global player_x,player_y,player_speed
player_x+=player_speed
player = pygame.image.load("macchina.png").convert_alpha()
screen.blit(player,(player_x,player_y))
def enemy_a():
global enemy_x,enemy_y,enemy_speed,enemy2_x,enemy2_y,enemy3_x,enemy3_y,enemy4_x,enemy4_y,enemy5_x,enemy5_y
enemy_y += enemy_speed
enemy2_y += enemy_speed
enemy = pygame.image.load("crepa.png").convert_alpha()
enemy_2 = pygame.image.load("crepa.png").convert_alpha()
screen.blit(enemy,(enemy_x,enemy_y))
screen.blit(enemy,(enemy2_x,enemy2_y))
def enemy_b():
global police_x,police_y,police_speed,police2_x,police2_y
police_y -= police_speed
police = pygame.image.load("polizia.png").convert_alpha()
screen.blit(police,(police_x,police_y))
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_a:
player_speed -= 5
if event.key == pygame.K_d:
player_speed += 5
if event.type == pygame.KEYUP:
if event.key == pygame.K_a:
player_speed += 5
if event.key == pygame.K_d:
player_speed -= 5
screen.fill((200,200,200))
player_a()
if enemy_y >= 700:
enemy_y = -(random.randint(500,1200))
enemy_x = random.randint(0,425)
score += 1
if enemy2_y >= 700:
enemy2_y = -(random.randint(0,750))
enemy2_x = random.randint(0,425)
score += 1
if police_y <= 40:
police_y = random.randint(750,1900)
police_x = random.randint(0,425)
score += 1
enemy_a()
if score >= 7:
enemy_b()
if score >= 15:
police_speed += 0.0001
enemy = pygame.image.load("crepa.png").convert_alpha()
enemy_2 = pygame.image.load("crepa.png").convert_alpha()
police = pygame.image.load("polizia.png").convert_alpha()
playerr = player.get_rect()
enemyr = enemy.get_rect()
policer = police.get_rect()
enemyr2 = enemy_2.get_rect()
if enemyr.colliderect(playerr):
pygame.quit()
sys.exit()
if enemyr2.colliderect(playerr):
pygame.quit()
sys.exit()
if crepar.colliderect(policer):
enemy_b()
if player.colliderect(policer):
pygame.quit()
ys.exit()
pygame.display.flip()
clock.tick(60)
pygame.Surface.get_rect.get_rect() returns a rectangle with the size of the Surface object, that always starts at (0, 0) since a Surface object has no position. A Surface is blit at a position on the screen. The position of the rectangle can be specified by a keyword argument. For example, the top left of the rectangle can be specified with the keyword argument topleft:
playerr = player.get_rect(topleft = (player_x, player_y))
enemyr = enemy.get_rect(topleft = (enemy_x, enemy_y))
policer = police.get_rect(topleft = (police_x, police_y))
enemyr2 = enemy_2.get_rect(topleft = (enemy2_x, enemy2_y))
if enemyr.colliderect(playerr):
pygame.quit()
sys.exit()
if enemyr2.colliderect(playerr):
pygame.quit()
sys.exit()
if player.colliderect(policer):
pygame.quit()
sys.exit()
I'm trying to build a space invader-like game for fun.
It's mostly done, but when I shoot the enemy I want the text on the screen with his health to decrease.
Here is my code stripped only to the health updating part:
import pygame
from sys import exit
enemy_health = 10
pygame.init()
win = pygame.display.set_mode((1000, 1000))
pygame.display.set_caption("Fighter Pilot Go!")
clock = pygame.time.Clock()
font = pygame.font.Font(None, 55)
enemy_health_text = font.render(f'Enemy Health: {enemy_health}', False, 'white')
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
enemy_health_text -= 1
win.blit(enemy_health_text, (350, 60)
That's not all of the game, but it's the basic idea.
The score doesn't update in the game till a laser hits the enemy.
Here is the whole game, if the code helps you understand my issue:
import pygame
from sys import exit
import random
speed = 5
laser_speed = 7
bullets = []
score = 0
max_num_of_bullet = 3
background_speed = 3
enemy_health = 10
direction = True
enemy_speed = 7
pygame.init()
win = pygame.display.set_mode((1000, 1000))
pygame.display.set_caption("Fighter Pilot Go!")
clock = pygame.time.Clock()
background1 = pygame.image.load('assets/background.gif')
background2 = pygame.image.load('assets/background.gif')
background1_rect = background1.get_rect(topleft=(0, 0))
background2_rect = background2.get_rect(topleft=(0, -1000))
player = pygame.image.load('assets/player.gif')
player_rect = player.get_rect(midtop=(500, 750))
enemy = pygame.image.load('assets/enemy.gif')
enemy_rect = enemy.get_rect(center=(500, 350))
laser = pygame.image.load('assets/laser.gif')
# laser_rect = laser.get_rect(midtop=(500, 800))
font = pygame.font.Font(None, 55)
enemy_health_text = font.render(f'Enemy Health: {enemy_health}', False, 'white')
def is_collided_with(a, b):
return abs(a[0] - b.centerx) < 51 and abs(a[1] - b.centery) < 51
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
if len(bullets) <= max_num_of_bullet - 1:
bullets.append([player_rect.x + 49, player_rect.y - 60])
elif len(bullets) > max_num_of_bullet - 1:
continue
else:
print("Something Weird is Happening!")
key = pygame.key.get_pressed()
if key[pygame.K_a]:
player_rect.x -= speed
if key[pygame.K_d]:
player_rect.x += speed
win.blit(background1, background1_rect)
win.blit(background2, background2_rect)
win.blit(player, player_rect)
win.blit(enemy, enemy_rect)
background1_rect.y += background_speed
background2_rect.y += background_speed
if direction:
enemy_rect.x -= enemy_speed
elif not direction:
enemy_rect.x += enemy_speed
if enemy_rect.x <= 0:
direction = False
elif enemy_rect.x >= 900:
direction = True
if player_rect.x < -20:
player_rect.x = 1020
if player_rect.x > 1020:
player_rect.x = -20
for bullet in bullets:
win.blit(laser, bullet)
for bullet in bullets:
bullet[1] -= laser_speed
win.blit(enemy_health_text, (350, 60))
for bullet in bullets:
if is_collided_with(bullet, enemy_rect):
bullets.remove(bullet)
enemy_health -= 1
for bullet in bullets:
if bullet[1] < 0:
bullets.remove(bullet)
if background1_rect.y >= 1000:
background1_rect.topleft = (0, -1000)
if background2_rect.y >= 1000:
background2_rect.topleft = (0, -1000)
if enemy_health <= 0:
pass
pygame.display.update()
clock.tick(60)
Any help would be appreciated. :) Thanks!
The text is rendered in the enemy_health_text Surface with the value of enemy_health. You have to change enemy_health and render the text again:
font = pygame.font.Font(None, 55)
enemy_health_text = font.render(f'Enemy Health: {enemy_health}', False, 'white')
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
enemy_health -= 1
enemy_health_text = font.render(f'Enemy Health: {enemy_health}', False, 'white')
win.fill(0)
win.blit(enemy_health_text, (350, 60)
pygame.display.flip()
This question already has answers here:
How do I detect collision in pygame?
(5 answers)
How to detect collisions between two rectangular objects or images in pygame
(1 answer)
Closed 2 years ago.
I am trying to write a pygame program where the user dodges objects falling from the top of the screen. However, when I run, collideRect activates too early. Any suggestions?
import pygame
import sys
import time
import random
pygame.init()
size = width, height = 500, 500
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Avalanche!")
character = pygame.image.load("C:/Python27/Lib/site-packages/StickBasic.png")
boulder = pygame.image.load("C:/Python27/Lib/site-packages/Boulder1.png")
charRect = character.get_rect()
charRect.left = 246
charRect.bottom = 450
running = True
skyBlue = 0, 255, 255
groundBrown = 100, 0, 0
direction = 0
timer = 0
boulderFrequency = 20
boulders = []
def endgame():
global running
running = False
while True:
for e in pygame.event.get():
if e.type == pygame.QUIT:
sys.exit()
def bg():
screen.fill(skyBlue)
pygame.draw.rect(screen, groundBrown, (0, 450, 500, 500))
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
if charRect.left > 0:
direction = -1
elif event.key == pygame.K_RIGHT:
if charRect.right < 500:
direction = 1
elif event.type == pygame.KEYUP:
direction = 0
if (direction < 0) and (charRect.left > 0):
charRect.left -= 1
if (direction > 0) and (charRect.right < 500):
charRect.left += 1
if timer >= boulderFrequency:
timer = 0
newBoulder = {
'rect': pygame.Rect(random.randint(0, 460), -40, 40, 40),
'surface': boulder}
boulders.append(newBoulder)
bg()
for b in boulders:
b['rect'].move_ip(0, 5)
if b['rect'].top > 500:
boulders.remove(b)
for b in boulders:
screen.blit(b['surface'], b['rect'])
screen.blit(character, charRect)
pygame.display.flip()
timer += 1
for b in boulders:
if charRect.colliderect(b['rect']):
endgame()
time.sleep(0.02)
PS: I know that the coding is not very clean, but I am relatively knew to coding.
So I am making a simple "Dodge the Meteor Game" with Python 27 and Pygame. So everything ran smoothly, until I wanted to make classes, so I could make multiple meteors without retyping the same code. After I did this, when I run it, it stops responding with no error message. Here is my code:
import pygame
from pygame.locals import *
import sys
import random
pygame.init()
width,height = 800,600
gameDisplay = pygame.display.set_mode((width,height))
pygame.display.set_caption("Fifteen Minute Game ")
gameStart = False
bg = pygame.image.load("C:\Users\DEREK\Desktop\Python\\space.jpg")
bg = pygame.transform.scale(bg,(900,600))
x = 300
y = 300
move_x = 0
move_y = 0
playerspeed = 3
pellet_x = random.randint(0,800)
pellet_y = random.randint(0,550)
player = pygame.draw.rect( gameDisplay, (255,255,255), (x,y,30,30) )
pellet = pygame.draw.rect( gameDisplay, (255,255,255), (pellet_x,pellet_y,15,15) )
count = 0
#Functions
def pelletxy():
global pellet_x, pellet_y
pellet_x = random.randint(0,770)
pellet_y = random.randint(0,570)
def collision(rect1,rect2):
global player, count, pellet
if rect1.colliderect(rect2):
if rect2 == pellet:
pelletxy()
count +=1
class Meteor():
def __init__(self):
self.meteor_x = random.randint(0,800)
self.meteor_y = 0
self.meteorfall = 3
self.meteor = pygame.draw.rect( gameDisplay, (255,255,255), (self.meteor_x,self.meteor_y,35,35) )
def collision(self,rect1,rect2):
if rect1.colliderect(rect2):
if rect2 == self.meteor:
print "Good Game"
print "MUA HAHAHAHA"
print ""
print "Your score:" + str(count)
pygame.quit()
sys.exit()
def meteorxy(self):
self.meteor_x = random.randint(0,800)
self.meteor_y = 0
def render(self):
self.meteor_y += self.meteorfall
self.meteor
if meteor_y > 600:
meteorxy()
m1 = Meteor()
#Game Loop
while gameStart:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# Keyboard Movement
if event.type == pygame.KEYDOWN:
if event.key == K_UP:
move_y -= playerspeed
if event.key == K_DOWN:
move_y += playerspeed
if event.key == K_LEFT:
move_x -= playerspeed
if event.key == K_RIGHT:
move_x += playerspeed
if event.type == pygame.KEYUP:
if event.key == K_UP:
move_y = 0
if event.key == K_DOWN:
move_y = 0
if event.key == K_LEFT:
move_x = 0
if event.key == K_RIGHT:
move_x = 0
#Calculate new position
x = x + move_x
y = y + move_y
#Stop Movement on boundaries
if x > 830:
x = -30
elif x < -30:
x = 830
elif y < -30:
y = 630
elif y > 630:
y = -30
#Check Different Collision Scenarios
collision(player, pellet)
m1.collision(player, m1.meteor)
#Draw the things onto the screen
gameDisplay.blit(bg,(0,0))
player = pygame.draw.rect( gameDisplay, (255,255,255), (x,y,30,30) )
pellet_outline = pygame.draw.rect( gameDisplay, (255,255,255), ((pellet_x - 1), (pellet_y - 1), 17,17))
pellet = pygame.draw.rect( gameDisplay, (0,0,255), (pellet_x,pellet_y,15,15) )
m1.render
pygame.display.update()
I don't know what I'm doing wrong, but I know it is with the classes. Thanks in advance
Hobby Programmer, Derek
Well, it's probably because gameStart is always False. So you're never getting into the game loop.
You should get to know debugging. You can use pdb or any IDE like Eclipse. The important thing is that it can help you understand what code is being running.
if event.key == K_RIGHT:
move_x = 0
#Calculate new position
x = x + move_x
y = y + move_y
See how the indentation changes? In Python, indentation is very important. Because all of your code after the line 'move_x = 0' is not indented adequately, it is not part of your while loop; therefore, it does not get executed in the loop. Fix your indentation.