首页 > 编程问答 >如何通过按键在pygame中移动图像?

如何通过按键在pygame中移动图像?

时间:2024-08-01 03:56:24浏览次数:6  
标签:python pygame

我正在用 pygame 制作一个简单的游戏,我想移动一张图片,但该图片似乎每次点击都会制作,这根本不是我想要的,我想通过按键来移动它,但每次时间移动了一个

screen shot

代码:

# import modules
import pygame
from pygame.locals import *
import sys
import os
#################
pygame.init()
#################

#Colors
red = (255 , 0 , 0) # RED
green = (0, 255, 0) # GREEN
blue = (10, 60, 225) # BLUE
white = (255, 255, 255) # WHITE
black = (0, 0, 0) # BLACK

# window
window = pygame.display.set_mode((600, 400)) # window size
pygame.display.set_caption("Ball away") # title
window.fill(white) # backgrond color
img = pygame.image.load("bin/images/icon.png") # window icon
pygame.display.set_icon(img) # load icon

# screen
#lines
lineup = pygame.draw.line(window, black, (0,35), (100000,0),4)
linedown = pygame.draw.line(window, black, (0,350), (1000000,4),4)
#TEXTS
ping_text = "Ping : 50"
font = pygame.font.SysFont(None, 25)
t_p = font.render(ping_text, True, (0, 0, 0))
window.blit(t_p, (515, 10))

count_win = "0 - 0"
font = pygame.font.SysFont(None, 30)
c_w = font.render(count_win, True, (0, 0, 0))
window.blit(c_w, (284, 10))


exit_ico = pygame.image.load("bin/images/exit.png")
exit_i = pygame.transform.scale(exit_ico,(30, 30))
window.blit(exit_i , (3, 3))

# players
    # RED
P1_x = 3
P1_y = 140
speed = 5

Player_RED = pygame.image.load("bin/images/Player1_RED.png")
player1_red = pygame.transform.scale(Player_RED,(80, 85))

    # BLUE
P2_x = 520
P2_y = 145
speed = 5

Player_BLUE = pygame.image.load("bin/images/Player2_BLUE.png")
player2_blue = pygame.transform.scale(Player_BLUE,(80, 85))

# ball
Ball_lets = pygame.transform.scale(img,(35,35))
window.blit(Ball_lets, (300, 170))

# soundObj = pygame.mixer.Sound('bin/sounds/Music.mp3')
# soundObj.play()

# main loop
running = True
while running:
    
    
    for event in pygame.event.get():
        if event.type == QUIT:
            os.system('cls')
            running = False
            
        if event.type == KEYUP:
            if event.key == K_w:
                P1_y -= speed
            if event.key == K_s:
                P1_y += speed
        window.blit(player1_red, (P1_x, P1_y))

        if event.type == KEYUP:
            if event.key == K_UP:
                P2_y -= speed
            if event.key == K_DOWN:
                P2_y += speed
        window.blit(player2_blue, (P2_x, P2_y))

    pygame.display.update()
pygame.quit()
sys.exit()

缩进不是我的问题,我是 Stack Overflow 的新手


问题在于你是在 每次 按键事件发生时都在绘制图像,而不是在特定位置更新图像的位置。这样一来,看起来图像就在不断地被“绘制”出来,而不是移动。

以下是如何修改代码以正确移动图像的方法:

# import modules
import pygame
from pygame.locals import *
import sys
import os
#################
pygame.init()
#################

# ... [其余的代码与之前相同] ...

# main loop
running = True
while running:
    # 处理事件
    for event in pygame.event.get():
        if event.type == QUIT:
            os.system('cls')
            running = False

        if event.type == KEYDOWN:  # 检查按键按下事件
            if event.key == K_w:
                P1_y -= speed
            if event.key == K_s:
                P1_y += speed
            if event.key == K_UP:
                P2_y -= speed
            if event.key == K_DOWN:
                P2_y += speed

    # 更新游戏状态
    # ... [这里可以添加任何游戏逻辑,例如球的移动、碰撞检测等] ...

    # 绘制游戏画面
    window.fill(white)  # 清除屏幕

    #lines
    lineup = pygame.draw.line(window, black, (0,35), (100000,0),4)
    linedown = pygame.draw.line(window, black, (0,350), (1000000,4),4)

    #TEXTS
    window.blit(t_p, (515, 10))
    window.blit(c_w, (284, 10))
    window.blit(exit_i , (3, 3))

    # players
    window.blit(player1_red, (P1_x, P1_y))  # 在新位置绘制图像
    window.blit(player2_blue, (P2_x, P2_y))  # 在新位置绘制图像

    # ball
    window.blit(Ball_lets, (300, 170))

    # 更新显示
    pygame.display.update()

pygame.quit()
sys.exit()

主要的变化是:

  1. 事件处理 : 我们现在在 KEYDOWN 事件中检查按键按下,这意味着只有当按键被按下时才会移动图像。
  2. 游戏循环结构 : 我们将代码分为三个部分:
    • 事件处理 : 处理用户的输入。
    • 更新游戏状态 : 更新游戏对象的位置和其他属性。
    • 绘制游戏画面 : 将更新后的游戏画面绘制到屏幕上。
  3. 清除屏幕 : 在每一帧开始时使用 window.fill(white) 清除屏幕,以防止图像出现“拖尾”现象。

通过这些修改,你的图像现在应该可以平滑地移动了。

标签:python,pygame
From: 67230513

相关文章

  • 解决python自动化操作异常处理的问题
    在python自动化领域,往往要用到pyautogui,pywin32等模块实现自动化操作。然而,这种自动化操作,本身具有一定的局限性,其中最主要的一个问题就是,一旦执行结果不按照脚本预设的来执行,往往会抛出异常,导致程序中断。解决这个问题,主要有这么几种思路:第一,每一次操作后分情况讨论。这种方......
  • Python爬虫入门03:用Urllib假装我们是浏览器
    文章目录引言Urllib库简介Request模块详解Error模块与异常处理Parse模块与URL解析Robotparser模块模拟浏览器请求使用Request方法添加请求头信息代码示例1.设置请求URL和请求头2.定义请求参数并转换为适当的格式3.使用Request方法封装请求4.发送请求并获取响应常用......
  • 请以零基础学Python 之 第二十讲 分组和贪婪匹配
    当我们处理字符串时,有时候需要根据特定的模式来分割或者提取信息。Python提供了强大的正则表达式库re,可以帮助我们实现这些复杂的字符串操作。本篇博客将介绍两个常用的正则表达式技巧:分组和贪婪匹配。分组(Grouping)在正则表达式中,分组是将多个模式单元组合为一个单元,以便......
  • 零基础学python 之 第十九讲 正则表达式
    当你开始学习Python编程时,正则表达式是一项非常强大的工具,用于处理文本数据中的模式匹配和搜索。本篇博客将带你从零开始学习如何在Python中使用正则表达式。1.什么是正则表达式?正则表达式(RegularExpression)是用于描述字符串模式的一种工具,可以用来匹配、查找、替换符合特......
  • python之贪吃蛇
    废话不多说,直接上代码(确保已经安装pygame)importpygameimportrandom#基础设置#屏幕高度SCREEN_HEIGHT=480#屏幕宽度SCREEN_WIDTH=600#小方格大小GRID_SIZE=20#颜色设置WHITE=(255,255,255)BLACK=(0,0,0)GREEN=(0,255,0)#初始化Pyg......
  • Python - Context Managers
    withstatementHereisthesyntaxofthewithstatement:withexpressionasvar:statementsTheexpressionshouldbeacontextmanagerobject,oritshouldproduceacontextmanagerobject.Whenthiswithstatementisexecuted,thefirstthingthat......
  • python装饰器
    一前言环境:win10python3.10二函数中的函数如果定义了一个函数A,现在想在不影响函数A原先功能的情况下,新增加一些额外的功能,怎么办,下面是一个例子如上,本来原先执行test_except那句话只会打印over那句话,但现在执行test_except却会输出一些另外的东西这其中有个巧妙地东西就......
  • Python - Built-in Exceptions: Python Exceptions Class Hierarchy
     Figure20.4:Built-inexceptionsTheclassBaseExceptionisthebaseclassofallthebuilt-inexceptionclasses.FromBaseException,fourclassesnamedException,SystemExit,KeyboardInterruptandGeneratorExitarederived.Alltheremainingbuilt-in......
  • Python - Strategies to handle exceptions in your code
    Therearetwoapproachesthatcanbefollowedwhenwewanttodealwithexceptionsthatoccurduetounusualevents:LBYL-LookBeforeYouLeapEAFP-EasiertoAskforForgivenessthanPermissionIntheLBYLapproach,weavoidexceptions,whileinthe......
  • 全网最适合入门的面向对象编程教程:29 类和对象的Python实现-断言与防御性编程和help函
    全网最适合入门的面向对象编程教程:29类和对象的Python实现-断言与防御性编程和help函数的使用摘要:在Python中,断言是一种常用的调试工具,它允许程序员编写一条检查某个条件。本文主要介绍了断言的应用场景和特点以及assert语句的使用,同时介绍了防御性编程和help()函数......