首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么我的代码无法定义car_racing,以及如何从菜单无缝过渡到游戏?

为什么我的代码无法定义car_racing,以及如何从菜单无缝过渡到游戏?
EN

Stack Overflow用户
提问于 2021-11-02 12:43:06
回答 1查看 0关注 0票数 0
代码语言:javascript
复制
import random
from time import sleep

import pygame


class CarRacing:
    def __init__(self):

        pygame.init()
        self.display_width = 800
        self.display_height = 600
        self.black = (0, 0, 0)
        self.white = (255, 255, 255)
        self.clock = pygame.time.Clock()
        self.gameDisplay = None
        self.initialize()

    def initialize(self):

        self.crashed = False

        self.carImg = pygame.image.load('.\\img\\car.png')
        self.car_x_coordinate = (self.display_width * 0.45)
        self.car_y_coordinate = (self.display_height * 0.8)
        self.car_width = 49

        # enemy_car
        self.enemy_car = pygame.image.load('.\\img\\enemy_car_1.png')
        self.enemy_car_startx = random.randrange(310, 450)
        self.enemy_car_starty = -600
        self.enemy_car_speed = 5
        self.enemy_car_width = 49
        self.enemy_car_height = 100

        # Background
        self.bgImg = pygame.image.load(".\\img\\background-1_0.png")
        self.bg_x1 = (self.display_width / 2) - (360 / 2)
        self.bg_x2 = (self.display_width / 2) - (360 / 2)
        self.bg_y1 = 0
        self.bg_y2 = -600
        self.bg_speed = 3
        self.count = 0

    def car(self, car_x_coordinate, car_y_coordinate):
        self.gameDisplay.blit(self.carImg, (car_x_coordinate, car_y_coordinate))

    def racing_window(self):
        self.gameDisplay = pygame.display.set_mode((self.display_width, self.display_height))
        pygame.display.set_caption('Inline Overdrive')
        self.run_car()

    def run_car(self):

        while not self.crashed:

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    self.crashed = True
                # print(event)

                if (event.type == pygame.KEYDOWN):
                    if (event.key == pygame.K_LEFT):
                        self.car_x_coordinate -= 50
                        print ("CAR X COORDINATES: %s" % self.car_x_coordinate)
                    if (event.key == pygame.K_RIGHT):
                        self.car_x_coordinate += 50
                        print ("CAR X COORDINATES: %s" % self.car_x_coordinate)
                    print ("x: {x}, y: {y}".format(x=self.car_x_coordinate, y=self.car_y_coordinate))

            self.gameDisplay.fill(self.black)
            self.back_ground_road()

            self.run_enemy_car(self.enemy_car_startx, self.enemy_car_starty)
            self.enemy_car_starty += self.enemy_car_speed

            if self.enemy_car_starty > self.display_height:
                self.enemy_car_starty = 0 - self.enemy_car_height
                self.enemy_car_startx = random.randrange(310, 450)

            self.car(self.car_x_coordinate, self.car_y_coordinate)
            self.highscore(self.count)
            self.count += 1
            if (self.count % 100 == 0):
                self.enemy_car_speed += 1
                self.bg_speed += 1
            if self.car_y_coordinate < self.enemy_car_starty + self.enemy_car_height:
                if self.car_x_coordinate > self.enemy_car_startx and self.car_x_coordinate < self.enemy_car_startx + self.enemy_car_width or self.car_x_coordinate + self.car_width > self.enemy_car_startx and self.car_x_coordinate + self.car_width < self.enemy_car_startx + self.enemy_car_width:
                    self.crashed = True
                    self.display_message("You have crashed!")

            if self.car_x_coordinate < 310 or self.car_x_coordinate > 460:
                self.crashed = True
                self.display_message("You have crashed!")

            pygame.display.update()
            self.clock.tick(60)

    def display_message(self, msg):
        font = pygame.font.SysFont("comicsansms", 72, True)
        text = font.render(msg, True, (255, 255, 255))
        self.gameDisplay.blit(text, (400 - text.get_width() // 2, 240 - text.get_height() // 2))
        self.display_credit()
        pygame.display.update()
        self.clock.tick(60)
        sleep(1)
        car_racing.initialize()
        car_racing.racing_window()

    def back_ground_road(self):
        self.gameDisplay.blit(self.bgImg, (self.bg_x1, self.bg_y1))
        self.gameDisplay.blit(self.bgImg, (self.bg_x2, self.bg_y2))

        self.bg_y1 += self.bg_speed
        self.bg_y2 += self.bg_speed

        if self.bg_y1 >= self.display_height:
            self.bg_y1 = -600

        if self.bg_y2 >= self.display_height:
            self.bg_y2 = -600

    def run_enemy_car(self, thingx, thingy):
        self.gameDisplay.blit(self.enemy_car, (thingx, thingy))

    def highscore(self, count):
        font = pygame.font.SysFont("arial", 20)
        text = font.render("Score : " + str(count), True, self.white)
        self.gameDisplay.blit(text, (0, 0))

    def display_credit(self):
        font = pygame.font.SysFont("lucidaconsole", 14)
        text = font.render("Thank You For Playing!", True, self.white)
        self.gameDisplay.blit(text, (600, 520))

import pygame
from pygame.locals import *
import os

# Game Initialization
pygame.init()

# Center the Game Application
os.environ['SDL_VIDEO_CENTERED'] = '1'

# Game Resolution
screen_width=800
screen_height=600
screen=pygame.display.set_mode((screen_width, screen_height))

# Text Renderer
def text_format(message, textFont, textSize, textColor):
    newFont=pygame.font.Font(textFont, textSize)
    newText=newFont.render(message, 0, textColor)

    return newText


# Colors
white=(255, 255, 255)
black=(0, 0, 255)
gray=(50, 50, 50)
red=(255, 0, 0)
green=(0, 255, 0)
blue=(0, 0, 0)
yellow=(255, 255, 0)

# Game Fonts
font = "RacingNumbers.ttf"


# Game Framerate
clock = pygame.time.Clock()
FPS=30

# Main Menu
def main_menu():

    menu=True
    selected="start"

    while menu:
        for event in pygame.event.get():
            if event.type==pygame.QUIT:
                pygame.quit()
                quit()
            if event.type==pygame.KEYDOWN:
                if event.key==pygame.K_UP:
                    selected="start"
                elif event.key==pygame.K_DOWN:
                    selected="quit"
                elif event.key==pygame.K_DOWN:
                    selected="options"
                if event.key==pygame.K_RETURN:
                    if selected=="start":
                        car_racing = CarRacing()
                        car_racing.racing_window()
                    if selected=="quit":
                        pygame.quit()
                        quit()
                    if selected=="options":
                            print(options)
                    
                        

        # Main Menu UI
        screen.fill(blue)
        title=text_format("Inline Overdrive", font, 90, white)
        if selected=="start":
            text_start=text_format("START", font, 75, red)
        else:
            text_start = text_format("START", font, 75, white)
        if selected=="quit":
            text_quit=text_format("QUIT", font, 75, red)
        else:
            text_quit = text_format("QUIT", font, 75, white)
        if selected=="options":
            text_options=text_format("OPTIONS", font, 75, red)
        else:
            text_options = text_format("OPTIONS", font, 75, white)

            
        title_rect=title.get_rect()
        start_rect=text_start.get_rect()
        quit_rect=text_quit.get_rect()
        options_rect=text_options.get_rect()

        # Main Menu Text
        screen.blit(title, (screen_width/2 - (title_rect[2]/2), 80))
        screen.blit(text_start, (screen_width/2 - (start_rect[2]/2), 300))
        screen.blit(text_quit, (screen_width/2 - (quit_rect[2]/2), 360))
        screen.blit(text_options, (screen_width/2 - (quit_rect[2]/2), 420))
        pygame.display.update()
        clock.tick(FPS)
        pygame.display.set_caption("Inline Overdrive")

#Initialize the Game
main_menu()
pygame.quit()
quit()

当汽车撞到树区时,它显示的是:

回溯(最近一次调用):文件"\hs-srv-hsdc-fs2\2015_hd\14782\Documents\Year 12和13\计算机科学\单元3\最终产品\在线过驱动测试4.py",第238行,在main_menu()文件"\hs-srv-hsdc-fs2\2015_hd\14782\Documents\Year 12和13\计算机科学\单元3\最终产品\在线过驱动测试4.py",第197行,在"\hs-srv-hsdc-fs2\2015_hd\14782\Documents\Year 12和13\Computer self.run_car()文件"\hs-srv-hsdc-fs2\2015_hd\14782\Documents\Year 12和13\Computer Science\Unit 3\Final Product\Inline Overdrive Test4.py“中,第51行,在racing_window self.run_car()文件”\hs-srv-hsdc-fs2\2015_hd\14782\Documents\Year 12和13\Computer self.run_car\Unit 3\Final Product\Inline Overdrive Test4.py“中,在run_car self.display_message中,第94行(”You have crashed!")File "\hs-srv-hsdc-fs2\2015_hd\14782\Documents\Year 12 and 13\Computer Science\Unit3\Final Product\Inline Overdrive Test4.py“,display_message car_racing.initialize() NameError: name 'car_racing‘中的第107行

为什么没有定义car_racing,如何让我的游戏从菜单无缝过渡到游戏?

EN

回答 1

Stack Overflow用户

发布于 2021-11-02 15:59:44

好的,这就是问题所在,你调用car_racing.initialize()car_racing.racing_window()的方法无法访问car_racing实例。我建议您在编写这种冗长且“复杂”的代码时,使用一些IDE来查看这些问题。顺便说一句,这里还有一些其他的问题,比如这里,print(options)一旦你的代码到达这里,你会在这里得到另一个错误。我更新了你的代码,花了一些时间,但它不会给你同样的错误,run_car方法和display_message方法是这里的提示符,这里使用这个方法,而我所做的就是将initialize和racing_window方法移到上面,你的代码可以访问它们。

代码语言:javascript
复制
def run_car(self):

    while not self.crashed:

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                self.crashed = True
            # print(event)

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    self.car_x_coordinate -= 50
                    print("CAR X COORDINATES: %s" % self.car_x_coordinate)
                if event.key == pygame.K_RIGHT:
                    self.car_x_coordinate += 50
                    print("CAR X COORDINATES: %s" % self.car_x_coordinate)
                print("x: {x}, y: {y}".format(x=self.car_x_coordinate, y=self.car_y_coordinate))

        self.gameDisplay.fill(self.black)
        self.back_ground_road()

        self.run_enemy_car(self.enemy_car_startx, self.enemy_car_starty)
        self.enemy_car_starty += self.enemy_car_speed

        if self.enemy_car_starty > self.display_height:
            self.enemy_car_starty = 0 - self.enemy_car_height
            self.enemy_car_startx = random.randrange(310, 450)

        self.car(self.car_x_coordinate, self.car_y_coordinate)
        self.highscore(self.count)
        self.count += 1
        if (self.count % 100 == 0):
            self.enemy_car_speed += 1
            self.bg_speed += 1
        if self.car_y_coordinate < self.enemy_car_starty + self.enemy_car_height:
            if self.car_x_coordinate > self.enemy_car_startx and self.car_x_coordinate < self.enemy_car_startx + self.enemy_car_width or self.car_x_coordinate + self.car_width > self.enemy_car_startx and self.car_x_coordinate + self.car_width < self.enemy_car_startx + self.enemy_car_width:
                self.crashed = True
                self.display_message("You have crashed!")
                self.initialize()
                self.racing_window()

        if self.car_x_coordinate < 310 or self.car_x_coordinate > 460:
            self.crashed = True
            self.display_message("You have crashed!")
            self.initialize()
            self.racing_window()

        pygame.display.update()
        self.clock.tick(60)

def display_message(self, msg):
    font = pygame.font.SysFont("comicsansms", 72, True)
    text = font.render(msg, True, (255, 255, 255))
    self.gameDisplay.blit(text, (400 - text.get_width() // 2, 240 - text.get_height() // 2))
    self.display_credit()
    pygame.display.update()
    self.clock.tick(60)
    sleep(1)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69810667

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档