首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >乒乓球与突围小游戏

乒乓球与突围小游戏
EN

Code Review用户
提问于 2020-08-18 23:02:26
回答 1查看 633关注 0票数 2

所以我在度假的时候做了两个没有互联网的游戏。我用海龟是因为我没有安装游戏。我在想如何改进我的游戏。以下是代码:

乒乓球:

代码语言:javascript
复制
from turtle import *
from time import sleep
import random, keyboard, math

setup(width=800, height=700)

if(input('Do you want to have a AI? (Y or N) ') == 'Y'):
    Ai = True
else:
    Ai = False

ts = getscreen()
ts.bgcolor('black')
title('Pong')

P1_Score = 0
P2_Score = 0
Paddle_2_dir = 225
Paddle_1_dir = -45
Paddle_2_y_bot = 0
Paddle_2_y_top = 0
Paddle_1_y_bot = 0
Paddle_1_y_top = 0
Ball_y = 0
random_range = []
random_int = 0
in_section = False

if(Ai == True):
    for i in range(-90, 90):
        random_range.append(i)

Score = Turtle()
Paddle_1 = Turtle()
Ball = Turtle()
Paddle_2 = Turtle()

Score.speed(1000)
Paddle_1.speed(1000)
Ball.speed(1000)
Paddle_2.speed(1000)

Score.ht()

Score.color('white')
Paddle_1.color('white')
Ball.color('white')
Paddle_2.color('white')

Score.pu()
Paddle_1.pu()
Ball.pu()
Paddle_2.pu()

Score.goto(0, 290)
Paddle_2.goto(350, 0)
Paddle_1.goto(-350, 0)
Ball.goto(0, 0)

Score.shape("circle")
Paddle_2.shape("square")
Paddle_2.shapesize(stretch_wid=8, stretch_len=1, outline=None)
Paddle_1.shape("square")
Paddle_1.shapesize(stretch_wid=8, stretch_len=1, outline=None)
Ball.shape("circle")

Ball.seth(0)

Score.write(f"{P1_Score} | {P2_Score}", False, align="center", font='Arial 35 normal')

print('Started!')

def Win(Winner):
    Score.clear()
    Score.write(f"{Winner} Wins!", False, align="center", font='Arial 35 normal')
    ts.bgcolor('red')
    ht()
    sleep(0.5)
    ts.bgcolor('blue')
    sleep(0.5)
    ts.bgcolor('yellow')
    sleep(0.5)
    ts.bgcolor('green')
    sleep(2)
    bye()

while True:
    Ball.fd(5)

    if keyboard.is_pressed('up'):
        Paddle_2.goto(350, Paddle_2.ycor() + 8)
    if keyboard.is_pressed('down'):
        Paddle_2.goto(350, Paddle_2.ycor() - 8)
    if keyboard.is_pressed('w'):
        Paddle_1.goto(-350, Paddle_1.ycor() + 8)
    if keyboard.is_pressed('s'):
        Paddle_1.goto(-350, Paddle_1.ycor() - 8)

    if(Ball.xcor() > 400):
        Score.clear()
        P1_Score += 1        
        Ball.goto(0, 0)
        Ball.seth(180)
        Paddle_2.sety(0)
        Paddle_1.sety(0)
        Score.write(f"{P1_Score} | {P2_Score}", False, align="center", font='Arial 35 normal')
    elif(Ball.xcor() < -400):
        Score.clear()
        P2_Score += 1
        Ball.goto(0, 0)
        Ball.seth(0)
        Paddle_2.sety(0)
        Paddle_1.sety(0)
        Score.write(f"{P1_Score} | {P2_Score}", False, align="center", font='Arial 35 normal')

    if(round(Ball.xcor()) < 0 and in_section == False and Ai == True):
        random_int = random.choice(random_range)
        fail = random.randint(1, 18)
        fail_distance = random.randint(10, 30)
        in_section = True
    elif(round(Ball.xcor()) > 0 and in_section == True and Ai == True):
        in_section = False

    if(round(Paddle_1.ycor()) != round(Ball.ycor()) and Ai == True and round(Ball.xcor()) < 0):
        if(fail == 1):
            Paddle_1.sety(Ball.ycor() + (100 + fail_distance))
        elif(fail == 2):
            Paddle_1.sety(Ball.ycor() - (100 + fail_distance))
        else:
            Paddle_1.sety(Ball.ycor() + random_int)

    if(Ball.xcor() >= Paddle_2.xcor() and Ball.xcor() <= Paddle_2.xcor() + 5):
        Paddle_2_y_top = round(Paddle_2.ycor())
        Paddle_2_y_top += 90

        Paddle_2_y_bot = round(Paddle_2.ycor())
        Paddle_2_y_bot -= 90

        Ball_y = round(Ball.ycor())
        
        Paddle_2_dir = 225
        
        for i in range(Paddle_2_y_bot, Paddle_2_y_top):

            Paddle_2_dir -= .5
            
            if(int(round(Ball_y)) == int(round(i))):
                Ball.seth(Paddle_2_dir + 0.5)
                break

    if(Ball.xcor() <= Paddle_1.xcor() and Ball.xcor() >= Paddle_1.xcor() - 5):
        Paddle_1_y_top = round(Paddle_1.ycor())
        Paddle_1_y_top += 90

        Paddle_1_y_bot = round(Paddle_1.ycor())
        Paddle_1_y_bot -= 90

        Ball_y = round(Ball.ycor())

        Paddle_1_dir = -45
        
        for i in range(Paddle_1_y_bot, Paddle_1_y_top):

            Paddle_1_dir += .5
            
            if(int(round(Ball_y)) == int(round(i))):
                Ball.seth(Paddle_1_dir - 0.5)
                break

    if(round(Paddle_2.ycor()) >= 310):
        Paddle_2.goto(350, 300)
    elif(round(Paddle_2.ycor()) <= -310):
        Paddle_2.goto(350, -300)
    if(round(Paddle_1.ycor()) >= 310):
        Paddle_1.goto(-350, 300)
    elif(round(Paddle_1.ycor()) <= -310):
        Paddle_1.goto(-350, -300)

    if(round(Ball.ycor()) >= 320 or round(Ball.ycor()) <= -320):
        Ball.seth(-Ball.heading())

    if(P1_Score == 3):
        Win('Player 1')
        print('Finished!')
        break
    if(P2_Score == 3):
        Win('Player 2')
        print('Finished!')
        break

    if keyboard.is_pressed('Esc'):
        while True:
            if not keyboard.is_pressed('Esc'):
                break

        while True:
            keyboard.wait('Esc')
            while keyboard.is_pressed('Esc'):
                sleep(0.1)
            break

突破:

代码语言:javascript
复制
from turtle import *
from time import sleep
import random, keyboard, math

ht()
setup(width=800, height=700)

Block_color_row_len = 0
Block_Place_X = 0
Block_Place_y = 0
Blocks = 0
Lives = 3
Alive_blocks_int = 0
Resets = 0
Prev_x = 0
Prev_y = 0
new_x = 0
new_y =0

Ball_x = 0

Paddle_dir = 135
Paddle_x_right = 0
Paddle_x_left = 0

Block_pos = [(-350,250), (-250,250), (-150,250), (-50,250), (50,250), (150,250), (250,250), (350,250),
             (-350,210), (-250,210), (-150,210), (-50,210), (50,210), (150,210), (250,210), (350,210),
             (-350,170), (-250,170), (-150,170), (-50,170), (50,170), (150,170), (250,170), (350,170),
             (-350,130), (-250,130), (-150,130), (-50,130), (50,130), (150,130), (250,130), (350,130),
             (-350,90), (-250,90), (-150,90), (-50,90), (50,90), (150,90), (250,90), (350,90)]
Block_default = [True, True, True, True, True, True, True, True,
                 True, True, True, True, True, True, True, True,
                 True, True, True, True, True, True, True, True,
                 True, True, True, True, True, True, True, True,
                 True, True, True, True, True, True, True, True]
Block_y = [250, 250, 250, 250, 250, 250, 250, 250,
           210, 210, 210, 210, 210, 210, 210, 210,
           170, 170, 170, 170, 170, 170, 170, 170,
           130, 130, 130, 130, 130, 130, 130, 130,
           90, 90, 90, 90, 90, 90, 90, 90]
Block_x = [-350, -250, -150, -50, 50, 150, 250, 350,
           -350, -250, -150, -50, 50, 150, 250, 350,
           -350, -250, -150, -50, 50, 150, 250, 350,
           -350, -250, -150, -50, 50, 150, 250, 350,
           -350, -250, -150, -50, 50, 150, 250, 350]
Block_color_row = [8, 8, 8, 8, 8]
Block_color = ['red', 'orange', 'yellow', 'green', 'blue']
Block_color_cur = []
Block_alive = []

Blocks = len(Block_pos)

def Block(Turtle, Color):
    Block_Place_X = Turtle.xcor() - 40
    Block_Place_y = Turtle.ycor() - 10

    Turtle.goto(Block_Place_X, Block_Place_y)
    Turtle.color(Color)
    Turtle.begin_fill()
    Turtle.pd()

    Turtle.goto(Block_Place_X, Block_Place_y + 20)
    Turtle.goto(Block_Place_X + 80, Block_Place_y + 20)
    Turtle.goto(Block_Place_X + 80, Block_Place_y)
    Turtle.goto(Block_Place_X, Block_Place_y)

    Turtle.end_fill()
    Turtle.pu()
    Turtle.goto(Block_Place_X + (Block_Place_X / 2), Block_Place_y + (Block_Place_y / 2))

def New(Turtle):
    global Block_pos, Block, Block_color, Block_color_row_len, Block_color_cur, Block_default, Block_alive, Blocks

    Turtle.clear()

    Block_color_row_len = len(Block_color_row)
    Block_color_cur = []
    Block_alive = Block_default

    for i in range(Block_color_row_len):
        for a in range(Block_color_row[i]):
            Block_color_cur.append(Block_color[i])
    
    for i in range(Blocks):
        Turtle.goto(Block_pos[i])
        
        Block(Turtle, Block_color_cur[i])

ts = getscreen()
ts.bgcolor('black')
title('Breakout')

Block_Creator = Turtle()
Paddle = Turtle()
Ball = Turtle()

Block_Creator.color('black')
Paddle.color('brown')
Ball.color('white')

Block_Creator.pu()
Paddle.pu()
Ball.pu()

Block_Creator.speed(1000)
Paddle.speed(1000)
Ball.speed(1000)

Block_Creator.goto(0, 0)
Paddle.goto(0, -300)
Ball.goto(0, 0)

Block_Creator.ht()

Paddle.shape("square")
Paddle.shapesize(stretch_wid=1, stretch_len=8, outline=None)
Ball.shape("circle")

New(Block_Creator)

Ball.seth(270)

while True:
    prev_x = round(Ball.xcor())
    prev_y = round(Ball.ycor())
    
    Ball.fd(8)

    new_x = round(Ball.xcor())
    new_y = round(Ball.ycor())
    
    if keyboard.is_pressed('a') or keyboard.is_pressed('left') and not Paddle.xcor() < -350:
        Paddle.bk(8)
    elif keyboard.is_pressed('d') or keyboard.is_pressed('right') and Paddle.xcor() < -340:
        Paddle.fd(8)
    if keyboard.is_pressed('d') or keyboard.is_pressed('right') and not Paddle.xcor() > 350:
        Paddle.fd(8)
    elif keyboard.is_pressed('a') or keyboard.is_pressed('left') and Paddle.xcor() > 340:
        Paddle.bk(8)

    if keyboard.is_pressed('Esc'):
        bye()
        break

    if keyboard.is_pressed('space'):
        Ball.goto(random.choice(Block_pos))

    if(round(Ball.ycor()) <= Paddle.ycor() and round(Ball.ycor()) >= Paddle.ycor() - 4):
        Paddle_x_right = round(Paddle.xcor())
        Paddle_x_right += 90

        Paddle_x_left = round(Paddle.xcor())
        Paddle_x_left -= 90

        Ball_x = round(Ball.xcor())
        
        Paddle_dir = 135
        
        for i in range(Paddle_x_left, Paddle_x_right):

            Paddle_dir -= .5
            
            if(int(round(Ball_x)) == int(round(i))):
                Ball.seth(Paddle_dir + 0.5)
                break
    if(round(Ball.ycor()) >= 80):
        for i in range(Blocks):
            for a in range(Block_x[i] - 50, Block_x[i] + 50):
                if(round(Ball.xcor()) == a):
                    for f in range(Block_y[i] - 25, Block_y[i] + 25):
                        if(round(Ball.ycor()) == f):
                            if(Block_alive[i] == True):
                                Block_alive[i] = False
                                Block_Creator.goto(Block_pos[i])
                                Block(Block_Creator, 'black')
                                Ball.sety(Ball.ycor() + 0.01)
                                Ball.sety(Ball.ycor() - 0.01)
                                Ball.seth(-Ball.heading())

    if(Ball.ycor() < -370):
        if(Lives >= 1 and Lives != 0):
            Lives -= 1
            Ball.seth(270)
            Ball.goto(0, 0)
            Paddle.setx(0)
            for i in range(3):
                Ball.color('red')
                sleep(0.2)
                Ball.color('white')
                sleep(0.2)
        if(Lives == 0):
            Ball.seth(270)
            Ball.goto(0, 0)
            Paddle.setx(0)
            Ball.color('red')
            sleep(2)
        
    if(Lives <= 0 or Resets > 3):
        # End game event here
        bye()
        break

    if(round(Ball.ycor()) >= 330):
        Ball.seth(-Ball.heading())
    if(round(Ball.xcor()) >= 400 or round(Ball.xcor()) <= -400):
        Ball.seth(-Ball.heading() + 180)

    Alive_blocks_int = 0
    
    for i in range(Blocks):
        if(Block_alive[i] == False):
            Alive_blocks_int += 1

    if(Alive_blocks_int == 40):
        Resets += 1
        New(Block_Creator)
        Ball.goto(0, 0)
        Ball.seth(270)
        Paddle.setx(0)
        Block_alive = Block_default

这两款游戏都很好,但是如果你击中了块的一侧,角度计算就不起作用了,这就把整排都打倒了。这是一个小问题,我仍然需要解决,但总的来说,它似乎是可行的。

EN

回答 1

Code Review用户

回答已采纳

发布于 2020-08-19 16:53:17

用于乒乓球:

代码语言:javascript
复制
if(input('Do you want to have a AI? (Y or N) ') == 'Y'):
    Ai = True
else:
    Ai = False

这可以缩短为简单

代码语言:javascript
复制
ai = input('Do you want to have a AI? (Y or N) ').upper() == 'Y'

==已经计算为True/False,因此在一个条件下使用它,然后分配给True/False是多余的。我还添加了一个对upper的调用,这样用户就可以输入"y“的任何一种情况,并且仍然可以工作。

代码语言:javascript
复制
random_range = []

if(ai == True):
    for i in range(-90, 90):
        random_range.append(i)

有几件事要注意:

  • 与以前类似,使用True==进行比较是多余的。ai要么已经是True,要么已经是False,这就是ai == True对任何方面的评估。if ai:很好。
  • 如果您只是简单地在循环中对列表进行append处理,则应该考虑使用列表理解。不过,在这里,您的目的只是将range转换成一个列表,这样random_range = list(range(-90, 90))就可以正常工作了。
  • 只有在以后使用random_range时才会使用ai == true。您可以无条件地创建列表,而不是检查ai是什么。是啊,那是浪费一点时间,但是对于这么小的清单来说,时间应该是可以忽略不计的。

用于突破:

我会用“列表乘法”来整理你在顶部的所有庞大的列表。例如,Block_default可以是:

代码语言:javascript
复制
block_default = [True] * (5 * 8)  # Or just [True] * 40

类似地,Block_y可以是这样的:

代码语言:javascript
复制
block_y = [row
           for val in range(250, 89, -40)  # Generate each of the vals
           for row in [val] * 8]  # Use list multiplication, then flatten

如果在顶部设置了一些变量来存储块的高度和宽度,则可以使用它们,还可以使用一些更多的序列操作,如zip,以极大地减少重复:

代码语言:javascript
复制
BLOCKS_WIDTH = 8
BLOCKS_HEIGHT = 5

block_default = [True] * (BLOCKS_HEIGHT * BLOCKS_WIDTH)

block_y = [row
           for val in range(250, 89, -40)
           for row in [val] * BLOCKS_WIDTH]

block_x = list(range(-350, 351, 100)) * BLOCKS_HEIGHT

# Take the two existing coordinate lists, and "zip" them together
block_pos = list(zip(block_x, block_y))  

还要注意,我把你们的名字都改好了。PEP8说普通变量应该在"snake_case“中

除此之外,我从来没有用过甲鱼,所以我不能对其他任何事情发表评论。

票数 2
EN
页面原文内容由Code Review提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://codereview.stackexchange.com/questions/248112

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档