Welcome!

By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.


    To learn more about how to use our BBCode feature, please click here.

    Thank you, Code Forum.

Python Win Screen Error

PythonCoder

New Coder
Python:
import pygame
import random
from pygame.locals import *
import time

pygame.init()

# Screen dimensions
screen_width = 800
screen_height = 600

# Initialize pygame screen
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption('Simple Game')

# Game variables for the first game
player_width = 50
player_height = 50
player_pos2 = [screen_width - 100, 270]
player_pos1 = [screen_width - 100, 430]
player_speed = 5
enemy1_width = 50
enemy1_height = 50
enemy1_speed = 3
enemies1 = []
score1 = 0
game_over1 = False
win1 = False
game_active = True

# Game variables for the second game
player2_width = 50
normal_height = 50
crouch_height = 25
player_pos = [0, screen_height - normal_height]
player_speed = 5
player_current_height = normal_height
enemy2_width = 40
enemy2_height = 25
initial_enemy2_speed = 3
enemy2_speed = initial_enemy2_speed
enemies2 = []
score2 = 0
game_over2 = False
win2 = False
start_ticks = pygame.time.get_ticks()
boom = 1000
start2_ticks = pygame.time.get_ticks()


# Function to spawn enemy for the first game
def spawn_enemy_game1():
x = 0
y = random.randint(60, screen_height - 110)
enemies1.append(pygame.Rect(x, y, enemy1_width, enemy1_height))


# Function to spawn enemy for the second game
def spawn_enemy_game2():
y = random.choice([screen_height - 50, screen_height - 25])
enemy = pygame.Rect(screen_width, y, enemy2_width, enemy2_height)
enemies2.append(enemy)


# Function to check collision with player in the first game
def check_collision_game1(player_rect1, player_rect2):
for enemy in enemies1:
if player_rect1.colliderect(enemy) or player_rect2.colliderect(enemy):
return True
return False


# Function to check collision with player in the second game
def check_collision_game2(player_rect):
for enemy in enemies2:
if player_rect.colliderect(enemy):
return True
return False


# Function to restart game for the first game
def restart_game1():
global player_pos1, player_pos2, enemies1, game_over1, win1, score1
player_pos1 = [screen_width - 100, 430]
player_pos2 = [screen_width - 100, 270]
enemies1.clear()
game_over1 = False
win1 = False
score1 = 0


# Function to restart game for the second game
def restart_game2():
global player_pos, enemies2, game_over2, win2, enemy2_speed, start_ticks, player_current_height, score2, player2_width, boom, start2_ticks
player_current_height = normal_height
player_pos = [0, screen_height - normal_height]
enemies2.clear()
game_over2 = False
win2 = False
enemy2_speed = initial_enemy2_speed
start_ticks = pygame.time.get_ticks()
start2_ticks = pygame.time.get_ticks()
score2 = 0
player2_width = 50
boom = 1000


# Menu function
def show_menu():
screen.fill((0, 0, 0))
menu_font = pygame.font.SysFont(None, 60)
menu_text1 = menu_font.render('Press 1 to open first game', True, (255, 255, 255))
menu_text2 = menu_font.render('Press 2 to open the other game', True, (255, 255, 255))
screen.blit(menu_text1, (screen_width // 2 - menu_text1.get_width() // 2, screen_height // 2 - 30))
screen.blit(menu_text2, (screen_width // 2 - menu_text2.get_width() // 2, screen_height // 2 + 30))
pygame.display.flip()


# Function to show pause menu
def show_pause_menu():
screen.fill((0, 0, 0))
pause_font = pygame.font.SysFont(None, 60)
pause_text = pause_font.render('Press SPACE to Continue', True, (255, 255, 255))
screen.blit(pause_text, (screen_width // 2 - pause_text.get_width() // 2, screen_height // 2 - 30))
pygame.display.flip()


# Function to show game over menu
def show_game_over_menu():
screen.fill((0, 0, 0))
game_over_font = pygame.font.SysFont(None, 60)
game_over_text = game_over_font.render("Game Over!", True, (255, 0, 0))
screen.blit(game_over_text, (screen_width // 2 - game_over_text.get_width() // 2, screen_height // 2 - 30))
pygame.display.flip()


# Function to show win menu
def show_win_menu():
global game_active
screen.fill((0, 0, 0))
win_font = pygame.font.SysFont(None, 60)
win_text = win_font.render("You Win!", True, (0, 255, 0))
screen.blit(win_text, (screen_width // 2 - win_text.get_width() // 2, screen_height // 2 - 30))
pygame.display.flip()
game_active = False


# Game loop
clock = pygame.time.Clock()
running = True
in_menu = True
game1_active = False
game2_active = False
paused = False
show_pause = False

while running:
dt = clock.tick(60) / 1000.0

for event in pygame.event.get():
if event.type == QUIT:
running = False
if event.type == pygame.KEYDOWN:
if win2:
if event.key == pygame.K_r:
paused = False
win2 = False # Reset win2 to avoid re-entering this block immediately
restart_game2()
elif event.type == KEYDOWN:
if event.key == K_ESCAPE:
if not in_menu:
if not paused:
paused = True
show_pause = True
else:
paused = False
show_pause = False
elif event.key == K_SPACE and show_pause:
paused = False
show_pause = False
elif event.key == K_m:
if not in_menu:
in_menu = True
game1_active = False
game2_active = False
elif event.key == K_1:
if in_menu:
in_menu = False
game1_active = True
game2_active = False
restart_game1()
elif event.key == K_2:
if in_menu:
in_menu = False
game1_active = False
game2_active = True
restart_game2()
elif event.key == K_r:
if game1_active and game_over1:
restart_game1()
if game2_active and game_over2:
restart_game2()
elif event.key == K_DOWN:
if game2_active:
player_current_height = crouch_height
player_pos[1] = screen_height - crouch_height
elif event.key == K_UP:
if game2_active:
player_current_height = crouch_height
player_pos[1] = 550

current_time = pygame.time.get_ticks()

# Calculate the elapsed time
elapsed_time = (current_time - start2_ticks) / 1000 # Convert milliseconds to seconds

# Adjust boom and player width based on elapsed time
if 10 <= score2 < 20:
boom = 500
player2_width = 25
if 20 <= score2 < 30:
boom = 400
player2_width = 12.5
if 30 <= elapsed_time <= 40:
boom = 300
if 40 <= score2:
boom = 250



if in_menu:
show_menu()
elif show_pause:
show_pause_menu()
elif game1_active:
if not paused:
keys = pygame.key.get_pressed()
if keys[K_DOWN] and player_pos2[1] + player_height < screen_height:
player_pos2[1] += player_speed
player_pos1[1] += player_speed
if keys[K_UP] and player_pos2[1] > 0:
player_pos2[1] -= player_speed
player_pos1[1] -= player_speed

player_pos1[1] = max(0, min(player_pos1[1], screen_height - player_height))
player_pos2[1] = max(0, min(player_pos2[1], 390))

player_rect1 = pygame.Rect(player_pos1[0], player_pos1[1], player_width, player_height)
player_rect2 = pygame.Rect(player_pos2[0], player_pos2[1], player_width, player_height)

middle_top = min(player_pos1[1], player_pos2[1]) + player_height
middle_bottom = max(player_pos1[1], player_pos2[1])
middle_rect = pygame.Rect(player_pos1[0], middle_top, 60, middle_bottom - middle_top)

if random.randint(1, 100) == 1:
spawn_enemy_game1()

for enemy in enemies1[:]:
enemy.x += enemy1_speed
if enemy.x > screen_width:
enemies1.remove(enemy)

if check_collision_game1(player_rect1, player_rect2):
game_over1 = True

screen.fill((0, 0, 0))

pygame.draw.rect(screen, (255, 255, 255), player_rect1)
pygame.draw.rect(screen, (255, 255, 255), player_rect2)

for enemy in enemies1[:]:
pygame.draw.rect(screen, (255, 0, 0), enemy)
if enemy.colliderect(middle_rect):
score1 += 1
enemies1.remove(enemy)

score_font = pygame.font.SysFont(None, 36)
score_text = score_font.render(f"Score: {score1}", True, (255, 255, 255))
screen.blit(score_text, (10, 10))

if game_over1:
show_game_over_menu()

elif game2_active:
if not paused:
keys = pygame.key.get_pressed()
if keys[K_UP]:
player_current_height = crouch_height
player_pos[1] = 550
elif keys[K_DOWN]:
player_current_height = crouch_height
player_pos[1] = screen_height - crouch_height
else:
player_current_height = 50
player_pos[1] = 550

if pygame.time.get_ticks() - start_ticks > boom:
spawn_enemy_game2()
start_ticks = pygame.time.get_ticks()

for enemy in enemies2[:]:
enemy.x -= enemy2_speed
if enemy.x < 0:
score2 += 1
enemies2.remove(enemy)
if score2 >= 1:
win2 = True

if check_collision_game2(pygame.Rect(player_pos[0], player_pos[1], player2_width, player_current_height)):
game_over2 = True

screen.fill((0, 0, 0))

pygame.draw.rect(screen, (255, 255, 255),
pygame.Rect(player_pos[0], player_pos[1], player2_width, player_current_height))

for enemy in enemies2[:]:
pygame.draw.rect(screen, (255, 0, 0), enemy)

score_font = pygame.font.SysFont(None, 36)
score_text = score_font.render(f"Score: {score2}", True, (255, 255, 255))
screen.blit(score_text, (10, 10))

if game_over2:
show_game_over_menu()

pygame.display.flip()

pygame.quit()
can anyone help me fix the bug when you win in game 2 it doesnt stop and after that is just chaos

when you win in game 2 there should be a you win screen and you can restart the game by r but it basically doesnt work (i made it show up at 1 score so that you could test it but its supposed to be 75)
 
Last edited by a moderator:
Hi there, when posting code, please post the code in code blocks. I've done this for you, but indentation seems to have been lost during posting. Please edit your original post with the indented code.
 
I tried to make sense of your code by indenting where I thought was the proper place but, kept getting errors. The last being player1_rect not defined.

If you correct the the indented code, I'll give it a go. I'm usually pretty fair at pygame code.
Might even be able to show a easier way.

Here is a game that I done in pygame. Maybe it will help.
Shmup version 0.02

Here is a pong game that I was playing around with a while back. Much simpler than the shmup game.
I have attached the start page image.

Python:
import pygame
from random import randint, choice
import sys
 
pygame.init()
 
window  = (800,600)
bgcolor = 'white'
 
screen = pygame.display.set_mode(window)
pygame.display.set_caption('PyGame Pong')
 
pongimg = pygame.image.load('Python/pygame/ping-pong.png')
pygame.display.set_icon(pongimg)
 
players = []
allsprites = pygame.sprite.Group()
 
class Player(pygame.sprite.Sprite):
    ''' Set player class attributes and add the sorite to group '''
    def __init__(self):
        super().__init__()
        self.name = ''
        self.score = 0
        self.width = 10
        self.height = 100
        self.direction = 1
 
        self.image = pygame.Surface([self.width, self.height])
        self.image.fill('black')
        self.image.set_colorkey('white')
 
        pygame.draw.rect(self.image, 'black', [0, 0, self.width, self.height])
 
        self.rect = self.image.get_rect()
 
        players.append(self)
 
 
    def moveup(self, pixels):
        ''' Method for moving player up '''
        self.rect.y -= pixels
        if self.rect.y <= 39:
            self.rect.y = 39
 
    def movedown(self, pixels):
        ''' Method for moving player down '''
        self.rect.y += pixels
        if self.rect.y >= window[1] - 100:
            self.rect.y = window[1] - 100
 
# Create a ball sprite
class Ball(pygame.sprite.Sprite):
    ''' Create the ball class and add to sprite group '''
    def __init__(self, color='black'):
        super().__init__()
        self.image = pygame.Surface([25,25])
        self.image.fill('white')
        self.image.set_colorkey('white')
        self.color = color
 
        pygame.draw.circle(self.image, self.color, [12.5,12.5], 12.5)
        
        self.velocity = [randint(4,8), randint(-6,6)]
 
        self.rect = self.image.get_rect()
 
        screen.blit(self.image, self.rect)
 
        self.hidden = False
 
    # Update ball positions / Unhide ball if hidden
    def update(self):
        if self.hidden:
            self.hidden = False
 
        self.rect.x += self.velocity[0]
        self.rect.y += self.velocity[1]
 
    # Create a ball bounce when it collides with a paddle
    def bounce(self):
        self.velocity[0] = -self.velocity[0]
        self.velocity[1] = randint(-6, 6)
 
    # Hide the ball if it passes a score boundry
    def hide(self):
        self.hidden = True
        self.rect.x = window[0]/2-12.5
        self.rect.y = choice((50, 560))
 
 
# Class creates a start/title page
class Page:
    ''' Create the start page class '''
    def title(self):
        screen.fill('white')
 
        # Set title text
        font = pygame.font.Font(None, 40)
        text = font.render('Pygame Pong', True, 'blue')
        text_rect = text.get_rect(center = (window[0]//2, 30))
        screen.blit(text, text_rect)
 
        # Set pong image
        img = pygame.transform.scale(pongimg, (pongimg.get_rect().width//2+100, pongimg.get_rect().height//2+100))
        img_rect = img.get_rect(center = (window[0]//2, window[1]//2))
        screen.blit(img, img_rect)
 
        # Set text on how to leave the screen
        font = pygame.font.Font(None, 30)
        text = font.render('Press Enter to start game', 1, 'tomato')
        text_rect = text.get_rect(center=(window[0]//2, window[1]//2 + window[1]//2-50))
        screen.blit(text, text_rect)
 
        font = pygame.font.Font(None, 23)
        string = 'Gaming-Rat Productions ' + U'\u00A9'
        string = string.encode('iso-8859-1')
        text = font.render(string, True, (90,150,220))
        screen.blit(text, (10, window[1]-25))
        
        waiting = True
        while waiting:
            event = pygame.event.poll()
            if event.type == pygame.QUIT:
                waiting = False
                sys.exit()
 
            keys = pygame.key.get_pressed()
            if keys[pygame.K_KP_ENTER] or keys[pygame.K_RETURN]:
                waiting = False
 
            pygame.display.flip()
 
# Create human player
player1 = Player()
player1.rect.x = 10
player1.rect.centery = (window[1]/2)-40
 
# Create computer player
player2 = Player()
player2.rect.x = window[0] - 20
player2.rect.centery = (window[1]/2)-40
 
# Create ball and starting position
# To change ball color do Ball('some color')
ball = Ball('navy')
ball.rect.x = window[0]/2-12.5
ball.rect.y = 50
 
# Add sprites to group
allsprites.add(player1)
allsprites.add(player2)
allsprites.add(ball)
 
# Initialize Page class
page = Page()
 
# Set some variables Human set to True allows a human to play as player 1
# game_over set to True for the start/title page to show
# running for the main game screen
Human = False
game_over = True
running = True
 
while running:
 
    # If game_over is set to True show start/title page
    # Set game_over to false to show game screen
    if game_over:
        page.title()
        game_over = False
 
    # Screen background color
    screen.fill(bgcolor)
    
    # Get pygame events
    event = pygame.event.poll()
    if event.type == pygame.QUIT:
        running = False
 
    # Get pressed keys
    keys = pygame.key.get_pressed()
 
    # Human Player
    if Human:
        if keys[pygame.K_w] or keys[pygame.K_UP]:
            player1.moveup(5)
        if keys[pygame.K_s] or keys[pygame.K_DOWN]:
            player1.movedown(5)
    else:
        if player1.rect.y > ball.rect.y:
            player1.moveup(5)
        if player1.rect.y < ball.rect.y:
            player1.movedown(5)
 
    # Computer player movement
    # Computer paddle will follow balls y position
    if player2.rect.y > ball.rect.y:
        player2.moveup(5)
    if player2.rect.y < ball.rect.y:
        player2.movedown(5)
 
    # Ball directions and score boundries
    if ball.rect.right >= window[0]+50:
        player1.score += 1
        ball.hide()
        ball.velocity[0] = -ball.velocity[0]
        
    if ball.rect.left <= -50:
        player2.score += 1
        ball.hide()
        ball.velocity[0] = -ball.velocity[0]
 
    # Boundies for top and bottom
    if ball.rect.top <= 40:
        ball.rect.top = 42
        ball.velocity[1] = -ball.velocity[1]
 
    if ball.rect.bottom >= window[1]:
        ball.rect.bottom = window[1] - 2
        ball.velocity[1] = -ball.velocity[1]
 
    # Detect ball and paddle collisions / bounce back
    if pygame.sprite.collide_rect(ball, player1) or pygame.sprite.collide_rect(ball, player2):
        ball.bounce()
        
    # Draw the line in the middle of the court
    pygame.draw.line(screen, (150,150,150), [window[0]/2, 0], [window[0]/2, window[1]], 3)
 
    # Draw the scoreboard to screen
    board = pygame.Surface([window[0], 40])
    board.fill((60,60,60))
    screen.blit(board, (0,0))
 
    # Add a font
    font = pygame.font.Font(None, 24)
 
    player = 'Player' if Human else 'Computer'
    # Render and blit player text to screen
    player_text = font.render(f'{player}: {player1.score}', True, 'white')
    screen.blit(player_text, (150, 10))
 
    # Render and blit computer text to screen
    computer_text = font.render(f'Computer: {player2.score}', True, 'white')
    screen.blit(computer_text, (550, 10))
 
    # Update all sprites
    allsprites.update()
 
    # Draw all sprites to screen
    allsprites.draw(screen)
 
    # Update the screen/window
    pygame.display.flip()
 
    # Set frames per second
    pygame.time.Clock().tick(60)
 
pygame.quit()
 

Attachments

  • ping-pong.png
    ping-pong.png
    14.5 KB · Views: 0
Last edited:

New Threads

Latest posts

Buy us a coffee!

Back
Top Bottom