python第六周小测

1. 按奇偶排序数组(leetcode)
给定一个非负整数数组 A,返回一个数组,在该数组中, A 的所有偶数元素之后跟着所有奇数元素。你可以返回满足此条件的任何数组作为答案。
示例:
输入:[3,1,2,4]
输出:[2,4,3,1]
输出 [4,2,3,1],[2,4,1,3] 和 [4,2,1,3] 也会被接受。

方法一:sorted()方法

class Solution:
    def sortArrayByParity(self, A: List[int]) -> List[int]:
        return sorted(A,key=lambda x: 0 if x%2==0 else 1)

方法二:双指针遍历,然后交换奇偶数位置

class Solution:
    def sortArrayByParity(self, A: List[int]) -> List[int]:
        i = 0
        j = len(A)-1
        while i<j:
            if A[i]%2!=0:
                if A[j]%2==0:
                    A[i],A[j]=A[j],A[i]
                else:
                    j-=1
            else:
                i+=1
        return A      

方法三:偶数奇数分别存储在列表中,最后将列表拼接

class Solution:
    def sortArrayByParity(self, A: List[int]) -> List[int]:
        odd=[]
        even=[]
        for i in A:
            if i %2==0:
                even.append(i)
            else:
                odd.append(i)
        A=even+odd
        return A

2.给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。
给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。(leetcode)

class Solution:
    def letterCombinations(self, digits: str) -> List[str]:
        if len(digits) == 0:
            return [] 
        numbers = {'2': ['a', 'b', 'c'],
                 '3': ['d', 'e', 'f'],
                 '4': ['g', 'h', 'i'],
                 '5': ['j', 'k', 'l'],
                 '6': ['m', 'n', 'o'],
                 '7': ['p', 'q', 'r', 's'],
                 '8': ['t', 'u', 'v'],
                 '9': ['w', 'x', 'y', 'z']}
        
        res = []
        path = ''
        
        def comb(num,path):
            if len(path) == len(digits):
                res.append(path)
            else:
                for i in numbers[digits[num]]:
                    comb(num+1,path+i)
        comb(0,'')
        return res

3.思聪爱吃热狗游戏

双人版的思聪吃热狗游戏,你可以自己调节思聪的位置, 移动时会消耗能量 10, 游戏中吃到热狗分数加1, 能量加20,最后的目标就是称霸世界咯, 吃掉 所有的热狗即游戏胜利。王思聪能量消耗完毕即游戏失败。
玩家1:WASD
玩家2:↑↓←→

#encoding:utf-8


import random
import time

import pygame
import sys
from pygame.locals import *
width = 640
height = 480

pygame.init()
screen = pygame.display.set_mode([width, height])
pygame.display.set_caption('思聪吃热狗')  # 定义窗口的标题
background = pygame.image.load("./img/bg.jpg").convert()
breadImg = pygame.image.load("./img/mianbao.png").convert_alpha()
sicongImg = pygame.image.load("./img/sicong.png").convert_alpha()

# 背景音乐
pygame.mixer.music.load("./img/game_music.mp3")
pygame.mixer.music.play(loops=0, start=0.0)

# 成绩文字显示
count = 0
count1 = 0
font = pygame.font.SysFont("arial", 30)

# 显示游戏状态
status = font.render("Gaming" , True, (255, 255, 255))


w_width = sicongImg.get_width() - 5  # 思聪图片的宽度
w_height = sicongImg.get_height() - 5  # 思聪图片的高度

y_width = breadImg.get_width() - 5  # 面包图片的宽度
y_height = breadImg.get_height() - 5  # 面包图片的高度
fpsClock = pygame.time.Clock()  # 创建一个新的Clock对象,可以用来跟踪总共的时间


# 思聪类
class sicong:
    def __init__(self):
        self.power = 200  # 体力
        # 思聪坐标
        self.x = random.randint(0, width - w_width)
        self.y = random.randint(0, height - w_height)

    # 思聪移动的方法:移动方向均随机
    def move(self, new_x, new_y):
        # 判断移动后是否超出边界
        if new_x < 0:
            self.x = width-w_width
        elif new_x > width:
            # self.x=width-(new_x-width)
            self.x = 0
        else:
            # 不越界则移动思聪的位置
            self.x = new_x
        if new_y < 0:
            self.y = height - w_height
        elif new_y > height:
            # self.y=height-(new_y-height)
            self.y = 0
        else:
            # 不越界则移动思聪的位置
            self.y = new_y
        self.power -= 5  # 思聪每移动一次,体力消耗5

    def eat(self):
        self.power += 20  # 思聪吃掉热狗,思聪体力增加20
        if self.power > 200:
            self.power = 200  # 思聪体力上限


# 面包类
class Bread:
    def __init__(self):
        # 面包坐标
        self.x = random.randint(0, width - y_width)
        self.y = random.randint(0, height - y_height)

    def move(self):
        new_x = self.x + random.choice([-10])
        if new_x < 0:
            self.x = width
        else:
            self.x = new_x

        # 开始测试数据


player1 = sicong()  # 生成思聪,一个
player2 = sicong()
score = font.render("score %d" % count,True, (255, 255, 255))
score1 = font.render("score1 %d" % count1, True, (255, 255, 255))
bread = []
#随机生成面包个数
for item in range(random.randint(10,40)):
    newbread = Bread()
    bread.append(newbread)

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
        if event.type == KEYDOWN:
            # 通过上下左右方向键控制思聪的动向
            if event.key == pygame.K_LEFT:
                player1.move(player1.x - 20, player1.y)
            if event.key == pygame.K_RIGHT:
                player1.move(player1.x + 10, player1.y)
            if event.key == pygame.K_UP:
                player1.move(player1.x, player1.y - 10)
            if event.key == pygame.K_DOWN:
                player1.move(player1.x, player1.y + 10)
            #第二个思聪移动
            if event.key == pygame.K_a:
                player2.move(player2.x - 10, player2.y)
            if event.key == pygame.K_d:
                player2.move(player2.x + 10, player2.y)
            if event.key == pygame.K_w:
                player2.move(player2.x, player2.y - 10)
            if event.key == pygame.K_s:
                player2.move(player2.x, player2.y + 10)

    screen.blit(background, (0, 0))  # 绘制背景图片
    screen.blit(score, (450, 20))  # 绘制思聪1的分数
    screen.blit(score1, (450, 50)) #绘制思聪2的分数
    screen.blit(status, (0, 400))
    # 绘制面包
    for item in bread:
        screen.blit(breadImg, (item.x, item.y))
        item.move()  # 面包移动
    screen.blit(sicongImg, (player1.x, player1.y))  # 绘制第一思聪
    screen.blit(sicongImg, (player2.x, player2.y))  #绘制第二思聪

    # 判断游戏是否结束:当思聪体力值为0(挂掉)或者面包的数量为0游戏结束
    if player1.power < 0 :
        #print("Game Over: player2 win!")
        # 显示游戏状态
        status = font.render("Game Over: player2 win!", True, (255, 255, 255))
        pygame.display.update()  # 更新到游戏窗口
        time.sleep(10)
        sys.exit(0)
    elif player2.power<0:
        status = font.render("Game Over: player1 win!", True, (255, 255, 255))
        pygame.display.update()  # 更新到游戏窗口
        time.sleep(10)
        sys.exit(0)
    elif len(bread) == 0:
        if count>count1:
            status = font.render("Game Over: player1 win!", True, (255, 255, 255))
        else:
            status = font.render("Game Over: player2 win!", True, (255, 255, 255))
        pygame.display.update()
        time.sleep(10)
        sys.exit(0)
    for item in bread:
        # 判断面包和思聪是否碰撞?
        if  ((player1.x < item.x + y_width) and (player1.x + w_width > item.x)
            and (player1.y < item.y + y_height) and (w_height + player1.y > item.y)) :

            bread.remove(item)  # 面包消失
            player1.eat()
            count = count + 1  # 累加
            score = font.render("score %d" % count, True, (255, 255, 255))
            pygame.display.update()
        if  ((player2.x < item.x + y_width) and (player2.x + w_width > item.x)
            and (player2.y < item.y + y_height) and (w_height + player2.y > item.y)) :

            bread.remove(item)  # 面包消失
            player2.eat()
            count1 = count1 + 1  # 累加
            score1 = font.render("score1 %d" %count1, True, (255, 255, 255))
            pygame.display.update()
    pygame.display.update()  # 更新到游戏窗口
    fpsClock.tick(10)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值