【问题标题】:How to make a ball go around the edge of the screen continuously? (Python 2.7)如何让球连续绕过屏幕边缘? (Python 2.7)
【发布时间】:2016-09-29 15:15:30
【问题描述】:

我的动画代码需要帮助。到目前为止,我让球绕着屏幕的 3 个边缘移动。但我不知道如何让它绕过最后一个屏幕。

#-------------------------------------------------------------------------------
# Name:        U1A4.py
# Purpose:     To animate the ball going around the edge of the screen
#-------------------------------------------------------------------------------

import pygame
import sys
pygame.init()

# Screen
screenSize = (800,600)
displayScreen = pygame.display.set_mode(screenSize,0)
pygame.display.set_caption("Animation Assignment 1")

# Colours
WHITE = (255,255,255)
GREEN = (0,255,0)
RED = (255,0,0)
BLUE = (0,0,255)

displayScreen.fill(WHITE)
pygame.display.update()

# ----------------- Leave animation code here ---------------------------------#

# THU/09/29
# Need to complete the last turn with the ball

x = 50
y = 50
dx = 0
dy = 2
stop = False
while not stop:
    for event in pygame.event.get():
        if event.type ==pygame.QUIT:
            stop = True

    displayScreen.fill(WHITE)

    x = x + dx
    y = y + dy

    if (x>=750):
            dx = 0
            dy = -2

    if (y>=550)and dy>0:
            dy = 0
            dx = 2

    if (x>=750)and dy>0:
            dy = 0
            dx = 2

    if (y>=550)and dy>0:
            dx = 0
            dy = -2


    pygame.draw.circle(displayScreen, GREEN, (x,y),50, 0)
    pygame.display.update()

pygame.quit()
sys.exit()

小球需要连续绕屏幕边界,欢迎任何提示或直接答案。谢谢。

【问题讨论】:

  • 你的代码有什么问题?

标签: python python-2.7 pygame


【解决方案1】:

这是我对你的问题的看法:

import sys, pygame
pygame.init()
size = width, height = 800, 800
speed = [1, 0]
black = 0, 0, 0
screen = pygame.display.set_mode(size)
ball = pygame.image.load("ball.bmp")
ballrect = ball.get_rect()
while 1:
    for event in pygame.event.get():
        if event.type == pygame.QUIT: sys.exit()
    ballrect = ballrect.move(speed)
    if ballrect.right > width:
        speed = [0, 1]
    if ballrect.left < 0:
        speed = [0, -1]
    if (ballrect.bottom > height) and not (ballrect.left < 0):
        speed = [-1,0]
    if (ballrect.top < 0) and not (ballrect.right > width):
        speed = [1, 0]
    screen.fill(black)
    screen.blit(ball, ballrect)
    pygame.display.flip()

让我感觉有点恶心。

编辑 - 将此用于 ball.bmp:

http://everitas.rmcclub.ca/wp-content/uploads/2007/11/soccer_ball_1.bmp

【讨论】:

    【解决方案2】:

    球只在角落改变方向,所以你只需要覆盖四种情况(两个if嵌套在两个if中):

    x += dx
    y += dy
    
    if x >= 750:
      if y >= 550:
        dx = 0
        dy = -2
      elif y <= 50:
        dx = -2
        dy = 0
    elif x <= 50:
      if y >= 550:
        dx = 2
        dy = 0
      elif y <= 50:
        dx = 0
        dy = 2
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-21
      • 1970-01-01
      • 1970-01-01
      • 2020-05-26
      • 2014-06-06
      相关资源
      最近更新 更多