玩家自行移动

如何解决玩家自行移动

所以我遇到的问题是,当我降低P1的速度并提高P2的速度时(通过更改sped和speed的值)。在“呼巴”状态下(当P1失去生命时变为True),P1将开始新回合,并自动朝着上一个回合的方向移动; P2也会自动移动,但移动方向与上次相反-这两个移动均未达到指定的速度(Norm),但似乎只有一半。有没有办法防止这种情况。

注意: 游戏的每一轮都有3秒的暂停时间,这对游戏至关重要吗? 以前,我在其他游戏机制的while循环中进一步遇到了Huba条件,将其放置在当前位置可以确保仅当两个放置器都在碰撞时移动时才发生错误。

关于游戏的注意事项: 用矩形表示的2个玩家在地图上移动(有点像2个玩家的pac-man),但他们彼此追逐。当奔跑者被追赶者抓住时,它失去了生命,下一轮比赛以可见的3秒计时器开始。

我为解决此问题所做的尝试: 移动后将速度恢复为0,这会导致运动非常僵硬。 将速度变化置于循环的不同部分(例如,在我的倒计时嵌入式循环结束时)。 还可以打印测试速度和sped的值,这些值会响应。

根据要求提供更多代码,虽然很多,但减少了很多,并没有包括墙壁

#  Importing neccessary modules and libraries
import pygame
import ctypes
import time
user32 = ctypes.windll.user32

Touch = False
#pause = True
seconds = 5
milliseconds = 0
ELMO = True
player1_Lives = 3
player2_Lives = 3
P1_score = 0
P2_score = 0
P1_scoreSeconds = 0
P2_scoreSeconds = 0
resetTimer = 5
P1_scoreSeconds = 0
P2_scoreSeconds = 0
P1_score = 0
P2_score = 0
D_BLUE = (0,24,46)
BLACK = (0,0)
WHITE = (255,255,255)
SCREEN_WIDTH = user32.GetSystemMetrics(78)#1536
SCREEN_HEIGHT = user32.GetSystemMetrics(79)#864
Touch = False
THREE = pygame.image.load('Three.png')
TWO = pygame.image.load('Two.png')
ONE = pygame.image.load('One.png')

class Player(pygame.sprite.Sprite):
    global Touch
    #  Constructor function
    def __init__(self,x,y,colour):
        # Call the parent's constructor
        super().__init__()

        #  Set height,width and then making use of colour as a parameter
        self.image = pygame.Surface([20,20])
        self.image.fill(colour)
 
        #  Make our top-left corner the passed-in location.
        self.rect = self.image.get_rect()
        #if Touch == False:
        self.rect.y = y
        self.rect.x = x
        #else:
            #self.rect.y = 500
            #self.rect.x = 500
 
        #  Set speed vector
        self.change_x = 0
        self.change_y = 0

        #  Creating lists of objects (self.walls/ all_sprites) for later use but ensuring their values don't interfere
        self.walls = None
        self.all_sprites = None
        #  Creating objects (self.walls/ all_sprites) for later use but ensuring their values don't interfere
        self.P1 = None
        self.P2 = None
 
    def changespeed(self,y):
        self.change_x += x
        self.change_y += y

    def reset(self,r,q):
        self.rect.y = q
        self.rect.x = r
        
    #  Detects collisions when the players position is updated
    def update(self):
        global Touch
        # Move left/right
        self.rect.x += self.change_x

        Apple = pygame.sprite.collide_rect(P1,P2)
        if Apple:
            Touch = True
 
        #  Did this update cause us to hit a wall?
        block_hit_list = pygame.sprite.spritecollide(self,self.all_sprites,False)
        for block in block_hit_list:
            if block != self:
                #Touch = True
                #time.sleep(0.1)
                #Touch = False
            #  If we are moving right,set our right side to the left side of the item we hit
                if self.change_x > 0:
                    self.rect.right = block.rect.left

                else:
                #  Otherwise if we are moving left,do the opposite.
                    self.rect.left = block.rect.right
            
 
        #  Collisons on the y-axis
        self.rect.y += self.change_y

        Apple = pygame.sprite.collide_rect(P1,P2)
        if Apple:
            Touch = True
 
        #  Check and see if we hit anything
        block_hit_list = pygame.sprite.spritecollide(self,False)
        for block in block_hit_list:
            if block != self:
            #  Reset our position based on the top/bottom of the object.
                if self.change_y > 0:
                    self.rect.bottom = block.rect.top

                else:
                    self.rect.top = block.rect.bottom
#  Create the player paddle object
P2 = Player(400,400,RED)
P1 = Player(600,WHITE)

#  Wall interaction
P1.walls = wall_list
P2.walls = wall_list

#  Adding the players to the list of sprites
all_sprite_list.add(P1)
all_sprite_list.add(P2)

#  Assigns the attribute all_sprites all_sprites_list for the players
P1.all_sprites = all_sprite_list
P2.all_sprites = all_sprite_list

#  Defining a clock to be used later
clock = pygame.time.Clock()

# A function that allows you to create a message in a predifined font
def text_objects(text,font,colour):
    textSurface = font.render(text,True,colour)
    return textSurface,textSurface.get_rect()

def Text(message,size,colour,y):
    msgg = str(message)
    MediumText = pygame.font.Font('freesansbold.ttf',size)
    TextSurf,TextRect = text_objects(msgg,MediumText,colour)
    TextRect.center = ((x),(y))
    screen.blit(TextSurf,TextRect)

def Gameplay():
    global P1_sped
    global P1_speed
    global P2_sped
    global P2_speed
    global Touch
    global player1_Lives
    global player2_Lives
    global P1_score
    global P2_score
    global done
    global seconds
    global milliseconds
    global ELMO
    global P1_scoreSeconds
    global P2_scoreSeconds
    global resetTimer
    global P1_score
    global P2_score

    if ELMO == True:
        Player_1_turn = True
        Player_2_turn = False
        P1_Turns = 3
        P2_Turns = 3

        #resetTimer = 5
        clock = pygame.time.Clock()


        P1_sped = P1_sped + 1
        P1_speed = P1_speed - 1
        print(P1_sped,"sped")
        print(P1_speed,"speed")

        Countdown = True
        done = False
        #Billy = True
        Huba = None

    else:
        #resetTimer = 5
        clock = pygame.time.Clock()
        ELMO = True
    while not done:

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                done = True
            
            # Keydown movement bindings
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    P2.changespeed(P2_speed,0)
                if event.key == pygame.K_RIGHT:
                    P2.changespeed(P2_sped,0)
                if event.key == pygame.K_UP:
                    P2.changespeed(0,P2_speed)
                if event.key == pygame.K_DOWN:
                    P2.changespeed(0,P2_sped)
                if event.key == pygame.K_a:
                    P1.changespeed(P1_speed,0)
                if event.key == pygame.K_d:
                    P1.changespeed(P1_sped,0)
                if event.key == pygame.K_w:
                    P1.changespeed(0,P1_speed)
                if event.key == pygame.K_s:
                    P1.changespeed(0,P1_sped)
                if event.key == pygame.K_p:
                    Paused()

                    
            # Keyup movement bindings          
            elif event.type == pygame.KEYUP:
                if event.key == pygame.K_LEFT:
                    P2.changespeed(P2_sped,0)
                if event.key == pygame.K_RIGHT:
                    P2.changespeed(P2_speed,P2_sped)
                if event.key == pygame.K_DOWN:
                    P2.changespeed(0,P2_speed)
                if event.key == pygame.K_a:
                    P1.changespeed(P1_sped,0)
                if event.key == pygame.K_d:
                    P1.changespeed(P1_speed,P1_sped)
                if event.key == pygame.K_s:
                    P1.changespeed(0,P1_speed)

                if Huba == True:
                    AppleSauce()
                    P1_sped -= 1
                    P1_speed += 1
                    P2_sped += 1
                    P2_speed -= 1
                    Huba = False

                    
        if Touch == True:
            #Countdown = True
            Countdown = True
            P1.reset(500,500)
            P2.reset(800,500)
            if Player_1_turn == True:
                P2_score += 300
                P1_scoreSeconds += seconds
                if player1_Lives > 0:
                    player1_Lives -= 1
                    P1_Turns -= 1
                    seconds = resetTimer
                
                if player1_Lives == 0:

                    Huba = True

                    
                    Player_1_turn = False
                    Player_2_turn = True
                    Text("GameOver Player1",100,WHITE,SCREEN_WIDTH/2,SCREEN_HEIGHT/2)
                    pygame.display.update()
                    time.sleep(1)
                    #print(P1_sped,"P1_sped again")
                    #print(P1_speed,"P1_speed again")
                    #print(P2_sped,"P2_sped")
                    #print(P2_speed,"P2_speed")
                    
            else:
            #if Player_2_turn == True:
                P1_score += 300
                P2_scoreSeconds += seconds
                if player2_Lives > 0:
                    player2_Lives -= 1
                    P2_Turns -= 1
                    seconds = resetTimer
                if player2_Lives == 0:
                    Text("GameOver Player2",SCREEN_HEIGHT/2)
                    pygame.display.update()
                    time.sleep(1)
                    GameEnd()
            Touch = False
                

        #  Applying an update to the spries
        all_sprite_list.update()

        #  Backgorund colour
        screen.fill(D_BLUE)

        #  Applying the sprites
        all_sprite_list.draw(screen)

        #  The countdown used before the game starts
        if Countdown == True:
            screen.blit(THREE,(SCREEN_WIDTH/2-53.5,SCREEN_HEIGHT/2-91.5))
            pygame.display.update()
            time.sleep(1)
            screen.fill(D_BLUE)
            all_sprite_list.draw(screen)
            #pygame.draw.rect(screen,BLACK,(SCREEN_WIDTH/2-250,SCREEN_HEIGHT/2-250,500,500))


            screen.blit(TWO,(SCREEN_WIDTH/2-52,SCREEN_HEIGHT/2-88.5))
            pygame.display.update()
            time.sleep(1)
            screen.fill(D_BLUE)
            all_sprite_list.draw(screen)
            #pygame.draw.rect(screen,500))

            screen.blit(ONE,(SCREEN_WIDTH/2-39,SCREEN_HEIGHT/2-87))
            pygame.display.update()
            time.sleep(1)

            clock.tick(60)
            Countdown = False
            
        milliseconds += clock.tick(300)
            
        if milliseconds > 1000:
            seconds -= 1
            milliseconds -= 1000
        #if seconds > 60:
            #minutes += 1
            #seconds -= 60
        if seconds == 0:
            #Countdown = True
            P1.reset(500,500)
            if Player_1_turn:
                P1_score += 1000
                P1_Turns -= 1
                Countdown = True
                seconds = resetTimer
                if P1_Turns == 0:
                    Text("GameOver Player1",SCREEN_HEIGHT/2)
                    #screen.blit(Text("GameOver Player1",SCREEN_HEIGHT/2)) #Optional alternative
                    pygame.display.update()
                    time.sleep(1)
                    Player_2_turn = True
                    Player_1_turn = False
            else:
            #if Player_2_turn == True or Player_1_turn == False:
                P2_score += 1000
                P2_Turns -= 1
                Countdown = True
                seconds = resetTimer
                if P2_Turns == 0:
                    Text("GameOver Player2",SCREEN_HEIGHT/2)
                    pygame.display.update()
                    time.sleep(1)
                    #GameEnd()

        if seconds > 5:
            seconds = 5
        Text(seconds,SCREEN_HEIGHT/2-350)
        
        pygame.display.flip()

        
StartScreen()
pygame.quit()

问题重点从这里开始(原文)

Norm = 5
P1_sped = Norm
P1_speed = -Norm

P2_sped = Norm
P2_speed = -Norm
while not done:
        

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                done = True
            
            # Keydown movement bindings
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    P2.changespeed(P2_speed,P1_sped)
                if event.key == pygame.K_p:
                    Paused()
                    
            # Keyup movement bindings          
            elif event.type == pygame.KEYUP:
                if event.key == pygame.K_LEFT:
                    P2.changespeed(P2_sped,P1_speed)

                if Huba == True:
                    AppleSauce()
                    P1_sped -= 1
                    P1_speed += 1
                    P2_sped += 1
                    P2_speed -= 1
                    Huba = False

image for countdown

image for countdown

image for countdown

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

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 <select id="xxx"> SELECT di.id, di.name, di.work_type, di.updated... <where> <if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 <property name="dynamic.classpath" value="tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams['font.sans-serif'] = ['SimHei'] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -> systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping("/hires") public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate<String
使用vite构建项目报错 C:\Users\ychen\work>npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-