Dash 无法在 pygame 制作的 2D PONG 中工作

问题描述 投票:0回答:1

让我们为我的问题添加一个上下文:我是一名计算机科学专业的学生,我已经学习Python有一段时间了。我们的老师要求我们通过分析使用“pygame”模块的开源项目并向其添加功能来学习如何营销该模块。所以我选择了在 github 上找到的一个简单、经典的 pong。我决定添加的功能是:纹理包管理器(以便社区可以创建自己的纹理包并将其拖到游戏中)、简单的菜单、多人游戏模式(我还没有完成,但这不是重点在这里),最后,稍微使用一下 pygame,一个带有冲刺和加载射击的能力系统。然而,我一开始是改进对手的人工智能,制作菜单,以及改变游戏纹理包的可能性,但当我开始研究能力系统时,我陷入了困境。

问题是这样的,即使在调试之后我也无法弄清楚如何让我的破折号在不干扰游戏其余部分的情况下工作。另外,速度仍然停留在 5,尽管我的冲刺应该会增加速度。

我正在寻求一位勇敢的人的帮助,他愿意帮助我,因为我已经非常努力,甚至在朋友的帮助下实现了这个项目,但我还没有成功。

以下是包含有缺陷的多人游戏部分的一般代码: main.py:

from game import Game

g = Game()

while g.running:
    g.curr_menu.display_menu()
    g.game_loop()

游戏.py:

import sys, random
import socket
import threading
from menu import *
import pygame
import json


class GameState:
    def __init__(self, player_y, opponent_y, ball_x, ball_y):
        self.player_y = player_y
        self.opponent_y = opponent_y
        self.ball_x = ball_x
        self.ball_y = ball_y

    def to_json(self):
        return json.dumps({
            'player_y': self.player_y,
            'opponent_y': self.opponent_y,
            'ball_x': self.ball_x,
            'ball_y': self.ball_y
        })

    @classmethod
    def from_json(cls, json_str):
        data = json.loads(json_str)
        return cls(data['player_y'], data['opponent_y'], data['ball_x'], data['ball_y'])


font_img = pygame.image.load('pong.jpg')

# Constants
SCREEN_WIDTH = 960
SCREEN_HEIGHT = 720
middle_strip = pygame.Rect(SCREEN_WIDTH / 2 - 2, 0, 4, SCREEN_HEIGHT)

# Initialize Pygame
pygame.init()
clock = pygame.time.Clock()
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption('Pong')


def ressource_pack():
    def load_resource_config(pack_path):
        try:
            print(pack_path)
            with open(pack_path, 'r') as config_file:
                return json.load(config_file)
        except FileNotFoundError:
            print("Resource pack not found. Using default settings.")
            return {
                "colors": {
                    "background": "#2F373F",
                },
                "images": {
                    "ball": "Ball.png",
                    "player": "Paddle.png"
                },
                "sounds": {
                    "hit": "pong.ogg",
                    "score": "score.ogg"
                },
                "fonts": {
                    "font": "freesansbold.ttf"
                }
            }


    # Load the resource pack
    resource_pack_path = "ressources/PIXEL_INK/config.json"
    resource_config = load_resource_config(resource_pack_path)

    # Use the colors from the configuration
    bg_color = pygame.Color(resource_config["colors"]["background"])
    background_image = resource_config["images"].get("background", None)
    if background_image:
        background = pygame.image.load(background_image)
    else:
        background = bg_color


    ball_image = resource_config["images"]["ball"]
    visual_ball = pygame.image.load(ball_image)

    player_image = resource_config["images"]["player"]
    visual_player = pygame.image.load(player_image)

    # Load the sounds from the configuration
    hit_sound_path = resource_config["sounds"]["hit"]
    score_sound_path = resource_config["sounds"]["score"]

    # Load the font from the configuration
    font = resource_config["fonts"]["font"]

    return background, visual_ball, visual_player, hit_sound_path, score_sound_path, font

class Game():
    def __init__(self):
        pygame.init()
        self.running, self.playing = True, False
        self.UP_KEY, self.DOWN_KEY, self.START_KEY, self.BACK_KEY = False, False, False, False
        self.DISPLAY_W, self.DISPLAY_H = 480, 480
        self.display = pygame.Surface((self.DISPLAY_W,self.DISPLAY_H))
        self.window = pygame.display.set_mode(((self.DISPLAY_W,self.DISPLAY_H)))
        self.font_name = '8-BIT WONDER.TTF'
        self.BLACK, self.WHITE = (0, 0, 0), (255, 255, 255)
        self.main_menu = MainMenu(self)
        self.options = OptionsMenu(self)
        self.credits = CreditsMenu(self)
        self.curr_menu = self.main_menu

    def game_loop(self):
        while self.playing:
            self.check_events()
            if self.START_KEY:
                self.playing= False
            connection()



    def check_events(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                self.running, self.playing = False, False
                self.curr_menu.run_display = False
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_RETURN:
                    self.START_KEY = True
                if event.key == pygame.K_BACKSPACE:
                    self.BACK_KEY = True
                if event.key == pygame.K_DOWN:
                    self.DOWN_KEY = True
                if event.key == pygame.K_UP:
                    self.UP_KEY = True

    def reset_keys(self):
        self.UP_KEY, self.DOWN_KEY, self.START_KEY, self.BACK_KEY = False, False, False, False

    def draw_text(self, text, size, x, y ):
        font = pygame.font.Font(self.font_name,size)
        text_surface = font.render(text, True, self.WHITE)
        text_rect = text_surface.get_rect()
        text_rect.center = (x,y)
        self.display.blit(text_surface,text_rect)

def connection(client_socket=None):
    a = str(input("Voulez vous:  [1] - Héberger une partie | [2] - Rejoindre une partie"))
    if a == "1":
        threading.Thread(target=server).start()
        main_game()
    elif a == "2":
        host = str(input("Enter the host's address: "))
        port = 2345

        client_socket = socket.socket()
        client_socket.connect((host, port))

        threading.Thread(target=main_game, args=(client_socket,)).start()
    else:
        print("Enter \"1\" or \"2\"")

def main_game(client_socket=None):
    background, visual_ball, visual_player, hit_sound_path, score_sound_path, font = ressource_pack()

    class Block(pygame.sprite.Sprite):
        def __init__(self, image, x_pos, y_pos):
            super().__init__()
            self.image = image
            self.rect = self.image.get_rect(center=(x_pos, y_pos))

    class Player(Block):
        def __init__(self, image, x_pos, y_pos, speed):
            super().__init__(image, x_pos, y_pos)
            self.speed = speed
            self.movement = 0

        def screen_constrain(self):
            if self.rect.top <= 0:
                self.rect.top = 0
            if self.rect.bottom >= screen_height:
                self.rect.bottom = screen_height

        def update(self,ball_group):
            self.rect.y += self.movement
            self.screen_constrain()

    class Ball(Block):
        def __init__(self,path,x_pos,y_pos,speed_x,speed_y,paddles):
            super().__init__(path,x_pos,y_pos)
            self.speed_x = speed_x * random.choice((-1,1))
            self.speed_y = speed_y * random.choice((-1,1))
            self.paddles = paddles
            self.active = False
            self.score_time = 0

        def update(self):
            if self.active:
                self.rect.x += self.speed_x
                self.rect.y += self.speed_y
                self.collisions()
            else:
                self.restart_counter()

        def collisions(self):
            if self.rect.top <= 0 or self.rect.bottom >= screen_height:
                pygame.mixer.Sound.play(plob_sound)
                self.speed_y *= -1

            if pygame.sprite.spritecollide(self,self.paddles,False):
                pygame.mixer.Sound.play(plob_sound)
                collision_paddle = pygame.sprite.spritecollide(self,self.paddles,False)[0].rect
                if abs(self.rect.right - collision_paddle.left) < 10 and self.speed_x > 0:
                    self.speed_x *= -1
                if abs(self.rect.left - collision_paddle.right) < 10 and self.speed_x < 0:
                    self.speed_x *= -1
                if abs(self.rect.top - collision_paddle.bottom) < 10 and self.speed_y < 0:
                    self.rect.top = collision_paddle.bottom
                    self.speed_y *= -1
                if abs(self.rect.bottom - collision_paddle.top) < 10 and self.speed_y > 0:
                    self.rect.bottom = collision_paddle.top
                    self.speed_y *= -1

        def reset_ball(self):
            self.active = False
            self.speed_x *= random.choice((-1,1))
            self.speed_y *= random.choice((-1,1))
            self.score_time = pygame.time.get_ticks()
            self.rect.center = (screen_width/2,screen_height/2)
            pygame.mixer.Sound.play(score_sound)

        def restart_counter(self):
            current_time = pygame.time.get_ticks()
            countdown_number = 3

            if current_time - self.score_time <= 700:
                countdown_number = 3
            if 700 < current_time - self.score_time <= 1400:
                countdown_number = 2
            if 1400 < current_time - self.score_time <= 2100:
                countdown_number = 1
            if current_time - self.score_time >= 2100:
                self.active = True

            time_counter = basic_font.render(str(countdown_number),True,accent_color)
            time_counter_rect = time_counter.get_rect(center = (screen_width/2,screen_height/2 + 50))
            pygame.draw.rect(screen,bg_color,time_counter_rect)
            screen.blit(time_counter,time_counter_rect)

    class Opponent(Block):
        def __init__(self, path, x_pos, y_pos, speed, difficulty_level):
            super().__init__(path, x_pos, y_pos)
            self.speed = speed
            self.difficulty_level = difficulty_level

        def update(self, ball_group):
            if self.difficulty_level == 'easy':
                # Simple movement, follows the ball but with a delay
                if self.rect.centery < ball_group.sprite.rect.centery:
                    self.rect.y += self.speed * 0.7
                elif self.rect.centery > ball_group.sprite.rect.centery:
                    self.rect.y -= self.speed * 0.7
            elif self.difficulty_level == 'medium':
                # Predicts the ball's position and follows accordingly
                if self.rect.centery < ball_group.sprite.rect.centery:
                    self.rect.y += self.speed
                elif self.rect.centery > ball_group.sprite.rect.centery:
                    self.rect.y -= self.speed
            elif self.difficulty_level == 'hard':
                # Predicts the ball's position and moves quickly to intercept
                target_y = ball_group.sprite.rect.centery
                if self.rect.centery < target_y:
                    self.rect.y += self.speed * 1.5
                elif self.rect.centery > target_y:
                    self.rect.y -= self.speed * 1.5

            self.constrain()

        def constrain(self):
            if self.rect.top <= 0:
                self.rect.top = 0
            if self.rect.bottom >= screen_height:
                self.rect.bottom = screen_height

    class GameManager:
        def __init__(self,ball_group,paddle_group):
            self.player_score = 0
            self.opponent_score = 0
            self.ball_group = ball_group
            self.paddle_group = paddle_group

        def run_game(self):
            # Drawing the game objects
            self.paddle_group.draw(screen)
            self.ball_group.draw(screen)

            # Updating the game objects
            self.paddle_group.update(self.ball_group)
            self.ball_group.update()
            self.reset_ball()
            self.draw_score()

        def reset_ball(self):
            if self.ball_group.sprite.rect.right >= screen_width:
                self.opponent_score += 1
                self.ball_group.sprite.reset_ball()
            if self.ball_group.sprite.rect.left <= 0:
                self.player_score += 1
                self.ball_group.sprite.reset_ball()

        def draw_score(self):
            player_score = basic_font.render(str(self.player_score),True,accent_color)
            opponent_score = basic_font.render(str(self.opponent_score),True,accent_color)

            player_score_rect = player_score.get_rect(midleft = (screen_width / 2 + 40,screen_height/2))
            opponent_score_rect = opponent_score.get_rect(midright = (screen_width / 2 - 40,screen_height/2))

            screen.blit(player_score,player_score_rect)
            screen.blit(opponent_score,opponent_score_rect)

    # General setup
    pygame.mixer.pre_init(44100,-16,2,512)
    pygame.init()
    clock = pygame.time.Clock()

    # Main Window
    screen_width = 960
    screen_height = 720
    screen = pygame.display.set_mode((screen_width,screen_height))
    pygame.display.set_caption('Pong')

    # Global Variables
    bg_color = pygame.Color(background)
    accent_color = (27,35,43)
    basic_font = pygame.font.Font(font, 32)
    plob_sound = pygame.mixer.Sound(hit_sound_path)
    score_sound = pygame.mixer.Sound(score_sound_path)
    middle_strip = pygame.Rect(screen_width/2 - 2,0,4,screen_height)

    player = Player(visual_player,screen_width - 20,screen_height/2,5)
    # Game objects
    if client_socket is None:
        opponent = Opponent(visual_player, 20, screen_width / 2, 5, 'medium')
    else:
        opponent = None

    paddle_group = pygame.sprite.Group()
    paddle_group.add(player)
    if opponent:
        paddle_group.add(opponent)

    ball = Ball(visual_ball,screen_width/2,screen_height/2,4,4,paddle_group)
    ball_sprite = pygame.sprite.GroupSingle()
    ball_sprite.add(ball)

    game_manager = GameManager(ball_sprite,paddle_group)

    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_UP:
                    player.movement -= player.speed
                if event.key == pygame.K_DOWN:
                    player.movement += player.speed
            if event.type == pygame.KEYUP:
                if event.key == pygame.K_UP:
                    player.movement += player.speed
                if event.key == pygame.K_DOWN:
                    player.movement -= player.speed
        if opponent:
            opponent.update(ball_sprite)

        if client_socket:
            try:
                data = client_socket.recv(1024).decode()
                if data:
                    game_state = GameState.from_json(data)
                    player.rect.centery = game_state.player_y
                    if game_state.opponent_y:
                        if opponent:
                            opponent.rect.centery = game_state.opponent_y
                        else:
                            opponent = Opponent(visual_player, 20, game_state.opponent_y, 5, 'medium')
                            paddle_group.add(opponent)
            except ConnectionResetError:
                break
        else:
            opponent.update(ball_sprite)

        if client_socket:
            game_state = GameState(player.rect.centery, opponent.rect.centery if opponent else None, None, None)
            client_socket.send(game_state.to_json().encode())

        # Background Stuff
        screen.fill(bg_color)
        pygame.draw.rect(screen,accent_color,middle_strip)

        # Run the game
        game_manager.run_game()

        # Rendering
        pygame.display.flip()
        clock.tick(120)

菜单.py:

import pygame

class Menu():
    def __init__(self, game):
        self.game = game
        self.mid_w, self.mid_h = self.game.DISPLAY_W / 2, self.game.DISPLAY_H / 2
        self.run_display = True
        self.cursor_rect = pygame.Rect(0, 0, 20, 20)
        self.offset = - 100

    def draw_cursor(self):
        self.game.draw_text('*', 15, self.cursor_rect.x, self.cursor_rect.y)

    def blit_screen(self):
        self.game.window.blit(self.game.display, (0, 0))
        pygame.display.update()
        self.game.reset_keys()

class MainMenu(Menu):
    def __init__(self, game):
        Menu.__init__(self, game)
        self.state = "Start"
        self.startx, self.starty = self.mid_w, self.mid_h + 20
        self.optionsx, self.optionsy = self.mid_w, self.mid_h + 60
        self.creditsx, self.creditsy = self.mid_w, self.mid_h + 80
        self.cursor_rect.midtop = (self.startx + self.offset, self.starty)

        self.menu_image = pygame.image.load('pong.jpg')

    def display_menu(self):
        self.run_display = True
        while self.run_display:
            self.game.check_events()
            self.check_input()
            self.game.display.blit(self.menu_image, (0, 0))
            self.game.draw_text('S P A R C', 20, self.game.DISPLAY_W / 2, self.game.DISPLAY_H / 2 - 70)
            self.game.draw_text('Special Pong Abilities', 15, self.game.DISPLAY_W / 2, self.game.DISPLAY_H / 2 - 40)
            self.game.draw_text('and Reaction Challenges', 15, self.game.DISPLAY_W / 2, self.game.DISPLAY_H / 2 - 25)
            self.game.draw_text("Start Game", 20, self.startx, self.starty)
            self.game.draw_text("Options", 20, self.optionsx, self.optionsy)
            self.game.draw_text("Credits", 20, self.creditsx, self.creditsy)
            self.draw_cursor()
            self.blit_screen()


    def move_cursor(self):
        if self.game.DOWN_KEY:
            if self.state == 'Start':
                self.cursor_rect.midtop = (self.optionsx + self.offset, self.optionsy)
                self.state = 'Options'
            elif self.state == 'Options':
                self.cursor_rect.midtop = (self.creditsx + self.offset, self.creditsy)
                self.state = 'Credits'
            elif self.state == 'Credits':
                self.cursor_rect.midtop = (self.startx + self.offset, self.starty)
                self.state = 'Start'
        elif self.game.UP_KEY:
            if self.state == 'Start':
                self.cursor_rect.midtop = (self.creditsx + self.offset, self.creditsy)
                self.state = 'Credits'
            elif self.state == 'Options':
                self.cursor_rect.midtop = (self.startx + self.offset, self.starty)
                self.state = 'Start'
            elif self.state == 'Credits':
                self.cursor_rect.midtop = (self.optionsx + self.offset, self.optionsy)
                self.state = 'Options'

    def check_input(self):
        self.move_cursor()
        if self.game.START_KEY:
            if self.state == 'Start':
                self.game.playing = True
            elif self.state == 'Options':
                self.game.curr_menu = self.game.options
            elif self.state == 'Credits':
                self.game.curr_menu = self.game.credits
            self.run_display = False

class OptionsMenu(Menu):
    def __init__(self, game):
        Menu.__init__(self, game)
        self.state = 'Volume'
        self.volx, self.voly = self.mid_w, self.mid_h + 20
        self.controlsx, self.controlsy = self.mid_w, self.mid_h + 40
        self.cursor_rect.midtop = (self.volx + self.offset, self.voly)
        self.menu_image = pygame.image.load('pong.jpg')

    def display_menu(self):
        self.run_display = True
        while self.run_display:
            self.game.check_events()
            self.check_input()
            self.game.display.blit(self.menu_image, (0, 0))
            self.game.draw_text('Options', 20, self.game.DISPLAY_W / 2, self.game.DISPLAY_H / 2 - 30)
            self.game.draw_text("Volume", 15, self.volx, self.voly)
            self.game.draw_text("Controls", 15, self.controlsx, self.controlsy)
            self.draw_cursor()
            self.blit_screen()

    def check_input(self):
        if self.game.BACK_KEY:
            self.game.curr_menu = self.game.main_menu
            self.run_display = False
        elif self.game.UP_KEY or self.game.DOWN_KEY:
            if self.state == 'Volume':
                self.state = 'Controls'
                self.cursor_rect.midtop = (self.controlsx + self.offset, self.controlsy)
            elif self.state == 'Controls':
                self.state = 'Volume'
                self.cursor_rect.midtop = (self.volx + self.offset, self.voly)
        elif self.game.START_KEY:
            # TO-DO: Create a Volume Menu and a Controls Menu
            pass

class CreditsMenu(Menu):
    def __init__(self, game):
        Menu.__init__(self, game)
        self.menu_image = pygame.image.load('pong.jpg')

    def display_menu(self):
        self.run_display = True
        while self.run_display:
            self.game.check_events()
            if self.game.START_KEY or self.game.BACK_KEY:
                self.game.curr_menu = self.game.main_menu
                self.run_display = False
            self.game.display.blit(self.menu_image, (0, 0))
            self.game.draw_text('Credits', 20, self.game.DISPLAY_W / 2, self.game.DISPLAY_H / 2 - 20)
            self.game.draw_text('Made by Me', 15, self.game.DISPLAY_W / 2, self.game.DISPLAY_H / 2 + 10)
            self.blit_screen()

这是我测试破折号的代码:

dash_test.py:

import pygame, sys, random

class Block(pygame.sprite.Sprite):
    def __init__(self,path,x_pos,y_pos):
        super().__init__()
        self.image = pygame.image.load(path)
        self.rect = self.image.get_rect(center = (x_pos,y_pos))

class Player(Block):
    def __init__(self,path,x_pos,y_pos,speed):
        super().__init__(path,x_pos,y_pos)
        self.speed = speed
        self.movement = 0
        self.dashing = False
        self.dash_timer = 3

    def screen_constrain(self):
        if self.rect.top <= 0:
            self.rect.top = 0
        if self.rect.bottom >= screen_height:
            self.rect.bottom = screen_height

    def update(self,ball_group):
        self.rect.y += self.movement
        self.screen_constrain()

    def dash(self, delta):
        self.dash_timer -= delta

        if self.speed == 5:
            self.speed += 500
            print("Dash")
        if self.dash_timer <= 0:
            self.speed -= 500
            self.dashing = False
            self.dash_timer = 0.5
            print("False")
        else:
            self.dash(delta)

class Ball(Block):
    def __init__(self,path,x_pos,y_pos,speed_x,speed_y,paddles):
        super().__init__(path,x_pos,y_pos)
        self.speed_x = speed_x * random.choice((-1,1))
        self.speed_y = speed_y * random.choice((-1,1))
        self.paddles = paddles
        self.active = False
        self.score_time = 0

    def update(self):
        if self.active:
            self.rect.x += self.speed_x
            self.rect.y += self.speed_y
            self.collisions()
        else:
            self.restart_counter()
        
    def collisions(self):
        if self.rect.top <= 0 or self.rect.bottom >= screen_height:
            pygame.mixer.Sound.play(plob_sound)
            self.speed_y *= -1

        if pygame.sprite.spritecollide(self,self.paddles,False):
            pygame.mixer.Sound.play(plob_sound)
            collision_paddle = pygame.sprite.spritecollide(self,self.paddles,False)[0].rect
            if abs(self.rect.right - collision_paddle.left) < 10 and self.speed_x > 0:
                self.speed_x *= -1
            if abs(self.rect.left - collision_paddle.right) < 10 and self.speed_x < 0:
                self.speed_x *= -1
            if abs(self.rect.top - collision_paddle.bottom) < 10 and self.speed_y < 0:
                self.rect.top = collision_paddle.bottom
                self.speed_y *= -1
            if abs(self.rect.bottom - collision_paddle.top) < 10 and self.speed_y > 0:
                self.rect.bottom = collision_paddle.top
                self.speed_y *= -1

    def reset_ball(self):
        self.active = False
        self.speed_x *= random.choice((-1,1))
        self.speed_y *= random.choice((-1,1))
        self.score_time = pygame.time.get_ticks()
        self.rect.center = (screen_width/2,screen_height/2)
        pygame.mixer.Sound.play(score_sound)

    def restart_counter(self):
        current_time = pygame.time.get_ticks()
        countdown_number = 3

        if current_time - self.score_time <= 700:
            countdown_number = 3
        if 700 < current_time - self.score_time <= 1400:
            countdown_number = 2
        if 1400 < current_time - self.score_time <= 2100:
            countdown_number = 1
        if current_time - self.score_time >= 2100:
            self.active = True

        time_counter = basic_font.render(str(countdown_number),True,accent_color)
        time_counter_rect = time_counter.get_rect(center = (screen_width/2,screen_height/2 + 50))
        pygame.draw.rect(screen,bg_color,time_counter_rect)
        screen.blit(time_counter,time_counter_rect)

class Opponent(Block):
    def __init__(self, path, x_pos, y_pos, speed, difficulty_level):
        super().__init__(path, x_pos, y_pos)
        self.speed = speed
        self.difficulty_level = difficulty_level

    def update(self, ball_group):
        if self.difficulty_level == 'easy':
            if self.rect.centery < ball_group.sprite.rect.centery:
                self.rect.y += self.speed * 0.7
            elif self.rect.centery > ball_group.sprite.rect.centery:
                self.rect.y -= self.speed * 0.7
        elif self.difficulty_level == 'medium':
            if self.rect.centery < ball_group.sprite.rect.centery:
                self.rect.y += self.speed
            elif self.rect.centery > ball_group.sprite.rect.centery:
                self.rect.y -= self.speed
        elif self.difficulty_level == 'hard':
            target_y = ball_group.sprite.rect.centery
            if self.rect.centery < target_y:
                self.rect.y += self.speed * 1.5
            elif self.rect.centery > target_y:
                self.rect.y -= self.speed * 1.5

        self.constrain()

    def constrain(self):
        if self.rect.top <= 0:
            self.rect.top = 0
        if self.rect.bottom >= screen_height:
            self.rect.bottom = screen_height

class GameManager:
    def __init__(self,ball_group,paddle_group):
        self.player_score = 0
        self.opponent_score = 0
        self.ball_group = ball_group
        self.paddle_group = paddle_group

    def run_game(self):
        # Drawing the game objects
        self.paddle_group.draw(screen)
        self.ball_group.draw(screen)

        # Updating the game objects
        self.paddle_group.update(self.ball_group)
        self.ball_group.update()
        self.reset_ball()
        self.draw_score()

    def reset_ball(self):
        if self.ball_group.sprite.rect.right >= screen_width:
            self.opponent_score += 1
            self.ball_group.sprite.reset_ball()
        if self.ball_group.sprite.rect.left <= 0:
            self.player_score += 1
            self.ball_group.sprite.reset_ball()

    def draw_score(self):
        player_score = basic_font.render(str(self.player_score),True,accent_color)
        opponent_score = basic_font.render(str(self.opponent_score),True,accent_color)

        player_score_rect = player_score.get_rect(midleft = (screen_width / 2 + 40,screen_height/2))
        opponent_score_rect = opponent_score.get_rect(midright = (screen_width / 2 - 40,screen_height/2))

        screen.blit(player_score,player_score_rect)
        screen.blit(opponent_score,opponent_score_rect)

# General setup
pygame.mixer.pre_init(44100,-16,2,512)
pygame.init()
clock = pygame.time.Clock()

# Main Window
screen_width = 960
screen_height = 720
screen = pygame.display.set_mode((screen_width,screen_height))
pygame.display.set_caption('Pong')

# Global Variables
bg_color = pygame.Color('#2F373F')
accent_color = (27,35,43)
basic_font = pygame.font.Font('freesansbold.ttf', 32)
plob_sound = pygame.mixer.Sound("pong.ogg")
score_sound = pygame.mixer.Sound("score.ogg")
middle_strip = pygame.Rect(screen_width/2 - 2,0,4,screen_height)

# Game objects
player = Player('Paddle.png',screen_width - 20,screen_height/2,5)
opponent = Opponent('Paddle.png', 20, screen_width / 2, 5, 'hard')
paddle_group = pygame.sprite.Group()
paddle_group.add(player)
paddle_group.add(opponent)

ball = Ball('Ball.png',screen_width/2,screen_height/2,4,4,paddle_group)
ball_sprite = pygame.sprite.GroupSingle()
ball_sprite.add(ball)

game_manager = GameManager(ball_sprite,paddle_group)

while True:
    for event in pygame.event.get():
        print(player.speed)
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP:
                player.movement -= player.speed
            if event.key == pygame.K_DOWN:
                player.movement += player.speed
            if event.key == pygame.K_SPACE:
                player.dashing = True
                delta = clock.tick(30) / 1000
                player.dash(delta)

        if event.type == pygame.KEYUP:
            if event.key == pygame.K_UP:
                player.movement += player.speed
            if event.key == pygame.K_DOWN:
                player.movement -= player.speed
            if event.key == pygame.K_SPACE:
                player.dashing = True
                delta = clock.tick(30) / 1000
                player.dash(delta)
    
    # Background Stuff
    screen.fill(bg_color)
    pygame.draw.rect(screen,accent_color,middle_strip)
    
    # Run the game
    game_manager.run_game()

    # Rendering
    pygame.display.flip()
    clock.tick(120)

提前致谢。

python python-3.x pygame pong
1个回答
0
投票

这里有一些信息可以帮助您朝着正确的方向前进。从你的冲刺机制开始。

当按下空格键时,将调用 Player 类的

dash
方法。然而,破折号的方法有点奇怪。由于末尾的递归行
self.dash(delta)
,dash 方法不断调用自身,这可能会导致“堆栈溢出”或意外行为。另外,使用
self.dash_timer
作为倒计时器有点含糊。

从这里开始,看看是否有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.