B. Two Buttons

本文深入解析Codeforces Round #295(Div. 2)的B题,通过提供详细算法逻辑与优化策略,阐述如何在有限操作下实现从初始值n到目标值m的转换。同时,对比两种操作路径,揭示m大于n且为偶数时除以2的最优解原理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这是Codeforces Round #295 (Div. 2) 的B 题,题意为:

给出n, m, 有两种操作,n 减一 和 n 乘以 2,问最少要多少次操作才能把n 变成 m。

Sample test(s)
input
4 6
output
2
input
10 1
output
9
input 是 n 和 m ,output 是次数。

可以用BFS来做,在遍历每一层的时候,要记录一下当前的值,并且要防止同一个值被遍历两次。要是遇到当前值是目标值,那么变成当前值的次数必然是最少的。

但是,也可以反过来做,求m变成n,有两种操作m除以2 和 m加1,求最少操作次数。要是遇到m小于n的话,m就加一,因为加一是最好的操作,要是遇到m大于n的话,这里有2种情况,如果m是偶数的话,m就除以2,否则m加1。

这里讨论一下,为什么 m > n && m%2 == 0 时,m 要除以2(m > n 且 m 是奇数时,m不能被2整除,只能加1)

假设:  m > n 且 m 是偶数。

那么m 有两种情况 : ① m >= 2n ; ② 2n > m > n 。

第①种就直接 m 除以2 了,如果m越加 1,到最后还是要除以2,这样次数会越来越多,明显没必要,直接m除以2。

第②种的话,有两种选择: 

A. m加1直到 m == n,操作次数是 2n-m+1(当然m加2后,还可以选择是否要除以2,但是要除以2的话,倒是没有B快)

B. m除以2然后一直加一直到m == n,操作次数是 n-m/2+1

来看一下哪个次数最多,把A的次数减去B的次数,得到

n-m/2 ,因2n > m > n ,所以 n > m/2 > n/2,则 n-m/2 > 0 ,所以,B是最优的方法,也就是说,m > n && m%2 == 0 时,将m除以2。

#include <iostream>
using namespace std;

int main(){
    int n, m, cnt = 0;
    cin >> n >> m;
    if(n >= m) {
	    cout << n-m; return 0;
    }
    while(n != m){
	    if(m < n) m++;
	    else if(m % 2) m++;
	    else m /= 2;
	    cnt++;
    }
    cout << cnt;
    return 0;
}





版权声明:本文为博主原创文章,未经博主允许不得转载。

转载于:https://www.cnblogs.com/Rex7/p/4752532.html

# SPDX-FileCopyrightText: 2018 Dan Halbert for Adafruit Industries # # SPDX-License-Identifier: MIT """ `Gamepad` ==================================================== * Author(s): Dan Halbert """ import struct import time from adafruit_hid import find_device class Gamepad: """Emulate a generic gamepad controller with 16 buttons, numbered 1-16, and two joysticks, one controlling ``x` and ``y`` values, and the other controlling ``z`` and ``r_z`` (z rotation or ``Rz``) values. The joystick values could be interpreted differently by the receiving program: those are just the names used here. The joystick values are in the range -127 to 127.""" def __init__(self, devices): """Create a Gamepad object that will send USB gamepad HID reports. Devices can be a list of devices that includes a gamepad device or a gamepad device itself. A device is any object that implements ``send_report()``, ``usage_page`` and ``usage``. """ self._gamepad_device = find_device(devices, usage_page=0x1, usage=0x05) # Reuse this bytearray to send mouse reports. # Typically controllers start numbering buttons at 1 rather than 0. # report[0] buttons 1-8 (LSB is button 1) # report[1] buttons 9-16 # report[2] joystick 0 x: -127 to 127 # report[3] joystick 0 y: -127 to 127 # report[4] joystick 1 x: -127 to 127 # report[5] joystick 1 y: -127 to 127 self._report = bytearray(6) # Remember the last report as well, so we can avoid sending # duplicate reports. self._last_report = bytearray(6) # Store settings separately before putting into report. Saves code # especially for buttons. self._buttons_state = 0 self._joy_x = 0 self._joy_y = 0 self._joy_z = 0 self._joy_r_z = 0 # Send an initial report to test if HID device is ready. # If not, wait a bit and try once more. try: self.reset_all() except OSError: time.sleep(1) self.reset_all() def press_buttons(self, *buttons): """Press and hold the given buttons.""" for button in buttons: self._buttons_state |= 1 << self._validate_button_number(button) - 1 self._send() def release_buttons(self, *buttons): """Release the given buttons.""" for button in buttons: self._buttons_state &= ~(1 << self._validate_button_number(button) - 1) self._send() def release_all_buttons(self): """Release all the buttons.""" self._buttons_state = 0 self._send() def click_buttons(self, *buttons): """Press and release the given buttons.""" self.press_buttons(*buttons) self.release_buttons(*buttons) def move_joysticks(self, x=None, y=None, z=None, r_z=None): """Set and send the given joystick values. The joysticks will remain set with the given values until changed One joystick provides ``x`` and ``y`` values, and the other provides ``z`` and ``r_z`` (z rotation). Any values left as ``None`` will not be changed. All values must be in the range -127 to 127 inclusive. Examples:: # Change x and y values only. gp.move_joysticks(x=100, y=-50) # Reset all joystick values to center position. gp.move_joysticks(0, 0, 0, 0) """ if x is not None: self._joy_x = self._validate_joystick_value(x) if y is not None: self._joy_y = self._validate_joystick_value(y) if z is not None: self._joy_z = self._validate_joystick_value(z) if r_z is not None: self._joy_r_z = self._validate_joystick_value(r_z) self._send() def reset_all(self): """Release all buttons and set joysticks to zero.""" self._buttons_state = 0 self._joy_x = 0 self._joy_y = 0 self._joy_z = 0 self._joy_r_z = 0 self._send(always=True) def _send(self, always=False): """Send a report with all the existing settings. If ``always`` is ``False`` (the default), send only if there have been changes. """ struct.pack_into( "<Hbbbb", self._report, 0, self._buttons_state, self._joy_x, self._joy_y, self._joy_z, self._joy_r_z, ) if always or self._last_report != self._report: self._gamepad_device.send_report(self._report) # Remember what we sent, without allocating new storage. self._last_report[:] = self._report @staticmethod def _validate_button_number(button): if not 1 <= button <= 16: raise ValueError("Button number must in range 1 to 16") return button @staticmethod def _validate_joystick_value(value): if not -127 <= value <= 127: raise ValueError("Joystick value must be in range -127 to 127") return value 使用这个库
最新发布
08-16
import os import math import time import pygame import pymunk as pm from characters import Bird from level import Level current_path = os.getcwd() pygame.init() screen = pygame.display.set_mode((1200, 650)) redbird = pygame.image.load( "D:/python_code/resources/images/red-bird3.png").convert_alpha() yellowbird = pygame.image.load( "D:/python_code/resources/images/yellowbird1.png").convert_alpha() yellowbird2 = pygame.image.load( "D:/python_code/resources/images/yellowbird2.png").convert_alpha() bluebird = pygame.image.load( "D:/python_code/resources/images/bluebird1.png").convert_alpha() bluebird2 = pygame.image.load( "D:/python_code/resources/images/bluebird2.png").convert_alpha() background1 = pygame.image.load( "D:/python_code/resources/images/background1.png").convert_alpha() background2 = pygame.image.load( "D:/python_code/resources/images/background3.png").convert_alpha() sling_image = pygame.image.load( "D:/python_code/resources/images/sling-3.png").convert_alpha() full_sprite = pygame.image.load( "D:/python_code/resources/images/full-sprite.png").convert_alpha() rect = pygame.Rect(181, 1050, 50, 50) cropped = full_sprite.subsurface(rect).copy() pig_image = pygame.transform.scale(cropped, (30, 30)) buttons = pygame.image.load( "D:/python_code/resources/images/selected-buttons.png").convert_alpha() pig_happy = pygame.image.load( "D:/python_code/resources/images/pig_failed.png").convert_alpha() pig_1 = pygame.image.load( "D:/python_code/resources/images/pig_1.png").convert_alpha() pig_2 = pygame.image.load( "D:/python_code/resources/images/pig_2.png").convert_alpha() stars = pygame.image.load( "D:/python_code/resources/images/stars-edited.png").convert_alpha() rect = pygame.Rect(0, 0, 200, 200) star1 = stars.subsurface(rect).copy() rect = pygame.Rect(204, 0, 200, 200) star2 = stars.subsurface(rect).copy() rect = pygame.Rect(426, 0, 200, 200) star3 = stars.subsurface(rect).copy() rect = pygame.Rect(164, 10, 60, 60) pause_button = buttons.subsurface(rect).copy() rect = pygame.Rect(24, 4, 100, 100) replay_button = buttons.subsurface(rect).copy() rect = pygame.Rect(142, 365, 130, 100) next_button = buttons.subsurface(rect).copy() clock = pygame.time.Clock() rect = pygame.Rect(18, 212, 100, 100) play_button = buttons.subsurface(rect).copy() # 创建一个简单的火焰图像(圆形渐变) flame_surface = pygame.Surface((30, 30), pygame.SRCALPHA) pygame.draw.circle(flame_surface, (255, 140, 0, 180), (15, 15), 15) pygame.draw.circle(flame_surface, (255, 255, 0, 120), (15, 15), 10) pygame.draw.circle(flame_surface, (255, 255, 255, 60), (15, 15), 5) running = True # the base of the physics space = pm.Space() space.gravity = (0.0, -700.0) pigs = [] birds = [] balls = [] polys = [] beams = [] columns = [] poly_points = [] ball_number = 0 polys_dict = {} mouse_distance = 0 rope_lenght = 90 angle = 0 x_mouse = 0 y_mouse = 0 count = 0 mouse_pressed = False t1 = 0 tick_to_next_circle = 10 RED = (255, 0, 0) BLUE = (0, 0, 255) BLACK = (0, 0, 0) WHITE = (255, 255, 255) sling_x, sling_y = 135, 450 sling2_x, sling2_y = 160, 450 score = 0 game_state = 0 bird_path = [] counter = 0 restart_counter = False bonus_score_once = True bold_font = pygame.font.SysFont("arial", 30, bold=True) bold_font2 = pygame.font.SysFont("arial", 40, bold=True) bold_font3 = pygame.font.SysFont("arial", 50, bold=True) wall = False # Static floor static_body = pm.Body(body_type=pm.Body.STATIC) static_lines = [pm.Segment(static_body, (0.0, 060.0), (1200.0, 060.0), 0.0)] static_lines1 = [pm.Segment(static_body, (1200.0, 060.0), (1200.0, 800.0), 0.0)] for line in static_lines: line.elasticity = 0.95 line.friction = 1 line.collision_type = 3 for line in static_lines1: line.elasticity = 0.95 line.friction = 1 line.collision_type = 3 space.add(static_body) for line in static_lines: space.add(line) def to_pygame(p): """Convert pymunk to pygame coordinates""" return int(p.x), int(-p.y + 600) def vector(p0, p1): """Return the vector of the points p0 = (xo,yo), p1 = (x1,y1)""" a = p1[0] - p0[0] b = p1[1] - p0[1] return a, b def unit_vector(v): """Return the unit vector of the points v = (a,b)""" h = ((v[0] ** 2) + (v[1] ** 2)) ** 0.5 if h == 0: h = 0.000000000000001 ua = v[0] / h ub = v[1] / h return ua, ub def distance(xo, yo, x, y): """distance between points""" dx = x - xo dy = y - yo d = ((dx ** 2) + (dy ** 2)) ** 0.5 return d def load_music(): """Load the music""" song1 = '../resources/sounds/angry-birds.ogg' pygame.mixer.music.load(song1) pygame.mixer.music.play(-1) def sling_action(bird_type): """Set up sling behavior""" global mouse_distance global rope_lenght global angle global x_mouse global y_mouse # Fixing bird to the sling rope v = vector((sling_x, sling_y), (x_mouse, y_mouse)) uv = unit_vector(v) uv1 = uv[0] uv2 = uv[1] mouse_distance = distance(sling_x, sling_y, x_mouse, y_mouse) pu = (uv1 * rope_lenght + sling_x, uv2 * rope_lenght + sling_y) bigger_rope = 102 x_redbird = x_mouse - 20 y_redbird = y_mouse - 20 if mouse_distance > rope_lenght: pux, puy = pu pux -= 20 puy -= 20 pul = pux, puy if bird_type == 'yellow': screen.blit(yellowbird, pul) pu2 = (uv1 * bigger_rope + sling_x, uv2 * bigger_rope + sling_y) pygame.draw.line(screen, (0, 0, 0), (sling2_x, sling2_y), pu2, 5) screen.blit(yellowbird, pul) pygame.draw.line(screen, (0, 0, 0), (sling_x, sling_y), pu2, 5) elif bird_type == 'red': screen.blit(redbird, pul) pu2 = (uv1 * bigger_rope + sling_x, uv2 * bigger_rope + sling_y) pygame.draw.line(screen, (0, 0, 0), (sling2_x, sling2_y), pu2, 5) screen.blit(redbird, pul) pygame.draw.line(screen, (0, 0, 0), (sling_x, sling_y), pu2, 5) elif bird_type == 'blue': screen.blit(bluebird, pul) pu2 = (uv1 * bigger_rope + sling_x, uv2 * bigger_rope + sling_y) pygame.draw.line(screen, (0, 0, 0), (sling2_x, sling2_y), pu2, 5) screen.blit(bluebird, pul) pygame.draw.line(screen, (0, 0, 0), (sling_x, sling_y), pu2, 5) else: mouse_distance += 10 pu3 = (uv1 * mouse_distance + sling_x, uv2 * mouse_distance + sling_y) pygame.draw.line(screen, (0, 0, 0), (sling2_x, sling2_y), pu3, 5) if bird_type == 'yellow': screen.blit(yellowbird, (x_redbird, y_redbird)) elif bird_type == 'red': screen.blit(redbird, (x_redbird, y_redbird)) elif bird_type == 'blue': screen.blit(bluebird, (x_redbird, y_redbird)) pygame.draw.line(screen, (0, 0, 0), (sling_x, sling_y), pu3, 5) # Angle of impulse dy = y_mouse - sling_y dx = x_mouse - sling_x if dx == 0: dx = 0.00000000000001 angle = math.atan((float(dy)) / dx) def draw_level_cleared(): """Draw level cleared""" global game_state global bonus_score_once global score level_cleared = bold_font3.render("Level Cleared!", 1, WHITE) score_level_cleared = bold_font2.render(str(score), 1, WHITE) if level.number_of_birds >= 0 and len(pigs) == 0: if bonus_score_once: score += (level.number_of_birds - 1) * 10000 bonus_score_once = False game_state = 4 rect = pygame.Rect(300, 0, 600, 800) pygame.draw.rect(screen, BLACK, rect) screen.blit(level_cleared, (450, 90)) if level.one_star <= score <= level.two_star: screen.blit(star1, (310, 190)) if level.two_star <= score <= level.three_star: screen.blit(star1, (310, 190)) screen.blit(star2, (500, 170)) if score >= level.three_star: screen.blit(star1, (310, 190)) screen.blit(star2, (500, 170)) screen.blit(star3, (700, 200)) screen.blit(score_level_cleared, (550, 400)) screen.blit(replay_button, (510, 480)) screen.blit(next_button, (620, 480)) def draw_level_failed(): """Draw level failed""" global game_state failed = bold_font3.render("Level Failed", 1, WHITE) if level.number_of_birds <= 0 < len(pigs) and time.time() - t2 > 5: game_state = 3 rect = pygame.Rect(300, 0, 600, 800) pygame.draw.rect(screen, BLACK, rect) screen.blit(failed, (450, 90)) screen.blit(pig_happy, (380, 120)) screen.blit(replay_button, (520, 460)) def restart(): """Delete all objects of the level""" pigs_to_remove = [] birds_to_remove = [] columns_to_remove = [] beams_to_remove = [] for pig in pigs: pigs_to_remove.append(pig) for pig in pigs_to_remove: space.remove(pig.shape, pig.shape.body) pigs.remove(pig) for bird in birds: birds_to_remove.append(bird) for bird in birds_to_remove: space.remove(bird.shape, bird.shape.body) birds.remove(bird) for column in columns: columns_to_remove.append(column) for column in columns_to_remove: space.remove(column.shape, column.shape.body) columns.remove(column) for beam in beams: beams_to_remove.append(beam) for beam in beams_to_remove: space.remove(beam.shape, beam.shape.body) beams.remove(beam) def post_solve_bird_pig(arbiter, space, _): """Collision between bird and pig""" surface = screen a, b = arbiter.shapes bird_body = a.body pig_body = b.body p = to_pygame(bird_body.position) p2 = to_pygame(pig_body.position) r = 30 pygame.draw.circle(surface, BLACK, p, r, 4) pygame.draw.circle(surface, RED, p2, r, 4) pigs_to_remove = [] for pig in pigs: if pig_body == pig.body: pig.life -= 20 pigs_to_remove.append(pig) global score score += 10000 for pig in pigs_to_remove: space.remove(pig.shape, pig.shape.body) pigs.remove(pig) def post_solve_bird_wood(arbiter, space, _): """Collision between bird and wood""" poly_to_remove = [] if arbiter.total_impulse.length > 1100: a, b = arbiter.shapes for column in columns: if b == column.shape: poly_to_remove.append(column) for beam in beams: if b == beam.shape: poly_to_remove.append(beam) for poly in poly_to_remove: if poly in columns: columns.remove(poly) if poly in beams: beams.remove(poly) space.remove(b, b.body) global score score += 5000 def post_solve_pig_wood(arbiter, space, _): """Collision between pig and wood""" pigs_to_remove = [] if arbiter.total_impulse.length > 700: pig_shape, wood_shape = arbiter.shapes for pig in pigs: if pig_shape == pig.shape: pig.life -= 20 global score score += 10000 if pig.life <= 0: pigs_to_remove.append(pig) for pig in pigs_to_remove: space.remove(pig.shape, pig.shape.body) pigs.remove(pig) # bird and pigs space.add_collision_handler(0, 1).post_solve = post_solve_bird_pig # bird and wood space.add_collision_handler(0, 2).post_solve = post_solve_bird_wood # pig and wood space.add_collision_handler(1, 2).post_solve = post_solve_pig_wood load_music() level = Level(pigs, columns, beams, space) level.number = 0 level.load_level() bird_type_list = ['red', 'yellow', 'blue', 'yellow'] while running: # Input handling for event in pygame.event.get(): if event.type == pygame.QUIT: running = False elif event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE: running = False elif event.type == pygame.KEYDOWN and event.key == pygame.K_w: # Toggle wall if wall: for line in static_lines1: space.remove(line) wall = False else: for line in static_lines1: space.add(line) wall = True elif event.type == pygame.KEYDOWN and event.key == pygame.K_s: space.gravity = (0.0, -10.0) level.bool_space = True # restart() # level.load_level() elif event.type == pygame.KEYDOWN and event.key == pygame.K_n: space.gravity = (0.0, -700.0) level.bool_space = False # restart() # level.load_level() elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1: for bird in birds: # 确保是黄色小鸟、已经发射、还没加速过 if hasattr(bird, 'bird_type') and bird.bird_type == 'yellow' and not bird.has_boosted: vel = bird.shape.body.velocity # 计算单位向量方向 direction = vel.normalized() # 设置加速倍数(可调) boost_factor = 1.8 new_velocity = direction * vel.length * boost_factor bird.shape.body.velocity = new_velocity bird.has_boosted = True elif hasattr(bird, 'bird_type') and bird.bird_type == 'blue' and not bird.has_split: if bird.shape.body.velocity.length > 5: bird.has_split = True pos = bird.shape.body.position vel = bird.shape.body.velocity speed = vel.length direction = vel.normalized() angle = math.atan2(direction.y, direction.x) delta_angle = math.radians(15) # 偏移角度(上下15°) angle_up = angle + delta_angle vel_up = pm.Vec2d(math.cos(angle_up), math.sin(angle_up)) * speed angle_down = angle - delta_angle vel_down = pm.Vec2d(math.cos(angle_down), math.sin(angle_down)) * speed offset = 30 bird1 = Bird(0, 0, 0, 0, space, bird_type='blue') bird1.shape.body.position = pos + pm.Vec2d(0, offset) bird1.shape.body.velocity = vel_up bird1.has_split = True bird2 = Bird(0, 0, 0, 0, space, bird_type='blue') bird2.shape.body.position = pos + pm.Vec2d(0, -offset) bird2.shape.body.velocity = vel_down bird2.has_split = True birds.append(bird1) birds.append(bird2) if pygame.mouse.get_pressed()[0] and 100 < x_mouse < 250 and 370 < y_mouse < 550: mouse_pressed = True if (event.type == pygame.MOUSEBUTTONUP and event.button == 1 and mouse_pressed): # Release new bird mouse_pressed = False if level.number_of_birds > 0: level.number_of_birds -= 1 t1 = time.time() * 1000 xo = 154 yo = 156 if mouse_distance > rope_lenght: mouse_distance = rope_lenght bird_index = 4 - level.number_of_birds - 1 # 当前是第几只鸟(从 0 开始) bird_type = bird_type_list[bird_index] if x_mouse < sling_x + 5: bird = Bird(mouse_distance, angle, xo, yo, space, bird_type=bird_type) birds.append(bird) else: bird = Bird(-mouse_distance, angle, xo, yo, space, bird_type=bird_type) birds.append(bird) if level.number_of_birds == 0: t2 = time.time() if event.type == pygame.MOUSEBUTTONUP and event.button == 1: if x_mouse < 60 and 155 > y_mouse > 90: game_state = 1 if game_state == 1: if x_mouse > 500 and 200 < y_mouse < 300: # Resume in the paused screen game_state = 0 if x_mouse > 500 and y_mouse > 300: # Restart in the paused screen restart() level.load_level() bird_type_list = ['red', 'yellow', 'blue', 'yellow'] game_state = 0 bird_path = [] if game_state == 3: # Restart in the failed level screen if x_mouse > 500 and x_mouse < 620 and y_mouse > 450: restart() level.load_level() bird_type_list = ['red', 'yellow', 'blue', 'yellow'] game_state = 0 bird_path = [] score = 0 if game_state == 4: # Build next level if x_mouse > 610 and y_mouse > 450: restart() level.number += 1 game_state = 0 level.load_level() bird_type_list = ['red', 'yellow', 'blue', 'yellow'] score = 0 bird_path = [] bonus_score_once = True if 610 > x_mouse > 500 and y_mouse > 450: # Restart in the level cleared screen restart() level.load_level() bird_type_list = ['red', 'yellow', 'blue', 'yellow'] game_state = 0 bird_path = [] score = 0 x_mouse, y_mouse = pygame.mouse.get_pos() # Draw background screen.fill((130, 200, 100)) # screen.blit(background2, (0, -50)) # 显示“no-gravity”标识 if space.gravity == (0.0, -10.0): screen.blit(background1, (0, -50)) ng_text = bold_font.render("NO-GRAVITY", True, (255, 0, 0)) screen.blit(ng_text, (20, 20)) else: screen.blit(background2, (0, -50)) # 显示“WALL ON”或“WALL OFF”标识 if wall: wall_text = bold_font.render("WALL: ON", True, (0, 200, 255)) else: wall_text = bold_font.render("WALL: OFF", True, (200, 0, 0)) if wall: pygame.draw.rect(screen, (255, 0, 0), (1195, 60, 5, 540)) # 亮红色墙体 screen.blit(wall_text, (20, 50)) # Draw first part of the sling rect = pygame.Rect(50, 0, 70, 220) screen.blit(sling_image, (138, 420), rect) # Draw the trail left behind for point in bird_path: pygame.draw.circle(screen, WHITE, point, 5, 0) # Draw the birds in the wait line if level.number_of_birds > 0: for i in range(level.number_of_birds - 1): x = 30 + (i * 35) bird_index = 4 - i - 1 # 当前是第几只鸟(从 0 开始) bird_type_l = ['yellow', 'blue', 'yellow', 'red'] bird_type = bird_type_list[bird_index] if bird_type == 'yellow': screen.blit(yellowbird, (x, 508)) elif bird_type == 'red': screen.blit(redbird, (x, 508)) elif bird_type == 'blue': screen.blit(bluebird, (x, 508)) # Draw sling behavior if mouse_pressed and level.number_of_birds > 0: # 在弹弓上的鸟 bird_index = 4 - level.number_of_birds # 当前是第几只鸟(从 0 开始) bird_type_list = ['red', 'yellow', 'blue', 'yellow'] bird_type = bird_type_list[bird_index] sling_action(bird_type) else: if time.time() * 1000 - t1 > 300 and level.number_of_birds > 0: bird_index = 4 - level.number_of_birds # 当前是第几只鸟(从 0 开始) bird_type_list = ['red', 'yellow', 'blue', 'yellow'] bird_type = bird_type_list[bird_index] if bird_type == 'yellow': screen.blit(yellowbird, (130, 426)) elif bird_type == 'red': screen.blit(redbird, (130, 426)) elif bird_type == 'blue': screen.blit(bluebird, (130, 426)) else: pygame.draw.line(screen, (0, 0, 0), (sling_x, sling_y - 8), (sling2_x, sling2_y - 7), 5) birds_to_remove = [] pigs_to_remove = [] counter += 1 # Draw birds for bird in birds: if bird.shape.body.position.y < 0: birds_to_remove.append(bird) p = to_pygame(bird.shape.body.position) x, y = p x -= 22 y -= 20 # if hasattr(bird, 'bird_type') and bird.bird_type == 'yellow': # 飞出去的鸟 # screen.blit(yellowbird, (x, y)) if hasattr(bird, 'bird_type') and bird.bird_type == 'yellow': if bird.has_boosted: vel = bird.shape.body.velocity direction = vel.normalized() offset_x = int(-direction.x * 25) offset_y = int(direction.y * 25) flame_pos = (x + offset_x, y + offset_y) screen.blit(flame_surface, flame_pos) screen.blit(yellowbird2, (x, y)) # 加速状态图 else: screen.blit(yellowbird, (x, y)) # 普通图 elif bird.bird_type == 'red': screen.blit(redbird, (x, y)) elif bird.bird_type == 'blue': if bird.has_split: screen.blit(bluebird2, (x, y)) # 分裂后的蓝鸟图像 else: screen.blit(bluebird, (x, y)) # 普通蓝鸟图像 # pygame.draw.circle(screen, BLUE, # p, int(bird.shape.radius), 2) if counter >= 3 and time.time() - t1 < 5: bird_path.append(p) restart_counter = True if restart_counter: counter = 0 restart_counter = False # Remove birds and pigs for bird in birds_to_remove: space.remove(bird.shape, bird.shape.body) birds.remove(bird) for pig in pigs_to_remove: space.remove(pig.shape, pig.shape.body) pigs.remove(pig) # Draw static lines for line in static_lines: body = line.body pv1 = body.position + line.a.rotated(body.angle) pv2 = body.position + line.b.rotated(body.angle) p1 = to_pygame(pv1) p2 = to_pygame(pv2) pygame.draw.lines(screen, (150, 150, 150), False, [p1, p2]) i = 0 # Draw pigs for pig in pigs: i += 1 # print (i,pig.life) pig = pig.shape if pig.body.position.y < 0: pigs_to_remove.append(pig) p = to_pygame(pig.body.position) x, y = p angle_degrees = math.degrees(pig.body.angle) img = pygame.transform.rotate(pig_image, angle_degrees) w, h = img.get_size() x -= w * 0.5 y -= h * 0.5 screen.blit(img, (x, y)) pygame.draw.circle(screen, BLUE, p, int(pig.radius), 2) # Draw columns and Beams for column in columns: column.draw_poly('columns', screen) for beam in beams: beam.draw_poly('beams', screen) # Update physics dt = 1.0 / 50.0 / 2. for x in range(2): space.step(dt) # make two updates per frame for better stability # Drawing second part of the sling rect = pygame.Rect(0, 0, 60, 200) screen.blit(sling_image, (120, 420), rect) # Draw score score_font = bold_font.render("SCORE", 1, WHITE) number_font = bold_font.render(str(score), 1, WHITE) screen.blit(score_font, (1060, 90)) if score == 0: screen.blit(number_font, (1100, 130)) else: screen.blit(number_font, (1060, 130)) screen.blit(pause_button, (10, 90)) # Pause option if game_state == 1: screen.blit(play_button, (500, 200)) screen.blit(replay_button, (500, 300)) draw_level_cleared() draw_level_failed() pygame.display.flip() clock.tick(50) pygame.display.set_caption("fps: " + str(clock.get_fps())) 分析代码并找出space ATTRIBUTE错误的原因
06-28
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值