社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
私信  •  关注

cdlane

cdlane 最近创建的主题
cdlane 最近回复了
3 年前
回复了 cdlane 创建的主题 » Python Turtle-Snake程序中的自定义形状问题

当我将其更改为自定义图像时,问题是它已打印 在第一个身体部位下方,不能转动。

至于不转向,这在 register_shape() 又称作 addshape() :

注: 当转动海龟时,图像形状不会旋转,所以它们会旋转 不要显示海龟的头部!

至于重叠问题,我只能猜测。一般来说,海龟的规则是,最后移动的东西在上面。因此,转动你的普通头部形状会使其位于顶部,但因为你的图像形状实际上没有转动,所以它会位于底部。再说一次,只是猜测而已。

4 年前
回复了 cdlane 创建的主题 » python元胞自动机图形库中的图形表现异常

我发现这里的复杂性在于每次通过主循环创建新的图形对象。让我们重新设计程序,在循环之前创建一次图形对象,然后在循环过程中简单地操纵它们的颜色,在循环结束时更新屏幕:

import time
import numpy as np
from graphics import *

quick_start = int(input("debug:quickstart:"))

if quick_start:
    wHeightWidth = 600
    xysize = 5
    iLoops = 1000
    OnColor = "grey"
    OffColor = "white"
    # startBoard = np.array([[0, 0, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 1, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 0, 0]])
else:
    wHeightWidth = int(input("Window Size:"))
    xysize = int(input("Board Size:"))
    iLoops = int(input("Number of loops:"))
    OnColor = str(input("On Color:"))
    OffColor = str(input("Off Color:"))

startBoard = np.random.randint(0, 2, size=(xysize, xysize))
nextStep = np.full(startBoard.shape, 0)

wHeight = wWidth = wHeightWidth
window = GraphWin(width=wWidth, height=wHeight, autoflush=False)

squareOrigin = Point(0, 0)

increaseAmountX = wWidth/xysize
increaseAmountY = wHeight/xysize

print(startBoard)

screenBoard = []

for r in range(xysize):
    screenBoard.append(list())

    for c in range(xysize):
        newSquare = Rectangle(squareOrigin, Point(squareOrigin.x + increaseAmountX, squareOrigin.y + increaseAmountY))

        if startBoard[r][c] == 1:
            newSquare.setFill(OnColor)
        else:
            newSquare.setFill(OffColor)

        screenBoard[r].append(newSquare)

        newSquare.draw(window)

        squareOrigin.x += increaseAmountX

    squareOrigin.x = 0
    squareOrigin.y += increaseAmountY

window.update()

for i in range(iLoops):

    for r in range(xysize):
        for c in range(xysize):
            iNei = 0
            # cardinal directions

            # check left & right
            try:
                if startBoard[r+1][c] == 1:
                    iNei += 1
            except IndexError:
                pass
            try:
                if startBoard[r-1][c] == 1:
                    iNei += 1
            except IndexError:
                pass

            # check up & down
            try:
                if startBoard[r][c+1] == 1:
                    iNei += 1
            except IndexError:
                pass
            try:
                if startBoard[r][c-1] == 1:
                    iNei += 1
            except IndexError:
                pass

            # diagonals
            try:
                if startBoard[r+1][c+1] == 1:
                    iNei += 1
            except IndexError:
                pass
            try:
                if startBoard[r-1][c-1] == 1:
                    iNei += 1
            except IndexError:
                pass
            try:
                if startBoard[r+1][c-1] == 1:
                    iNei += 1
            except IndexError:
                pass
            try:
                if startBoard[r-1][c+1] == 1:
                    iNei += 1
            except IndexError:
                pass

            if startBoard[r][c] == 1:
                if iNei < 2:
                    nextStep[r][c] = 0
                elif iNei > 3:
                    nextStep[r][c] = 0
                else:
                    nextStep[r][c] = startBoard[r][c]
            else:
                if iNei == 3:
                    nextStep[r][c] = 1
                elif iNei == 2:
                    nextStep[r][c] = startBoard[r][c]

            if startBoard[r][c] == 1:
                screenBoard[r][c].setFill(OnColor)
            else:
                screenBoard[r][c].setFill(OffColor)

    window.update()

    print("\n", "-" * 25, "\n")
    print(nextStep)
    startBoard = nextStep
    nextStep = np.full(startBoard.shape, 0)
    time.sleep(5)

enter image description here

安慰

> python3 test.py
debug:quickstart:1
[[1 0 0 0 0]
 [0 0 1 1 0]
 [1 0 0 0 0]
 [1 0 0 0 1]
 [0 1 1 0 1]]

 ------------------------- 

名字 repr 已经属于Python内置函数,因此与其重新定义它,不如假设您的代码是:

def my_repr(e):
    if isinstance(e, (list, tuple)):
        return "(%s)" % " ".join(map(my_repr, e))

    return str(e)

假设您不想进行简单的字符串操作,而是实际遍历列表,我们可以替换 隐性的 递归堆栈 堆栈:

def my_repr(e):
    stack = [e]

    result = ""

    while stack:
        item = stack.pop()

        if isinstance(item, (list, tuple)):
            stack.append(")")
            stack.extend(reversed(item))
            result += "("
        elif item == ")":
            result += item
        else:
            result += str(item) + " "

    return result

item 作为将其添加到字符串的一部分,例如:

            result += str(item * item) + " "

输出字符串现在包含输入结构中数字的平方。或者别的什么。

C类 reversed() . 这种非递归实现的一个优点是,大型、复杂的输入不应该像递归输入一样,触发Python的调用堆栈限制。

6 年前
回复了 cdlane 创建的主题 » 如何在python3中使用graphics.py获取和设置像素的颜色值

Zelle graphics提供操作员来操作代码中记录的图像像素:

该库还为基于像素的图像提供了一个非常简单的类 使用图像对象。提供getPixel和setPixel方法 用于处理图像。

这个答案 Get color of coordinate of figure drawn with Python Zelle graphics 演示如何 得到 设置

5 年前
回复了 cdlane 创建的主题 » Python错误:模块“turtle”没有属性“Pen”

您的代码正确:

import turtle
t = turtle.Pen()

确保你没有自己的文件 turtle.py 因为这会干扰Python自己的加载 乌龟.py 图书馆。

6 年前
回复了 cdlane 创建的主题 » 如何用Python制作带有turtle图形的线性图形计算器?

为什么当我试图绘制图形时,这段代码不起作用?

我认为有两个问题:1)你似乎做事情的顺序不对;2)你错误地认为如果y是f(x),那么f(-x)是-y,这不是真的:

from turtle import *

m = float(input("What is the slope? "))

b = float(input("What is the y-intercept? "))

x, y = window_width(), window_height()

# Draw Axes
penup()
goto(x / 2, 0)
pendown()
goto(-x / 2, 0)
penup()
goto(0, y / 2)
pendown()
goto(0, -y / 2)

# Plot function

y = int(m * x + b)

penup()
goto(x, y)

x = -x
y = int(m * x + b)

pendown()
goto(x, y)

done()

用法

> python3 test.py
What is the slope? 0.5
What is the y-intercept? 100
>

输出

enter image description here

6 年前
回复了 cdlane 创建的主题 » python turtle module object.hideturtle不工作

我无法重现你的问题。我重新编写了下面的代码:我删除了图像和声音,以便任何人都可以运行它并帮助您调试它;我放弃了 isCollision() 编码和替换海龟自己的 distance() 方法;我替换了 while True: Loop,在Turtle这样的事件驱动世界中没有位置,它有一个计时器事件;我已经简化了代码,可以:

from turtle import Screen, Turtle
from random import randint

PLAYER_SPEED = 15
BULLET_SPEED = 20

# Choose a number of enemies
NUMBER_OF_ENEMIES = 20

SMALL_FONT = ('Arial', 14, 'normal')
LARGE_FONT = ('Arial', 60, 'normal')

# Move the player left and right
def move_left():
    x = player.xcor() - PLAYER_SPEED

    if x < -280:
        x = -280

    player.setx(x)

def move_right():
    x = player.xcor() + PLAYER_SPEED

    if x > 280:
        x = 280

    player.setx(x)

def fire_bullet():
    if not bullet.isvisible():
        # Move the bullet to the just above the player
        x, y = player.position()
        bullet.setposition(x, y + 10)
        bullet.showturtle()

# Check collision between enemy and bullet
def isCollision(t1, t2):
    return t1.distance(t2) < 20

# Set up the screen
wn = Screen()
wn.bgcolor('black')
wn.title("Space Invaders")

# Draw border
border_pen = Turtle(visible=False)
border_pen.speed('fastest')
border_pen.color('white')
border_pen.pensize(3)

border_pen.penup()
border_pen.setposition(-300, -300)
border_pen.pendown()

for _ in range(4):
    border_pen.fd(600)
    border_pen.lt(90)

# Set the score to 0
score = 0

# Draw score
score_pen = Turtle(visible=False)
score_pen.speed('fastest')
score_pen.color('white')
score_pen.penup()

score_pen.setposition(-290, 280)
scorestring = "Score: %s" % score
score_pen.write(scorestring, False, align='left', font=SMALL_FONT)

# Game Over
game_over = Turtle(visible=False)
game_over.speed('fastest')
game_over.color('red')
game_over.penup()
gameOverMsg = "Game Over!"

# Create player
player = Turtle('turtle')
player.speed('fastest')
player.color('blue')
player.penup()
player.setposition(0, -230)
player.setheading(90)

# Create empty list of enemies
enemies = []

# Add enemies to list
for _ in range(NUMBER_OF_ENEMIES):
    # Create the enemy
    enemy = Turtle('turtle', visible=False)
    enemy.settiltangle(270)  # for non GIF version of game
    enemy.speed('fastest')
    enemy.color('red')
    enemy.penup()
    enemy.setposition(randint(-200, 200), randint(100, 250))

    enemies.append(enemy)

for enemy in enemies:
    enemy.showturtle()

# Create the player's bullet
bullet = Turtle('triangle', visible=False)
bullet.color('yellow')
bullet.penup()
bullet.speed('fastest')
bullet.setheading(90)
bullet.shapesize(0.5)

# Create keyboard bindings
wn.onkeypress(move_left, 'Left')
wn.onkeypress(move_right, 'Right')
wn.onkeypress(fire_bullet, 'space')
wn.listen()

enemy_speed = NUMBER_OF_ENEMIES * 0.5

# Main game loop
def move():
    global score, enemy_speed

    collision = False

    for enemy in enemies:

        # Move the enemy
        enemy.forward(enemy_speed)

        # Check for a collision between the bullet and the enemy
        if isCollision(bullet, enemy):
            # Reset the bullet
            bullet.hideturtle()
            # Reset the enemy
            enemy.setposition(randint(-200, 200), randint(100, 250))
            # Update the score
            score += 10
            scorestring = "Score: %s" % score
            score_pen.clear()
            score_pen.write(scorestring, False, align='left', font=SMALL_FONT)

        if isCollision(player, enemy):
            player.hideturtle()
            enemy.hideturtle()
            game_over.write(gameOverMsg, False, align='center', font=LARGE_FONT)
            collision = True
            break

    if any(enemy.xcor() < -280 or enemy.xcor() > 280 for enemy in enemies):
        # Move all enemies down
        for enemy in enemies:
            enemy.sety(enemy.ycor() - 40)

        # Change enemy direction
        enemy_speed *= -1

    # Move the bullet
    if bullet.isvisible():
        bullet.forward(BULLET_SPEED)
        # Check border collision
        if bullet.ycor() > 290:
            bullet.hideturtle()

    if not collision:
        wn.ontimer(move, 50)

move()

wn.mainloop()

这个节目对我来说是似曾相识的 with respect to this question 所以看 my answer to it 更多的想法。另外,请看这个答案 another space invaders game in turtle 看看你能从中学到什么来完善你的游戏。

6 年前
回复了 cdlane 创建的主题 » 从Python到Java的BaILePSW素数测试算法故障转换部分

我能看到的一个地方是你对这句话的翻译,还有三个类似的地方:

U, V = (P*U + V + n) >> 1, (D*U + P*V + n) >> 1

这些是 平行 python中的赋值,即 V 正在计算 古老的 价值 U 在陈述之前。但在你的翻译中:

U = (P*U + V + n) >> 1;
V = (D*U + P*V + n) >> 1;

这个 V 正在使用 新的 价值 U . 更好的翻译可能是这样的:

long old_U = U;
U = (P*U + V + n) >> 1;
V = (D*old_U + P*V + n) >> 1;

同样,其他平行作业也需要这样做。

6 年前
回复了 cdlane 创建的主题 » 在python中使用zelle图形的动画

相反,轮流完全地移动每个圆圈,切碎这些动作,并交替进行,这样在循环赛中每个圆圈一次移动一点。我猜这和你想做的很接近:

from random import randrange
from graphics import *

def rand_color():
    """ Generate a random color and return it. """

    return color_rgb(randrange(256), randrange(256), randrange(256))

win = GraphWin("My Circle", 500, 500)

circles = []

for x in [-1, 1]:
    for y in [-1, 1]:
        circle = Circle(Point(250, 250), 20)
        circle.setFill(rand_color())
        circle.draw(win)
        circles.append((circle, (x, y)))

for _ in range(250):
    for circle, (x, y) in circles:
        circle.move(x, y)

win.getMouse()  # Pause to view result
win.close()  # Close window when done

enter image description here

6 年前
回复了 cdlane 创建的主题 » 检测是否在python zelle图形中的框内单击

如果你点击外面的任何地方,我怎么才能关闭程序 盒子

考虑到你设计界面的方式,这很简单。我们可以更改此代码:

inst.append(Rectangle(Point(max_x/2-59,190), Point(max_x/2+59, 210)))

...

p_win.getMouse()

取而代之的是:

rectangle = Rectangle(Point(max_x/2 - 59, 190), Point(max_x/2 + 59, 210))
inst.append(rectangle)

...

point = p_win.getMouse()
if not inside(point, rectangle):
    p_win.close()
    exit()

在哪里? inside() 定义为:

def inside(point, rectangle):
    p1 = rectangle.getP1()
    p2 = rectangle.getP2()

    return  p1.getX() <= point.getX() <= p2.getX() and p1.getY() <= point.getY() <= p2.getY()

我们也可以这样做 'PLAY AGAIN' .

但是,您的代码很难遵循,因为它是密集的,并且嵌入在内部 main() . 我重新编写了下面的代码,从 主体() ,进行上述更改,并处理样式:

from random import randrange
from graphics import *

MAX_X, MAX_Y = 500, 300

PIP_SIZE = 4
DICE_SIZE = 50

class Pips():
    """ Draw pips """

    def __init__(self, x, y, dice_size):
        self.m_x = x
        self.m_y = y

        d = dice_size / 4

        self.m_items = []

        self.m_items.append(Circle(Point(x + 2 * d, y + 2 * d), PIP_SIZE))
        self.m_items.append(Circle(Point(x + 1 * d, y + 1 * d), PIP_SIZE))
        self.m_items.append(Circle(Point(x + 1 * d, y + 2 * d), PIP_SIZE))
        self.m_items.append(Circle(Point(x + 1 * d, y + 3 * d), PIP_SIZE))
        self.m_items.append(Circle(Point(x + 3 * d, y + 1 * d), PIP_SIZE))
        self.m_items.append(Circle(Point(x + 3 * d, y + 2 * d), PIP_SIZE))
        self.m_items.append(Circle(Point(x + 3 * d, y + 3 * d), PIP_SIZE))

        for pip in self.m_items:
            pip.setFill('black')

    def undraw(self):
        for pip in self.m_items:
            pip.undraw()

    def draw(self, p_win, p_num):
        """ Draw Dice """

        self.undraw()

        if p_num == 1:
            self.m_items[0].draw(p_win)
        elif p_num == 2:
            self.m_items[3].draw(p_win)
            self.m_items[4].draw(p_win)
        elif p_num == 3:
            self.m_items[0].draw(p_win)
            self.m_items[3].draw(p_win)
            self.m_items[4].draw(p_win)
        elif p_num == 4:
            self.m_items[1].draw(p_win)
            self.m_items[3].draw(p_win)
            self.m_items[4].draw(p_win)
            self.m_items[6].draw(p_win)
        elif p_num == 5:
            self.m_items[0].draw(p_win)
            self.m_items[1].draw(p_win)
            self.m_items[3].draw(p_win)
            self.m_items[4].draw(p_win)
            self.m_items[6].draw(p_win)
        elif p_num == 6:
            self.m_items[1].draw(p_win)
            self.m_items[2].draw(p_win)
            self.m_items[3].draw(p_win)
            self.m_items[4].draw(p_win)
            self.m_items[5].draw(p_win)
            self.m_items[6].draw(p_win)

class Dice_t:
    """ Prepares for next roll """

    def __init__(self, x, y):
        self.m_x = x
        self.m_y = y
        self.m_s = DICE_SIZE

        self.m_item = Rectangle(Point(x, y), Point(x + self.m_s, y + self.m_s))
        self.m_item.setFill('white')
        self.m_pips = Pips(x, y, self.m_s)

    def draw_die(self, p_win):
        self.m_item.undraw()
        self.m_item.draw(p_win)

    def draw(self, p_win, p_num):
        self.draw_die(p_win)
        self.m_pips.draw(p_win, p_num)

    def undraw(self):
        self.m_item.undraw()
        self.m_pips.undraw()

def inside(point, rectangle):
    p1 = rectangle.getP1()
    p2 = rectangle.getP2()

    return  p1.getX() <= point.getX() <= p2.getX() and p1.getY() <= point.getY() <= p2.getY()

def get_bet(p_win, p_balance, p_def_bet):
    """ Text and instructions/rules"""

    inst = []
    inst.append(Text(Point(MAX_X/2, 20), "MAKE YOUR BET:"))
    inst.append(Text(Point(MAX_X/2, 40), "BALANCE: " + str(p_balance)))
    inst.append(Text(Point(MAX_X/2, 70), "Rules:"))
    inst.append(Text(Point(MAX_X/2, 90), "If you roll a 3 or 18 in total your bet winnings will be 10x your bet."))
    inst.append(Text(Point(MAX_X/2, 110), "If you roll a 4 or 17 in total your bet winnings will be 5x your bet."))
    inst.append(Text(Point(MAX_X/2, 130), "If you roll triples besides a 3 and 18 your bet winnings will be 2x your bet."))
    inst.append(Text(Point(MAX_X/2, 150), "If you roll anything else, you lose your bet."))
    rectangle = Rectangle(Point(MAX_X/2 - 59, 190), Point(MAX_X/2 + 59, 210))
    inst.append(rectangle)
    inst.append(Text(Point(MAX_X/2, 200), 'CLICK TO ROLL'))

    for item in inst:
        item.draw(p_win)

    bet_input = Entry(Point(MAX_X/2 + 100, 20), 5)
    bet_input.setText(str(p_def_bet))
    bet_input.draw(p_win)

    point = p_win.getMouse()
    if not inside(point, rectangle):
        p_win.close()
        exit()

    bet = int(bet_input.getText())
    bet_input.undraw()

    for item in inst:
        item.undraw()

    return bet

def show_winnings(p_win, p_winnings):
    """ Shows winnings, checks for winner, updates total, and returns the updated total """

    inst = []
    inst.append(Text(Point(MAX_X/2, 90), "Your WINNINGS: " + str(p_winnings)))
    rectangle = Rectangle(Point(MAX_X/2 - 50, 190), Point(MAX_X/2 + 50, 210))
    inst.append(rectangle)
    inst.append(Text(Point(MAX_X/2, 200), 'PLAY AGAIN'))

    for item in inst:
        item.draw(p_win)

    point = p_win.getMouse()
    if not inside(point, rectangle):
        p_win.close()
        exit()

    for item in inst:
        item.undraw()

def check_winner(p_rolls):
    """ Winnings and losing calculation """

    last = None
    total = 0
    triple = True

    for r in p_rolls:
        if last is not None and last != r:
            triple = False
        last = r
        total += r

    if total == 3 or total == 18:
        return 10
    if total == 4 or total == 17:
        return 5
    if triple:
        return 2

    return -1

def show_bet_invalid(p_win):
    """ Shows invalid bet """

    inst = []
    inst.append(Text(Point(MAX_X/2, 90), "YOUR BET WAS INVALID"))
    inst.append(Rectangle(Point(MAX_X/2 -50, 190), Point(MAX_X/2 + 50, 210)))
    inst.append(Text(Point(MAX_X/2, 200), 'TRY AGAIN'))

    for item in inst:
        item.draw(p_win)

    p_win.getMouse()

    for item in inst:
        item.undraw()

def show_game_over(p_win):
    """ Shows game over """

    inst = []
    inst.append(Text(Point(MAX_X/2, 90), "YOU ARE OUT OF MONEY"))
    inst.append(Rectangle(Point(MAX_X/2 - 50, 190), Point(MAX_X/2 + 50, 210)))
    inst.append(Text(Point(MAX_X/2, 200), 'QUIT'))

    for item in inst:
        item.draw(p_win)

    p_win.getMouse()

    for item in inst:
        item.undraw()

def main():
    """ Drives the program """

    # M A I N and balances along with random outputs
    #################################################

    win = GraphWin("Dice Rolls", MAX_X, MAX_Y)

    dice = [Dice_t(MAX_X/2 - 90 + d * 60, 5) for d in range(3)]

    balance = 100
    def_bet = 10

    while balance > 0:
        bet_invalid = True

        while bet_invalid:
            bet = get_bet(win, balance, def_bet)
            if 1 <= bet <= balance:
                bet_invalid = False
            else:
                show_bet_invalid(win)
        def_bet = bet
        rolls = []

        for r in range(3):
            roll = randrange(1, 7)
            dice[r].draw(win, roll)
            rolls.append(roll)

        winnings = check_winner(rolls) * bet
        balance += winnings
        show_winnings(win, winnings)

        for r in range(3):
            dice[r].undraw()

    show_game_over(win)

main()

他们被称为 皮普 不是 .

6 年前
回复了 cdlane 创建的主题 » 关于python递归的困惑

第一个程序在 res ,递归调用 findSchedulesHelper() 调用后,删除添加的项:

res.append(i)
findSchedulesHelper(workHours_left - i, dayHoursLimit, days_left - 1, res)
res.pop()

而第二个程序通过一个新的列表 物件 加上额外的物品。在递归调用后不需要清理:

findSchedulesHelper(workHours_left - i, dayHoursLimit, days_left - 1, res + [i])

两者之间的一个区别是由于以下代码:

for i in range(days_left):
    res.append(0)

也就是说,递归调用 findscheduleshelper()。 有改变的潜力 物件 . 如果是这样的话, res.pop() 作为回报,你可能会移除一些你认为没有的东西。最后可能会有额外的数据 物件 下一个电话。第二个程序在传递 物件 再也不要查看或重复使用副本。

下一个潜在问题是多个调用:

results.append(res)

在第一个节目中,你通过了相同的 物件 列出,所以 results 以多个指向 物件 所有这些都是 相同的 精确列表,始终反映其当前状态,而不是添加到的状态 结果 . 在第二个程序中,您将传递 物件 所以所有的条目 结果 不同的 ,的状态 物件 当它被添加到 结果 .

6 年前
回复了 cdlane 创建的主题 » “str”对象在python turtle中没有属性“turtle”

此代码中有几个错误。连同@piokuc提到的缺少括号:

ft = turtle.Turtle()

此行还将导致错误:

ft.color(255)

这个 color() 函数的参数相当灵活:

color(colorstring), color((r,g,b)), color(r,g,b)

但是 ft.color(255) 因为两个原因无效。第一,它不是一个有效的参数,第二,它假设0-255的色阶是不正确的。Turtle的默认颜色模式为0.0-1.0,除非使用 turtle.colormode(255) .

最后,你可能想以 turtle.done() 在代码的底部,除非您在不需要它的开发环境下运行。

附言:你的“T”被颠覆了!