微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

游戏“乒乓”我的代码有问题

如何解决游戏“乒乓”我的代码有问题

我已经编写了 Pong 游戏。可以打开播放了,但是还是提示错误

Traceback (most recent call last):
File "/Users/xxxxxxxxxxr/PycharmProjects/Python/666.py",line 245,in <module>
game_to_five()
File "/Users/xxxxxxxxr/PycharmProjects/Python/666.py",line 240,in game_to_five
pygame.display.update()
pygame.error: video system not initialized

我希望你能帮助我。希望得到任何答案:) 也许您对我的代码有一些想法或意见。 我的游戏代码是:

# Importieren einer Bibiothek
import pygame
from pygame.locals import *

# Pygame initialisieren
pygame.init()
# Uhr erstellen // weil sonst der Computer es so schnell wie möglich versucht abzuspielen "Bildfrequenz-Limit"
Clock = pygame.time.Clock()
# Bilschirm Größe
screen_width = 1000
screen_height = 500

# Bilschirm ertsllen mit Überschrift
screen = pygame.display.set_mode((screen_width,screen_height))
pygame.display.set_caption('Pong von Ramon')

# Farbe definieren
bg = pygame.Color("#458B74")
black = (0,0)
white = (255,255,255)
blue = (255,255)
orange = (255,140,0)

# Soounds
plob_sound = pygame.mixer.sound("pong.ogg")
score_sound = pygame.mixer.sound("score.ogg")

# define game variables
margin = 50

# define font
basic_font = pygame.font.SysFont("freesansbold.ttf",60)


# basic_font = pygame.font.SysFont("Helvetica",60)


# Text erstllen und den text umwandeln in ein Bild und dieses auf das Spielbildschirm bringen
# dafür muss ich eine font (Schriftart) erstellen
def draw_text(text,basic_font,text_col,x,y):
    img = basic_font.render(text,True,text_col)
    screen.blit(img,(x,y))


def draw_board():
    screen.fill(bg)
    pygame.draw.line(screen,white,(0,margin),(screen_width,4)
    pygame.draw.line(screen,(500,500),4)
    # Kreis in der Mitte
    pygame.draw.ellipse(screen,[400,180,200,200],4)


# Man kann nicht direkt einen Text schreiben,mann muss es den text in ein Bild konvertieren und diesen mit screen.blit
# auf das "Screen" tun / x und y steht für wo der "Text" am Ende wo es sein soll // font muss noch bestimmt werden //
# text ist der text den man sehen möchte
def draw_text(text,y))


class paddle():
    def __init__(self,y):
        self.x = x
        self.y = y
        self.rect = Rect(x,y,10,150)
        self.speed = 5
        self.ai_speed = 5

    # damit man den Paddle bewegen kann muss man die Tastatur mit einbinden wenn man eine Tast gefrückt hat und wie der Paddle
    # sich zu verhalten hat
    def move(self):
        key = pygame.key.get_pressed()
        # Wenn der UP-Key gedrückt wurde und "Grenzen" einrichten (solange der "Top" größer als margin ist kann man nach oben gehen
        # also unter dem Rand ist
        if key[pygame.K_UP] and self.rect.top > margin:
            self.rect.move_ip(0,-1 * self.speed)
        if key[pygame.K_DOWN] and self.rect.bottom < screen_height:
            self.rect.move_ip(0,self.speed)

    def draw(self):
        pygame.draw.rect(screen,self.rect)

    def ai(self):
        # ai to move the paddle automatically
        # move down
        if self.rect.centery < pong.rect.top and self.rect.bottom < screen_height:
            self.rect.move_ip(0,self.ai_speed)
        # move up
        if self.rect.centery > pong.rect.bottom and self.rect.top > margin:
            self.rect.move_ip(0,-1 * self.ai_speed)


class ball():

    def __init__(self,y):
        self.reset(x,y)

    def move(self):

        # check collision with top margin
        if self.rect.top < margin:
            pygame.mixer.sound.play(plob_sound)
            self.speed_y *= -1
        # check collision with bottom of the screen
        if self.rect.bottom > screen_height:
            pygame.mixer.sound.play(plob_sound)
            self.speed_y *= -1
        if self.rect.colliderect(player_paddle) or self.rect.colliderect(cpu_paddle):
            pygame.mixer.sound.play(plob_sound)
            self.speed_x *= -1

        # check for out of bounds
        if self.rect.left < 0:
            pygame.mixer.sound.play(score_sound)
            self.winner = 1
        if self.rect.left > screen_width:
            pygame.mixer.sound.play(score_sound)
            self.winner = -1

        # update ball position
        self.rect.x += self.speed_x
        self.rect.y += self.speed_y

        return self.winner

    def draw(self):
        pygame.draw.circle(screen,orange,(self.rect.x + self.ball_rad,self.rect.y + self.ball_rad),self.ball_rad)

    def reset(self,y):
        self.x = x
        self.y = y
        self.ball_rad = 8
        self.rect = Rect(x,self.ball_rad * 2,self.ball_rad * 2)
        self.speed_x = -4
        self.speed_y = 4
        self.winner = 0  # 1 is the player and -1 is the cpu


# create paddles
player_paddle = paddle(screen_width - 40,screen_height // 2)
cpu_paddle = paddle(20,screen_height // 2)

# create pong ball
pong = ball(screen_width - 60,screen_height // 2 + 50)


def game_to_five():
    player_score = 0
    opp_score = 0

    live_ball = False
    winner = 0
    speed_increase = 0

    run = True
    while (player_score < 5 and opp_score < 5) and run:

        Clock.tick(60)

        draw_board()
        draw_text('OPP: ' + str(opp_score),20,15)
        draw_text('P1: ' + str(player_score),screen_width - 115,15)
        draw_text('TEMPO: ' + str(abs(pong.speed_x)),screen_width // 2 - 100,15)

        # draw paddles
        player_paddle.draw()
        cpu_paddle.draw()

        if live_ball == True:
            speed_increase += 1
            winner = pong.move()
            if winner == 0:
                # draw ball
                pong.draw()
                # move paddles
                player_paddle.move()
                cpu_paddle.ai()
            else:
                live_ball = False
                if winner == 1:
                    player_score += 1
                elif winner == -1:
                    opp_score += 1

        # print player instructions
        if live_ball == False:
            if winner == 0:
                draw_text('Zum Starten klicken',black,300,screen_width // 2 - 300)
            if winner == 1:
                draw_text('YOU scoreD!',355,160)
                draw_text('CLICK ANYWHERE TO START',200)
            if winner == -1:
                draw_text('cpu scoreD!',160)

                draw_text('CLICK ANYWHERE TO START',200)

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
            if event.type == pygame.MOUSEBUTTONDOWN and live_ball == False:
                live_ball = True
                pong.reset(500,250)
            # screen_width - 60,screen_height // 2 + 50)

        if speed_increase > 500:
            speed_increase = 0
            if pong.speed_x < 0:
                pong.speed_x -= 1
            if pong.speed_x > 0:
                pong.speed_x += 1
            if pong.speed_y < 0:
                pong.speed_y -= 1
            if pong.speed_y > 0:
                pong.speed_y += 1

        pygame.display.update()

    new_game = False
    while not new_game:

        draw_board()
        draw_text('OPP: ' + str(opp_score),15)

        if player_score == 5:
            draw_text('P1 hat gewonnen!',160)
        elif opp_score == 5:
            draw_text('OPP hat gewonnen!',160)
        draw_text('Klicken um fortzufahren',260,200)

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
            if event.type == pygame.MOUSEBUTTONDOWN:
                pong.reset(500,250)
                new_game = True

        pygame.display.update()


# create game loop
while True:
    game_to_five()

pygame.quit()

解决方法

跑步时:

if event.type == pygame.QUIT:
    pygame.quit()

它取消初始化视频(又名显示)系统。然后您再次调用 pygame.display.update()。由于视频系统未初始化,因此会出现该错误。

与其在那里运行 pygame.quit(),不如更改一个将结束游戏循环的变量。

您的代码应如下所示:

# Importieren einer Bibiothek
import pygame
from pygame.locals import *

# Pygame initialisieren
pygame.init()
# Uhr erstellen // weil sonst der Computer es so schnell wie möglich versucht abzuspielen "Bildfrequenz-Limit"
Clock = pygame.time.Clock()
# Bilschirm Größe
screen_width = 1000
screen_height = 500

# Bilschirm ertsllen mit Überschrift
screen = pygame.display.set_mode((screen_width,screen_height))
pygame.display.set_caption('Pong von Ramon')

# Farbe definieren
bg = pygame.Color("#458B74")
black = (0,0)
white = (255,255,255)
blue = (255,255)
orange = (255,140,0)

# Soounds
plob_sound = pygame.mixer.Sound("pong.ogg")
score_sound = pygame.mixer.Sound("score.ogg")

# define game variables
margin = 50

# define font
basic_font = pygame.font.SysFont("freesansbold.ttf",60)


# basic_font = pygame.font.SysFont("Helvetica",60)


# Text erstllen und den text umwandeln in ein Bild und dieses auf das Spielbildschirm bringen
# dafür muss ich eine font (Schriftart) erstellen
def draw_text(text,basic_font,text_col,x,y):
    img = basic_font.render(text,True,text_col)
    screen.blit(img,(x,y))


def draw_board():
    screen.fill(bg)
    pygame.draw.line(screen,white,(0,margin),(screen_width,4)
    pygame.draw.line(screen,(500,500),4)
    # Kreis in der Mitte
    pygame.draw.ellipse(screen,[400,180,200,200],4)


# Man kann nicht direkt einen Text schreiben,mann muss es den text in ein Bild konvertieren und diesen mit screen.blit
# auf das "Screen" tun / x und y steht für wo der "Text" am Ende wo es sein soll // font muss noch bestimmt werden //
# text ist der text den man sehen möchte
def draw_text(text,y))


class paddle():
    def __init__(self,y):
        self.x = x
        self.y = y
        self.rect = Rect(x,y,10,150)
        self.speed = 5
        self.ai_speed = 5

    # damit man den Paddle bewegen kann muss man die Tastatur mit einbinden wenn man eine Tast gefrückt hat und wie der Paddle
    # sich zu verhalten hat
    def move(self):
        key = pygame.key.get_pressed()
        # Wenn der UP-Key gedrückt wurde und "Grenzen" einrichten (solange der "Top" größer als margin ist kann man nach oben gehen
        # also unter dem Rand ist
        if key[pygame.K_UP] and self.rect.top > margin:
            self.rect.move_ip(0,-1 * self.speed)
        if key[pygame.K_DOWN] and self.rect.bottom < screen_height:
            self.rect.move_ip(0,self.speed)

    def draw(self):
        pygame.draw.rect(screen,self.rect)

    def ai(self):
        # ai to move the paddle automatically
        # move down
        if self.rect.centery < pong.rect.top and self.rect.bottom < screen_height:
            self.rect.move_ip(0,self.ai_speed)
        # move up
        if self.rect.centery > pong.rect.bottom and self.rect.top > margin:
            self.rect.move_ip(0,-1 * self.ai_speed)


class ball():

    def __init__(self,y):
        self.reset(x,y)

    def move(self):

        # check collision with top margin
        if self.rect.top < margin:
            pygame.mixer.Sound.play(plob_sound)
            self.speed_y *= -1
        # check collision with bottom of the screen
        if self.rect.bottom > screen_height:
            pygame.mixer.Sound.play(plob_sound)
            self.speed_y *= -1
        if self.rect.colliderect(player_paddle) or self.rect.colliderect(cpu_paddle):
            pygame.mixer.Sound.play(plob_sound)
            self.speed_x *= -1

        # check for out of bounds
        if self.rect.left < 0:
            pygame.mixer.Sound.play(score_sound)
            self.winner = 1
        if self.rect.left > screen_width:
            pygame.mixer.Sound.play(score_sound)
            self.winner = -1

        # update ball position
        self.rect.x += self.speed_x
        self.rect.y += self.speed_y

        return self.winner

    def draw(self):
        pygame.draw.circle(screen,orange,(self.rect.x + self.ball_rad,self.rect.y + self.ball_rad),self.ball_rad)

    def reset(self,y):
        self.x = x
        self.y = y
        self.ball_rad = 8
        self.rect = Rect(x,self.ball_rad * 2,self.ball_rad * 2)
        self.speed_x = -4
        self.speed_y = 4
        self.winner = 0  # 1 is the player and -1 is the CPU


# create paddles
player_paddle = paddle(screen_width - 40,screen_height // 2)
cpu_paddle = paddle(20,screen_height // 2)

# create pong ball
pong = ball(screen_width - 60,screen_height // 2 + 50)

run = True
def game_to_five():
    global run
    player_score = 0
    opp_score = 0

    live_ball = False
    winner = 0
    speed_increase = 0

    run = True
    while (player_score < 5 and opp_score < 5) and run:

        Clock.tick(60)

        draw_board()
        draw_text('OPP: ' + str(opp_score),20,15)
        draw_text('P1: ' + str(player_score),screen_width - 115,15)
        draw_text('TEMPO: ' + str(abs(pong.speed_x)),screen_width // 2 - 100,15)

        # draw paddles
        player_paddle.draw()
        cpu_paddle.draw()

        if live_ball == True:
            speed_increase += 1
            winner = pong.move()
            if winner == 0:
                # draw ball
                pong.draw()
                # move paddles
                player_paddle.move()
                cpu_paddle.ai()
            else:
                live_ball = False
                if winner == 1:
                    player_score += 1
                elif winner == -1:
                    opp_score += 1

        # print player instructions
        if live_ball == False:
            if winner == 0:
                draw_text('Zum Starten klicken',black,300,screen_width // 2 - 300)
            if winner == 1:
                draw_text('YOU SCORED!',355,160)
                draw_text('CLICK ANYWHERE TO START',200)
            if winner == -1:
                draw_text('CPU SCORED!',160)

                draw_text('CLICK ANYWHERE TO START',200)

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
            if event.type == pygame.MOUSEBUTTONDOWN and live_ball == False:
                live_ball = True
                pong.reset(500,250)
            # screen_width - 60,screen_height // 2 + 50)

        if speed_increase > 500:
            speed_increase = 0
            if pong.speed_x < 0:
                pong.speed_x -= 1
            if pong.speed_x > 0:
                pong.speed_x += 1
            if pong.speed_y < 0:
                pong.speed_y -= 1
            if pong.speed_y > 0:
                pong.speed_y += 1

        pygame.display.update()

    new_game = False
    while not new_game:

        draw_board()
        draw_text('OPP: ' + str(opp_score),15)

        if player_score == 5:
            draw_text('P1 hat gewonnen!',160)
        elif opp_score == 5:
            draw_text('OPP hat gewonnen!',160)
        draw_text('Klicken um fortzufahren',260,200)

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
            if event.type == pygame.MOUSEBUTTONDOWN:
                pong.reset(500,250)
                new_game = True

        pygame.display.update()


# create game loop
while run:
    game_to_five()

pygame.quit()

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。