我在下面提供的以下程序是我开发的一个程序,可以随意随意地在屏幕上移动。我一直试图做的下一件事是,如果你用鼠标点击球,它会移动到一个随机位置。我试过if语句但是无法工作?有任何想法吗??真的很感激帮助!
from pygame import *
import random
init()
size = width, height = 800, 600
screen = display.set_mode(size)
#Setting up colour
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
# setting up constants to help with the parts of the list
BALLX = 0
BALLY = 1
BALLSPEEDX = 2
BALLSPEEDY = 3
# function to set up a ball with random attributes
def initBall():
ballx = random.randint(0, 800) # randomly setting the x position
bally = random.randint(0, 600) # randomly setting the y position
dirx = random.randint(-5,5) # randomly setting the x speed
diry = random.randint(-5,5) # randomly setting the y speed
data = [ballx, bally, dirx, diry] # returning a list with all the data the ball needs
return data # returning the list
def moveBall(data): # takes in the list of the ball
data[BALLX] += data[BALLSPEEDX] # increases the position of the ball
data[BALLY] += data[BALLSPEEDY]
# checks to see if the ball is hitting the walls in the x direction
if data[BALLX] > 800:
data[BALLX] = 800
data[BALLSPEEDX] *= -1
elif data[BALLX] < 0:
data[BALLX] = 0
data[BALLSPEEDX] *= -1
# checks to see if the ball is hitting the walls in the y direction
if data[BALLY] < 0:
data[BALLY] = 0
data[BALLSPEEDY] *= -1
elif data[BALLY] > 600:
data[BALLY] = 600
data[BALLSPEEDY] *= -1
return data # returning the updated list
def drawScreen(data): # sends a ball to be displayed
draw.rect(screen, BLACK, (0, 0, 800, 600))
# drawing a ball at the x and y position
draw.circle(screen, RED, (data[BALLX], data[BALLY]), 10)
display.flip()
running = True # variable that controls the main loop
myClock = time.Clock() # for controlling the frames per second
ball = initBall() # initializing the ball
# Game Loop
while running == True: # do this loop as long as running is True
# events all ready
for evnt in event.get(): # checks all events that happen
if evnt.type == QUIT:
running = False
if evnt.type == MOUSEBUTTONDOWN:
mx, my = evnt.pos
button = evnt.button
# calling the draw screen function and sending the ball information
drawScreen(ball)
# moving the ball function, notice ball = the returned value
ball = moveBall(ball)
myClock.tick(60) # waits long enough to have 60 frames per second
quit()
答案 0 :(得分:0)
首先,您需要做的是围绕您的球。
好的,基本上您需要做的是,获取鼠标坐标并检查它们是否与您的球形图像发生碰撞。
您可以在循环中使用以下代码来检查鼠标坐标是否与球碰撞(rect)。
for event in pygame.event.get():
if event.type==pygame.QUIT:
running=False
pygame.quit()
quit()
if event.type == pygame.MOUSEBUTTONDOWN:
# Set the x, y postions of the mouse click
x, y = event.pos
if ballrect.collidepoint(x, y):
ballrect.center=(random.randint(5,1060),random.randint(5,700))
continue